summaryrefslogtreecommitdiff
path: root/openEMS
diff options
context:
space:
mode:
Diffstat (limited to 'openEMS')
-rw-r--r--openEMS/Analyse/PlotVoltage.m70
-rw-r--r--openEMS/CMakeLists.txt208
-rw-r--r--openEMS/COPYING674
-rw-r--r--openEMS/Common/CMakeLists.txt23
-rw-r--r--openEMS/Common/engine_interface_base.cpp39
-rw-r--r--openEMS/Common/engine_interface_base.h88
-rw-r--r--openEMS/Common/operator_base.cpp154
-rw-r--r--openEMS/Common/operator_base.h179
-rw-r--r--openEMS/Common/processcurrent.cpp168
-rw-r--r--openEMS/Common/processcurrent.h41
-rw-r--r--openEMS/Common/processfieldprobe.cpp92
-rw-r--r--openEMS/Common/processfieldprobe.h43
-rw-r--r--openEMS/Common/processfields.cpp341
-rw-r--r--openEMS/Common/processfields.h104
-rw-r--r--openEMS/Common/processfields_fd.cpp225
-rw-r--r--openEMS/Common/processfields_fd.h43
-rw-r--r--openEMS/Common/processfields_sar.cpp335
-rw-r--r--openEMS/Common/processfields_sar.h61
-rw-r--r--openEMS/Common/processfields_td.cpp91
-rw-r--r--openEMS/Common/processfields_td.h42
-rw-r--r--openEMS/Common/processing.cpp372
-rw-r--r--openEMS/Common/processing.h204
-rw-r--r--openEMS/Common/processintegral.cpp177
-rw-r--r--openEMS/Common/processintegral.h71
-rw-r--r--openEMS/Common/processmodematch.cpp265
-rw-r--r--openEMS/Common/processmodematch.h68
-rw-r--r--openEMS/Common/processvoltage.cpp40
-rw-r--r--openEMS/Common/processvoltage.h39
-rw-r--r--openEMS/Common/readme.txt6
-rw-r--r--openEMS/Doxyfile1551
-rw-r--r--openEMS/FDTD/CMakeLists.txt30
-rw-r--r--openEMS/FDTD/engine.cpp232
-rw-r--r--openEMS/FDTD/engine.h104
-rw-r--r--openEMS/FDTD/engine_cylinder.cpp38
-rw-r--r--openEMS/FDTD/engine_cylinder.h36
-rw-r--r--openEMS/FDTD/engine_cylindermultigrid.cpp226
-rw-r--r--openEMS/FDTD/engine_cylindermultigrid.h85
-rw-r--r--openEMS/FDTD/engine_interface_cylindrical_fdtd.cpp64
-rw-r--r--openEMS/FDTD/engine_interface_cylindrical_fdtd.h39
-rw-r--r--openEMS/FDTD/engine_interface_fdtd.cpp274
-rw-r--r--openEMS/FDTD/engine_interface_fdtd.h65
-rw-r--r--openEMS/FDTD/engine_interface_sse_fdtd.cpp69
-rw-r--r--openEMS/FDTD/engine_interface_sse_fdtd.h38
-rw-r--r--openEMS/FDTD/engine_mpi.cpp211
-rw-r--r--openEMS/FDTD/engine_mpi.h57
-rw-r--r--openEMS/FDTD/engine_multithread.cpp343
-rw-r--r--openEMS/FDTD/engine_multithread.h127
-rw-r--r--openEMS/FDTD/engine_sse.cpp176
-rw-r--r--openEMS/FDTD/engine_sse.h60
-rw-r--r--openEMS/FDTD/engine_sse_compressed.cpp163
-rw-r--r--openEMS/FDTD/engine_sse_compressed.h38
-rw-r--r--openEMS/FDTD/excitation.cpp304
-rw-r--r--openEMS/FDTD/excitation.h115
-rw-r--r--openEMS/FDTD/extensions/CMakeLists.txt32
-rw-r--r--openEMS/FDTD/extensions/OptimizeCondSheetParameter.m107
-rw-r--r--openEMS/FDTD/extensions/cond_sheet_parameter.h14
-rw-r--r--openEMS/FDTD/extensions/engine_ext_cylinder.cpp101
-rw-r--r--openEMS/FDTD/extensions/engine_ext_cylinder.h49
-rw-r--r--openEMS/FDTD/extensions/engine_ext_cylindermultigrid.cpp165
-rw-r--r--openEMS/FDTD/extensions/engine_ext_cylindermultigrid.h58
-rw-r--r--openEMS/FDTD/extensions/engine_ext_dispersive.cpp162
-rw-r--r--openEMS/FDTD/extensions/engine_ext_dispersive.h51
-rw-r--r--openEMS/FDTD/extensions/engine_ext_excitation.cpp170
-rw-r--r--openEMS/FDTD/extensions/engine_ext_excitation.h40
-rw-r--r--openEMS/FDTD/extensions/engine_ext_lorentzmaterial.cpp322
-rw-r--r--openEMS/FDTD/extensions/engine_ext_lorentzmaterial.h48
-rw-r--r--openEMS/FDTD/extensions/engine_ext_mur_abc.cpp263
-rw-r--r--openEMS/FDTD/extensions/engine_ext_mur_abc.h63
-rw-r--r--openEMS/FDTD/extensions/engine_ext_steadystate.cpp112
-rw-r--r--openEMS/FDTD/extensions/engine_ext_steadystate.h51
-rw-r--r--openEMS/FDTD/extensions/engine_ext_tfsf.cpp215
-rw-r--r--openEMS/FDTD/extensions/engine_ext_tfsf.h40
-rw-r--r--openEMS/FDTD/extensions/engine_ext_upml.cpp493
-rw-r--r--openEMS/FDTD/extensions/engine_ext_upml.h55
-rw-r--r--openEMS/FDTD/extensions/engine_extension.cpp95
-rw-r--r--openEMS/FDTD/extensions/engine_extension.h88
-rw-r--r--openEMS/FDTD/extensions/operator_ext_conductingsheet.cpp261
-rw-r--r--openEMS/FDTD/extensions/operator_ext_conductingsheet.h51
-rw-r--r--openEMS/FDTD/extensions/operator_ext_cylinder.cpp114
-rw-r--r--openEMS/FDTD/extensions/operator_ext_cylinder.h60
-rw-r--r--openEMS/FDTD/extensions/operator_ext_dispersive.cpp78
-rw-r--r--openEMS/FDTD/extensions/operator_ext_dispersive.h56
-rw-r--r--openEMS/FDTD/extensions/operator_ext_excitation.cpp372
-rw-r--r--openEMS/FDTD/extensions/operator_ext_excitation.h84
-rw-r--r--openEMS/FDTD/extensions/operator_ext_lorentzmaterial.cpp453
-rw-r--r--openEMS/FDTD/extensions/operator_ext_lorentzmaterial.h62
-rw-r--r--openEMS/FDTD/extensions/operator_ext_mur_abc.cpp210
-rw-r--r--openEMS/FDTD/extensions/operator_ext_mur_abc.h68
-rw-r--r--openEMS/FDTD/extensions/operator_ext_steadystate.cpp104
-rw-r--r--openEMS/FDTD/extensions/operator_ext_steadystate.h61
-rw-r--r--openEMS/FDTD/extensions/operator_ext_tfsf.cpp429
-rw-r--r--openEMS/FDTD/extensions/operator_ext_tfsf.h82
-rw-r--r--openEMS/FDTD/extensions/operator_ext_upml.cpp478
-rw-r--r--openEMS/FDTD/extensions/operator_ext_upml.h106
-rw-r--r--openEMS/FDTD/extensions/operator_extension.cpp54
-rw-r--r--openEMS/FDTD/extensions/operator_extension.h87
-rw-r--r--openEMS/FDTD/openems_fdtd_mpi.cpp545
-rw-r--r--openEMS/FDTD/openems_fdtd_mpi.h72
-rw-r--r--openEMS/FDTD/operator.cpp2131
-rw-r--r--openEMS/FDTD/operator.h287
-rw-r--r--openEMS/FDTD/operator_cylinder.cpp576
-rw-r--r--openEMS/FDTD/operator_cylinder.h118
-rw-r--r--openEMS/FDTD/operator_cylindermultigrid.cpp569
-rw-r--r--openEMS/FDTD/operator_cylindermultigrid.h109
-rw-r--r--openEMS/FDTD/operator_mpi.cpp209
-rw-r--r--openEMS/FDTD/operator_mpi.h90
-rw-r--r--openEMS/FDTD/operator_multithread.cpp203
-rw-r--r--openEMS/FDTD/operator_multithread.h89
-rw-r--r--openEMS/FDTD/operator_sse.cpp91
-rw-r--r--openEMS/FDTD/operator_sse.h63
-rw-r--r--openEMS/FDTD/operator_sse_compressed.cpp251
-rw-r--r--openEMS/FDTD/operator_sse_compressed.h84
-rw-r--r--openEMS/INSTALL27
-rw-r--r--openEMS/NEWS40
-rw-r--r--openEMS/README19
-rw-r--r--openEMS/TESTSUITE/combinedtests/Coax.m158
-rw-r--r--openEMS/TESTSUITE/combinedtests/README3
-rw-r--r--openEMS/TESTSUITE/combinedtests/cavity.m229
-rw-r--r--openEMS/TESTSUITE/enginetests/cavity.m190
-rw-r--r--openEMS/TESTSUITE/helperscripts/check_frequency.m31
-rw-r--r--openEMS/TESTSUITE/helperscripts/check_limits.m22
-rw-r--r--openEMS/TESTSUITE/probes/fieldprobes.m324
-rw-r--r--openEMS/TESTSUITE/run_testsuite.m58
-rw-r--r--openEMS/TODO14
-rwxr-xr-xopenEMS/astyle.sh4
-rw-r--r--openEMS/cmake/Modules/FindTinyXML.cmake74
-rw-r--r--openEMS/known_bugs1
-rw-r--r--openEMS/known_problems4
-rw-r--r--openEMS/linux/CalcNF2FF.m.patch14
-rw-r--r--openEMS/linux/README.patch15
-rw-r--r--openEMS/linux/debian.changelog27
-rw-r--r--openEMS/linux/debian.control12
-rw-r--r--openEMS/linux/debian.docs2
-rw-r--r--openEMS/linux/debian.rules90
-rw-r--r--openEMS/linux/debian.series3
-rw-r--r--openEMS/linux/fedora17.diff13
-rw-r--r--openEMS/linux/invoke_openEMS.m.patch15
-rw-r--r--openEMS/linux/openEMS.dsc9
-rw-r--r--openEMS/linux/openEMS.spec113
-rw-r--r--openEMS/main.cpp81
-rw-r--r--openEMS/matlab/AR_estimate.m115
-rw-r--r--openEMS/matlab/Add2Queue.m48
-rw-r--r--openEMS/matlab/AddCPWPort.m285
-rw-r--r--openEMS/matlab/AddCircWaveGuidePort.m109
-rw-r--r--openEMS/matlab/AddCoaxialPort.m232
-rw-r--r--openEMS/matlab/AddCurvePort.m182
-rw-r--r--openEMS/matlab/AddLumpedPort.m129
-rw-r--r--openEMS/matlab/AddMRStub.m73
-rw-r--r--openEMS/matlab/AddMSLPort.m265
-rw-r--r--openEMS/matlab/AddPML.m92
-rw-r--r--openEMS/matlab/AddRectWaveGuidePort.m92
-rw-r--r--openEMS/matlab/AddStripLinePort.m283
-rw-r--r--openEMS/matlab/AddWaveGuidePort.m119
-rw-r--r--openEMS/matlab/AnalyzeNF2FF.m231
-rw-r--r--openEMS/matlab/CalcNF2FF.m161
-rw-r--r--openEMS/matlab/CheckQueue.m60
-rw-r--r--openEMS/matlab/ConvertHDF5_VTK.m100
-rw-r--r--openEMS/matlab/CreateNF2FFBox.m94
-rw-r--r--openEMS/matlab/DFT_time2freq.m47
-rw-r--r--openEMS/matlab/Dump2VTK.m179
-rw-r--r--openEMS/matlab/DumpFF2VTK.m105
-rw-r--r--openEMS/matlab/FFT_time2freq.m18
-rw-r--r--openEMS/matlab/FindFreeSSH.m87
-rw-r--r--openEMS/matlab/FinishQueue.m40
-rw-r--r--openEMS/matlab/GetField_Interpolation.m147
-rw-r--r--openEMS/matlab/GetField_Range.m71
-rw-r--r--openEMS/matlab/GetField_SubSampling.m63
-rw-r--r--openEMS/matlab/GetField_TD2FD.m48
-rw-r--r--openEMS/matlab/InitCylindricalFDTD.m21
-rw-r--r--openEMS/matlab/InitFDTD.m64
-rw-r--r--openEMS/matlab/InitQueue.m90
-rw-r--r--openEMS/matlab/PlotHDF5FieldData.m94
-rw-r--r--openEMS/matlab/ReadHDF5Attribute.m33
-rw-r--r--openEMS/matlab/ReadHDF5Dump.m92
-rw-r--r--openEMS/matlab/ReadHDF5FieldData.m119
-rw-r--r--openEMS/matlab/ReadHDF5Mesh.m80
-rw-r--r--openEMS/matlab/ReadUI.m107
-rw-r--r--openEMS/matlab/ResultsQueue.m24
-rw-r--r--openEMS/matlab/RunOpenEMS.m186
-rw-r--r--openEMS/matlab/RunOpenEMS_MPI.m125
-rw-r--r--openEMS/matlab/RunOpenEMS_Parallel.m92
-rw-r--r--openEMS/matlab/SetBoundaryCond.m68
-rw-r--r--openEMS/matlab/SetCustomExcite.m21
-rw-r--r--openEMS/matlab/SetDiracExcite.m3
-rw-r--r--openEMS/matlab/SetGaussExcite.m18
-rw-r--r--openEMS/matlab/SetSinusExcite.m14
-rw-r--r--openEMS/matlab/SetStepExcite.m3
-rw-r--r--openEMS/matlab/SetupMPI.m17
-rw-r--r--openEMS/matlab/Tutorials/Bent_Patch_Antenna.m197
-rw-r--r--openEMS/matlab/Tutorials/CRLH_Extraction.m155
-rw-r--r--openEMS/matlab/Tutorials/CRLH_LeakyWaveAnt.m168
-rw-r--r--openEMS/matlab/Tutorials/Circ_Waveguide.m105
-rw-r--r--openEMS/matlab/Tutorials/Conical_Horn_Antenna.m180
-rw-r--r--openEMS/matlab/Tutorials/CreateCRLH.m55
-rw-r--r--openEMS/matlab/Tutorials/CylindricalWave_CC.m104
-rw-r--r--openEMS/matlab/Tutorials/Dipole_SAR.m221
-rw-r--r--openEMS/matlab/Tutorials/Helical_Antenna.m202
-rw-r--r--openEMS/matlab/Tutorials/Horn_Antenna.m202
-rw-r--r--openEMS/matlab/Tutorials/MRI_LP_Birdcage.m320
-rw-r--r--openEMS/matlab/Tutorials/MRI_Loop_Coil.m334
-rw-r--r--openEMS/matlab/Tutorials/MSL_NotchFilter.m92
-rw-r--r--openEMS/matlab/Tutorials/Parallel_Plate_Waveguide.m51
-rw-r--r--openEMS/matlab/Tutorials/Patch_Antenna_Array.m170
-rw-r--r--openEMS/matlab/Tutorials/Patch_Antenna_Phased_Array.m166
-rw-r--r--openEMS/matlab/Tutorials/RCS_Sphere.m138
-rw-r--r--openEMS/matlab/Tutorials/Rect_Waveguide.m121
-rw-r--r--openEMS/matlab/Tutorials/Simple_Patch_Antenna.m180
-rw-r--r--openEMS/matlab/Tutorials/readme1
-rw-r--r--openEMS/matlab/WriteHDF5.m73
-rw-r--r--openEMS/matlab/WriteOpenEMS.m19
-rw-r--r--openEMS/matlab/calcLumpedPort.m107
-rw-r--r--openEMS/matlab/calcPort.m82
-rw-r--r--openEMS/matlab/calcTLPort.m173
-rw-r--r--openEMS/matlab/calcWGPort.m145
-rw-r--r--openEMS/matlab/calc_ypar.m69
-rw-r--r--openEMS/matlab/examples/__deprecated__/MSL2.m254
-rw-r--r--openEMS/matlab/examples/antennas/Bi_Quad_Antenna.m139
-rw-r--r--openEMS/matlab/examples/antennas/Patch_Antenna.m218
-rw-r--r--openEMS/matlab/examples/antennas/Patch_Antenna_Array.m256
-rw-r--r--openEMS/matlab/examples/antennas/infDipol.m121
-rw-r--r--openEMS/matlab/examples/antennas/inverted_f.m205
-rw-r--r--openEMS/matlab/examples/optimizer/optimizer_asco.m36
-rw-r--r--openEMS/matlab/examples/optimizer/optimizer_simfun.m134
-rw-r--r--openEMS/matlab/examples/other/Helix.m154
-rw-r--r--openEMS/matlab/examples/other/LumpedElement.m158
-rw-r--r--openEMS/matlab/examples/other/Metamaterial_PlaneWave_Drude.m147
-rw-r--r--openEMS/matlab/examples/other/PML_reflection_analysis.m196
-rw-r--r--openEMS/matlab/examples/other/PlaneWave.m69
-rw-r--r--openEMS/matlab/examples/other/gauss_excitation_test.m72
-rw-r--r--openEMS/matlab/examples/other/resistance_sheet.m207
-rw-r--r--openEMS/matlab/examples/transmission_lines/CPW_Line.m125
-rw-r--r--openEMS/matlab/examples/transmission_lines/Finite_Stripline.m91
-rw-r--r--openEMS/matlab/examples/transmission_lines/MSL.m185
-rw-r--r--openEMS/matlab/examples/transmission_lines/MSL_Losses.m102
-rw-r--r--openEMS/matlab/examples/transmission_lines/Stripline.m78
-rw-r--r--openEMS/matlab/examples/transmission_lines/directional_coupler.m261
-rw-r--r--openEMS/matlab/examples/waveguide/Circ_Waveguide.m207
-rw-r--r--openEMS/matlab/examples/waveguide/Circ_Waveguide_CylinderCoords.m204
-rw-r--r--openEMS/matlab/examples/waveguide/Coax.m120
-rw-r--r--openEMS/matlab/examples/waveguide/Coax_CylinderCoords.m190
-rw-r--r--openEMS/matlab/examples/waveguide/Coax_Cylindrical_MG.m155
-rw-r--r--openEMS/matlab/examples/waveguide/Rect_Waveguide.m240
-rwxr-xr-xopenEMS/matlab/h5readatt_octave.cc135
-rw-r--r--openEMS/matlab/harminv.m77
-rw-r--r--openEMS/matlab/optimize.m203
-rw-r--r--openEMS/matlab/optimizer_asco_sim.m88
-rw-r--r--openEMS/matlab/physical_constants.m12
-rw-r--r--openEMS/matlab/plotFF3D.m91
-rw-r--r--openEMS/matlab/plotFFdB.m78
-rw-r--r--openEMS/matlab/polarFF.m172
-rw-r--r--openEMS/matlab/private/ReadNF2FF.m82
-rw-r--r--openEMS/matlab/private/invoke_openEMS.m47
-rw-r--r--openEMS/matlab/queue_addProcess.m22
-rw-r--r--openEMS/matlab/queue_checkProcess.m25
-rw-r--r--openEMS/matlab/queue_delProcess.m40
-rw-r--r--openEMS/matlab/setup.m36
-rw-r--r--openEMS/nf2ff/CMakeLists.txt51
-rw-r--r--openEMS/nf2ff/main.cpp44
-rw-r--r--openEMS/nf2ff/nf2ff.cpp661
-rw-r--r--openEMS/nf2ff/nf2ff.h74
-rw-r--r--openEMS/nf2ff/nf2ff_calc.cpp513
-rw-r--r--openEMS/nf2ff/nf2ff_calc.h136
-rwxr-xr-xopenEMS/openEMS.sh11
-rw-r--r--openEMS/openEMS_MPI.pro5
-rwxr-xr-xopenEMS/openEMS_MPI.sh11
-rw-r--r--openEMS/openems.cpp1231
-rw-r--r--openEMS/openems.h167
-rw-r--r--openEMS/tools/AdrOp.cpp554
-rw-r--r--openEMS/tools/AdrOp.h149
-rw-r--r--openEMS/tools/CMakeLists.txt28
-rw-r--r--openEMS/tools/ErrorMsg.cpp98
-rw-r--r--openEMS/tools/ErrorMsg.h50
-rw-r--r--openEMS/tools/ExpenseLog.cpp145
-rw-r--r--openEMS/tools/ExpenseLog.h92
-rw-r--r--openEMS/tools/aligned_allocator.h173
-rw-r--r--openEMS/tools/array_ops.cpp144
-rw-r--r--openEMS/tools/array_ops.h196
-rw-r--r--openEMS/tools/constants.h29
-rw-r--r--openEMS/tools/global.cpp78
-rw-r--r--openEMS/tools/global.h65
-rw-r--r--openEMS/tools/hdf5_file_reader.cpp689
-rw-r--r--openEMS/tools/hdf5_file_reader.h78
-rw-r--r--openEMS/tools/hdf5_file_writer.cpp515
-rw-r--r--openEMS/tools/hdf5_file_writer.h68
-rw-r--r--openEMS/tools/sar_calculation.cpp656
-rw-r--r--openEMS/tools/sar_calculation.h122
-rw-r--r--openEMS/tools/useful.cpp185
-rw-r--r--openEMS/tools/useful.h44
-rw-r--r--openEMS/tools/vtk_file_writer.cpp340
-rw-r--r--openEMS/tools/vtk_file_writer.h94
290 files changed, 43355 insertions, 0 deletions
diff --git a/openEMS/Analyse/PlotVoltage.m b/openEMS/Analyse/PlotVoltage.m
new file mode 100644
index 0000000..19989c1
--- /dev/null
+++ b/openEMS/Analyse/PlotVoltage.m
@@ -0,0 +1,70 @@
+%close all;
+clear all;
+clc
+
+fmax = 50e6;
+
+figure(1);
+tmpu = load('../tmp/u1');
+tmpi = load('../tmp/i1');
+
+t = tmpu(:,1);
+u = tmpu(:,2);
+
+subplot(2,2,1);
+title('u_1 TD');
+plot(t,u);
+xlabel('t \rightarrow');
+ylabel('ut_1 \rightarrow');
+grid on;
+
+dt=t(2)-t(1);
+u= [u ; zeros(5000,1)];
+L=numel(u);
+t = (1:L)*dt;
+
+f = (0:L-1)/L/dt;
+fu = fft(u)/L;
+subplot(2,2,2);
+title('u_1 FD');
+plot(f(1:L/2),abs(fu(1:L/2)));
+xlabel('f \rightarrow');
+ylabel('|uf_1| \rightarrow');
+grid on;
+
+
+t = tmpi(:,1);
+i = tmpi(:,2);
+
+subplot(2,2,3);
+title('i_1 TD');
+plot(t,i);
+xlabel('t \rightarrow');
+ylabel('it_1 \rightarrow');
+grid on;
+
+dt=t(2)-t(1);
+i = [i; zeros(5000,1)];
+L=numel(i);
+t = (1:L)*dt;
+f = (0:L-1)/L/dt;
+
+fi = fft(i)/L;
+subplot(2,2,4);
+title('i_1 FD');
+plot(f(1:L/2),abs(fi(1:L/2)));
+xlabel('f \rightarrow');
+ylabel('|if_1| \rightarrow');
+grid on;
+
+figure(2);
+subplot(2,1,1);
+plot(f,real(fu./fi));
+xlim([0 fmax]);
+grid on;
+subplot(2,1,2);
+plot(f,imag(fu./fi));
+xlim([0 fmax]);
+grid on;
+
+
diff --git a/openEMS/CMakeLists.txt b/openEMS/CMakeLists.txt
new file mode 100644
index 0000000..5434138
--- /dev/null
+++ b/openEMS/CMakeLists.txt
@@ -0,0 +1,208 @@
+
+# define build type
+IF( DEFINED CMAKE_BUILD_TYPE )
+ SET( CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Set to either \"Release\" or \"Debug\"" )
+ELSE()
+ SET( CMAKE_BUILD_TYPE Release CACHE STRING "Set to either \"Release\" or \"Debug\"" )
+ENDIF()
+
+PROJECT(openEMS CXX)
+cmake_minimum_required(VERSION 2.8)
+
+# default
+set(LIB_VERSION_MAJOR 0)
+set(LIB_VERSION_MINOR 0)
+set(LIB_VERSION_PATCH 34)
+set(LIB_VERSION_STRING ${LIB_VERSION_MAJOR}.${LIB_VERSION_MINOR}.${LIB_VERSION_PATCH})
+
+set(VERSION "v${LIB_VERSION_STRING}")
+
+IF(EXISTS ${PROJECT_SOURCE_DIR}/localConfig.cmake)
+ include(${PROJECT_SOURCE_DIR}/localConfig.cmake)
+ENDIF()
+
+set(VERSION "v0.0.34")
+
+# add git revision
+IF(EXISTS ${PROJECT_SOURCE_DIR}/.git )
+ FIND_PACKAGE(Git)
+ # Get the latest abbreviated commit hash of the working branch
+ execute_process(
+ COMMAND ${GIT_EXECUTABLE} describe --tags
+ WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
+ OUTPUT_VARIABLE GITREV
+ )
+ set(VERSION ${GITREV})
+ string(STRIP ${VERSION} VERSION)
+ message(STATUS "Found Git repository, ${PROJECT_NAME} version tag: ${VERSION}")
+ENDIF()
+
+ADD_DEFINITIONS(-DGIT_VERSION=\"${VERSION}\")
+
+#
+# Set up RPATH for the project
+#
+option(ENABLE_RPATH "Enable rpath support on Linux and Mac" ON)
+if(NOT CMAKE_INSTALL_RPATH)
+ # the RPATH to be used when installing, but only if it's not a system directory
+ LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}" isSystemDir)
+ IF("${isSystemDir}" STREQUAL "-1")
+ SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}")
+ ENDIF("${isSystemDir}" STREQUAL "-1")
+endif()
+if(APPLE AND NOT CMAKE_INSTALL_NAME_DIR)
+ set(CMAKE_INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}")
+endif()
+if(UNIX AND ENABLE_RPATH)
+ set(CMAKE_SKIP_BUILD_RPATH FALSE)
+ set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
+ set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
+endif()
+
+
+if (WITH_MPI)
+ ADD_DEFINITIONS(-DMPI_SUPPORT)
+ # Require MPI for this project:
+ find_package(MPI REQUIRED)
+ INCLUDE_DIRECTORIES( ${MPI_INCLUDE_PATH} )
+
+ message(STATUS "Found MPI. INCLUDE " ${MPI_INCLUDE_PATH})
+endif()
+
+# Set locations of extra CMake modules
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${openEMS_SOURCE_DIR}/cmake/Modules/")
+
+# fparser
+# $ cmake -D FPARSER_ROOT_DIR=~/opt/openEMS .
+# SET(FPARSER_ROOT_DIR ~/opt/openEMS)
+find_library(fparser_LIBRARIES
+ NAMES fparser
+ HINTS ${FPARSER_ROOT_DIR}/lib${LIB_SUFFIX}
+ NO_CMAKE_FIND_ROOT_PATH
+)
+message(STATUS "fparser: ${fparser_LIBRARIES}" )
+#TODO test if fparser was found
+INCLUDE_DIRECTORIES( ${FPARSER_ROOT_DIR}/include )
+
+# CSXCAD
+# $ cmake -D CSXCAD_ROOT_DIR=~/opt/openEMS .
+# SET(CSXCAD_ROOT_DIR ~/opt/openEMS)
+find_library(CSXCAD_LIBRARIES
+ NAMES CSXCAD
+ HINTS ${CSXCAD_ROOT_DIR}/lib${LIB_SUFFIX}
+ NO_CMAKE_FIND_ROOT_PATH
+)
+message(STATUS "CSXCAD_LIBRARIES: ${CSXCAD_LIBRARIES}" )
+#TODO test if CSXCADs was found
+find_path(CSXCAD_INCLUDE_DIR
+ NAMES ContinuousStructure.h
+ HINTS ${CSXCAD_ROOT_DIR}/include
+ PATH_SUFFIXES "CSXCAD" ${CSXCAD_INCLUDE_DIR}
+ NO_CMAKE_FIND_ROOT_PATH
+)
+message(STATUS "CSXCAD_INCLUDE_DIR: ${CSXCAD_INCLUDE_DIR}" )
+INCLUDE_DIRECTORIES( ${CSXCAD_INCLUDE_DIR} )
+
+# TinyXML module from https://github.com/ros/cmake_modules
+find_package(TinyXML REQUIRED)
+ADD_DEFINITIONS( -DTIXML_USE_STL )
+
+# hdf5
+find_package(HDF5 1.8 COMPONENTS C HL REQUIRED)
+INCLUDE_DIRECTORIES (${HDF5_INCLUDE_DIR})
+link_directories(${HDF5_LIBRARY_DIRS})
+
+# hdf5 compat
+ADD_DEFINITIONS( -DH5_USE_16_API )
+
+# boost
+find_package(Boost 1.46 COMPONENTS
+ thread
+ system
+ date_time
+ serialization
+ chrono
+)
+
+# vtk
+if (WIN32)
+ find_package(VTK 6.1 REQUIRED)
+else()
+ # prefer >=6.1, fallback to >=5.4
+ find_package(VTK 6.1 COMPONENTS vtkIOXML vtkIOGeometry vtkIOLegacy vtkIOPLY NO_MODULE)
+ IF (NOT ${VTK_FOUND})
+ find_package(VTK REQUIRED)
+ endif()
+endif()
+
+message(STATUS "Found package VTK. Using version " ${VTK_VERSION})
+if("${VTK_MAJOR_VERSION}" GREATER 5)
+ set( vtk_LIBS ${VTK_LIBRARIES} )
+else()
+ set( vtk_LIBS
+ vtkCommon
+ vtkIO
+ )
+endif()
+message(STATUS "vtk libraries " ${vtk_LIBS})
+
+include(${VTK_USE_FILE})
+INCLUDE_DIRECTORIES (${VTK_INCLUDE_DIR})
+
+#set(CMAKE_CXX_FLAGS "-msse -march=native")
+
+# independent tool
+ADD_SUBDIRECTORY( nf2ff )
+
+set(SOURCES
+ openems.cpp
+)
+
+# libs
+ADD_SUBDIRECTORY( tools )
+ADD_SUBDIRECTORY( FDTD )
+ADD_SUBDIRECTORY( FDTD/extensions )
+ADD_SUBDIRECTORY( Common )
+
+INCLUDE_DIRECTORIES( ${openEMS_SOURCE_DIR} ) #find tools
+
+message(STATUS "Sources:" ${SOURCES})
+
+if (${MPI_CXX_FOUND})
+ set(CMAKE_CXX_COMPILE_FLAGS ${CMAKE_CXX_COMPILE_FLAGS} ${MPI_COMPILE_FLAGS})
+ set(CMAKE_CXX_LINK_FLAGS ${CMAKE_CXX_LINK_FLAGS} ${MPI_LINK_FLAGS})
+ SET(CMAKE_CXX_COMPILER ${MPI_CXX_COMPILER})
+endif()
+
+add_library( openEMS SHARED ${SOURCES})
+set_target_properties(openEMS PROPERTIES VERSION ${LIB_VERSION_STRING} SOVERSION ${LIB_VERSION_MAJOR})
+TARGET_LINK_LIBRARIES( openEMS
+ ${CSXCAD_LIBRARIES}
+ ${fparser_LIBRARIES}
+ tinyxml
+ ${HDF5_LIBRARIES}
+ ${Boost_LIBRARIES}
+ ${vtk_LIBS}
+ ${MPI_LIBRARIES}
+)
+
+# main program
+ADD_EXECUTABLE( openEMS_bin main.cpp )
+SET_TARGET_PROPERTIES(openEMS_bin PROPERTIES OUTPUT_NAME openEMS)
+TARGET_LINK_LIBRARIES(openEMS_bin openEMS)
+
+INSTALL(TARGETS openEMS DESTINATION lib${LIB_SUFFIX})
+INSTALL(TARGETS openEMS_bin DESTINATION bin )
+
+if (UNIX)
+ INSTALL( FILES openEMS.sh
+ DESTINATION bin
+ PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)
+ if (WITH_MPI)
+ INSTALL( FILES openEMS_MPI.sh
+ DESTINATION bin
+ PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)
+ endif()
+endif ()
+INSTALL( DIRECTORY matlab DESTINATION share/openEMS )
+# TODO mpi, tarball, debug, release
diff --git a/openEMS/COPYING b/openEMS/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/openEMS/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/openEMS/Common/CMakeLists.txt b/openEMS/Common/CMakeLists.txt
new file mode 100644
index 0000000..004b35e
--- /dev/null
+++ b/openEMS/Common/CMakeLists.txt
@@ -0,0 +1,23 @@
+
+#INCLUDE_DIRECTORIES( ${openEMS_SOURCE_DIR} )
+
+set(SOURCES
+ ${SOURCES}
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_interface_base.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_base.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processcurrent.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processfieldprobe.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processfields.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processfields_fd.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processfields_sar.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processfields_td.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processing.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processintegral.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processmodematch.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/processvoltage.cpp
+ PARENT_SCOPE
+)
+
+# Common lib
+#add_library( Common STATIC ${SOURCES} )
+
diff --git a/openEMS/Common/engine_interface_base.cpp b/openEMS/Common/engine_interface_base.cpp
new file mode 100644
index 0000000..4db393c
--- /dev/null
+++ b/openEMS/Common/engine_interface_base.cpp
@@ -0,0 +1,39 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_interface_base.h"
+#include "string"
+
+Engine_Interface_Base::Engine_Interface_Base(Operator_Base* base_op)
+{
+ m_Op_Base = base_op;
+ m_InterpolType = NO_INTERPOLATION;
+}
+
+std::string Engine_Interface_Base::GetInterpolationNameByType(InterpolationType mode)
+{
+ switch (mode)
+ {
+ case NO_INTERPOLATION:
+ return std::string("None");
+ case NODE_INTERPOLATE:
+ return std::string("Node");
+ case CELL_INTERPOLATE:
+ return std::string("Cell");
+ }
+ return std::string();
+}
diff --git a/openEMS/Common/engine_interface_base.h b/openEMS/Common/engine_interface_base.h
new file mode 100644
index 0000000..6ce466b
--- /dev/null
+++ b/openEMS/Common/engine_interface_base.h
@@ -0,0 +1,88 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_INTERFACE_BASE_H
+#define ENGINE_INTERFACE_BASE_H
+
+#include "tools/global.h"
+
+class Operator_Base;
+
+//! This is the abstact base for all Engine Interface classes.
+/*!
+ This is the abstact base for all Engine Interface classes. It will provide unified access to the field information of the corresponding engine.
+ All processing methods should only access this base class.
+*/
+class Engine_Interface_Base
+{
+public:
+ enum InterpolationType { NO_INTERPOLATION, NODE_INTERPOLATE, CELL_INTERPOLATE };
+
+ virtual ~Engine_Interface_Base() {;} //!< provide a virtual destructor to correctly delete derived objects
+
+ //! Set the operator used for this engine interface.
+ virtual void SetOperator(Operator_Base* base_op) {m_Op_Base=base_op;}
+ //! Get the operator used for this engine interface.
+ virtual const Operator_Base* GetOperator() const {return m_Op_Base;}
+
+ //! Set the current interpolation type \sa GetInterpolationType
+ void SetInterpolationType(InterpolationType type) {m_InterpolType=type;}
+ //! Set the current interpolation type \sa GetInterpolationType
+ void SetInterpolationType(int type) {m_InterpolType=(InterpolationType)type;}
+ //! Get the current interpolation type as string \sa SetInterpolationType GetInterpolationType GetInterpolationNameByType
+ std::string GetInterpolationTypeString() {return GetInterpolationNameByType(m_InterpolType);}
+ //! Get the current interpolation type \sa SetInterpolationType
+ InterpolationType GetInterpolationType() {return m_InterpolType;}
+
+ //! Get the (interpolated) electric field at \p pos. \sa SetInterpolationType
+ virtual double* GetEField(const unsigned int* pos, double* out) const =0;
+ //! Get the (interpolated) magnetic field at \p pos. \sa SetInterpolationType
+ virtual double* GetHField(const unsigned int* pos, double* out) const =0;
+ //! Get the (interpolated) electric current density field at \p pos. \sa SetInterpolationType
+ virtual double* GetJField(const unsigned int* pos, double* out) const =0;
+ //! Get the total current density field by rot(H) at \p pos. \sa SetInterpolationType
+ virtual double* GetRotHField(const unsigned int* pos, double* out) const =0;
+
+ //! Calculate the electric field integral along a given line
+ virtual double CalcVoltageIntegral(const unsigned int* start, const unsigned int* stop) const =0;
+
+ //! Convert the interpolation type into a string.
+ static std::string GetInterpolationNameByType(InterpolationType mode);
+
+ //! Get the current simulation time
+ virtual double GetTime(bool dualTime=false) const =0;
+
+ //! Get the current number of timesteps
+ virtual unsigned int GetNumberOfTimesteps() const =0;
+
+ //! Calc (roughly) the total energy
+ /*!
+ This method only calculates a very rough estimate of the total energy in the simulation domain.
+ The result may even be roughly proportional to the real system energy only.
+ Primary goal is speed, not accuracy.
+ */
+ virtual double CalcFastEnergy() const =0;
+
+protected:
+ Engine_Interface_Base(Operator_Base* base_op);
+
+ Operator_Base* m_Op_Base;
+
+ InterpolationType m_InterpolType;
+};
+
+#endif // ENGINE_INTERFACE_BASE_H
diff --git a/openEMS/Common/operator_base.cpp b/openEMS/Common/operator_base.cpp
new file mode 100644
index 0000000..e5d26f5
--- /dev/null
+++ b/openEMS/Common/operator_base.cpp
@@ -0,0 +1,154 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_base.h"
+
+using namespace std;
+
+Operator_Base::Operator_Base()
+{
+ Init();
+ m_MeshType = CARTESIAN;
+ m_StoreMaterial[0]=false;
+ m_StoreMaterial[1]=false;
+ m_StoreMaterial[2]=false;
+ m_StoreMaterial[3]=false;
+}
+
+Operator_Base::~Operator_Base()
+{
+ Delete();
+}
+
+bool Operator_Base::SetGeometryCSX(ContinuousStructure* geo)
+{
+ if (geo==NULL) return false;
+ CSX = geo;
+
+ return true;
+}
+
+std::string Operator_Base::GetDirName(int ny) const
+{
+ if (ny==0) return "x";
+ if (ny==1) return "y";
+ if (ny==2) return "z";
+ return "";
+}
+
+void Operator_Base::Init()
+{
+ CSX = NULL;
+
+ dT = 0;
+ for (int n=0; n<3; ++n)
+ discLines[n]=NULL;
+ for (int n=0; n<6; ++n)
+ m_BC[n]=0;
+
+ SetBackgroundMaterial(1,1,0,0);
+}
+
+void Operator_Base::Delete()
+{
+ for (int n=0; n<3; ++n)
+ {
+ delete[] discLines[n];
+ discLines[n]=0;
+ }
+ for (int n=0; n<6; ++n)
+ m_BC[n]=0;
+ dT = 0;
+}
+
+void Operator_Base::Reset()
+{
+ Delete();
+}
+
+void Operator_Base::SetMaterialStoreFlags(int type, bool val)
+{
+ if ((type<0) || (type>4))
+ return;
+ m_StoreMaterial[type]=val;
+}
+
+bool Operator_Base::GetCellCenterMaterialAvgCoord(const unsigned int pos[3], double coord[3]) const
+{
+ int ipos[3] = {(int)pos[0], (int)pos[1], (int)pos[2]};
+ return GetCellCenterMaterialAvgCoord(ipos, coord);
+}
+
+void Operator_Base::SetBackgroundMaterial(double epsR, double mueR, double kappa, double sigma, double density)
+{
+ SetBackgroundEpsR(epsR);
+ SetBackgroundMueR(mueR);
+ SetBackgroundKappa(kappa);
+ SetBackgroundSigma(sigma);
+ SetBackgroundDensity(density);
+}
+
+void Operator_Base::SetBackgroundEpsR(double val)
+{
+ if (val<1)
+ {
+ cerr << __func__ << ": Warning, a relative electric permittivity <1 it not supported, skipping" << endl;
+ return;
+ }
+ m_BG_epsR=val;
+}
+
+void Operator_Base::SetBackgroundMueR(double val)
+{
+ if (val<1)
+ {
+ cerr << __func__ << ": Warning, a relative magnetic permeability <1 it not supported, skipping" << endl;
+ return;
+ }
+ m_BG_mueR=val;
+}
+
+void Operator_Base::SetBackgroundKappa(double val)
+{
+ if (val<0)
+ {
+ cerr << __func__ << ": Warning, an electric conductivity <0 it not supported, skipping" << endl;
+ return;
+ }
+ m_BG_kappa=val;
+}
+
+void Operator_Base::SetBackgroundSigma(double val)
+{
+ if (val<0)
+ {
+ cerr << __func__ << ": Warning, an artifival magnetic conductivity <0 it not supported, skipping" << endl;
+ return;
+ }
+ m_BG_sigma=val;
+}
+
+
+void Operator_Base::SetBackgroundDensity(double val)
+{
+ if (val<0)
+ {
+ cerr << __func__ << ": Warning, a mass density <0 it not supported, skipping" << endl;
+ return;
+ }
+ m_BG_density=val;
+}
diff --git a/openEMS/Common/operator_base.h b/openEMS/Common/operator_base.h
new file mode 100644
index 0000000..cfbd40b
--- /dev/null
+++ b/openEMS/Common/operator_base.h
@@ -0,0 +1,179 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_BASE_H
+#define OPERATOR_BASE_H
+
+#include "ContinuousStructure.h"
+#include "tools/global.h"
+#include "Common/processing.h"
+#include "string"
+
+typedef struct
+{
+ std::vector<unsigned int> posPath[3];
+ std::vector<unsigned short> dir;
+} Grid_Path;
+
+//! Abstract base-class for a common operator
+class Operator_Base
+{
+public:
+ virtual ~Operator_Base();
+
+ virtual bool SetGeometryCSX(ContinuousStructure* geo);
+ virtual ContinuousStructure* GetGeometryCSX() const {return CSX;}
+
+ //! Get the timestep used by this operator
+ virtual double GetTimestep() const {return dT;}
+
+ //! Get the number of cells or nodes defined by this operator
+ virtual double GetNumberCells() const =0;
+
+ //! Get the number of timesteps satisfying the nyquist condition (may depend on the excitation)
+ virtual unsigned int GetNumberOfNyquistTimesteps() const =0;
+
+ //! Returns the number of lines as needed for post-processing etc.
+ virtual unsigned int GetNumberOfLines(int ny, bool full=false) const =0;
+
+ //! Get the name for the given direction: 0 -> x, 1 -> y, 2 -> z
+ virtual std::string GetDirName(int ny) const;
+
+ //! Get the grid drawing unit in m
+ virtual double GetGridDelta() const =0;
+
+ //! Get the disc line in \a n direction (in drawing units)
+ virtual double GetDiscLine(int n, unsigned int pos, bool dualMesh=false) const =0;
+
+ //! Get the disc line delta in \a n direction (in drawing units)
+ virtual double GetDiscDelta(int n, unsigned int pos, bool dualMesh=false) const =0;
+
+ //! Get the node width for a given direction \a n and a given mesh position \a pos
+ virtual double GetNodeWidth(int ny, const unsigned int pos[3], bool dualMesh = false) const =0;
+
+ //! Get the node area for a given direction \a n and a given mesh position \a pos
+ virtual double GetNodeArea(int ny, const unsigned int pos[3], bool dualMesh = false) const =0;
+
+ //! Get the length of an FDTD edge (unit is meter).
+ virtual double GetEdgeLength(int ny, const unsigned int pos[3], bool dualMesh = false) const =0;
+
+ //! Get the area around an edge for a given direction \a n and a given mesh posisition \a pos
+ /*!
+ This will return the area around an edge with a given direction, measured at the middle of the edge.
+ In a cartesian mesh this is equal to the NodeArea, may be different in other coordinate systems.
+ */
+ virtual double GetEdgeArea(int ny, const unsigned int pos[3], bool dualMesh = false) const =0;
+
+ //! Get the volume of an FDTD cell
+ virtual double GetCellVolume(const unsigned int pos[3], bool dualMesh = false) const =0;
+
+ //! Snap the given coodinates to mesh indices, return box dimension
+ virtual bool SnapToMesh(const double* coord, unsigned int* uicoord, bool dualMesh=false, bool fullMesh=false, bool* inside=NULL) const =0;
+
+ //! Snap a given box to the operator mesh, uiStart will be always <= uiStop
+ /*!
+ \param[in] start the box-start coorindate
+ \param[in] stop the box-stopt coorindate
+ \param[out] uiStart the snapped box-start coorindate index
+ \param[out] uiStop the snapped box-stop coorindate index
+ \param[in] dualMesh snap to main or dual mesh (default is main mesh)
+ \param[in] SnapMethod Snapping method, 0=snap to closest line, 1/(2)=snap such that given box is inside (outside) the snapped lines
+ \return returns the box dimension or -1 if box is not inside the simulation domain
+ */
+ virtual int SnapBox2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh=false, bool fullMesh=false, int SnapMethod=0, bool* bStartIn=NULL, bool* bStopIn=NULL) const =0;
+
+ //! Set the boundary conditions
+ virtual void SetBoundaryCondition(int* BCs) {for (int n=0; n<6; ++n) m_BC[n]=BCs[n];}
+
+ //! Set flags to store material data for post-processing
+ virtual void SetMaterialStoreFlags(int type, bool val);
+
+ //! Check storage flags and cleanup
+ virtual void CleanupMaterialStorage() = 0;
+
+ //! Get stored discrete material (if storage is enabled).
+ virtual double GetDiscMaterial(int type, int ny, const unsigned int pos[3]) const = 0;
+
+ //! Get the cell center coordinate usable for material averaging (Warning, may not be the yee cell center)
+ bool GetCellCenterMaterialAvgCoord(const unsigned int pos[3], double coord[3]) const;
+
+ //! Get the cell center coordinate usable for material averaging (Warning, may not be the yee cell center)
+ virtual bool GetCellCenterMaterialAvgCoord(const int pos[3], double coord[3]) const = 0;
+
+ virtual std::vector<CSPrimitives*> GetPrimitivesBoundBox(int posX, int posY, int posZ, CSProperties::PropertyType type=CSProperties::ANY) const = 0;
+
+ //! Set the background material (default is vacuum)
+ virtual void SetBackgroundMaterial(double epsR=0, double mueR=0, double kappa=0, double sigma=0, double density=0);
+
+ //! Get background rel. electric permittivity
+ double GetBackgroundEpsR() const {return m_BG_epsR;}
+ //! Set background rel. electric permittivity
+ void SetBackgroundEpsR(double val);
+
+ //! Get background rel. magnetic permeability
+ double GetBackgroundMueR() const {return m_BG_mueR;}
+ //! Set background rel. magnetic permeability
+ void SetBackgroundMueR(double val);
+
+ //! Get background electric conductivity
+ double GetBackgroundKappa() const {return m_BG_kappa;}
+ //! Set background electric conductivity
+ void SetBackgroundKappa(double val);
+
+ //! Get background magnetic conductivity (artificial)
+ double GetBackgroundSigma() const {return m_BG_sigma;}
+ //! Set background magnetic conductivity (artificial)
+ void SetBackgroundSigma(double val);
+
+ //! Get background mass density
+ double GetBackgroundDensity() const {return m_BG_density;}
+ //! Set background mass density
+ void SetBackgroundDensity(double val);
+
+protected:
+ Operator_Base();
+
+ ContinuousStructure* CSX;
+
+ virtual void Init();
+ //! Cleanup data and reset
+ void Delete();
+ virtual void Reset();
+
+ //! boundary conditions
+ int m_BC[6];
+
+ //! The operator timestep
+ double dT;
+
+ //! bool flag array to store material data for post-processing
+ bool m_StoreMaterial[4];
+
+ //! background materials
+ double m_BG_epsR;
+ double m_BG_mueR;
+ double m_BG_kappa;
+ double m_BG_sigma;
+ double m_BG_density;
+
+ CoordinateSystem m_MeshType;
+ unsigned int numLines[3];
+ double* discLines[3];
+ double gridDelta;
+};
+
+#endif // OPERATOR_BASE_H
diff --git a/openEMS/Common/processcurrent.cpp b/openEMS/Common/processcurrent.cpp
new file mode 100644
index 0000000..8c35bf0
--- /dev/null
+++ b/openEMS/Common/processcurrent.cpp
@@ -0,0 +1,168 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tools/global.h"
+#include "processcurrent.h"
+#include "FDTD/engine_interface_fdtd.h"
+#include <iomanip>
+
+ProcessCurrent::ProcessCurrent(Engine_Interface_Base* eng_if) : ProcessIntegral(eng_if)
+{
+ m_SnapMethod=1;
+}
+
+ProcessCurrent::~ProcessCurrent()
+{
+}
+
+string ProcessCurrent::GetIntegralName(int row) const
+{
+ if (row==0)
+ return "current";
+ return "unknown";
+}
+
+void ProcessCurrent::DefineStartStopCoord(double* dstart, double* dstop)
+{
+ ProcessIntegral::DefineStartStopCoord(dstart, dstop);
+
+ if ((m_normDir<0) || (m_normDir>2))
+ {
+ if (m_Dimension!=2)
+ {
+ cerr << "ProcessCurrent::DefineStartStopCoord(): Warning Current Integration Box \"" << m_filename << "\" is not a surface (found dimension: " << m_Dimension << ") nor has it set a valid normal direction! --> disabled" << endl;
+ SetEnable(false);
+ return;
+ }
+
+ for (int n=0; n<3; ++n)
+ {
+ if (stop[n] == start[n])
+ m_normDir = n;
+ }
+ }
+ else
+ {
+ //expand dimension to 2 if possible
+ m_Dimension = 0;
+ for (int n=0; n<3; ++n)
+ {
+ if (n==m_normDir)
+ continue;
+ if (dstart[n]==dstop[n])
+ {
+ if ((Op->GetDiscLine( n, start[n], true ) > dstart[n]) && (start[n]>0))
+ --start[n];
+ if ((Op->GetDiscLine( n, start[n], true ) < dstart[n]) && (stop[n]<Op->GetNumberOfLines(n)-1))
+ ++stop[n];
+ }
+ if (stop[n] > start[n])
+ ++m_Dimension;
+ }
+ }
+
+ if (start[m_normDir]!=stop[m_normDir])
+ {
+ cerr << "ProcessCurrent::DefineStartStopCoord(): Warning Current Integration Box \"" << m_filename << "\" has an expansion in normal direction! --> disabled" << endl;
+ SetEnable(false);
+ return;
+ }
+
+ if ((m_normDir<0) || (m_normDir>2))
+ {
+ cerr << "ProcessCurrent::DefineStartStopCoord(): Warning Current Integration Box \"" << m_filename << "\" has an invalid normal direction --> disabled" << endl;
+ SetEnable(false);
+ return;
+ }
+}
+
+double ProcessCurrent::CalcIntegral()
+{
+ FDTD_FLOAT current=0;
+
+ Engine_Interface_FDTD* EI_FDTD = dynamic_cast<Engine_Interface_FDTD*>(m_Eng_Interface);
+
+ if (EI_FDTD)
+ {
+ const Engine* Eng = EI_FDTD->GetFDTDEngine();
+
+
+ switch (m_normDir)
+ {
+ case 0:
+ //y-current
+ if (m_stop_inside[0] && m_start_inside[2])
+ for (unsigned int i=start[1]+1; i<=stop[1]; ++i)
+ current+=Eng->GetCurr(1,stop[0],i,start[2]);
+ //z-current
+ if (m_stop_inside[0] && m_stop_inside[1])
+ for (unsigned int i=start[2]+1; i<=stop[2]; ++i)
+ current+=Eng->GetCurr(2,stop[0],stop[1],i);
+ //y-current
+ if (m_start_inside[0] && m_stop_inside[2])
+ for (unsigned int i=start[1]+1; i<=stop[1]; ++i)
+ current-=Eng->GetCurr(1,start[0],i,stop[2]);
+ //z-current
+ if (m_start_inside[0] && m_start_inside[1])
+ for (unsigned int i=start[2]+1; i<=stop[2]; ++i)
+ current-=Eng->GetCurr(2,start[0],start[1],i);
+ break;
+ case 1:
+ //z-current
+ if (m_start_inside[0] && m_start_inside[1])
+ for (unsigned int i=start[2]+1; i<=stop[2]; ++i)
+ current+=Eng->GetCurr(2,start[0],start[1],i);
+ //x-current
+ if (m_stop_inside[1] && m_stop_inside[2])
+ for (unsigned int i=start[0]+1; i<=stop[0]; ++i)
+ current+=Eng->GetCurr(0,i,stop[1],stop[2]);
+ //z-current
+ if (m_stop_inside[0] && m_stop_inside[1])
+ for (unsigned int i=start[2]+1; i<=stop[2]; ++i)
+ current-=Eng->GetCurr(2,stop[0],stop[1],i);
+ //x-current
+ if (m_start_inside[1] && m_start_inside[2])
+ for (unsigned int i=start[0]+1; i<=stop[0]; ++i)
+ current-=Eng->GetCurr(0,i,start[1],start[2]);
+ break;
+ case 2:
+ //x-current
+ if (m_start_inside[1] && m_start_inside[2])
+ for (unsigned int i=start[0]+1; i<=stop[0]; ++i)
+ current+=Eng->GetCurr(0,i,start[1],start[2]);
+ //y-current
+ if (m_stop_inside[0] && m_start_inside[2])
+ for (unsigned int i=start[1]+1; i<=stop[1]; ++i)
+ current+=Eng->GetCurr(1,stop[0],i,start[2]);
+ //x-current
+ if (m_stop_inside[1] && m_stop_inside[2])
+ for (unsigned int i=start[0]+1; i<=stop[0]; ++i)
+ current-=Eng->GetCurr(0,i,stop[1],stop[2]);
+ //y-current
+ if (m_start_inside[0] && m_stop_inside[2])
+ for (unsigned int i=start[1]+1; i<=stop[1]; ++i)
+ current-=Eng->GetCurr(1,start[0],i,stop[2]);
+ break;
+ default:
+ //this cannot happen...
+ return 0.0;
+ break;
+ }
+ }
+
+ return current;
+}
diff --git a/openEMS/Common/processcurrent.h b/openEMS/Common/processcurrent.h
new file mode 100644
index 0000000..5152b92
--- /dev/null
+++ b/openEMS/Common/processcurrent.h
@@ -0,0 +1,41 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSCURRENT_H
+#define PROCESSCURRENT_H
+
+#include "processintegral.h"
+
+class ProcessCurrent : public ProcessIntegral
+{
+public:
+ ProcessCurrent(Engine_Interface_Base* eng_if);
+ virtual ~ProcessCurrent();
+
+ virtual std::string GetProcessingName() const {return "current integration";}
+
+ virtual std::string GetIntegralName(int row) const;
+
+ virtual void DefineStartStopCoord(double* dstart, double* dstop);
+
+ //! Integrate currents flowing through an area
+ virtual double CalcIntegral();
+
+protected:
+};
+
+#endif // PROCESSCURRENT_H
diff --git a/openEMS/Common/processfieldprobe.cpp b/openEMS/Common/processfieldprobe.cpp
new file mode 100644
index 0000000..c456a22
--- /dev/null
+++ b/openEMS/Common/processfieldprobe.cpp
@@ -0,0 +1,92 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processfieldprobe.h"
+
+using namespace std;
+
+ProcessFieldProbe::ProcessFieldProbe(Engine_Interface_Base* eng_if, int type) : ProcessIntegral(eng_if)
+{
+ SetFieldType(type);
+}
+
+ProcessFieldProbe::~ProcessFieldProbe()
+{
+
+}
+
+string ProcessFieldProbe::GetProcessingName() const
+{
+ if (m_ModeFieldType==0)
+ return "electric field probe";
+ if (m_ModeFieldType==1)
+ return "magnetic field probe";
+ return "unknown field probe";
+}
+
+string ProcessFieldProbe::GetIntegralName(int row) const
+{
+ if (row==0)
+ {
+ if (m_ModeFieldType==0)
+ return "Ex/(V/m)";
+ if (m_ModeFieldType==1)
+ return "Hx/(A/m)";
+ }
+ if (row==1)
+ {
+ if (m_ModeFieldType==0)
+ return "Ey/(V/m)";
+ if (m_ModeFieldType==1)
+ return "Hy/(A/m)";
+ }
+ if (row==2)
+ {
+ if (m_ModeFieldType==0)
+ return "Ez/(V/m)";
+ if (m_ModeFieldType==1)
+ return "Hz/(A/m)";
+ }
+ return "unknown";
+}
+
+void ProcessFieldProbe::SetFieldType(int type)
+{
+ if ((type<0) || (type>1))
+ {
+ cerr << "ProcessFieldProbe::SetFieldType: Error: unknown field type... skipping" << endl;
+ Enabled=false;
+ }
+ m_ModeFieldType = type;
+}
+
+double* ProcessFieldProbe::CalcMultipleIntegrals()
+{
+ m_Eng_Interface->SetInterpolationType(Engine_Interface_Base::NO_INTERPOLATION);
+
+ switch (m_ModeFieldType)
+ {
+ case 0:
+ default:
+ m_Eng_Interface->GetEField(start,m_Results);
+ break;
+ case 1:
+ m_Eng_Interface->GetHField(start,m_Results);
+ break;
+ }
+ return m_Results;
+}
diff --git a/openEMS/Common/processfieldprobe.h b/openEMS/Common/processfieldprobe.h
new file mode 100644
index 0000000..342eba4
--- /dev/null
+++ b/openEMS/Common/processfieldprobe.h
@@ -0,0 +1,43 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSFIELDPROBE_H
+#define PROCESSFIELDPROBE_H
+
+#include "processintegral.h"
+
+class ProcessFieldProbe : public ProcessIntegral
+{
+public:
+ ProcessFieldProbe(Engine_Interface_Base* eng_if, int type=0);
+ virtual ~ProcessFieldProbe();
+
+ virtual std::string GetProcessingName() const;
+
+ virtual std::string GetIntegralName(int row) const;
+
+ //! Set the field type (0 electric field, 1 magnetic field)
+ void SetFieldType(int type);
+
+ virtual int GetNumberOfIntegrals() const {return 3;}
+ virtual double* CalcMultipleIntegrals();
+
+protected:
+ int m_ModeFieldType;
+};
+
+#endif // PROCESSFIELDPROBE_H
diff --git a/openEMS/Common/processfields.cpp b/openEMS/Common/processfields.cpp
new file mode 100644
index 0000000..f52fc14
--- /dev/null
+++ b/openEMS/Common/processfields.cpp
@@ -0,0 +1,341 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <iomanip>
+#include "tools/global.h"
+#include "tools/vtk_file_writer.h"
+#include "tools/hdf5_file_writer.h"
+#include "processfields.h"
+#include "FDTD/engine_interface_fdtd.h"
+
+ProcessFields::ProcessFields(Engine_Interface_Base* eng_if) : Processing(eng_if)
+{
+ m_DumpType = E_FIELD_DUMP;
+ // vtk-file is default
+ m_fileType = VTK_FILETYPE;
+ m_SampleType = NONE;
+ m_Vtk_Dump_File = NULL;
+ m_HDF5_Dump_File = NULL;
+ SetPrecision(6);
+ m_dualTime = false;
+
+ // dump box should be always inside the snapped lines
+ m_SnapMethod = 1;
+
+ for (int n=0; n<3; ++n)
+ {
+ numLines[n]=0;
+ posLines[n]=NULL;
+ discLines[n]=NULL;
+ subSample[n]=1;
+ optResolution[n]=0;
+ }
+}
+
+ProcessFields::~ProcessFields()
+{
+ delete m_Vtk_Dump_File;
+ m_Vtk_Dump_File = NULL;
+ for (int n=0; n<3; ++n)
+ {
+ delete[] posLines[n];
+ posLines[n]=NULL;
+ delete[] discLines[n];
+ discLines[n]=NULL;
+ }
+}
+
+string ProcessFields::GetFieldNameByType(DumpType type)
+{
+ switch (type)
+ {
+ case E_FIELD_DUMP:
+ return "E-Field";
+ case H_FIELD_DUMP:
+ return "H-Field";
+ case J_FIELD_DUMP:
+ return "J-Field";
+ case ROTH_FIELD_DUMP:
+ return "RotH-Field";
+ case SAR_LOCAL_DUMP:
+ return "SAR-local";
+ case SAR_1G_DUMP:
+ return "SAR_1g";
+ case SAR_10G_DUMP:
+ return "SAR_10g";
+ case SAR_RAW_DATA:
+ return "SAR_raw_data";
+ }
+ return "unknown field";
+}
+
+bool ProcessFields::NeedConductivity() const
+{
+ switch (m_DumpType)
+ {
+ case J_FIELD_DUMP:
+ return true;
+ default:
+ return false;
+ }
+ return false;
+}
+
+void ProcessFields::InitProcess()
+{
+ if (Enabled==false) return;
+
+ CalcMeshPos();
+
+ if (m_fileType==VTK_FILETYPE)
+ {
+ delete m_Vtk_Dump_File;
+ m_Vtk_Dump_File = new VTK_File_Writer(m_filename,(int)m_Mesh_Type);
+
+ #ifdef OUTPUT_IN_DRAWINGUNITS
+ double discScaling = 1;
+ #else
+ double discScaling = Op->GetGridDelta();
+ #endif
+ m_Vtk_Dump_File->SetMeshLines(discLines,numLines,discScaling);
+ m_Vtk_Dump_File->SetNativeDump(g_settings.NativeFieldDumps());
+ }
+ if (m_fileType==HDF5_FILETYPE)
+ {
+ delete m_HDF5_Dump_File;
+ m_HDF5_Dump_File = new HDF5_File_Writer(m_filename+".h5");
+
+ #ifdef OUTPUT_IN_DRAWINGUNITS
+ double discScaling = 1;
+ #else
+ double discScaling = Op->GetGridDelta();
+ #endif
+ m_HDF5_Dump_File->WriteRectMesh(numLines,discLines,(int)m_Mesh_Type,discScaling);
+
+ m_HDF5_Dump_File->WriteAtrribute("/","openEMS_HDF5_version",0.2);
+ }
+}
+
+void ProcessFields::SetDumpMode(Engine_Interface_Base::InterpolationType mode)
+{
+ m_Eng_Interface->SetInterpolationType(mode);
+ if (mode==Engine_Interface_Base::CELL_INTERPOLATE)
+ m_dualMesh=true;
+ else if (mode==Engine_Interface_Base::NODE_INTERPOLATE)
+ m_dualMesh=false;
+ //else keep the preset/user defined case
+}
+
+void ProcessFields::DefineStartStopCoord(double* dstart, double* dstop)
+{
+ Processing::DefineStartStopCoord(dstart,dstop);
+
+ // normalize order of start and stop
+ for (int n=0; n<3; ++n)
+ {
+ if (start[n]>stop[n])
+ {
+ unsigned int help = start[n];
+ start[n]=stop[n];
+ stop[n]=help;
+ }
+ }
+}
+
+double ProcessFields::CalcTotalEnergyEstimate() const
+{
+ return m_Eng_Interface->CalcFastEnergy();
+}
+
+void ProcessFields::SetSubSampling(unsigned int subSampleRate, int dir)
+{
+ if (dir>2) return;
+ if (dir<0)
+ {
+ subSample[0]=subSampleRate;
+ subSample[1]=subSampleRate;
+ subSample[2]=subSampleRate;
+ }
+ else subSample[dir]=subSampleRate;
+ m_SampleType = SUBSAMPLE;
+}
+
+void ProcessFields::SetOptResolution(double optRes, int dir)
+{
+ if (dir>2) return;
+ if (dir<0)
+ {
+ optResolution[0]=optRes;
+ optResolution[1]=optRes;
+ optResolution[2]=optRes;
+ }
+ else optResolution[dir]=optRes;
+ m_SampleType = OPT_RESOLUTION;
+}
+
+void ProcessFields::CalcMeshPos()
+{
+ if ((m_SampleType==SUBSAMPLE) || (m_SampleType==NONE))
+ {
+ vector<unsigned int> tmp_pos;
+
+ for (int n=0; n<3; ++n)
+ {
+ // construct new discLines
+ tmp_pos.clear();
+ for (unsigned int i=start[n]; i<=stop[n]; i+=subSample[n])
+ tmp_pos.push_back(i);
+
+ numLines[n] = tmp_pos.size();
+ delete[] discLines[n];
+ discLines[n] = new double[numLines[n]];
+ delete[] posLines[n];
+ posLines[n] = new unsigned int[numLines[n]];
+ for (unsigned int i=0; i<numLines[n]; ++i)
+ {
+ posLines[n][i] = tmp_pos.at(i);
+ discLines[n][i] = Op->GetDiscLine(n,tmp_pos.at(i),m_dualMesh);
+ }
+ }
+ }
+ if ((m_SampleType==OPT_RESOLUTION))
+ {
+ vector<unsigned int> tmp_pos;
+ double oldPos=0;
+ for (int n=0; n<3; ++n)
+ {
+ // construct new discLines
+ tmp_pos.clear();
+ tmp_pos.push_back(start[n]);
+ oldPos=Op->GetDiscLine(n,start[n],m_dualMesh);
+ if (stop[n]==0)
+ tmp_pos.push_back(stop[n]);
+ else
+ for (unsigned int i=start[n]+1; i<=stop[n]-1; ++i)
+ {
+ if ( (Op->GetDiscLine(n,i+1,m_dualMesh)-oldPos) >= optResolution[n])
+ {
+ tmp_pos.push_back(i);
+ oldPos=Op->GetDiscLine(n,i,m_dualMesh);
+ }
+ }
+ if (start[n]!=stop[n])
+ tmp_pos.push_back(stop[n]);
+ numLines[n] = tmp_pos.size();
+ delete[] discLines[n];
+ discLines[n] = new double[numLines[n]];
+ delete[] posLines[n];
+ posLines[n] = new unsigned int[numLines[n]];
+ for (unsigned int i=0; i<numLines[n]; ++i)
+ {
+ posLines[n][i] = tmp_pos.at(i);
+ discLines[n][i] = Op->GetDiscLine(n,tmp_pos.at(i),m_dualMesh);
+ }
+ }
+ }
+}
+
+FDTD_FLOAT**** ProcessFields::CalcField()
+{
+ unsigned int pos[3];
+ double out[3];
+ //create array
+ FDTD_FLOAT**** field = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ switch (m_DumpType)
+ {
+ case E_FIELD_DUMP:
+ for (unsigned int i=0; i<numLines[0]; ++i)
+ {
+ pos[0]=posLines[0][i];
+ for (unsigned int j=0; j<numLines[1]; ++j)
+ {
+ pos[1]=posLines[1][j];
+ for (unsigned int k=0; k<numLines[2]; ++k)
+ {
+ pos[2]=posLines[2][k];
+
+ m_Eng_Interface->GetEField(pos,out);
+ field[0][i][j][k] = out[0];
+ field[1][i][j][k] = out[1];
+ field[2][i][j][k] = out[2];
+ }
+ }
+ }
+ return field;
+ case H_FIELD_DUMP:
+ for (unsigned int i=0; i<numLines[0]; ++i)
+ {
+ pos[0]=posLines[0][i];
+ for (unsigned int j=0; j<numLines[1]; ++j)
+ {
+ pos[1]=posLines[1][j];
+ for (unsigned int k=0; k<numLines[2]; ++k)
+ {
+ pos[2]=posLines[2][k];
+
+ m_Eng_Interface->GetHField(pos,out);
+ field[0][i][j][k] = out[0];
+ field[1][i][j][k] = out[1];
+ field[2][i][j][k] = out[2];
+ }
+ }
+ }
+ return field;
+ case J_FIELD_DUMP:
+ for (unsigned int i=0; i<numLines[0]; ++i)
+ {
+ pos[0]=posLines[0][i];
+ for (unsigned int j=0; j<numLines[1]; ++j)
+ {
+ pos[1]=posLines[1][j];
+ for (unsigned int k=0; k<numLines[2]; ++k)
+ {
+ pos[2]=posLines[2][k];
+
+ m_Eng_Interface->GetJField(pos,out);
+ field[0][i][j][k] = out[0];
+ field[1][i][j][k] = out[1];
+ field[2][i][j][k] = out[2];
+ }
+ }
+ }
+ return field;
+ case ROTH_FIELD_DUMP:
+ for (unsigned int i=0; i<numLines[0]; ++i)
+ {
+ pos[0]=posLines[0][i];
+ for (unsigned int j=0; j<numLines[1]; ++j)
+ {
+ pos[1]=posLines[1][j];
+ for (unsigned int k=0; k<numLines[2]; ++k)
+ {
+ pos[2]=posLines[2][k];
+
+ m_Eng_Interface->GetRotHField(pos,out);
+ field[0][i][j][k] = out[0];
+ field[1][i][j][k] = out[1];
+ field[2][i][j][k] = out[2];
+ }
+ }
+ }
+ return field;
+ default:
+ cerr << "ProcessFields::CalcField(): Error, unknown dump type..." << endl;
+ return field;
+ }
+}
+
diff --git a/openEMS/Common/processfields.h b/openEMS/Common/processfields.h
new file mode 100644
index 0000000..3d4085b
--- /dev/null
+++ b/openEMS/Common/processfields.h
@@ -0,0 +1,104 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSFIELDS_H
+#define PROCESSFIELDS_H
+
+#include "processing.h"
+#include "tools/array_ops.h"
+
+#define __VTK_DATA_TYPE__ "double"
+
+class VTK_File_Writer;
+class HDF5_File_Writer;
+
+class ProcessFields : public Processing
+{
+public:
+ ProcessFields(Engine_Interface_Base* eng_if);
+ virtual ~ProcessFields();
+
+ //! File type definition.
+ enum FileType { VTK_FILETYPE, HDF5_FILETYPE};
+
+ //! Dump type definitions.
+ /*!
+ Current dump types are electric field (E_FIELD_DUMP), magnetic field (H_FIELD_DUMP),
+ (conduction) electric current density (kappa*E) (J_FIELD_DUMP) and total current density (rotH)
+ */
+ enum DumpType { E_FIELD_DUMP=0, H_FIELD_DUMP=1, J_FIELD_DUMP=2, ROTH_FIELD_DUMP=3, SAR_LOCAL_DUMP=20, SAR_1G_DUMP=21, SAR_10G_DUMP=22, SAR_RAW_DATA=29};
+
+ virtual std::string GetProcessingName() const {return "common field processing";}
+
+ virtual void InitProcess();
+
+ virtual void DefineStartStopCoord(double* dstart, double* dstop);
+
+ //! Define a field dump sub sampling rate for a given direction (default: \a dir = -1 means all directions)
+ virtual void SetSubSampling(unsigned int subSampleRate, int dir=-1);
+
+ //! Define a field dump optimal resolution for a given direction (default: \a dir = -1 means all directions)
+ virtual void SetOptResolution(double optRes, int dir=-1);
+
+ //! Set the filename for a hdf5 data group file (HDF5 FileType only) \sa SetFileType()
+ void SetFileName(std::string fn) {m_filename=fn;}
+ std::string SetFileName() const {return m_filename;}
+
+ //! Define the Dump-Mode
+ void SetDumpMode(Engine_Interface_Base::InterpolationType mode);
+ //! This methode will dump all fields on a main cell node using 2 E-field and 4 H-fields per direction.
+ void SetDumpMode2Node() {SetDumpMode(Engine_Interface_Base::NODE_INTERPOLATE);}
+ //! This methode will dump all fields in the center of a main cell (dual-node) using 4 E-field and 2 H-fields per direction.
+ void SetDumpMode2Cell() {SetDumpMode(Engine_Interface_Base::CELL_INTERPOLATE);}
+
+ //! Set dump type: 0 for E-fields, 1 for H-fields, 2 for D-fields, 3 for B-fields, 4 for J-fields, etc...
+ virtual void SetDumpType(DumpType type) {m_DumpType=type;}
+
+ double CalcTotalEnergyEstimate() const;
+
+ void SetFileType(FileType fileType) {m_fileType=fileType;}
+
+ static std::string GetFieldNameByType(DumpType type);
+
+ virtual bool NeedConductivity() const;
+
+protected:
+ DumpType m_DumpType;
+ FileType m_fileType;
+
+ VTK_File_Writer* m_Vtk_Dump_File;
+ HDF5_File_Writer* m_HDF5_Dump_File;
+
+ enum SampleType {NONE, SUBSAMPLE, OPT_RESOLUTION} m_SampleType;
+ virtual void CalcMeshPos();
+
+ //! field dump sub-sampling (if enabled)
+ unsigned int subSample[3];
+
+ //! field dump optimal resolution (if enabled)
+ double optResolution[3];
+
+ //! dump mesh information
+ unsigned int numLines[3]; //number of lines to dump
+ unsigned int* posLines[3]; //grid positions to dump
+ double* discLines[3]; //mesh disc lines to dump
+
+ //! Calculate and return the defined field. Caller has to cleanup the array.
+ FDTD_FLOAT**** CalcField();
+};
+
+#endif // PROCESSFIELDS_H
diff --git a/openEMS/Common/processfields_fd.cpp b/openEMS/Common/processfields_fd.cpp
new file mode 100644
index 0000000..ca59b2b
--- /dev/null
+++ b/openEMS/Common/processfields_fd.cpp
@@ -0,0 +1,225 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processfields_fd.h"
+#include "Common/operator_base.h"
+#include "tools/vtk_file_writer.h"
+#include "tools/hdf5_file_writer.h"
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+using namespace std;
+
+ProcessFieldsFD::ProcessFieldsFD(Engine_Interface_Base* eng_if) : ProcessFields(eng_if)
+{
+}
+
+ProcessFieldsFD::~ProcessFieldsFD()
+{
+ for (size_t n = 0; n<m_FD_Fields.size(); ++n)
+ {
+ Delete_N_3DArray(m_FD_Fields.at(n),numLines);
+ }
+ m_FD_Fields.clear();
+}
+
+void ProcessFieldsFD::InitProcess()
+{
+ if (Enabled==false) return;
+
+ if (m_FD_Samples.size()==0)
+ {
+ cerr << "ProcessFieldsFD::InitProcess: No frequencies found... skipping this dump!" << endl;
+ Enabled=false;
+ return;
+ }
+
+ //setup the hdf5 file
+ ProcessFields::InitProcess();
+
+ if (m_Vtk_Dump_File)
+ m_Vtk_Dump_File->SetHeader(string("openEMS FD Field Dump -- Interpolation: ")+m_Eng_Interface->GetInterpolationTypeString());
+
+ if (m_HDF5_Dump_File)
+ {
+ m_HDF5_Dump_File->SetCurrentGroup("/FieldData/FD");
+ m_HDF5_Dump_File->WriteAtrribute("/FieldData/FD","frequency",m_FD_Samples);
+ }
+
+ //create data structures...
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ std::complex<float>**** field_fd = Create_N_3DArray<std::complex<float> >(numLines);
+ m_FD_Fields.push_back(field_fd);
+ }
+}
+
+int ProcessFieldsFD::Process()
+{
+ if (Enabled==false) return -1;
+ if (CheckTimestep()==false) return GetNextInterval();
+
+ if ((m_FD_Interval==0) || (m_Eng_Interface->GetNumberOfTimesteps()%m_FD_Interval!=0))
+ return GetNextInterval();
+
+ FDTD_FLOAT**** field_td = CalcField();
+ std::complex<float>**** field_fd = NULL;
+
+ double T = m_Eng_Interface->GetTime(m_dualTime);
+ unsigned int pos[3];
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ std::complex<float> exp_jwt_2_dt = std::exp( (std::complex<float>)(-2.0 * _I * M_PI * m_FD_Samples.at(n) * T) );
+ exp_jwt_2_dt *= 2; // *2 for single-sided spectrum
+ exp_jwt_2_dt *= Op->GetTimestep() * m_FD_Interval; // multiply with timestep-interval
+ field_fd = m_FD_Fields.at(n);
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ field_fd[0][pos[0]][pos[1]][pos[2]] += field_td[0][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[1][pos[0]][pos[1]][pos[2]] += field_td[1][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[2][pos[0]][pos[1]][pos[2]] += field_td[2][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ }
+ }
+ }
+ }
+ Delete_N_3DArray<FDTD_FLOAT>(field_td,numLines);
+ ++m_FD_SampleCount;
+ return GetNextInterval();
+}
+
+void ProcessFieldsFD::PostProcess()
+{
+ DumpFDData();
+}
+
+void ProcessFieldsFD::DumpFDData()
+{
+ if (m_fileType==VTK_FILETYPE)
+ {
+ unsigned int pos[3];
+ FDTD_FLOAT**** field = Create_N_3DArray<float>(numLines);
+ std::complex<float>**** field_fd = NULL;
+ double angle=0;
+ int Nr_Ph = 21;
+
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ //dump multiple phase to vtk-files
+ for (int p=0; p<Nr_Ph; ++p)
+ {
+ angle = 2.0 * M_PI * p / Nr_Ph;
+ std::complex<float> exp_jwt = std::exp( (std::complex<float>)( _I * angle) );
+ field_fd = m_FD_Fields.at(n);
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ field[0][pos[0]][pos[1]][pos[2]] = real(field_fd[0][pos[0]][pos[1]][pos[2]] * exp_jwt);
+ field[1][pos[0]][pos[1]][pos[2]] = real(field_fd[1][pos[0]][pos[1]][pos[2]] * exp_jwt);
+ field[2][pos[0]][pos[1]][pos[2]] = real(field_fd[2][pos[0]][pos[1]][pos[2]] * exp_jwt);
+ }
+ }
+ }
+ stringstream ss;
+ ss << m_filename << fixed << "_f=" << m_FD_Samples.at(n) << "_p=" << std::setw( 3 ) << std::setfill( '0' ) <<(int)(angle * 180 / M_PI);
+
+ m_Vtk_Dump_File->SetFilename(ss.str());
+ m_Vtk_Dump_File->ClearAllFields();
+ m_Vtk_Dump_File->AddVectorField(GetFieldNameByType(m_DumpType),field);
+ if (m_Vtk_Dump_File->Write()==false)
+ cerr << "ProcessFieldsFD::Process: can't dump to file... abort! " << endl;
+ }
+
+ {
+ //dump magnitude to vtk-files
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ field[0][pos[0]][pos[1]][pos[2]] = abs(field_fd[0][pos[0]][pos[1]][pos[2]]);
+ field[1][pos[0]][pos[1]][pos[2]] = abs(field_fd[1][pos[0]][pos[1]][pos[2]]);
+ field[2][pos[0]][pos[1]][pos[2]] = abs(field_fd[2][pos[0]][pos[1]][pos[2]]);
+ }
+ }
+ }
+ stringstream ss;
+ ss << m_filename << fixed << "_f=" << m_FD_Samples.at(n) << "_abs";
+ m_Vtk_Dump_File->SetFilename(ss.str());
+ m_Vtk_Dump_File->ClearAllFields();
+ m_Vtk_Dump_File->AddVectorField(GetFieldNameByType(m_DumpType),field);
+ if (m_Vtk_Dump_File->Write()==false)
+ cerr << "ProcessFieldsFD::Process: can't dump to file... abort! " << endl;
+ }
+
+ {
+ //dump phase to vtk-files
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ field[0][pos[0]][pos[1]][pos[2]] = arg(field_fd[0][pos[0]][pos[1]][pos[2]]);
+ field[1][pos[0]][pos[1]][pos[2]] = arg(field_fd[1][pos[0]][pos[1]][pos[2]]);
+ field[2][pos[0]][pos[1]][pos[2]] = arg(field_fd[2][pos[0]][pos[1]][pos[2]]);
+ }
+ }
+ }
+ stringstream ss;
+ ss << m_filename << fixed << "_f=" << m_FD_Samples.at(n) << "_arg";
+ m_Vtk_Dump_File->SetFilename(ss.str());
+ m_Vtk_Dump_File->ClearAllFields();
+ m_Vtk_Dump_File->AddVectorField(GetFieldNameByType(m_DumpType),field);
+ if (m_Vtk_Dump_File->Write()==false)
+ cerr << "ProcessFieldsFD::Process: can't dump to file... abort! " << endl;
+ }
+ }
+ Delete_N_3DArray(field,numLines);
+ return;
+ }
+
+ if (m_fileType==HDF5_FILETYPE)
+ {
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ stringstream ss;
+ ss << "f" << n;
+ size_t datasize[]={numLines[0],numLines[1],numLines[2]};
+ if (m_HDF5_Dump_File->WriteVectorField(ss.str(), m_FD_Fields.at(n), datasize)==false)
+ cerr << "ProcessFieldsFD::Process: can't dump to file...! " << endl;
+
+ //legacy support, use /FieldData/FD frequency-Attribute in the future
+ float freq[1] = {(float)m_FD_Samples.at(n)};
+ if (m_HDF5_Dump_File->WriteAtrribute("/FieldData/FD/"+ss.str()+"_real","frequency",freq,1)==false)
+ cerr << "ProcessFieldsFD::Process: can't dump to file...! " << endl;
+ if (m_HDF5_Dump_File->WriteAtrribute("/FieldData/FD/"+ss.str()+"_imag","frequency",freq,1)==false)
+ cerr << "ProcessFieldsFD::Process: can't dump to file...! " << endl;
+ }
+ return;
+ }
+
+ cerr << "ProcessFieldsFD::Process: unknown File-Type" << endl;
+}
diff --git a/openEMS/Common/processfields_fd.h b/openEMS/Common/processfields_fd.h
new file mode 100644
index 0000000..2049cc3
--- /dev/null
+++ b/openEMS/Common/processfields_fd.h
@@ -0,0 +1,43 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSFIELDS_FD_H
+#define PROCESSFIELDS_FD_H
+
+#include "processfields.h"
+
+class ProcessFieldsFD : public ProcessFields
+{
+public:
+ ProcessFieldsFD(Engine_Interface_Base* eng_if);
+ virtual ~ProcessFieldsFD();
+
+ virtual std::string GetProcessingName() const {return "frequency domain field dump";}
+
+ virtual void InitProcess();
+
+ virtual int Process();
+ virtual void PostProcess();
+
+protected:
+ virtual void DumpFDData();
+
+ //! frequency domain field storage
+ std::vector<std::complex<float>****> m_FD_Fields;
+};
+
+#endif // PROCESSFIELDS_FD_H
diff --git a/openEMS/Common/processfields_sar.cpp b/openEMS/Common/processfields_sar.cpp
new file mode 100644
index 0000000..9bbdab2
--- /dev/null
+++ b/openEMS/Common/processfields_sar.cpp
@@ -0,0 +1,335 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processfields_sar.h"
+#include "operator_base.h"
+#include "tools/vtk_file_writer.h"
+#include "tools/hdf5_file_writer.h"
+#include "tools/sar_calculation.h"
+
+#include "CSPropMaterial.h"
+
+using namespace std;
+
+ProcessFieldsSAR::ProcessFieldsSAR(Engine_Interface_Base* eng_if) : ProcessFieldsFD(eng_if)
+{
+ m_UseCellKappa = true;
+ m_SAR_method = "Simple";
+}
+
+ProcessFieldsSAR::~ProcessFieldsSAR()
+{
+ for (size_t n = 0; n<m_E_FD_Fields.size(); ++n)
+ Delete_N_3DArray(m_E_FD_Fields.at(n),numLines);
+ m_E_FD_Fields.clear();
+
+ for (size_t n = 0; n<m_J_FD_Fields.size(); ++n)
+ Delete_N_3DArray(m_J_FD_Fields.at(n),numLines);
+ m_J_FD_Fields.clear();
+}
+
+void ProcessFieldsSAR::SetDumpType(DumpType type)
+{
+ if (type==SAR_RAW_DATA)
+ m_UseCellKappa = true;
+ ProcessFieldsFD::SetDumpType(type);
+}
+
+bool ProcessFieldsSAR::NeedConductivity() const
+{
+ return !m_UseCellKappa;
+}
+
+void ProcessFieldsSAR::SetSubSampling(unsigned int subSampleRate, int dir)
+{
+ UNUSED(subSampleRate);UNUSED(dir);
+ cerr << "ProcessFieldsSAR::SetSubSampling: Warning: Defining a sub-sampling for SAR calculation is not allowed!!! Skipped!" << endl;
+}
+
+void ProcessFieldsSAR::SetOptResolution(double optRes, int dir)
+{
+ UNUSED(optRes);UNUSED(dir);
+ cerr << "ProcessFieldsSAR::SetOptResolution: Warning: Defining a sub-sampling for SAR calculation is not allowed!!! Skipped!" << endl;
+}
+
+void ProcessFieldsSAR::InitProcess()
+{
+ if ((m_DumpType!=SAR_LOCAL_DUMP) && (m_DumpType!=SAR_1G_DUMP) && (m_DumpType!=SAR_10G_DUMP) && (m_DumpType!=SAR_RAW_DATA))
+ {
+ Enabled=false;
+ cerr << "ProcessFieldsSAR::InitProcess(): Error, wrong dump type... this should not happen... skipping!" << endl;
+ return;
+ }
+ if (m_Eng_Interface->GetInterpolationType()!=Engine_Interface_Base::CELL_INTERPOLATE)
+ {
+ cerr << "ProcessFieldsSAR::InitProcess(): Warning, interpolation type is not supported, resetting to CELL!" << endl;
+ SetDumpMode2Cell();
+ }
+
+ if ((m_DumpType==SAR_RAW_DATA) && (m_fileType!=HDF5_FILETYPE))
+ {
+ Enabled=false;
+ cerr << "ProcessFieldsSAR::InitProcess(): Error, wrong file type for dumping raw SAR data! skipping" << endl;
+ return;
+
+ }
+
+ ProcessFieldsFD::InitProcess();
+
+ if (Enabled==false) return;
+
+ //create data structures...
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ m_E_FD_Fields.push_back(Create_N_3DArray<std::complex<float> >(numLines));
+ if (!m_UseCellKappa)
+ m_J_FD_Fields.push_back(Create_N_3DArray<std::complex<float> >(numLines));
+ }
+}
+
+int ProcessFieldsSAR::Process()
+{
+ if (Enabled==false) return -1;
+ if (CheckTimestep()==false) return GetNextInterval();
+
+ if ((m_FD_Interval==0) || (m_Eng_Interface->GetNumberOfTimesteps()%m_FD_Interval!=0))
+ return GetNextInterval();
+
+ std::complex<float>**** field_fd = NULL;
+ unsigned int pos[3];
+ double T;
+ FDTD_FLOAT**** field_td=NULL;
+
+ //save dump type
+ DumpType save_dump_type = m_DumpType;
+
+ // calc E-field
+ m_DumpType = E_FIELD_DUMP;
+ field_td = CalcField();
+ T = m_Eng_Interface->GetTime(m_dualTime);
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ std::complex<float> exp_jwt_2_dt = std::exp( (std::complex<float>)(-2.0 * _I * M_PI * m_FD_Samples.at(n) * T) );
+ exp_jwt_2_dt *= 2; // *2 for single-sided spectrum
+ exp_jwt_2_dt *= Op->GetTimestep() * m_FD_Interval; // multiply with timestep-interval
+ field_fd = m_E_FD_Fields.at(n);
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ field_fd[0][pos[0]][pos[1]][pos[2]] += field_td[0][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[1][pos[0]][pos[1]][pos[2]] += field_td[1][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[2][pos[0]][pos[1]][pos[2]] += field_td[2][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ }
+ }
+ }
+ }
+ Delete_N_3DArray<FDTD_FLOAT>(field_td,numLines);
+
+ // calc J-field
+ if (!m_UseCellKappa)
+ {
+ m_DumpType = J_FIELD_DUMP;
+ field_td = CalcField();
+ T = m_Eng_Interface->GetTime(m_dualTime);
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ std::complex<float> exp_jwt_2_dt = std::exp( (std::complex<float>)(-2.0 * _I * M_PI * m_FD_Samples.at(n) * T) );
+ exp_jwt_2_dt *= 2; // *2 for single-sided spectrum
+ exp_jwt_2_dt *= Op->GetTimestep() * m_FD_Interval; // multiply with timestep-interval
+ field_fd = m_J_FD_Fields.at(n);
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ field_fd[0][pos[0]][pos[1]][pos[2]] += field_td[0][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[1][pos[0]][pos[1]][pos[2]] += field_td[1][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[2][pos[0]][pos[1]][pos[2]] += field_td[2][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ }
+ }
+ }
+ }
+ Delete_N_3DArray<FDTD_FLOAT>(field_td,numLines);
+ }
+
+ //reset dump type
+ m_DumpType = save_dump_type;
+
+ ++m_FD_SampleCount;
+ return GetNextInterval();
+}
+
+void ProcessFieldsSAR::DumpFDData()
+{
+ if (Enabled==false) return;
+ unsigned int pos[3];
+ unsigned int orig_pos[3];
+ float*** SAR = Create3DArray<float>(numLines);
+ double coord[3];
+ ContinuousStructure* CSX = Op->GetGeometryCSX();
+ CSProperties* prop = NULL;
+ CSPropMaterial* matProp = NULL;
+
+ double power;
+
+ float*** cell_volume = Create3DArray<float>(numLines);
+ float*** cell_density = Create3DArray<float>(numLines);
+ float*** cell_kappa = NULL;
+ if (m_UseCellKappa)
+ cell_kappa = Create3DArray<float>(numLines);
+
+ bool found_UnIsotropic=false;
+
+ // calculate volumes and masses for all cells
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ orig_pos[0] = posLines[0][pos[0]];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ orig_pos[1] = posLines[1][pos[1]];
+ vector<CSPrimitives*> vPrims = Op->GetPrimitivesBoundBox(orig_pos[0], orig_pos[1], -1, CSProperties::MATERIAL);
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ orig_pos[2] = posLines[2][pos[2]];
+
+ cell_volume[pos[0]][pos[1]][pos[2]] = Op->GetCellVolume(orig_pos);
+ cell_density[pos[0]][pos[1]][pos[2]] = 0.0;
+
+ Op->GetCellCenterMaterialAvgCoord(orig_pos, coord);
+ prop = CSX->GetPropertyByCoordPriority(coord, vPrims);
+// prop = CSX->GetPropertyByCoordPriority(coord,CSProperties::MATERIAL);
+ if (prop!=0)
+ {
+ matProp = dynamic_cast<CSPropMaterial*>(prop);
+ if (matProp)
+ {
+ found_UnIsotropic |= !matProp->GetIsotropy();
+ cell_density[pos[0]][pos[1]][pos[2]] = matProp->GetDensityWeighted(coord);
+ if (m_UseCellKappa)
+ cell_kappa[pos[0]][pos[1]][pos[2]] = matProp->GetKappaWeighted(0,coord);
+ }
+ }
+ }
+ }
+ }
+ if (found_UnIsotropic)
+ cerr << "ProcessFieldsSAR::DumpFDData(): Warning, found unisotropic material in SAR calculation... this is unsupported!" << endl;
+
+ float* cellWidth[3];
+ for (int n=0;n<3;++n)
+ {
+ cellWidth[n]=new float[numLines[n]];
+ for (unsigned int i=0;i<numLines[n];++i)
+ cellWidth[n][i]=Op->GetDiscDelta(n,posLines[n][i])*Op->GetGridDelta();
+ }
+
+ if (m_DumpType == SAR_RAW_DATA)
+ {
+ if (m_fileType!=HDF5_FILETYPE)
+ {
+ cerr << "ProcessFieldsSAR::DumpFDData(): Error, wrong file type, this should not happen!!! skipped" << endl;
+ return;
+ }
+
+ size_t datasize[]={numLines[0],numLines[1],numLines[2]};
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ stringstream ss;
+ ss << "f" << n;
+ if (m_HDF5_Dump_File->WriteVectorField(ss.str(), m_E_FD_Fields.at(n), datasize)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ }
+
+ m_HDF5_Dump_File->SetCurrentGroup("/CellData");
+ if (m_UseCellKappa==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: Error, cell conductivity data not available, this should not happen... skipping! " << endl;
+ else if (m_HDF5_Dump_File->WriteScalarField("Conductivity", cell_kappa, datasize)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ if (m_HDF5_Dump_File->WriteScalarField("Density", cell_density, datasize)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ if (m_HDF5_Dump_File->WriteScalarField("Volume", cell_volume, datasize)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ }
+ else
+ {
+ SAR_Calculation SAR_Calc;
+ SAR_Calc.SetAveragingMethod(m_SAR_method, g_settings.GetVerboseLevel()==0);
+ SAR_Calc.SetDebugLevel(g_settings.GetVerboseLevel());
+ SAR_Calc.SetNumLines(numLines);
+ if (m_DumpType == SAR_LOCAL_DUMP)
+ SAR_Calc.SetAveragingMass(0);
+ else if (m_DumpType == SAR_1G_DUMP)
+ SAR_Calc.SetAveragingMass(1e-3);
+ else if (m_DumpType == SAR_10G_DUMP)
+ SAR_Calc.SetAveragingMass(10e-3);
+ else
+ {
+ cerr << "ProcessFieldsSAR::DumpFDData: unknown SAR dump type...!" << endl;
+ }
+ SAR_Calc.SetCellDensities(cell_density);
+ SAR_Calc.SetCellWidth(cellWidth);
+ SAR_Calc.SetCellVolumes(cell_volume);
+ SAR_Calc.SetCellCondictivity(cell_kappa); // cell_kappa will be NULL if m_UseCellKappa is false
+
+ for (size_t n = 0; n<m_FD_Samples.size(); ++n)
+ {
+ SAR_Calc.SetEField(m_E_FD_Fields.at(n));
+ if (!m_UseCellKappa)
+ SAR_Calc.SetJField(m_J_FD_Fields.at(n));
+ power = SAR_Calc.CalcSARPower();
+ SAR_Calc.CalcSAR(SAR);
+
+ if (m_fileType==VTK_FILETYPE)
+ {
+ stringstream ss;
+ ss << m_filename << fixed << "_f=" << m_FD_Samples.at(n);
+
+ m_Vtk_Dump_File->SetFilename(ss.str());
+ m_Vtk_Dump_File->ClearAllFields();
+ m_Vtk_Dump_File->AddScalarField(GetFieldNameByType(m_DumpType),SAR);
+ if (m_Vtk_Dump_File->Write()==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ }
+ else if (m_fileType==HDF5_FILETYPE)
+ {
+ stringstream ss;
+ ss << "f" << n;
+ size_t datasize[]={numLines[0],numLines[1],numLines[2]};
+ if (m_HDF5_Dump_File->WriteScalarField(ss.str(), SAR, datasize)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ float freq[1] = {(float)m_FD_Samples.at(n)};
+ if (m_HDF5_Dump_File->WriteAtrribute("/FieldData/FD/"+ss.str(),"frequency",freq,1)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ float pow[1] = {(float)power};
+ if (m_HDF5_Dump_File->WriteAtrribute("/FieldData/FD/"+ss.str(),"power",pow,1)==false)
+ cerr << "ProcessFieldsSAR::DumpFDData: can't dump to file...! " << endl;
+ }
+ else
+ cerr << "ProcessFieldsSAR::DumpFDData: unknown File-Type" << endl;
+ }
+ }
+ for (int n=0;n<3;++n)
+ delete[] cellWidth[n];
+ Delete3DArray(cell_volume,numLines);
+ Delete3DArray(cell_density,numLines);
+ Delete3DArray(cell_kappa,numLines);
+ Delete3DArray(SAR,numLines);
+}
diff --git a/openEMS/Common/processfields_sar.h b/openEMS/Common/processfields_sar.h
new file mode 100644
index 0000000..289100d
--- /dev/null
+++ b/openEMS/Common/processfields_sar.h
@@ -0,0 +1,61 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSFIELDS_SAR_H
+#define PROCESSFIELDS_SAR_H
+
+#include "processfields_fd.h"
+
+class ProcessFieldsSAR : public ProcessFieldsFD
+{
+public:
+ ProcessFieldsSAR(Engine_Interface_Base* eng_if);
+ virtual ~ProcessFieldsSAR();
+
+ virtual void SetDumpType(DumpType type);
+
+ virtual bool NeedConductivity() const;
+
+ virtual std::string GetProcessingName() const {return "SAR dump";}
+
+ virtual void InitProcess();
+
+ virtual int Process();
+
+ virtual void SetSubSampling(unsigned int subSampleRate, int dir=-1);
+
+ virtual void SetOptResolution(double optRes, int dir=-1);
+
+ //! Set to true for using the conductivity found at the center of a cell, or false for E*J instead
+ virtual void SetUseCellConductivity(bool val) {m_UseCellKappa=val;}
+
+ virtual void SetSARAveragingMethod(std::string method) {m_SAR_method=method;}
+
+protected:
+ virtual void DumpFDData();
+
+ bool m_UseCellKappa;
+
+ std::string m_SAR_method;
+
+ //! frequency domain electric field storage
+ std::vector<std::complex<float>****> m_E_FD_Fields;
+ //! frequency domain current density storage
+ std::vector<std::complex<float>****> m_J_FD_Fields;
+};
+
+#endif // PROCESSFIELDS_SAR_H
diff --git a/openEMS/Common/processfields_td.cpp b/openEMS/Common/processfields_td.cpp
new file mode 100644
index 0000000..d67e48b
--- /dev/null
+++ b/openEMS/Common/processfields_td.cpp
@@ -0,0 +1,91 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processfields_td.h"
+#include "Common/operator_base.h"
+#include "tools/vtk_file_writer.h"
+#include "tools/hdf5_file_writer.h"
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+using namespace std;
+
+ProcessFieldsTD::ProcessFieldsTD(Engine_Interface_Base* eng_if) : ProcessFields(eng_if)
+{
+ pad_length = 8;
+}
+
+ProcessFieldsTD::~ProcessFieldsTD()
+{
+}
+
+void ProcessFieldsTD::InitProcess()
+{
+ if (Enabled==false) return;
+
+ ProcessFields::InitProcess();
+
+ if (m_Vtk_Dump_File)
+ m_Vtk_Dump_File->SetHeader(string("openEMS TD Field Dump -- Interpolation: ")+m_Eng_Interface->GetInterpolationTypeString());
+
+ if (m_HDF5_Dump_File)
+ m_HDF5_Dump_File->SetCurrentGroup("/FieldData/TD");
+}
+
+int ProcessFieldsTD::Process()
+{
+ if (Enabled==false) return -1;
+ if (CheckTimestep()==false) return GetNextInterval();
+
+ string filename = m_filename;
+
+ float**** field = CalcField();
+ bool success = true;
+
+ if (m_fileType==VTK_FILETYPE)
+ {
+ m_Vtk_Dump_File->SetTimestep(m_Eng_Interface->GetNumberOfTimesteps());
+ m_Vtk_Dump_File->ClearAllFields();
+ m_Vtk_Dump_File->AddVectorField(GetFieldNameByType(m_DumpType),field);
+ success &= m_Vtk_Dump_File->Write();
+ }
+ else if (m_fileType==HDF5_FILETYPE)
+ {
+ stringstream ss;
+ ss << std::setw( pad_length ) << std::setfill( '0' ) << m_Eng_Interface->GetNumberOfTimesteps();
+ size_t datasize[]={numLines[0],numLines[1],numLines[2]};
+ success &= m_HDF5_Dump_File->WriteVectorField(ss.str(), field, datasize);
+ float time[1] = {(float)m_Eng_Interface->GetTime(m_dualTime)};
+ success &= m_HDF5_Dump_File->WriteAtrribute("/FieldData/TD/"+ss.str(),"time",time,1);
+ }
+ else
+ {
+ success = false;
+ cerr << "ProcessFieldsTD::Process: unknown File-Type" << endl;
+ }
+
+ Delete_N_3DArray<FDTD_FLOAT>(field,numLines);
+
+ if (success==false)
+ {
+ SetEnable(false);
+ cerr << "ProcessFieldsTD::Process: can't dump to file... disabled! " << endl;
+ }
+
+ return GetNextInterval();
+}
diff --git a/openEMS/Common/processfields_td.h b/openEMS/Common/processfields_td.h
new file mode 100644
index 0000000..91c4c04
--- /dev/null
+++ b/openEMS/Common/processfields_td.h
@@ -0,0 +1,42 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSFIELDS_TD_H
+#define PROCESSFIELDS_TD_H
+
+#include "processfields.h"
+
+class ProcessFieldsTD : public ProcessFields
+{
+public:
+ ProcessFieldsTD(Engine_Interface_Base* eng_if);
+ virtual ~ProcessFieldsTD();
+
+ virtual std::string GetProcessingName() const {return "time domain field dump";}
+
+ virtual void InitProcess();
+
+ virtual int Process();
+
+ //! Set the length of the filename timestep pad filled with zeros (default is 8)
+ void SetPadLength(int val) {pad_length=val;};
+
+protected:
+ int pad_length;
+};
+
+#endif // PROCESSFIELDS_TD_H
diff --git a/openEMS/Common/processing.cpp b/openEMS/Common/processing.cpp
new file mode 100644
index 0000000..a444d9d
--- /dev/null
+++ b/openEMS/Common/processing.cpp
@@ -0,0 +1,372 @@
+/*
+* Copyright (C) 2010-2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tools/global.h"
+#include "tools/useful.h"
+#include "Common/operator_base.h"
+#include <algorithm>
+#include "processing.h"
+#include <climits>
+
+using namespace std;
+
+Processing::Processing(Engine_Interface_Base* eng_if)
+{
+ m_Eng_Interface = NULL;
+ SetEngineInterface(eng_if);
+
+ Enabled = true;
+ m_PS_pos = 0;
+ SetPrecision(12);
+ ProcessInterval=0;
+ m_FD_SampleCount=0;
+ m_FD_Interval=0;
+ m_weight=1;
+ m_Flush = false;
+ m_dualMesh = false;
+ m_dualTime = false;
+ m_SnapMethod = 0;
+ m_Mesh_Type = CARTESIAN_MESH;
+
+ startTS=0;
+ stopTS =UINT_MAX;
+ for (int n=0;n<3;++n)
+ {
+ start[n]=0;
+ stop[n]=0;
+ }
+}
+
+Processing::~Processing()
+{
+ SetEngineInterface(NULL);
+ file.close();
+}
+
+void Processing::Reset()
+{
+ m_PS_pos=0;
+}
+
+void Processing::SetEngineInterface(Engine_Interface_Base* eng_if)
+{
+ delete m_Eng_Interface;
+ m_Eng_Interface = eng_if;
+ if (m_Eng_Interface)
+ Op=m_Eng_Interface->GetOperator();
+ else
+ Op=NULL;
+}
+
+void Processing::SetName(string val, int number)
+{
+ stringstream ss;
+ ss << val << "_" << number;
+ SetName(ss.str());
+}
+
+bool Processing::CheckTimestep()
+{
+ unsigned int ts = m_Eng_Interface->GetNumberOfTimesteps();
+ if (ts<startTS || ts>stopTS)
+ return false;
+ if (m_ProcessSteps.size()>m_PS_pos)
+ {
+ if (m_ProcessSteps.at(m_PS_pos)==ts)
+ {
+ ++m_PS_pos;
+ return true;
+ }
+ }
+ if (ProcessInterval)
+ {
+ if (ts%ProcessInterval==0) return true;
+ }
+
+ if (m_FD_Interval)
+ {
+ if (ts%m_FD_Interval==0) return true;
+ }
+ return false;
+}
+
+int Processing::GetNextInterval() const
+{
+ if (Enabled==false) return -1;
+ int next=INT_MAX;
+ int ts = (int)m_Eng_Interface->GetNumberOfTimesteps();
+ if (m_ProcessSteps.size()>m_PS_pos)
+ {
+ next = (int)m_ProcessSteps.at(m_PS_pos)-ts;
+ }
+ if (ProcessInterval!=0)
+ {
+ int next_Interval = (int)ProcessInterval - ts%ProcessInterval;
+ if (next_Interval<next)
+ next = next_Interval;
+ }
+
+ //check for FD sample interval
+ if (m_FD_Interval!=0)
+ {
+ int next_Interval = (int)m_FD_Interval - ts%m_FD_Interval;
+ if (next_Interval<next)
+ next = next_Interval;
+ }
+
+ return next;
+}
+
+void Processing::AddStep(unsigned int step)
+{
+ if (m_ProcessSteps.size()==0)
+ m_ProcessSteps.push_back(step);
+ else if (find(m_ProcessSteps.begin(), m_ProcessSteps.end(),step)==m_ProcessSteps.end())
+ m_ProcessSteps.push_back(step);
+}
+
+void Processing::AddSteps(vector<unsigned int> steps)
+{
+ for (size_t n=0; n<steps.size(); ++n)
+ {
+ AddStep(steps.at(n));
+ }
+}
+
+void Processing::AddFrequency(double freq)
+{
+ unsigned int nyquistTS = CalcNyquistNum(freq,Op->GetTimestep());
+
+ if (nyquistTS == 0)
+ {
+ cerr << "Processing::AddFrequency: Requested frequency " << freq << " is too high for the current timestep used... skipping..." << endl;
+ return;
+ }
+ else if (nyquistTS<Op->GetNumberOfNyquistTimesteps())
+ {
+ cerr << "Processing::AddFrequency: Warning: Requested frequency " << freq << " is higher than maximum excited frequency..." << endl;
+ }
+
+ if (m_FD_Interval==0)
+ m_FD_Interval = Op->GetNumberOfNyquistTimesteps();
+ if (m_FD_Interval>nyquistTS)
+ m_FD_Interval = nyquistTS;
+
+ m_FD_Samples.push_back(freq);
+}
+
+void Processing::AddFrequency(vector<double> *freqs)
+{
+ for (size_t n=0; n<freqs->size(); ++n)
+ {
+ AddFrequency(freqs->at(n));
+ }
+}
+
+void Processing::DefineStartStopCoord(double* dstart, double* dstop)
+{
+ m_Dimension = Op->SnapBox2Mesh(dstart,dstop,start,stop,m_dualMesh,false,m_SnapMethod, m_start_inside, m_stop_inside);
+ if (m_Dimension<0)
+ {
+ cerr << "Processing::DefineStartStopCoord: Warning in " << m_Name << " (" << GetProcessingName() << ") : Box is outside the field domain!! Disabling" << endl;
+ Enabled = false;
+ return;
+ }
+}
+
+void Processing::ShowSnappedCoords()
+{
+ cerr << m_Name << ": snapped ";
+ if (m_dualMesh)
+ cerr << "dual";
+ else
+ cerr << "primary";
+ cerr << " coords: (" << Op->GetDiscLine( 0, start[0], m_dualMesh ) << ","
+ << Op->GetDiscLine( 1, start[1], m_dualMesh ) << "," << Op->GetDiscLine( 2, start[2], m_dualMesh ) << ") -> ("
+ << Op->GetDiscLine( 0, stop[0], m_dualMesh ) << ","<< Op->GetDiscLine( 1, stop[1], m_dualMesh ) << ","
+ << Op->GetDiscLine( 2, stop[2], m_dualMesh ) << ")";
+ cerr << " [" << start[0] << "," << start[1] << "," << start[2] << "] -> ["
+ << stop[0] << "," << stop[1] << "," << stop[2] << "]" << endl;
+}
+
+void Processing::SetProcessStartStopTime(double start, double stop)
+{
+ double dT = Op->GetTimestep();
+ startTS = 0;
+ stopTS = UINT_MAX;
+ if (start>0)
+ startTS = floor(start/dT);
+ if (stop>0)
+ stopTS = ceil(stop/dT);
+ if (stopTS<=startTS)
+ {
+ cerr << "Processing::SetProcessStartStopTimestep: Invalid start/stop values! Disabling!" << endl;
+ startTS = 0;
+ stopTS = UINT_MAX;
+ }
+}
+
+void Processing::OpenFile( string outfile )
+{
+ if (file.is_open())
+ file.close();
+
+ file.open( outfile.c_str() );
+ if (!file.is_open())
+ cerr << "Can't open file: " << outfile << endl;
+
+ m_filename = outfile;
+}
+
+void Processing::PostProcess()
+{
+ FlushData();
+}
+
+void Processing::DumpBox2File( string vtkfilenameprefix, bool dualMesh ) const
+{
+ string vtkfilename = vtkfilenameprefix + m_filename + ".vtk";
+
+ ofstream file( vtkfilename.c_str() );
+ if (!file.is_open())
+ {
+ cerr << "Processing::DumpBoxes2File(): Can't open file: " << vtkfilename << endl;
+ return;
+ }
+
+ // normalize coordinates
+ double s1[3], s2[3];
+ for (int i=0; i<3; i++)
+ {
+ s1[i] = min(Op->GetDiscLine(i,start[i],dualMesh),Op->GetDiscLine(i,stop[i],dualMesh));
+ s2[i] = max(Op->GetDiscLine(i,start[i],dualMesh),Op->GetDiscLine(i,stop[i],dualMesh));
+ }
+
+ // fix degenerate box/plane -> line (paraview display problem)
+ if (((s1[0] == s2[0]) && (s1[1] == s2[1])) || ((s1[0] == s2[0]) && (s1[2] == s2[2])) || ((s1[2] == s2[2]) && (s1[1] == s2[1])))
+ {
+ // line are not displayed correctly -> enlarge
+ for (int i=0; i<3; i++)
+ {
+ double delta = min( Op->GetEdgeLength( i, start,dualMesh ), Op->GetEdgeLength( i, stop,dualMesh ) ) / Op->GetGridDelta() / 4.0;
+ s1[i] -= delta;
+ s2[i] += delta;
+ }
+ }
+
+ // rescale coordinates
+#ifndef OUTPUT_IN_DRAWINGUNITS
+ double scaling = Op->GetGridDelta();
+ for (int i=0; i<3; i++)
+ {
+ s1[i] *= scaling;
+ s2[i] *= scaling;
+ }
+#endif
+
+ file << "# vtk DataFile Version 2.0" << endl;
+ file << "" << endl;
+ file << "ASCII" << endl;
+ file << "DATASET POLYDATA" << endl;
+
+ file << "POINTS 8 float" << endl;
+ file << s1[0] << " " << s1[1] << " " << s1[2] << endl;
+ file << s2[0] << " " << s1[1] << " " << s1[2] << endl;
+ file << s2[0] << " " << s2[1] << " " << s1[2] << endl;
+ file << s1[0] << " " << s2[1] << " " << s1[2] << endl;
+ file << s1[0] << " " << s1[1] << " " << s2[2] << endl;
+ file << s2[0] << " " << s1[1] << " " << s2[2] << endl;
+ file << s2[0] << " " << s2[1] << " " << s2[2] << endl;
+ file << s1[0] << " " << s2[1] << " " << s2[2] << endl;
+
+ file << "POLYGONS 6 30" << endl;
+ file << "4 0 1 2 3" << endl;
+ file << "4 4 5 6 7" << endl;
+ file << "4 7 6 2 3" << endl;
+ file << "4 4 5 1 0" << endl;
+ file << "4 0 4 7 3" << endl;
+ file << "4 5 6 2 1" << endl;
+
+ file.close();
+}
+
+void ProcessingArray::AddProcessing(Processing* proc)
+{
+ ProcessArray.push_back(proc);
+}
+
+void ProcessingArray::InitAll()
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i)
+ {
+ ProcessArray.at(i)->InitProcess();
+ }
+}
+
+void ProcessingArray::FlushNext()
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i)
+ {
+ ProcessArray.at(i)->FlushNext();
+ }
+}
+
+void ProcessingArray::Reset()
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i)
+ {
+ ProcessArray.at(i)->Reset();
+ }
+}
+
+void ProcessingArray::DeleteAll()
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i)
+ {
+ delete ProcessArray.at(i);
+ }
+ ProcessArray.clear();
+}
+
+void ProcessingArray::PreProcess()
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i) ProcessArray.at(i)->PreProcess();
+}
+
+int ProcessingArray::Process()
+{
+ int nextProcess=maxInterval;
+ //this could be done nicely in parallel??
+ for (size_t i=0; i<ProcessArray.size(); ++i)
+ {
+ int step = ProcessArray.at(i)->Process();
+ if ((step>0) && (step<nextProcess))
+ nextProcess=step;
+ }
+ return nextProcess;
+}
+
+void ProcessingArray::PostProcess()
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i) ProcessArray.at(i)->PostProcess();
+}
+
+void ProcessingArray::DumpBoxes2File( string vtkfilenameprefix ) const
+{
+ for (size_t i=0; i<ProcessArray.size(); ++i)
+ ProcessArray.at(i)->DumpBox2File( vtkfilenameprefix );
+}
diff --git a/openEMS/Common/processing.h b/openEMS/Common/processing.h
new file mode 100644
index 0000000..2042706
--- /dev/null
+++ b/openEMS/Common/processing.h
@@ -0,0 +1,204 @@
+/*
+* Copyright (C) 2010-2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSING_H
+#define PROCESSING_H
+
+#include <complex>
+typedef std::complex<double> double_complex;
+#define _I double_complex(0.0,1.0)
+
+#include <iostream>
+#include <fstream>
+#include <cmath>
+#include <stdio.h>
+#include <stdlib.h>
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include "Common/engine_interface_base.h"
+
+class Operator_Base;
+
+class Processing
+{
+public:
+ virtual ~Processing();
+
+ enum MeshType { CARTESIAN_MESH, CYLINDRICAL_MESH};
+
+ //! Set the interface to the engine. Each processing needs its own engine interface. This class will take ownership and cleanup the interface on deletion!
+ void SetEngineInterface(Engine_Interface_Base* eng_if);
+
+ virtual void SetName(std::string val) {m_Name=val;}
+ virtual void SetName(std::string val, int number);
+ virtual std::string GetName() const {return m_Name;}
+
+ //! Get the name for this processing, will be used in file description.
+ virtual std::string GetProcessingName() const = 0;
+
+ virtual void InitProcess() {};
+ virtual void Reset();
+
+ virtual void DefineStartStopCoord(double* dstart, double* dstop);
+
+ virtual void ShowSnappedCoords();
+
+ void SetProcessInterval(unsigned int interval) {ProcessInterval=std::max((unsigned int)1,interval);}
+ void SetProcessStartStopTime(double start, double stop);
+
+ void AddStep(unsigned int step);
+ void AddSteps(std::vector<unsigned int> steps);
+
+ void AddFrequency(double freq);
+ void AddFrequency(std::vector<double> *freqs);
+
+ bool CheckTimestep();
+
+ //! Process data prior to the simulation run.
+ virtual void PreProcess() {};
+
+ //! Process data during simulation run.
+ virtual int Process() {return GetNextInterval();}
+
+ //! Process data after simulation has finished.
+ virtual void PostProcess();
+
+ //! If disabled, Process() will do nothing...
+ virtual void SetEnable(bool val) {Enabled=val;}
+ //! If disabled, Process() will do nothing...
+ virtual bool GetEnable() const {return Enabled;}
+
+ virtual void SetWeight(double weight) {m_weight=weight;}
+ virtual double GetWeight() {return m_weight;}
+
+ //! Invoke this flag to flush all stored data to disk
+ virtual void FlushNext() {m_Flush = true;}
+ virtual void FlushData() {};
+
+ void SetMeshType(MeshType meshType) {m_Mesh_Type=meshType;}
+
+ //! Set the dump precision
+ void SetPrecision(unsigned int val) {m_precision = val;}
+
+ //! Dump probe geometry to file (will obay main or dual mesh property)
+ virtual void DumpBox2File(std::string vtkfilenameprefix) const {DumpBox2File(vtkfilenameprefix,m_dualMesh);}
+
+ //! Dump probe geometry to file
+ virtual void DumpBox2File(std::string vtkfilenameprefix, bool dualMesh) const;
+
+ virtual void SetDualMesh(bool val) {m_dualMesh=val;}
+ virtual void SetDualTime(bool val) {m_dualTime=val;}
+
+protected:
+ Processing(Engine_Interface_Base* eng_if);
+ Engine_Interface_Base* m_Eng_Interface;
+ const Operator_Base* Op;
+ MeshType m_Mesh_Type;
+
+ unsigned int m_precision;
+
+ std::string m_Name;
+
+ bool m_Flush;
+
+ double m_weight;
+
+ bool Enabled;
+
+ int GetNextInterval() const;
+ unsigned int ProcessInterval;
+
+ size_t m_PS_pos; //! current position in list of processing steps
+ std::vector<unsigned int> m_ProcessSteps; //! list of processing steps
+
+ //! Vector of frequency samples
+ std::vector<double> m_FD_Samples;
+ //! Number of samples already processed
+ unsigned int m_FD_SampleCount;
+ //! Sampling interval needed for the FD_Samples
+ unsigned int m_FD_Interval;
+
+ //! define if given coords are on main or dualMesh (default is false)
+ bool m_dualMesh;
+
+ //! define if given processing uses the dual time concept (default is false);
+ bool m_dualTime;
+
+ //! define the snap method used for this processing
+ int m_SnapMethod;
+
+ //! dimension of the snapped box
+ int m_Dimension;
+
+ //! define/store snapped start/stop coords as mesh index
+ unsigned int start[3];
+ unsigned int stop[3];
+
+ //! start/stop timestep
+ unsigned int startTS, stopTS;
+
+ //! define/store if snapped start/stop coords are inside the field domain
+ bool m_start_inside[3];
+ bool m_stop_inside[3];
+
+ std::ofstream file;
+ std::string m_filename;
+
+ virtual void OpenFile(std::string outfile);
+};
+
+class ProcessingArray
+{
+public:
+ ProcessingArray(unsigned int maximalInterval) {maxInterval=maximalInterval;}
+ ~ProcessingArray() {};
+
+ void AddProcessing(Processing* proc);
+
+ void InitAll();
+
+ //! Invoke this flag to flush all stored data to disk for all processings on next Process()
+ void FlushNext();
+
+ void Reset();
+
+ //! Deletes all given processing's, can be helpful, but use carefull!!!
+ void DeleteAll();
+
+ //! Invoke PreProcess() on all Processings.
+ void PreProcess();
+
+ //! Invoke Process() on all Processings. Will return the smallest next iteration interval.
+ int Process();
+
+ //! Invoke PostProcess() on all Processings.
+ void PostProcess();
+
+ void DumpBoxes2File(std::string vtkfilenameprefix ) const;
+
+ size_t GetNumberOfProcessings() const {return ProcessArray.size();}
+
+ Processing* GetProcessing(size_t number) {return ProcessArray.at(number);}
+
+protected:
+ unsigned int maxInterval;
+ std::vector<Processing*> ProcessArray;
+};
+
+#endif // PROCESSING_H
diff --git a/openEMS/Common/processintegral.cpp b/openEMS/Common/processintegral.cpp
new file mode 100644
index 0000000..b64b479
--- /dev/null
+++ b/openEMS/Common/processintegral.cpp
@@ -0,0 +1,177 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processintegral.h"
+#include "Common/operator_base.h"
+#include "time.h"
+#include <iomanip>
+
+using namespace std;
+
+ProcessIntegral::ProcessIntegral(Engine_Interface_Base* eng_if) : Processing(eng_if)
+{
+ m_Results=NULL;
+ m_FD_Results=NULL;
+ m_normDir = -1;
+}
+
+ProcessIntegral::~ProcessIntegral()
+{
+ delete[] m_Results;
+ delete[] m_FD_Results;
+ m_Results = NULL;
+ m_FD_Results = NULL;
+}
+
+
+void ProcessIntegral::InitProcess()
+{
+ delete[] m_Results; m_Results = NULL;
+ delete[] m_FD_Results; m_FD_Results = NULL;
+
+ if (!Enabled)
+ return;
+
+ m_Results = new double[GetNumberOfIntegrals()];
+ m_FD_Results = new vector<double_complex>[GetNumberOfIntegrals()];
+
+ m_filename = m_Name;
+ OpenFile(m_filename);
+
+ //write header
+ time_t rawTime;
+ time(&rawTime);
+ file << "% time-domain " << GetProcessingName() << " by openEMS " << GIT_VERSION << " @" << ctime(&rawTime);
+ file << "% start-coordinates: ("
+ << Op->GetDiscLine(0,start[0])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(1,start[1])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(2,start[2])*Op->GetGridDelta() << ") m -> [" << start[0] << "," << start[1] << "," << start[2] << "]" << endl;
+ file << "% stop-coordinates: ("
+ << Op->GetDiscLine(0,stop[0])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(1,stop[1])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(2,stop[2])*Op->GetGridDelta() << ") m -> [" << stop[0] << "," << stop[1] << "," << stop[2] << "]" << endl;
+ file << "% t/s";
+ for (int n=0;n<GetNumberOfIntegrals();++n)
+ {
+ file << "\t" << GetIntegralName(n);
+ }
+ file << endl;
+
+ for (int i=0;i<GetNumberOfIntegrals();++i)
+ {
+ for (size_t n=0; n<m_FD_Samples.size(); ++n)
+ {
+ m_FD_Results[i].push_back(0);
+ }
+ }
+}
+
+void ProcessIntegral::FlushData()
+{
+ if (!Enabled)
+ return;
+ if (m_FD_Samples.size())
+ Dump_FD_Data(1.0,m_filename + "_FD");
+}
+
+
+void ProcessIntegral::Dump_FD_Data(double factor, string filename)
+{
+ if (m_FD_Samples.size()==0)
+ return;
+ ofstream file;
+ file.open( filename.c_str() );
+ if (!file.is_open())
+ cerr << "ProcessIntegral::Dump_FD_Data: Error: Can't open file: " << filename << endl;
+
+ //write header
+ time_t rawTime;
+ time(&rawTime);
+ file << "% frequency-domain " << GetProcessingName() << " by openEMS " << GIT_VERSION << " @" << ctime(&rawTime);
+ file << "% start-coordinates: ("
+ << Op->GetDiscLine(0,start[0])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(1,start[1])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(2,start[2])*Op->GetGridDelta() << ") m -> [" << start[0] << "," << start[1] << "," << start[2] << "]" << endl;
+ file << "% stop-coordinates: ("
+ << Op->GetDiscLine(0,stop[0])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(1,stop[1])*Op->GetGridDelta() << ","
+ << Op->GetDiscLine(2,stop[2])*Op->GetGridDelta() << ") m -> [" << stop[0] << "," << stop[1] << "," << stop[2] << "]" << endl;
+ file << "% f/Hz";
+ for (int n=0;n<GetNumberOfIntegrals();++n)
+ {
+ file << "\t" << GetIntegralName(n) << "\t";
+ }
+ file << endl << "%";
+ for (int i = 0; i < GetNumberOfIntegrals();++i)
+ file << "\treal\timag";
+ file << endl;
+
+ for (size_t n=0; n<m_FD_Samples.size(); ++n)
+ {
+ file << m_FD_Samples.at(n) ;
+ for (int i = 0; i < GetNumberOfIntegrals();++i)
+ file << "\t" << std::real(m_FD_Results[i].at(n))*factor << "\t" << std::imag(m_FD_Results[i].at(n))*factor;
+ file << "\n";
+ }
+
+ file.close();
+}
+
+int ProcessIntegral::Process()
+{
+ if (Enabled==false) return -1;
+ if (CheckTimestep()==false) return GetNextInterval();
+
+ CalcMultipleIntegrals();
+ int NrInt = GetNumberOfIntegrals();
+ double time = m_Eng_Interface->GetTime(m_dualTime);
+
+ if (ProcessInterval)
+ {
+ if (m_Eng_Interface->GetNumberOfTimesteps()%ProcessInterval==0)
+ {
+ file << setprecision(m_precision) << time;
+ for (int n=0; n<NrInt; ++n)
+ file << "\t" << m_Results[n] * m_weight;
+ file << endl;
+ }
+ }
+
+ if (m_FD_Interval)
+ {
+ if (m_Eng_Interface->GetNumberOfTimesteps()%m_FD_Interval==0)
+ {
+ for (size_t n=0; n<m_FD_Samples.size(); ++n)
+ {
+ for (int i=0; i<NrInt; ++i)
+ m_FD_Results[i].at(n) += (double)m_Results[i] * m_weight * std::exp( -2.0 * _I * M_PI * m_FD_Samples.at(n) * time ) * 2.0 * Op->GetTimestep() * (double)m_FD_Interval;
+ }
+ ++m_FD_SampleCount;
+ if (m_Flush)
+ FlushData();
+ m_Flush = false;
+ }
+ }
+
+ return GetNextInterval();
+}
+
+double* ProcessIntegral::CalcMultipleIntegrals()
+{
+ m_Results[0] = CalcIntegral();
+ return m_Results;
+}
diff --git a/openEMS/Common/processintegral.h b/openEMS/Common/processintegral.h
new file mode 100644
index 0000000..1bddfd6
--- /dev/null
+++ b/openEMS/Common/processintegral.h
@@ -0,0 +1,71 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSINTEGRAL_H
+#define PROCESSINTEGRAL_H
+
+#include "processing.h"
+
+//! Abstract base class for integral parameter processing
+/*!
+ \todo Weighting is applied equally to all integral parameter --> todo: weighting for each result individually
+ */
+class ProcessIntegral : public Processing
+{
+public:
+ virtual ~ProcessIntegral();
+
+ virtual void InitProcess();
+
+ virtual std::string GetProcessingName() const = 0;
+
+ virtual void GetNormalDir(int nd) {m_normDir=nd;}
+
+ //! Flush FD data to disk
+ virtual void FlushData();
+
+ //! This method can calculate multiple integral parameter and must be overloaded for each derived class. \sa GetNumberOfIntegrals
+ /*!
+ This method will store its integral results internally with a size given by GetNumberOfIntegrals()
+ It will return the result for the CalcIntegral() as default.
+ */
+ virtual double* CalcMultipleIntegrals();
+
+ //! Get the name of the integral for the given row. The names will be used in the file header.
+ virtual std::string GetIntegralName(int row) const = 0;
+
+ //! Number of calculated results produced by this integral processing. \sa CalcMultipleIntegrals
+ virtual int GetNumberOfIntegrals() const {return 1;}
+
+ //! This method should calculate the integral parameter and must be overloaded for each derived class
+ virtual double CalcIntegral() {return 0;}
+
+ //! This method will write the TD and FD dump files using CalcIntegral() to calculate the integral parameter
+ virtual int Process();
+
+protected:
+ ProcessIntegral(Engine_Interface_Base* eng_if);
+
+ void Dump_FD_Data(double factor, std::string filename);
+
+ std::vector<double_complex> *m_FD_Results;
+ double *m_Results;
+
+ int m_normDir; // normal direction as required by some integral processings
+};
+
+#endif // PROCESSINTEGRAL_H
diff --git a/openEMS/Common/processmodematch.cpp b/openEMS/Common/processmodematch.cpp
new file mode 100644
index 0000000..9c71c7a
--- /dev/null
+++ b/openEMS/Common/processmodematch.cpp
@@ -0,0 +1,265 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processmodematch.h"
+#include "CSFunctionParser.h"
+#include "Common/operator_base.h"
+#include "tools/array_ops.h"
+
+using namespace std;
+
+ProcessModeMatch::ProcessModeMatch(Engine_Interface_Base* eng_if) : ProcessIntegral(eng_if)
+{
+ for (int n=0; n<2; ++n)
+ {
+ m_ModeParser[n] = new CSFunctionParser();
+ m_ModeDist[n] = NULL;
+ }
+ delete[] m_Results;
+ m_Results = new double[2];
+}
+
+ProcessModeMatch::~ProcessModeMatch()
+{
+ for (int n=0; n<2; ++n)
+ {
+ delete m_ModeParser[n];
+ m_ModeParser[n] = NULL;
+ }
+ Reset();
+}
+
+string ProcessModeMatch::GetIntegralName(int row) const
+{
+ if (row==0)
+ {
+ if (m_ModeFieldType==0)
+ return "voltage";
+ if (m_ModeFieldType==1)
+ return "current";
+ }
+ if (row==1)
+ {
+ return "mode_purity";
+ }
+ return "unknown";
+}
+
+string ProcessModeMatch::GetProcessingName() const
+{
+ if (m_ModeFieldType==0)
+ return "voltage mode matching";
+ if (m_ModeFieldType==1)
+ return "current mode matching";
+ return "unknown mode matching";
+}
+
+void ProcessModeMatch::InitProcess()
+{
+ if (!Enabled) return;
+
+ if (m_Eng_Interface==NULL)
+ {
+ cerr << "ProcessModeMatch::InitProcess: Error, Engine_Interface is NULL, abort mode mathcing..." << endl;
+ Enabled=false;
+ return;
+ }
+ m_Eng_Interface->SetInterpolationType(Engine_Interface_Base::NODE_INTERPOLATE);
+
+ int Dump_Dim=0;
+ m_ny = -1;
+ for (int n=0; n<3; ++n)
+ {
+ if (start[n]>stop[n])
+ {
+ unsigned int help=start[n];
+ start[n]=stop[n];
+ stop[n]=help;
+ }
+
+ //exclude boundaries from mode-matching
+ if (start[n]==0)
+ ++start[n];
+ if (stop[n]==Op->GetNumberOfLines(n)-1)
+ --stop[n];
+
+ if (stop[n]!=start[n])
+ ++Dump_Dim;
+
+ if (stop[n] == start[n])
+ m_ny = n;
+ }
+
+ if ((Dump_Dim!=2) || (m_ny<0))
+ {
+ cerr << "ProcessModeMatch::InitProcess(): Warning Mode Matching Integration Box \"" << m_filename << "\" is not a surface (found dimension: " << Dump_Dim << ")" << endl;
+ SetEnable(false);
+ Reset();
+ return;
+ }
+
+ int nP = (m_ny+1)%3;
+ int nPP = (m_ny+2)%3;
+ m_numLines[0] = stop[nP] - start[nP] + 1;
+ m_numLines[1] = stop[nPP] - start[nPP] + 1;
+
+ for (int n=0; n<2; ++n)
+ {
+ int ny = (m_ny+n+1)%3;
+ int res = m_ModeParser[n]->Parse(m_ModeFunction[ny], "x,y,z,rho,a,r,t");
+ if (res >= 0)
+ {
+ cerr << "ProcessModeMatch::InitProcess(): Warning, an error occured parsing the mode matching function (see below) ..." << endl;
+ cerr << m_ModeFunction[ny] << "\n" << string(res, ' ') << "^\n" << m_ModeParser[n]->ErrorMsg() << "\n";
+ SetEnable(false);
+ Reset();
+ }
+ }
+
+ for (int n=0; n<2; ++n)
+ {
+ m_ModeDist[n] = Create2DArray<double>(m_numLines);
+ }
+
+ unsigned int pos[3] = {0,0,0};
+ double discLine[3] = {0,0,0};
+ double gridDelta = 1; // 1 -> mode-matching function is definied in drawing units...
+ double var[7];
+ pos[m_ny] = start[m_ny];
+ discLine[m_ny] = Op->GetDiscLine(m_ny,pos[m_ny],m_dualMesh);
+ double norm = 0;
+ double area = 0;
+ for (unsigned int posP = 0; posP<m_numLines[0]; ++posP)
+ {
+ pos[nP] = start[nP] + posP;
+ discLine[nP] = Op->GetDiscLine(nP,pos[nP],m_dualMesh);
+ for (unsigned int posPP = 0; posPP<m_numLines[1]; ++posPP)
+ {
+ pos[nPP] = start[nPP] + posPP;
+ discLine[nPP] = Op->GetDiscLine(nPP,pos[nPP],m_dualMesh);
+
+ var[0] = discLine[0] * gridDelta; // x
+ var[1] = discLine[1] * gridDelta; // y
+ var[2] = discLine[2] * gridDelta; // z
+ var[3] = sqrt(discLine[0]*discLine[0] + discLine[1]*discLine[1]) * gridDelta; // rho = sqrt(x^2 + y^2)
+ var[4] = atan2(discLine[1], discLine[0]); // a = atan(y,x)
+ var[5] = sqrt(pow(discLine[0],2)+pow(discLine[1],2)+pow(discLine[2],2)) * gridDelta; // r
+ var[6] = asin(1)-atan(var[2]/var[3]); //theta (t)
+
+ if (m_Mesh_Type == CYLINDRICAL_MESH)
+ {
+ var[3] = discLine[0] * gridDelta; // rho
+ var[4] = discLine[1]; // a
+ var[0] = discLine[0] * cos(discLine[1]) * gridDelta; // x = r*cos(a)
+ var[1] = discLine[0] * sin(discLine[1]) * gridDelta; // y = r*sin(a)
+ var[5] = sqrt(pow(discLine[0],2)+pow(discLine[2],2)) * gridDelta; // r
+ var[6] = asin(1)-atan(var[2]/var[3]); //theta (t)
+ }
+ area = Op->GetNodeArea(m_ny,pos,m_dualMesh);
+ for (int n=0; n<2; ++n)
+ {
+ m_ModeDist[n][posP][posPP] = m_ModeParser[n]->Eval(var); //calc mode template
+ if ((isnan(m_ModeDist[n][posP][posPP])) || (isinf(m_ModeDist[n][posP][posPP])))
+ m_ModeDist[n][posP][posPP] = 0.0;
+ norm += pow(m_ModeDist[n][posP][posPP],2) * area;
+ }
+// cerr << discLine[0] << " " << discLine[1] << " : " << m_ModeDist[0][posP][posPP] << " , " << m_ModeDist[1][posP][posPP] << endl;
+ }
+ }
+
+ norm = sqrt(norm);
+// cerr << norm << endl;
+ // normalize template function...
+ for (unsigned int posP = 0; posP<m_numLines[0]; ++posP)
+ for (unsigned int posPP = 0; posPP<m_numLines[1]; ++posPP)
+ {
+ for (int n=0; n<2; ++n)
+ {
+ m_ModeDist[n][posP][posPP] /= norm;
+ }
+// cerr << posP << " " << posPP << " : " << m_ModeDist[0][posP][posPP] << " , " << m_ModeDist[1][posP][posPP] << endl;
+ }
+
+ ProcessIntegral::InitProcess();
+}
+
+void ProcessModeMatch::Reset()
+{
+ ProcessIntegral::Reset();
+ for (int n=0; n<2; ++n)
+ {
+ Delete2DArray<double>(m_ModeDist[n],m_numLines);
+ m_ModeDist[n] = NULL;
+ }
+}
+
+
+void ProcessModeMatch::SetModeFunction(int ny, string function)
+{
+ if ((ny<0) || (ny>2)) return;
+ m_ModeFunction[ny] = function;
+}
+
+void ProcessModeMatch::SetFieldType(int type)
+{
+ m_ModeFieldType = type;
+ if ((type<0) || (type>1))
+ cerr << "ProcessModeMatch::SetFieldType: Warning, unknown field type..." << endl;
+}
+
+double* ProcessModeMatch::CalcMultipleIntegrals()
+{
+ double value = 0;
+ double field = 0;
+ double purity = 0;
+ double area = 0;
+
+ int nP = (m_ny+1)%3;
+ int nPP = (m_ny+2)%3;
+
+ unsigned int pos[3] = {0,0,0};
+ pos[m_ny] = start[m_ny];
+
+ double out[3]={0,0,0};
+
+ for (unsigned int posP = 0; posP<m_numLines[0]; ++posP)
+ {
+ pos[nP] = start[nP] + posP;
+ for (unsigned int posPP = 0; posPP<m_numLines[1]; ++posPP)
+ {
+ pos[nPP] = start[nPP] + posPP;
+ area = Op->GetNodeArea(m_ny,pos,m_dualMesh);
+ if (m_ModeFieldType==0)
+ m_Eng_Interface->GetEField(pos,out);
+ if (m_ModeFieldType==1)
+ m_Eng_Interface->GetHField(pos,out);
+
+ for (int n=0; n<2; ++n)
+ {
+ field = out[(m_ny+n+1)%3];
+ value += field * m_ModeDist[n][posP][posPP] * area;
+ purity += field*field * area;
+ }
+ }
+ }
+ if (purity!=0)
+ m_Results[1] = value*value/purity;
+ else
+ m_Results[1] = 0;
+ m_Results[0] = value;
+ return m_Results;
+}
diff --git a/openEMS/Common/processmodematch.h b/openEMS/Common/processmodematch.h
new file mode 100644
index 0000000..0bb03b7
--- /dev/null
+++ b/openEMS/Common/processmodematch.h
@@ -0,0 +1,68 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSMODEMATCH_H
+#define PROCESSMODEMATCH_H
+
+#include "processintegral.h"
+
+class CSFunctionParser;
+
+//! Processing class to match a mode to a given analytic function and return the integral value.
+/*!
+ The analytric function has to be definied in drawing units.
+ It will return the integral value and the mode purity as a secondary value.
+ */
+class ProcessModeMatch : public ProcessIntegral
+{
+public:
+ ProcessModeMatch(Engine_Interface_Base* eng_if);
+ virtual ~ProcessModeMatch();
+
+ virtual std::string GetProcessingName() const;
+
+ virtual std::string GetIntegralName(int row) const;
+
+ virtual void InitProcess();
+ virtual void Reset();
+
+ //! Set the field type (0 electric field, 1 magnetic field)
+ void SetFieldType(int type);
+ //! Set the mode function in the given direction ny. For example: SetModeFunction(0,"cos(pi/1000*x)*sin(pi/500*y)");
+ void SetModeFunction(int ny, std::string function);
+
+ virtual int GetNumberOfIntegrals() const {return 2;}
+ virtual double* CalcMultipleIntegrals();
+
+protected:
+ //normal direction of the mode plane
+ int m_ny;
+
+ int m_ModeFieldType;
+
+ double GetField(int ny, const unsigned int pos[3]);
+ double GetEField(int ny, const unsigned int pos[3]);
+ double GetHField(int ny, const unsigned int pos[3]);
+
+ std::string m_ModeFunction[3];
+ CSFunctionParser* m_ModeParser[2];
+
+ unsigned int m_numLines[2];
+ double** m_ModeDist[2];
+};
+
+#endif // PROCESSMODEMATCH_H
diff --git a/openEMS/Common/processvoltage.cpp b/openEMS/Common/processvoltage.cpp
new file mode 100644
index 0000000..6875b03
--- /dev/null
+++ b/openEMS/Common/processvoltage.cpp
@@ -0,0 +1,40 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "processvoltage.h"
+#include <iomanip>
+
+ProcessVoltage::ProcessVoltage(Engine_Interface_Base* eng_if) : ProcessIntegral(eng_if)
+{
+}
+
+ProcessVoltage::~ProcessVoltage()
+{
+}
+
+std::string ProcessVoltage::GetIntegralName(int row) const
+{
+ if (row==0)
+ return "voltage";
+ return "unknown";
+}
+
+double ProcessVoltage::CalcIntegral()
+{
+ //integrate voltages from start to stop on a line
+ return m_Eng_Interface->CalcVoltageIntegral(start,stop);
+}
diff --git a/openEMS/Common/processvoltage.h b/openEMS/Common/processvoltage.h
new file mode 100644
index 0000000..509ddbf
--- /dev/null
+++ b/openEMS/Common/processvoltage.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PROCESSVOLTAGE_H
+#define PROCESSVOLTAGE_H
+
+#include "processintegral.h"
+
+//! Process voltage along a line from start to stop coordinates. ATM integration along the axis e.g.: in x, then y then z direction (Future: diagonal integration)
+class ProcessVoltage : public ProcessIntegral
+{
+public:
+ ProcessVoltage(Engine_Interface_Base* eng_if);
+ virtual ~ProcessVoltage();
+
+ virtual std::string GetProcessingName() const {return "voltage integration";}
+
+ virtual std::string GetIntegralName(int row) const;
+
+ virtual double CalcIntegral();
+
+protected:
+};
+
+#endif // PROCESSVOLTAGE_H
diff --git a/openEMS/Common/readme.txt b/openEMS/Common/readme.txt
new file mode 100644
index 0000000..8c62be8
--- /dev/null
+++ b/openEMS/Common/readme.txt
@@ -0,0 +1,6 @@
+readme for openEMS/Common
+
+- This folder contains all classes common for all numerical solver included in openEMS (currently only EC-FDTD)
+ - Operator-Base class
+ - Engine-Interface classes
+ - Common processing classes
diff --git a/openEMS/Doxyfile b/openEMS/Doxyfile
new file mode 100644
index 0000000..0b67b59
--- /dev/null
+++ b/openEMS/Doxyfile
@@ -0,0 +1,1551 @@
+# Doxyfile 1.6.3
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME = openEMS
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY = doc
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it parses.
+# With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this tag.
+# The format is ext=language, where ext is a file extension, and language is one of
+# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
+# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
+# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
+# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penality.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will rougly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or define consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and defines in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES = YES
+
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
+# doxygen. The layout file controls the global structure of the generated output files
+# in an output format independent way. The create the layout file that represents
+# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
+# file name after the option, if omitted DoxygenLayout.xml will be used as the name
+# of the layout file.
+
+LAYOUT_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = . FDTD FDTD/extensions Common tools
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+FILE_PATTERNS =
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE = NO
+
+# The EXCLUDE tag can be used to specify files and/or directories that should
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+
+EXCLUDE =
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX = NO
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header.
+
+HTML_HEADER =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET =
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP = YES
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
+# files or namespaces will be aligned in HTML using tables. If set to
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
+
+GENERATE_DOCSET = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
+# are set, an additional index file will be generated that can be used as input for
+# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
+# HTML documentation.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
+# For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears.
+
+GENERATE_ECLIPSEHELP = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
+# top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it.
+
+DISABLE_INDEX = NO
+
+# This tag can be used to set the number of enum values (range [1..20])
+# that doxygen will group on one line in the generated HTML documentation.
+
+ENUM_VALUES_PER_LINE = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW = NO
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH = 250
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE = 10
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = YES
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT = YES
+
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME = FreeSans
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK = NO
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are png, jpg, or gif
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT = png
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP = YES
diff --git a/openEMS/FDTD/CMakeLists.txt b/openEMS/FDTD/CMakeLists.txt
new file mode 100644
index 0000000..b0358d3
--- /dev/null
+++ b/openEMS/FDTD/CMakeLists.txt
@@ -0,0 +1,30 @@
+
+if (WITH_MPI)
+ set(MPI_SOURCES
+ ${CMAKE_CURRENT_SOURCE_DIR}/openems_fdtd_mpi.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_mpi.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_mpi.cpp
+ )
+endif()
+
+set(SOURCES
+ ${SOURCES}
+ ${MPI_SOURCES}
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_multithread.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_cylinder.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_cylinder.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_sse.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_sse.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_sse_compressed.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_sse_compressed.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_multithread.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/excitation.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_cylindermultigrid.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_cylindermultigrid.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_interface_fdtd.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_interface_sse_fdtd.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_interface_cylindrical_fdtd.cpp
+ PARENT_SCOPE
+)
diff --git a/openEMS/FDTD/engine.cpp b/openEMS/FDTD/engine.cpp
new file mode 100644
index 0000000..26725e6
--- /dev/null
+++ b/openEMS/FDTD/engine.cpp
@@ -0,0 +1,232 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine.h"
+#include "extensions/engine_extension.h"
+#include "extensions/operator_extension.h"
+#include "tools/array_ops.h"
+
+//! \brief construct an Engine instance
+//! it's the responsibility of the caller to free the returned pointer
+Engine* Engine::New(const Operator* op)
+{
+ cout << "Create FDTD engine" << endl;
+ Engine* e = new Engine(op);
+ e->Init();
+ return e;
+}
+
+Engine::Engine(const Operator* op)
+{
+ m_type = BASIC;
+ numTS = 0;
+ Op = op;
+ for (int n=0; n<3; ++n)
+ numLines[n] = Op->GetNumberOfLines(n, true);
+ volt=NULL;
+ curr=NULL;
+}
+
+Engine::~Engine()
+{
+ this->Reset();
+}
+
+void Engine::Init()
+{
+ numTS = 0;
+ volt = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ curr = Create_N_3DArray<FDTD_FLOAT>(numLines);
+
+ InitExtensions();
+ SortExtensionByPriority();
+}
+
+void Engine::InitExtensions()
+{
+ for (size_t n=0; n<Op->GetNumberOfExtentions(); ++n)
+ {
+ Operator_Extension* op_ext = Op->GetExtension(n);
+ Engine_Extension* eng_ext = op_ext->CreateEngineExtention();
+ if (eng_ext)
+ {
+ eng_ext->SetEngine(this);
+ m_Eng_exts.push_back(eng_ext);
+ }
+ }
+}
+
+void Engine::ClearExtensions()
+{
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ delete m_Eng_exts.at(n);
+ m_Eng_exts.clear();
+}
+
+bool CompareExtensions(Engine_Extension* i, Engine_Extension* j)
+{
+ return (*i<*j);
+}
+
+void Engine::SortExtensionByPriority()
+{
+ stable_sort(m_Eng_exts.begin(),m_Eng_exts.end(), CompareExtensions);
+ reverse(m_Eng_exts.begin(),m_Eng_exts.end());
+
+ if (g_settings.GetVerboseLevel()>1)
+ {
+ cout << "--- Engine::SortExtensionByPriority() ---" << endl;
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ cout << " #" << n << ": " << m_Eng_exts.at(n)->GetExtensionName() << " (" << m_Eng_exts.at(n)->GetPriority() << ")" << endl;
+ }
+}
+
+void Engine::Reset()
+{
+ Delete_N_3DArray(volt,numLines);
+ volt=NULL;
+ Delete_N_3DArray(curr,numLines);
+ curr=NULL;
+
+ ClearExtensions();
+}
+
+void Engine::UpdateVoltages(unsigned int startX, unsigned int numX)
+{
+ unsigned int pos[3];
+ bool shift[3];
+
+ pos[0] = startX;
+ //voltage updates
+ for (unsigned int posX=0; posX<numX; ++posX)
+ {
+ shift[0]=pos[0];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ shift[1]=pos[1];
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ shift[2]=pos[2];
+ //do the updates here
+ //for x
+ volt[0][pos[0]][pos[1]][pos[2]] *= Op->vv[0][pos[0]][pos[1]][pos[2]];
+ volt[0][pos[0]][pos[1]][pos[2]] += Op->vi[0][pos[0]][pos[1]][pos[2]] * ( curr[2][pos[0]][pos[1]][pos[2]] - curr[2][pos[0]][pos[1]-shift[1]][pos[2]] - curr[1][pos[0]][pos[1]][pos[2]] + curr[1][pos[0]][pos[1]][pos[2]-shift[2]]);
+
+ //for y
+ volt[1][pos[0]][pos[1]][pos[2]] *= Op->vv[1][pos[0]][pos[1]][pos[2]];
+ volt[1][pos[0]][pos[1]][pos[2]] += Op->vi[1][pos[0]][pos[1]][pos[2]] * ( curr[0][pos[0]][pos[1]][pos[2]] - curr[0][pos[0]][pos[1]][pos[2]-shift[2]] - curr[2][pos[0]][pos[1]][pos[2]] + curr[2][pos[0]-shift[0]][pos[1]][pos[2]]);
+
+ //for z
+ volt[2][pos[0]][pos[1]][pos[2]] *= Op->vv[2][pos[0]][pos[1]][pos[2]];
+ volt[2][pos[0]][pos[1]][pos[2]] += Op->vi[2][pos[0]][pos[1]][pos[2]] * ( curr[1][pos[0]][pos[1]][pos[2]] - curr[1][pos[0]-shift[0]][pos[1]][pos[2]] - curr[0][pos[0]][pos[1]][pos[2]] + curr[0][pos[0]][pos[1]-shift[1]][pos[2]]);
+ }
+ }
+ ++pos[0];
+ }
+}
+
+void Engine::UpdateCurrents(unsigned int startX, unsigned int numX)
+{
+ unsigned int pos[3];
+ pos[0] = startX;
+ for (unsigned int posX=0; posX<numX; ++posX)
+ {
+ for (pos[1]=0; pos[1]<numLines[1]-1; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]-1; ++pos[2])
+ {
+ //do the updates here
+ //for x
+ curr[0][pos[0]][pos[1]][pos[2]] *= Op->ii[0][pos[0]][pos[1]][pos[2]];
+ curr[0][pos[0]][pos[1]][pos[2]] += Op->iv[0][pos[0]][pos[1]][pos[2]] * ( volt[2][pos[0]][pos[1]][pos[2]] - volt[2][pos[0]][pos[1]+1][pos[2]] - volt[1][pos[0]][pos[1]][pos[2]] + volt[1][pos[0]][pos[1]][pos[2]+1]);
+
+ //for y
+ curr[1][pos[0]][pos[1]][pos[2]] *= Op->ii[1][pos[0]][pos[1]][pos[2]];
+ curr[1][pos[0]][pos[1]][pos[2]] += Op->iv[1][pos[0]][pos[1]][pos[2]] * ( volt[0][pos[0]][pos[1]][pos[2]] - volt[0][pos[0]][pos[1]][pos[2]+1] - volt[2][pos[0]][pos[1]][pos[2]] + volt[2][pos[0]+1][pos[1]][pos[2]]);
+
+ //for z
+ curr[2][pos[0]][pos[1]][pos[2]] *= Op->ii[2][pos[0]][pos[1]][pos[2]];
+ curr[2][pos[0]][pos[1]][pos[2]] += Op->iv[2][pos[0]][pos[1]][pos[2]] * ( volt[1][pos[0]][pos[1]][pos[2]] - volt[1][pos[0]+1][pos[1]][pos[2]] - volt[0][pos[0]][pos[1]][pos[2]] + volt[0][pos[0]][pos[1]+1][pos[2]]);
+ }
+ }
+ ++pos[0];
+ }
+}
+
+void Engine::DoPreVoltageUpdates()
+{
+ //execute extensions in reverse order -> highest priority gets access to the voltages last
+ for (int n=m_Eng_exts.size()-1; n>=0; --n)
+ m_Eng_exts.at(n)->DoPreVoltageUpdates();
+
+}
+
+void Engine::DoPostVoltageUpdates()
+{
+ //execute extensions in normal order -> highest priority gets access to the voltages first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ m_Eng_exts.at(n)->DoPostVoltageUpdates();
+}
+
+void Engine::Apply2Voltages()
+{
+ //execute extensions in normal order -> highest priority gets access to the voltages first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ m_Eng_exts.at(n)->Apply2Voltages();
+}
+
+void Engine::DoPreCurrentUpdates()
+{
+ //execute extensions in reverse order -> highest priority gets access to the currents last
+ for (int n=m_Eng_exts.size()-1; n>=0; --n)
+ m_Eng_exts.at(n)->DoPreCurrentUpdates();
+}
+
+void Engine::DoPostCurrentUpdates()
+{
+ //execute extensions in normal order -> highest priority gets access to the currents first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ m_Eng_exts.at(n)->DoPostCurrentUpdates();
+}
+
+void Engine::Apply2Current()
+{
+ //execute extensions in normal order -> highest priority gets access to the currents first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ m_Eng_exts.at(n)->Apply2Current();
+}
+
+bool Engine::IterateTS(unsigned int iterTS)
+{
+ for (unsigned int iter=0; iter<iterTS; ++iter)
+ {
+ //voltage updates with extensions
+ DoPreVoltageUpdates();
+ UpdateVoltages(0,numLines[0]);
+ DoPostVoltageUpdates();
+ Apply2Voltages();
+
+ //current updates with extensions
+ DoPreCurrentUpdates();
+ UpdateCurrents(0,numLines[0]-1);
+ DoPostCurrentUpdates();
+ Apply2Current();
+
+ ++numTS;
+ }
+ return true;
+}
diff --git a/openEMS/FDTD/engine.h b/openEMS/FDTD/engine.h
new file mode 100644
index 0000000..72d17e1
--- /dev/null
+++ b/openEMS/FDTD/engine.h
@@ -0,0 +1,104 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_H
+#define ENGINE_H
+
+#include <fstream>
+#include "operator.h"
+
+namespace NS_Engine_Multithread
+{
+class thread; // evil hack to access numTS from multithreading context
+}
+
+class Engine_Extension;
+
+class Engine
+{
+public:
+ enum EngineType
+ {
+ BASIC, SSE, UNKNOWN
+ };
+
+ static Engine* New(const Operator* op);
+ virtual ~Engine();
+
+ virtual void Init();
+ virtual void Reset();
+
+ //!Iterate a number of timesteps
+ virtual bool IterateTS(unsigned int iterTS);
+
+ virtual unsigned int GetNumberOfTimesteps() {return numTS;}
+
+ //this access functions muss be overloaded by any new engine using a different storage model
+ inline virtual FDTD_FLOAT GetVolt( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return volt[n][x][y][z]; }
+ inline virtual FDTD_FLOAT GetVolt( unsigned int n, const unsigned int pos[3] ) const { return volt[n][pos[0]][pos[1]][pos[2]]; }
+ inline virtual FDTD_FLOAT GetCurr( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return curr[n][x][y][z]; }
+ inline virtual FDTD_FLOAT GetCurr( unsigned int n, const unsigned int pos[3] ) const { return curr[n][pos[0]][pos[1]][pos[2]]; }
+
+ inline virtual void SetVolt( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value) { volt[n][x][y][z]=value; }
+ inline virtual void SetVolt( unsigned int n, const unsigned int pos[3], FDTD_FLOAT value ) { volt[n][pos[0]][pos[1]][pos[2]]=value; }
+ inline virtual void SetCurr( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value) { curr[n][x][y][z]=value; }
+ inline virtual void SetCurr( unsigned int n, const unsigned int pos[3], FDTD_FLOAT value ) { curr[n][pos[0]][pos[1]][pos[2]]=value; }
+
+ //! Execute Pre-Voltage extension updates
+ virtual void DoPreVoltageUpdates();
+ //! Main FDTD engine voltage updates
+ virtual void UpdateVoltages(unsigned int startX, unsigned int numX);
+ //! Execute Post-Voltage extension updates
+ virtual void DoPostVoltageUpdates();
+ //! Apply extension voltage changes
+ virtual void Apply2Voltages();
+
+ //! Execute Pre-Current extension updates
+ virtual void DoPreCurrentUpdates();
+ //! Main FDTD engine current updates
+ virtual void UpdateCurrents(unsigned int startX, unsigned int numX);
+ //! Execute Post-Current extension updates
+ virtual void DoPostCurrentUpdates();
+ //! Apply extension current changes
+ virtual void Apply2Current();
+
+ inline size_t GetExtensionCount() {return m_Eng_exts.size();}
+ inline Engine_Extension* GetExtension(size_t nr) {return m_Eng_exts.at(nr);}
+ virtual void SortExtensionByPriority();
+
+ EngineType GetType() const {return m_type;}
+
+protected:
+ EngineType m_type;
+
+ Engine(const Operator* op);
+ const Operator* Op;
+
+ unsigned int numLines[3];
+
+ FDTD_FLOAT**** volt;
+ FDTD_FLOAT**** curr;
+ unsigned int numTS;
+
+ virtual void InitExtensions();
+ virtual void ClearExtensions();
+ vector<Engine_Extension*> m_Eng_exts;
+
+ friend class NS_Engine_Multithread::thread; // evil hack to access numTS from multithreading context
+};
+
+#endif // ENGINE_H
diff --git a/openEMS/FDTD/engine_cylinder.cpp b/openEMS/FDTD/engine_cylinder.cpp
new file mode 100644
index 0000000..8d62cb9
--- /dev/null
+++ b/openEMS/FDTD/engine_cylinder.cpp
@@ -0,0 +1,38 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_cylinder.h"
+
+Engine_Cylinder::Engine_Cylinder(const Operator_Cylinder* op) : Engine_Multithread(op)
+{
+ m_Op_Cyl = op;
+}
+
+Engine_Cylinder::~Engine_Cylinder()
+{
+
+}
+
+Engine_Cylinder* Engine_Cylinder::New(const Operator_Cylinder* op, unsigned int numThreads)
+{
+ cout << "Create FDTD engine (cylindrical mesh using sse compression + multithreading)" << endl;
+ Engine_Cylinder* e = new Engine_Cylinder(op);
+ e->setNumThreads(numThreads);
+ e->Init();
+ return e;
+}
+
diff --git a/openEMS/FDTD/engine_cylinder.h b/openEMS/FDTD/engine_cylinder.h
new file mode 100644
index 0000000..cbf33c0
--- /dev/null
+++ b/openEMS/FDTD/engine_cylinder.h
@@ -0,0 +1,36 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_CYLINDER_H
+#define ENGINE_CYLINDER_H
+
+#include "operator_cylinder.h"
+#include "engine_multithread.h"
+
+class Engine_Cylinder : public Engine_Multithread
+{
+public:
+ static Engine_Cylinder* New(const Operator_Cylinder* op, unsigned int numThreads = 0);
+ virtual ~Engine_Cylinder();
+
+protected:
+ Engine_Cylinder(const Operator_Cylinder* op);
+
+ const Operator_Cylinder* m_Op_Cyl;
+};
+
+#endif // ENGINE_CYLINDER_H
diff --git a/openEMS/FDTD/engine_cylindermultigrid.cpp b/openEMS/FDTD/engine_cylindermultigrid.cpp
new file mode 100644
index 0000000..8e5ce85
--- /dev/null
+++ b/openEMS/FDTD/engine_cylindermultigrid.cpp
@@ -0,0 +1,226 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_cylindermultigrid.h"
+#include "operator_cylindermultigrid.h"
+#include "extensions/engine_ext_cylindermultigrid.h"
+
+Engine_CylinderMultiGrid* Engine_CylinderMultiGrid::New(const Operator_CylinderMultiGrid* op, unsigned int numThreads)
+{
+ cout << "Create FDTD engine (cylindrical multi grid mesh using sse compression + multithreading)" << endl;
+ Engine_CylinderMultiGrid* e = new Engine_CylinderMultiGrid(op);
+ e->setNumThreads( numThreads );
+ e->Init();
+ return e;
+}
+
+Engine_CylinderMultiGrid::Engine_CylinderMultiGrid(const Operator_CylinderMultiGrid* op) : Engine_Cylinder(op)
+{
+ Op_CMG = op;
+
+ m_WaitOnBase = new boost::barrier(2);
+ m_WaitOnChild = new boost::barrier(2);
+ m_WaitOnSync = new boost::barrier(2);
+
+ m_Eng_Ext_MG = new Engine_Ext_CylinderMultiGrid(NULL,true);
+ m_Eng_Ext_MG->SetBarrier(m_WaitOnBase, m_WaitOnChild, m_WaitOnSync);
+ m_Eng_Ext_MG->SetEngine(this);
+
+ Engine* eng = op->GetInnerOperator()->CreateEngine();
+ m_InnerEngine = dynamic_cast<Engine_Multithread*>(eng);
+
+ Engine_Ext_CylinderMultiGrid* m_InnerEng_Ext_MG = new Engine_Ext_CylinderMultiGrid(NULL,false);
+ m_InnerEng_Ext_MG->SetBarrier(m_WaitOnBase, m_WaitOnChild, m_WaitOnSync);
+
+ // if already has a base extension, switch places ... seems to be faster...
+ for (size_t n=0; n<m_InnerEngine->m_Eng_exts.size(); ++n)
+ {
+ Engine_Ext_CylinderMultiGrid* eng_mg = dynamic_cast<Engine_Ext_CylinderMultiGrid*>(m_InnerEngine->m_Eng_exts.at(n));
+ if (eng_mg)
+ {
+ m_InnerEngine->m_Eng_exts.at(n) = m_InnerEng_Ext_MG;
+ m_InnerEng_Ext_MG = eng_mg;
+ break;
+ }
+ }
+ m_InnerEngine->m_Eng_exts.push_back(m_InnerEng_Ext_MG);
+}
+
+Engine_CylinderMultiGrid::~Engine_CylinderMultiGrid()
+{
+#ifdef MPI_SUPPORT
+ delete m_InnerEngine->m_MPI_Barrier;
+ m_InnerEngine->m_MPI_Barrier = NULL;
+#endif
+
+ m_Thread_NumTS = 0;
+ m_startBarrier->wait();
+
+ m_IteratorThread_Group.join_all();
+
+ delete m_InnerEngine;
+ m_InnerEngine = NULL;
+
+ delete m_WaitOnBase;
+ m_WaitOnBase = NULL;
+ delete m_WaitOnChild;
+ m_WaitOnChild = NULL;
+ delete m_WaitOnSync;
+ m_WaitOnSync = NULL;
+
+ delete m_startBarrier;
+ m_startBarrier = NULL;
+ delete m_stopBarrier;
+ m_stopBarrier = NULL;
+}
+
+void Engine_CylinderMultiGrid::Init()
+{
+ Engine_Multithread::Init();
+
+ m_Eng_exts.push_back(m_Eng_Ext_MG);
+
+ m_startBarrier = new boost::barrier(3); //both engines + organizer
+ m_stopBarrier = new boost::barrier(3); //both engines + organizer
+
+ boost::thread *t = NULL;
+
+ t = new boost::thread( Engine_CylinderMultiGrid_Thread(this,m_startBarrier,m_stopBarrier,&m_Thread_NumTS, true) );
+ m_IteratorThread_Group.add_thread( t );
+
+ t = new boost::thread( Engine_CylinderMultiGrid_Thread(m_InnerEngine,m_startBarrier,m_stopBarrier,&m_Thread_NumTS, false) );
+ m_IteratorThread_Group.add_thread( t );
+
+ m_InnerEngine->SortExtensionByPriority();
+ SortExtensionByPriority();
+
+#ifdef MPI_SUPPORT
+ //assign an MPI barrier to inner Engine
+ m_InnerEngine->m_MPI_Barrier = new boost::barrier(2);
+#endif
+}
+
+bool Engine_CylinderMultiGrid::IterateTS(unsigned int iterTS)
+{
+ m_Thread_NumTS = iterTS;
+
+ m_startBarrier->wait(); //start base and child iterations
+
+ m_stopBarrier->wait(); //tell base and child to wait for another start event...
+
+ //interpolate child data to base mesh...
+ for (unsigned int n=0; n<Op_CMG->m_Split_Pos-1; ++n)
+ InterpolVoltChild2Base(n);
+ for (unsigned int n=0; n<Op_CMG->m_Split_Pos-2; ++n)
+ InterpolCurrChild2Base(n);
+
+ return true;
+}
+
+void Engine_CylinderMultiGrid::InterpolVoltChild2Base(unsigned int rPos)
+{
+ //interpolate voltages from child engine to the base engine...
+ unsigned int pos[3];
+ pos[0] = rPos;
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numVectors; ++pos[2])
+ {
+ //r - direction
+ f4_volt[0][pos[0]][pos[1]][pos[2]].v = Op_CMG->f4_interpol_v_2p[0][pos[1]].v * m_InnerEngine->f4_volt[0][pos[0]][Op_CMG->m_interpol_pos_v_2p[0][pos[1]]][pos[2]].v
+ + Op_CMG->f4_interpol_v_2pp[0][pos[1]].v * m_InnerEngine->f4_volt[0][pos[0]][Op_CMG->m_interpol_pos_v_2pp[0][pos[1]]][pos[2]].v;
+
+ //z - direction
+ f4_volt[2][pos[0]][pos[1]][pos[2]].v = Op_CMG->f4_interpol_v_2p[0][pos[1]].v * m_InnerEngine->f4_volt[2][pos[0]][Op_CMG->m_interpol_pos_v_2p[0][pos[1]]][pos[2]].v
+ + Op_CMG->f4_interpol_v_2pp[0][pos[1]].v * m_InnerEngine->f4_volt[2][pos[0]][Op_CMG->m_interpol_pos_v_2pp[0][pos[1]]][pos[2]].v;
+
+ //alpha - direction
+ f4_volt[1][pos[0]][pos[1]][pos[2]].v = Op_CMG->f4_interpol_v_2p[1][pos[1]].v * m_InnerEngine->f4_volt[1][pos[0]][Op_CMG->m_interpol_pos_v_2p[1][pos[1]]][pos[2]].v
+ + Op_CMG->f4_interpol_v_2pp[1][pos[1]].v * m_InnerEngine->f4_volt[1][pos[0]][Op_CMG->m_interpol_pos_v_2pp[1][pos[1]]][pos[2]].v;
+ }
+ }
+}
+
+void Engine_CylinderMultiGrid::InterpolCurrChild2Base(unsigned int rPos)
+{
+ //interpolate voltages from child engine to the base engine...
+ unsigned int pos[3];
+ pos[0] = rPos;
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numVectors; ++pos[2])
+ {
+ //r - direction
+ f4_curr[0][pos[0]][pos[1]][pos[2]].v = Op_CMG->f4_interpol_i_2p[0][pos[1]].v * m_InnerEngine->f4_curr[0][pos[0]][Op_CMG->m_interpol_pos_i_2p[0][pos[1]]][pos[2]].v
+ + Op_CMG->f4_interpol_i_2pp[0][pos[1]].v * m_InnerEngine->f4_curr[0][pos[0]][Op_CMG->m_interpol_pos_i_2pp[0][pos[1]]][pos[2]].v;
+
+ //z - direction
+ f4_curr[2][pos[0]][pos[1]][pos[2]].v = Op_CMG->f4_interpol_i_2p[0][pos[1]].v * m_InnerEngine->f4_curr[2][pos[0]][Op_CMG->m_interpol_pos_i_2p[0][pos[1]]][pos[2]].v
+ + Op_CMG->f4_interpol_i_2pp[0][pos[1]].v * m_InnerEngine->f4_curr[2][pos[0]][Op_CMG->m_interpol_pos_i_2pp[0][pos[1]]][pos[2]].v;
+
+ //alpha - direction
+ f4_curr[1][pos[0]][pos[1]][pos[2]].v = Op_CMG->f4_interpol_i_2p[1][pos[1]].v * m_InnerEngine->f4_curr[1][pos[0]][Op_CMG->m_interpol_pos_i_2p[1][pos[1]]][pos[2]].v
+ + Op_CMG->f4_interpol_i_2pp[1][pos[1]].v * m_InnerEngine->f4_curr[1][pos[0]][Op_CMG->m_interpol_pos_i_2pp[1][pos[1]]][pos[2]].v;
+ }
+ }
+}
+
+#ifdef MPI_SUPPORT
+ void Engine_CylinderMultiGrid::SendReceiveVoltages()
+ {
+ //do the local voltage sync, child is waiting...
+ Engine_Multithread::SendReceiveVoltages();
+
+ //run inner voltage sync
+ m_InnerEngine->m_MPI_Barrier->wait();
+ }
+
+ void Engine_CylinderMultiGrid::SendReceiveCurrents()
+ {
+ //do the local current sync, child is waiting...
+ Engine_Multithread::SendReceiveCurrents();
+
+ //run inner voltage sync
+ m_InnerEngine->m_MPI_Barrier->wait();
+ }
+
+#endif
+
+/****************************************************************************************/
+Engine_CylinderMultiGrid_Thread::Engine_CylinderMultiGrid_Thread( Engine_Multithread* engine, boost::barrier *start, boost::barrier *stop, volatile unsigned int* numTS, bool isBase)
+{
+ m_startBarrier = start;
+ m_stopBarrier = stop;
+ m_Eng=engine;
+ m_isBase=isBase;
+ m_numTS = numTS;
+}
+
+void Engine_CylinderMultiGrid_Thread::operator()()
+{
+ m_startBarrier->wait(); //wait for Base engine to start the iterations...
+
+ while (*m_numTS>0) //m_numTS==0 request to terminate this thread...
+ {
+ if (m_isBase)
+ m_Eng->Engine_Multithread::IterateTS(*m_numTS);
+ else
+ m_Eng->IterateTS(*m_numTS);
+ m_stopBarrier->wait(); //sync all workers after iterations are performed
+ m_startBarrier->wait(); //wait for Base engine to start the iterations again ...
+ }
+}
diff --git a/openEMS/FDTD/engine_cylindermultigrid.h b/openEMS/FDTD/engine_cylindermultigrid.h
new file mode 100644
index 0000000..66f337f
--- /dev/null
+++ b/openEMS/FDTD/engine_cylindermultigrid.h
@@ -0,0 +1,85 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_CYLINDERMULTIGRID_H
+#define ENGINE_CYLINDERMULTIGRID_H
+
+#include "engine_cylinder.h"
+
+class Operator_CylinderMultiGrid;
+class Engine_CylinderMultiGrid_Thread;
+class Engine_Ext_CylinderMultiGrid;
+
+class Engine_CylinderMultiGrid : public Engine_Cylinder
+{
+ friend class Engine_Ext_CylinderMultiGrid;
+public:
+// Engine_CylinderMultiGrid();
+
+ static Engine_CylinderMultiGrid* New(const Operator_CylinderMultiGrid* op, unsigned int numThreads = 0);
+ virtual ~Engine_CylinderMultiGrid();
+
+ virtual void InterpolVoltChild2Base(unsigned int rPos);
+ virtual void InterpolCurrChild2Base(unsigned int rPos);
+
+ virtual void Init();
+
+ //! Iterate \a iterTS number of timesteps
+ virtual bool IterateTS(unsigned int iterTS);
+
+protected:
+ Engine_CylinderMultiGrid(const Operator_CylinderMultiGrid* op);
+ const Operator_CylinderMultiGrid* Op_CMG;
+
+ Engine_Multithread* m_InnerEngine;
+
+ volatile unsigned int m_Thread_NumTS;
+ boost::thread_group m_IteratorThread_Group;
+ boost::barrier *m_startBarrier;
+ boost::barrier *m_stopBarrier;
+ Engine_CylinderMultiGrid_Thread* m_IteratorThread;
+ Engine_CylinderMultiGrid_Thread* m_InnerIteratorThread;
+
+ //extension barrier
+ boost::barrier *m_WaitOnBase;
+ boost::barrier *m_WaitOnChild;
+ boost::barrier *m_WaitOnSync;
+
+ Engine_Ext_CylinderMultiGrid* m_Eng_Ext_MG;
+
+#ifdef MPI_SUPPORT
+ virtual void SendReceiveVoltages();
+ virtual void SendReceiveCurrents();
+#endif
+};
+
+
+class Engine_CylinderMultiGrid_Thread
+{
+public:
+ Engine_CylinderMultiGrid_Thread( Engine_Multithread* engine, boost::barrier *start, boost::barrier *stop, volatile unsigned int* numTS, bool isBase);
+ void operator()();
+
+protected:
+ Engine_Multithread *m_Eng;
+ bool m_isBase;
+ boost::barrier *m_startBarrier;
+ boost::barrier *m_stopBarrier;
+ volatile unsigned int *m_numTS;
+};
+
+#endif // ENGINE_CYLINDERMULTIGRID_H
diff --git a/openEMS/FDTD/engine_interface_cylindrical_fdtd.cpp b/openEMS/FDTD/engine_interface_cylindrical_fdtd.cpp
new file mode 100644
index 0000000..065a4ef
--- /dev/null
+++ b/openEMS/FDTD/engine_interface_cylindrical_fdtd.cpp
@@ -0,0 +1,64 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_interface_cylindrical_fdtd.h"
+
+Engine_Interface_Cylindrical_FDTD::Engine_Interface_Cylindrical_FDTD(Operator_sse* op) : Engine_Interface_SSE_FDTD(op)
+{
+ m_Op_Cyl = dynamic_cast<Operator_Cylinder*>(op);
+ if (m_Op_Cyl==NULL)
+ {
+ cerr << "Engine_Interface_Cylindrical_FDTD::Engine_Interface_Cylindrical_FDTD: Error: Operator is not a cylindrical operator! Exit!" << endl;
+ exit(1);
+ }
+}
+
+Engine_Interface_Cylindrical_FDTD::~Engine_Interface_Cylindrical_FDTD()
+{
+}
+
+double* Engine_Interface_Cylindrical_FDTD::GetHField(const unsigned int* pos, double* out) const
+{
+ if (m_Op_Cyl->GetClosedAlpha()==false)
+ return Engine_Interface_FDTD::GetHField(pos, out);
+
+ unsigned int iPos[] = {pos[0],pos[1],pos[2]};
+
+ if ((m_InterpolType==CELL_INTERPOLATE) && (pos[1]==m_Op->GetNumberOfLines(1)))
+ iPos[1]=0;
+
+ if ((m_InterpolType==NODE_INTERPOLATE) && (iPos[1]==0))
+ iPos[1]=m_Op->GetNumberOfLines(1);
+
+ return Engine_Interface_FDTD::GetHField(iPos, out);
+}
+
+double* Engine_Interface_Cylindrical_FDTD::GetRawInterpolatedField(const unsigned int* pos, double* out, int type) const
+{
+ if (m_Op_Cyl->GetClosedAlpha()==false)
+ return Engine_Interface_FDTD::GetRawInterpolatedField(pos,out,type);
+
+ unsigned int iPos[] = {pos[0],pos[1],pos[2]};
+
+ if ((m_InterpolType==NODE_INTERPOLATE) && (pos[1]==0))
+ iPos[1]=m_Op->GetNumberOfLines(1);
+
+ if ((m_InterpolType==CELL_INTERPOLATE) && (pos[1]==m_Op->GetNumberOfLines(1)))
+ iPos[1]=0;
+
+ return Engine_Interface_FDTD::GetRawInterpolatedField(iPos,out,type);
+}
diff --git a/openEMS/FDTD/engine_interface_cylindrical_fdtd.h b/openEMS/FDTD/engine_interface_cylindrical_fdtd.h
new file mode 100644
index 0000000..adbe184
--- /dev/null
+++ b/openEMS/FDTD/engine_interface_cylindrical_fdtd.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_interface_sse_fdtd.h"
+#include "operator_cylinder.h"
+
+#ifndef ENGINE_INTERFACE_CYLINDRICAL_FDTD_H
+#define ENGINE_INTERFACE_CYLINDRICAL_FDTD_H
+
+class Engine_Interface_Cylindrical_FDTD : public Engine_Interface_SSE_FDTD
+{
+public:
+ Engine_Interface_Cylindrical_FDTD(Operator_sse* op);
+ virtual ~Engine_Interface_Cylindrical_FDTD();
+
+ virtual double* GetHField(const unsigned int* pos, double* out) const;
+
+protected:
+ Operator_Cylinder* m_Op_Cyl;
+
+ //! Internal method to get an interpolated field of a given type. (0: E, 1: J, 2: rotH)
+ virtual double* GetRawInterpolatedField(const unsigned int* pos, double* out, int type) const;
+};
+
+#endif // ENGINE_INTERFACE_CYLINDRICAL_FDTD_H
diff --git a/openEMS/FDTD/engine_interface_fdtd.cpp b/openEMS/FDTD/engine_interface_fdtd.cpp
new file mode 100644
index 0000000..b8fd9de
--- /dev/null
+++ b/openEMS/FDTD/engine_interface_fdtd.cpp
@@ -0,0 +1,274 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_interface_fdtd.h"
+
+Engine_Interface_FDTD::Engine_Interface_FDTD(Operator* op) : Engine_Interface_Base(op)
+{
+ if (op==NULL)
+ {
+ cerr << "Engine_Interface_FDTD::Engine_Interface_FDTD: Error: Operator is not set! Exit!" << endl;
+ exit(1);
+ }
+ m_Op = op;
+ m_Eng = m_Op->GetEngine();
+ if (m_Eng==NULL)
+ {
+ cerr << "Engine_Interface_FDTD::Engine_Interface_FDTD: Error: Engine is not set! Exit!" << endl;
+ exit(1);
+ }
+}
+
+Engine_Interface_FDTD::~Engine_Interface_FDTD()
+{
+}
+
+double* Engine_Interface_FDTD::GetEField(const unsigned int* pos, double* out) const
+{
+ return GetRawInterpolatedField(pos, out, 0);
+}
+
+double* Engine_Interface_FDTD::GetJField(const unsigned int* pos, double* out) const
+{
+ return GetRawInterpolatedField(pos, out, 1);
+}
+
+double* Engine_Interface_FDTD::GetRotHField(const unsigned int* pos, double* out) const
+{
+ return GetRawInterpolatedField(pos, out, 2);
+}
+
+double* Engine_Interface_FDTD::GetRawInterpolatedField(const unsigned int* pos, double* out, int type) const
+{
+ unsigned int iPos[] = {pos[0],pos[1],pos[2]};
+ int nP,nPP;
+ double delta;
+ switch (m_InterpolType)
+ {
+ default:
+ case NO_INTERPOLATION:
+ for (int n=0; n<3; ++n)
+ out[n] = GetRawField(n,pos,type);
+ break;
+ case NODE_INTERPOLATE:
+ for (int n=0; n<3; ++n)
+ {
+ if (pos[n]==m_Op->GetNumberOfLines(n, true)-1) // use only the "lower value" at the upper bound
+ {
+ --iPos[n];
+ out[n] = (double)GetRawField(n,iPos,type);
+ ++iPos[n];
+ continue;
+ }
+ delta = m_Op->GetEdgeLength(n,iPos);
+ out[n] = GetRawField(n,iPos,type);
+ if (delta==0)
+ {
+ out[n]=0;
+ continue;
+ }
+ if (pos[n]==0) // use only the "upper value" at the lower bound
+ continue;
+ --iPos[n];
+ double deltaDown = m_Op->GetEdgeLength(n,iPos);
+ double deltaRel = delta / (delta+deltaDown);
+ out[n] = out[n]*(1.0-deltaRel) + (double)GetRawField(n,iPos,type)*deltaRel;
+ ++iPos[n];
+ }
+ break;
+ case CELL_INTERPOLATE:
+ for (int n=0; n<3; ++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ if ((pos[0]==m_Op->GetNumberOfLines(0,true)-1) || (pos[1]==m_Op->GetNumberOfLines(1,true)-1) || (pos[2]==m_Op->GetNumberOfLines(2,true)-1))
+ {
+ out[n] = 0; //electric field outside the field domain is always zero
+ continue;
+ }
+ out[n]=GetRawField(n,iPos,type);
+ ++iPos[nP];
+ out[n]+=GetRawField(n,iPos,type);
+ ++iPos[nPP];
+ out[n]+=GetRawField(n,iPos,type);
+ --iPos[nP];
+ out[n]+=GetRawField(n,iPos,type);
+ --iPos[nPP];
+ out[n]/=4;
+ }
+ break;
+ }
+ return out;
+}
+
+double* Engine_Interface_FDTD::GetHField(const unsigned int* pos, double* out) const
+{
+ unsigned int iPos[] = {pos[0],pos[1],pos[2]};
+ int nP,nPP;
+ double delta;
+ switch (m_InterpolType)
+ {
+ default:
+ case NO_INTERPOLATION:
+ out[0] = m_Eng->GetCurr(0,pos) / m_Op->GetEdgeLength(0,pos,true);
+ out[1] = m_Eng->GetCurr(1,pos) / m_Op->GetEdgeLength(1,pos,true);
+ out[2] = m_Eng->GetCurr(2,pos) / m_Op->GetEdgeLength(2,pos,true);
+ break;
+ case NODE_INTERPOLATE:
+ for (int n=0; n<3; ++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ if ((pos[0]==m_Op->GetNumberOfLines(0,true)-1) || (pos[1]==m_Op->GetNumberOfLines(1,true)-1) || (pos[2]==m_Op->GetNumberOfLines(2,true)-1) || (pos[nP]==0) || (pos[nPP]==0))
+ {
+ out[n] = 0;
+ continue;
+ }
+ out[n]=m_Eng->GetCurr(n,iPos)/m_Op->GetEdgeLength(n,iPos,true);
+ --iPos[nP];
+ out[n]+=m_Eng->GetCurr(n,iPos)/m_Op->GetEdgeLength(n,iPos,true);
+ --iPos[nPP];
+ out[n]+=m_Eng->GetCurr(n,iPos)/m_Op->GetEdgeLength(n,iPos,true);
+ ++iPos[nP];
+ out[n]+=m_Eng->GetCurr(n,iPos)/m_Op->GetEdgeLength(n,iPos,true);
+ ++iPos[nPP];
+ out[n]/=4;
+ }
+ break;
+ case CELL_INTERPOLATE:
+ for (int n=0; n<3; ++n)
+ {
+ delta = m_Op->GetEdgeLength(n,iPos,true);
+ out[n] = m_Eng->GetCurr(n,iPos);
+ if ((pos[n]>=m_Op->GetNumberOfLines(n,true)-1))
+ {
+ out[n] = 0; //magnetic field on the outer boundaries is always zero
+ continue;
+ }
+ ++iPos[n];
+ double deltaUp = m_Op->GetEdgeLength(n,iPos,true);
+ double deltaRel = delta / (delta+deltaUp);
+ out[n] = out[n]*(1.0-deltaRel)/delta + (double)m_Eng->GetCurr(n,iPos)/deltaUp*deltaRel;
+ --iPos[n];
+ }
+ break;
+ }
+
+ return out;
+}
+
+double Engine_Interface_FDTD::CalcVoltageIntegral(const unsigned int* start, const unsigned int* stop) const
+{
+ double result=0;
+ for (int n=0; n<3; ++n)
+ {
+ if (start[n]<stop[n])
+ {
+ unsigned int pos[3]={start[0],start[1],start[2]};
+ for (; pos[n]<stop[n]; ++pos[n])
+ result += m_Eng->GetVolt(n,pos[0],pos[1],pos[2]);
+ }
+ else
+ {
+ unsigned int pos[3]={stop[0],stop[1],stop[2]};
+ for (; pos[n]<start[n]; ++pos[n])
+ result -= m_Eng->GetVolt(n,pos[0],pos[1],pos[2]);
+ }
+ }
+ return result;
+}
+
+
+double Engine_Interface_FDTD::GetRawField(unsigned int n, const unsigned int* pos, int type) const
+{
+ double value = m_Eng->GetVolt(n,pos[0],pos[1],pos[2]);
+ double delta = m_Op->GetEdgeLength(n,pos);
+ if ((type==0) && (delta))
+ return value/delta;
+ if ((type==1) && (m_Op->m_kappa) && (delta))
+ return value*m_Op->m_kappa[n][pos[0]][pos[1]][pos[2]]/delta;
+ if (type==2) //calc rot(H)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ unsigned int locPos[] = {pos[0],pos[1],pos[2]};
+ double area = m_Op->GetEdgeArea(n,pos);
+ value = m_Eng->GetCurr(nPP,pos);
+ value -= m_Eng->GetCurr(nP,pos);
+ if (pos[nPP]>0)
+ {
+ --locPos[nPP];
+ value += m_Eng->GetCurr(nP,locPos);
+ ++locPos[nPP];
+ }
+ if (pos[nP]>0)
+ {
+ --locPos[nP];
+ value -= m_Eng->GetCurr(nPP,locPos);
+ }
+ return value/area;
+ }
+
+ return 0.0;
+}
+
+double Engine_Interface_FDTD::CalcFastEnergy() const
+{
+ double E_energy=0.0;
+ double H_energy=0.0;
+
+ unsigned int pos[3];
+ if (m_Eng->GetType()==Engine::BASIC)
+ {
+ for (pos[0]=0; pos[0]<m_Op->GetNumberOfLines(0)-1; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<m_Op->GetNumberOfLines(1)-1; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<m_Op->GetNumberOfLines(2)-1; ++pos[2])
+ {
+ E_energy+=m_Eng->Engine::GetVolt(0,pos[0],pos[1],pos[2]) * m_Eng->Engine::GetVolt(0,pos[0],pos[1],pos[2]);
+ E_energy+=m_Eng->Engine::GetVolt(1,pos[0],pos[1],pos[2]) * m_Eng->Engine::GetVolt(1,pos[0],pos[1],pos[2]);
+ E_energy+=m_Eng->Engine::GetVolt(2,pos[0],pos[1],pos[2]) * m_Eng->Engine::GetVolt(2,pos[0],pos[1],pos[2]);
+
+ H_energy+=m_Eng->Engine::GetCurr(0,pos[0],pos[1],pos[2]) * m_Eng->Engine::GetCurr(0,pos[0],pos[1],pos[2]);
+ H_energy+=m_Eng->Engine::GetCurr(1,pos[0],pos[1],pos[2]) * m_Eng->Engine::GetCurr(1,pos[0],pos[1],pos[2]);
+ H_energy+=m_Eng->Engine::GetCurr(2,pos[0],pos[1],pos[2]) * m_Eng->Engine::GetCurr(2,pos[0],pos[1],pos[2]);
+ }
+ }
+ }
+ }
+ else
+ {
+ for (pos[0]=0; pos[0]<m_Op->GetNumberOfLines(0)-1; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<m_Op->GetNumberOfLines(1)-1; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<m_Op->GetNumberOfLines(2)-1; ++pos[2])
+ {
+ E_energy+=m_Eng->GetVolt(0,pos[0],pos[1],pos[2]) * m_Eng->GetVolt(0,pos[0],pos[1],pos[2]);
+ E_energy+=m_Eng->GetVolt(1,pos[0],pos[1],pos[2]) * m_Eng->GetVolt(1,pos[0],pos[1],pos[2]);
+ E_energy+=m_Eng->GetVolt(2,pos[0],pos[1],pos[2]) * m_Eng->GetVolt(2,pos[0],pos[1],pos[2]);
+
+ H_energy+=m_Eng->GetCurr(0,pos[0],pos[1],pos[2]) * m_Eng->GetCurr(0,pos[0],pos[1],pos[2]);
+ H_energy+=m_Eng->GetCurr(1,pos[0],pos[1],pos[2]) * m_Eng->GetCurr(1,pos[0],pos[1],pos[2]);
+ H_energy+=m_Eng->GetCurr(2,pos[0],pos[1],pos[2]) * m_Eng->GetCurr(2,pos[0],pos[1],pos[2]);
+ }
+ }
+ }
+ }
+ return __EPS0__*E_energy + __MUE0__*H_energy;
+}
diff --git a/openEMS/FDTD/engine_interface_fdtd.h b/openEMS/FDTD/engine_interface_fdtd.h
new file mode 100644
index 0000000..4e824ac
--- /dev/null
+++ b/openEMS/FDTD/engine_interface_fdtd.h
@@ -0,0 +1,65 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_INTERFACE_FDTD_H
+#define ENGINE_INTERFACE_FDTD_H
+
+#include <cmath>
+
+#include "Common/engine_interface_base.h"
+#include "operator.h"
+#include "engine.h"
+
+class Engine_Interface_FDTD : public Engine_Interface_Base
+{
+public:
+ Engine_Interface_FDTD(Operator* op);
+ virtual ~Engine_Interface_FDTD();
+
+ //! Set the FDTD operator
+ virtual void SetFDTDOperator(Operator* op) {SetOperator(op); m_Op=op;}
+ //! Set the FDTD engine
+ virtual void SetFDTDEngine(Engine* eng) {m_Eng=eng;}
+
+ //! Get the FDTD engine in case direct access is needed. Direct access is not recommended!
+ const Engine* GetFDTDEngine() const {return m_Eng;}
+ //! Get the FDTD operator in case direct access is needed. Direct access is not recommended!
+ const Operator* GetFDTDOperator() const {return m_Op;}
+
+ virtual double* GetEField(const unsigned int* pos, double* out) const;
+ virtual double* GetHField(const unsigned int* pos, double* out) const;
+ virtual double* GetJField(const unsigned int* pos, double* out) const;
+ virtual double* GetRotHField(const unsigned int* pos, double* out) const;
+
+ virtual double CalcVoltageIntegral(const unsigned int* start, const unsigned int* stop) const;
+
+ virtual double GetTime(bool dualTime=false) const {return ((double)m_Eng->GetNumberOfTimesteps() + (double)dualTime*0.5)*m_Op->GetTimestep();};
+ virtual unsigned int GetNumberOfTimesteps() const {return m_Eng->GetNumberOfTimesteps();}
+
+ virtual double CalcFastEnergy() const;
+
+protected:
+ Operator* m_Op;
+ Engine* m_Eng;
+
+ //! Internal method to get an interpolated field of a given type. (0: E, 1: J, 2: rotH)
+ virtual double* GetRawInterpolatedField(const unsigned int* pos, double* out, int type) const;
+ //! Internal method to get a raw field of a given type. (0: E, 1: J, 2: rotH)
+ virtual double GetRawField(unsigned int n, const unsigned int* pos, int type) const;
+};
+
+#endif // ENGINE_INTERFACE_FDTD_H
diff --git a/openEMS/FDTD/engine_interface_sse_fdtd.cpp b/openEMS/FDTD/engine_interface_sse_fdtd.cpp
new file mode 100644
index 0000000..b7e9a3c
--- /dev/null
+++ b/openEMS/FDTD/engine_interface_sse_fdtd.cpp
@@ -0,0 +1,69 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_interface_sse_fdtd.h"
+
+Engine_Interface_SSE_FDTD::Engine_Interface_SSE_FDTD(Operator_sse* op) : Engine_Interface_FDTD(op)
+{
+ m_Op_SSE = op;
+ m_Eng_SSE = dynamic_cast<Engine_sse*>(m_Op_SSE->GetEngine());
+ if (m_Eng_SSE==NULL)
+ {
+ cerr << "Engine_Interface_SSE_FDTD::Engine_Interface_SSE_FDTD: Error: SSE-Engine is not set! Exit!" << endl;
+ exit(1);
+ }
+}
+
+Engine_Interface_SSE_FDTD::~Engine_Interface_SSE_FDTD()
+{
+ m_Op_SSE=NULL;
+ m_Eng_SSE=NULL;
+}
+
+double Engine_Interface_SSE_FDTD::CalcFastEnergy() const
+{
+ f4vector E_energy;
+ E_energy.f[0]=0;
+ E_energy.f[1]=0;
+ E_energy.f[2]=0;
+ E_energy.f[3]=0;
+ f4vector H_energy;
+ H_energy = E_energy;
+
+ if (m_Eng_SSE->GetType()!=Engine::SSE)
+ return Engine_Interface_FDTD::CalcFastEnergy();
+
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<m_Op_SSE->GetNumberOfLines(0)-1; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<m_Op_SSE->GetNumberOfLines(1)-1; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<m_Op_SSE->numVectors; ++pos[2])
+ {
+ E_energy.v += m_Eng_SSE->Engine_sse::f4_volt[0][pos[0]][pos[1]][pos[2]].v * m_Eng_SSE->Engine_sse::f4_volt[0][pos[0]][pos[1]][pos[2]].v;
+ E_energy.v += m_Eng_SSE->Engine_sse::f4_volt[1][pos[0]][pos[1]][pos[2]].v * m_Eng_SSE->Engine_sse::f4_volt[1][pos[0]][pos[1]][pos[2]].v;
+ E_energy.v += m_Eng_SSE->Engine_sse::f4_volt[2][pos[0]][pos[1]][pos[2]].v * m_Eng_SSE->Engine_sse::f4_volt[2][pos[0]][pos[1]][pos[2]].v;
+
+ H_energy.v += m_Eng_SSE->Engine_sse::f4_curr[0][pos[0]][pos[1]][pos[2]].v * m_Eng_SSE->Engine_sse::f4_curr[0][pos[0]][pos[1]][pos[2]].v;
+ H_energy.v += m_Eng_SSE->Engine_sse::f4_curr[1][pos[0]][pos[1]][pos[2]].v * m_Eng_SSE->Engine_sse::f4_curr[1][pos[0]][pos[1]][pos[2]].v;
+ H_energy.v += m_Eng_SSE->Engine_sse::f4_curr[2][pos[0]][pos[1]][pos[2]].v * m_Eng_SSE->Engine_sse::f4_curr[2][pos[0]][pos[1]][pos[2]].v;
+ }
+ }
+ }
+
+ return __EPS0__*(E_energy.f[0]+E_energy.f[1]+E_energy.f[2]+E_energy.f[3]) + __MUE0__*(H_energy.f[0]+H_energy.f[1]+H_energy.f[2]+H_energy.f[3]);
+}
diff --git a/openEMS/FDTD/engine_interface_sse_fdtd.h b/openEMS/FDTD/engine_interface_sse_fdtd.h
new file mode 100644
index 0000000..b8f837a
--- /dev/null
+++ b/openEMS/FDTD/engine_interface_sse_fdtd.h
@@ -0,0 +1,38 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_INTERFACE_SSE_FDTD_H
+#define ENGINE_INTERFACE_SSE_FDTD_H
+
+#include "engine_interface_fdtd.h"
+#include "operator_sse.h"
+#include "engine_sse.h"
+
+class Engine_Interface_SSE_FDTD : public Engine_Interface_FDTD
+{
+public:
+ Engine_Interface_SSE_FDTD(Operator_sse* op);
+ virtual ~Engine_Interface_SSE_FDTD();
+
+ virtual double CalcFastEnergy() const;
+
+protected:
+ Operator_sse* m_Op_SSE;
+ Engine_sse* m_Eng_SSE;
+};
+
+#endif // ENGINE_INTERFACE_SSE_FDTD_H
diff --git a/openEMS/FDTD/engine_mpi.cpp b/openEMS/FDTD/engine_mpi.cpp
new file mode 100644
index 0000000..c6a5b2c
--- /dev/null
+++ b/openEMS/FDTD/engine_mpi.cpp
@@ -0,0 +1,211 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_mpi.h"
+
+Engine_MPI* Engine_MPI::New(const Operator_MPI* op)
+{
+ cout << "Create FDTD engine (compressed SSE + MPI)" << endl;
+ Engine_MPI* e = new Engine_MPI(op);
+ e->Init();
+ return e;
+}
+
+Engine_MPI::Engine_MPI(const Operator_MPI* op) : Engine_SSE_Compressed(op)
+{
+ m_Op_MPI = op;
+}
+
+Engine_MPI::~Engine_MPI()
+{
+ Reset();
+}
+
+void Engine_MPI::Init()
+{
+ Engine_SSE_Compressed::Init();
+
+ for (int i=0;i<3;++i)
+ {
+ m_BufferUp[i]=NULL;
+ m_BufferDown[i]=NULL;
+ m_BufferSize[i]=0;
+ }
+
+ if (m_Op_MPI->GetMPIEnabled())
+ {
+ // init buffers, nx*ny*2 for the tangential electric or magnetic fields at the interface
+ for (int n=0;n<3;++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ m_BufferSize[n] = m_Op_MPI->numLines[nP]*m_Op_MPI->numLines[nPP];
+
+ if (m_Op_MPI->m_NeighborDown[n]>=0)
+ {
+ m_BufferDown[n] = new float[m_BufferSize[n]*2];
+ }
+ if (m_Op_MPI->m_NeighborUp[n]>=0)
+ {
+ m_BufferUp[n] = new float[m_BufferSize[n]*2];
+ }
+ }
+ }
+}
+
+void Engine_MPI::Reset()
+{
+ for (int i=0;i<3;++i)
+ {
+ delete[] m_BufferUp[i];
+ delete[] m_BufferDown[i];
+ m_BufferUp[i]=NULL;
+ m_BufferDown[i]=NULL;
+ m_BufferSize[i]=0;
+ }
+
+ Engine_SSE_Compressed::Reset();
+}
+
+void Engine_MPI::SendReceiveVoltages()
+{
+ unsigned int pos[3];
+
+ //non-blocking prepare for receive...
+ for (int n=0;n<3;++n)
+ if (m_Op_MPI->m_NeighborDown[n]>=0)
+ MPI_Irecv( m_BufferDown[n] , m_BufferSize[n]*2, MPI_FLOAT, m_Op_MPI->m_NeighborDown[n], m_Op_MPI->m_MyTag, MPI_COMM_WORLD, &Recv_Request[n]);
+
+ for (int n=0;n<3;++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+
+ //send voltages
+ unsigned int iPos=0;
+ pos[n]=numLines[n]-2;
+ if (m_Op_MPI->m_NeighborUp[n]>=0)
+ {
+ for (pos[nP]=0; pos[nP]<numLines[nP]; ++pos[nP])
+ {
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ m_BufferUp[n][iPos++] = Engine_SSE_Compressed::GetVolt(nP ,pos);
+ m_BufferUp[n][iPos++] = Engine_SSE_Compressed::GetVolt(nPP,pos);
+ }
+ }
+ MPI_Isend( m_BufferUp[n] , m_BufferSize[n]*2, MPI_FLOAT, m_Op_MPI->m_NeighborUp[n], m_Op_MPI->m_MyTag, MPI_COMM_WORLD, &Send_Request[n]);
+ }
+
+ //receive voltages
+ pos[n]=0;
+ iPos=0;
+ if (m_Op_MPI->m_NeighborDown[n]>=0)
+ {
+ //wait for receive to finish...
+ MPI_Wait(&Recv_Request[n],&stat);
+ for (pos[nP]=0; pos[nP]<numLines[nP]; ++pos[nP])
+ {
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ Engine_SSE_Compressed::SetVolt(nP ,pos,m_BufferDown[n][iPos++]);
+ Engine_SSE_Compressed::SetVolt(nPP,pos,m_BufferDown[n][iPos++]);
+ }
+ }
+ }
+
+ }
+}
+
+void Engine_MPI::SendReceiveCurrents()
+{
+ unsigned int pos[3];
+
+ //non-blocking prepare for receive...
+ for (int n=0;n<3;++n)
+ if (m_Op_MPI->m_NeighborUp[n]>=0)
+ MPI_Irecv( m_BufferUp[n] , m_BufferSize[n]*2, MPI_FLOAT, m_Op_MPI->m_NeighborUp[n], m_Op_MPI->m_MyTag, MPI_COMM_WORLD, &Recv_Request[n]);
+
+ for (int n=0;n<3;++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+
+ //send currents
+ unsigned int iPos=0;
+ pos[n]=0;
+ if (m_Op_MPI->m_NeighborDown[n]>=0)
+ {
+ for (pos[nP]=0; pos[nP]<numLines[nP]; ++pos[nP])
+ {
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ m_BufferDown[n][iPos++] = Engine_SSE_Compressed::GetCurr(nP ,pos);
+ m_BufferDown[n][iPos++] = Engine_SSE_Compressed::GetCurr(nPP,pos);
+ }
+ }
+ MPI_Isend( m_BufferDown[n] , m_BufferSize[n]*2, MPI_FLOAT, m_Op_MPI->m_NeighborDown[n], m_Op_MPI->m_MyTag, MPI_COMM_WORLD, &Send_Request[n]);
+ }
+
+ //receive currents
+ pos[n]=numLines[n]-2;
+ iPos=0;
+ if (m_Op_MPI->m_NeighborUp[n]>=0)
+ {
+ //wait for receive to finish...
+ MPI_Wait(&Recv_Request[n],&stat);
+ for (pos[nP]=0; pos[nP]<numLines[nP]; ++pos[nP])
+ {
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ Engine_SSE_Compressed::SetCurr(nP ,pos,m_BufferUp[n][iPos++]);
+ Engine_SSE_Compressed::SetCurr(nPP,pos,m_BufferUp[n][iPos++]);
+ }
+ }
+ }
+
+ }
+}
+
+bool Engine_MPI::IterateTS(unsigned int iterTS)
+{
+ if (!m_Op_MPI->GetMPIEnabled())
+ {
+ return Engine_SSE_Compressed::IterateTS(iterTS);
+ }
+
+ for (unsigned int iter=0; iter<iterTS; ++iter)
+ {
+ //voltage updates with extensions
+ DoPreVoltageUpdates();
+ UpdateVoltages(0,numLines[0]);
+ DoPostVoltageUpdates();
+ Apply2Voltages();
+ SendReceiveVoltages();
+
+ //current updates with extensions
+ DoPreCurrentUpdates();
+ UpdateCurrents(0,numLines[0]-1);
+ DoPostCurrentUpdates();
+ Apply2Current();
+ SendReceiveCurrents();
+
+ ++numTS;
+ }
+ return true;
+}
+
diff --git a/openEMS/FDTD/engine_mpi.h b/openEMS/FDTD/engine_mpi.h
new file mode 100644
index 0000000..5aa1226
--- /dev/null
+++ b/openEMS/FDTD/engine_mpi.h
@@ -0,0 +1,57 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_MPI_H
+#define ENGINE_MPI_H
+
+#include "operator_mpi.h"
+#include "engine_sse_compressed.h"
+#include "mpi.h"
+
+class Engine_MPI : public Engine_SSE_Compressed
+{
+public:
+ Engine_MPI();
+
+ static Engine_MPI* New(const Operator_MPI* op);
+ virtual ~Engine_MPI();
+
+ virtual void Init();
+ virtual void Reset();
+
+ virtual bool IterateTS(unsigned int iterTS);
+
+protected:
+ Engine_MPI(const Operator_MPI* op);
+ const Operator_MPI* m_Op_MPI;
+
+ MPI_Status stat;
+ MPI_Request Send_Request[3];
+ MPI_Request Recv_Request[3];
+
+ //field buffer for MPI transfer...
+ unsigned int m_BufferSize[3];
+ float* m_BufferUp[3];
+ float* m_BufferDown[3];
+
+ //! Transfer all tangential voltages at the upper bounds to the lower bounds of the neighbouring MPI-processes
+ virtual void SendReceiveVoltages();
+ //! Transfer all tangential currents at the lower bounds to the upper bounds of the neighbouring MPI-processes
+ virtual void SendReceiveCurrents();
+};
+
+#endif // ENGINE_MPI_H
diff --git a/openEMS/FDTD/engine_multithread.cpp b/openEMS/FDTD/engine_multithread.cpp
new file mode 100644
index 0000000..7370198
--- /dev/null
+++ b/openEMS/FDTD/engine_multithread.cpp
@@ -0,0 +1,343 @@
+/*
+* Copyright (C) 2010 Sebastian Held (sebastian.held@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+//#define ENABLE_DEBUG_TIME
+
+#ifdef ENABLE_DEBUG_TIME
+#define DEBUG_TIME(x) x;
+#else
+#define DEBUG_TIME(x) ;
+#endif
+
+
+
+#include "engine_multithread.h"
+#include "extensions/engine_extension.h"
+#include "tools/array_ops.h"
+
+#include "boost/date_time/posix_time/posix_time.hpp"
+#include "boost/date_time/gregorian/gregorian.hpp"
+#include <iomanip>
+#include <xmmintrin.h>
+
+//! \brief construct an Engine_Multithread instance
+//! it's the responsibility of the caller to free the returned pointer
+Engine_Multithread* Engine_Multithread::New(const Operator_Multithread* op, unsigned int numThreads)
+{
+ cout << "Create FDTD engine (compressed SSE + multi-threading)" << endl;
+ Engine_Multithread* e = new Engine_Multithread(op);
+ e->setNumThreads( numThreads );
+ e->Init();
+ return e;
+}
+
+Engine_Multithread::Engine_Multithread(const Operator_Multithread* op) : ENGINE_MULTITHREAD_BASE(op)
+{
+ m_Op_MT = op;
+ m_type = SSE;
+ m_IterateBarrier = 0;
+ m_startBarrier = 0;
+ m_stopBarrier = 0;
+
+#ifdef ENABLE_DEBUG_TIME
+ m_MPI_Barrier = 0;
+#endif
+}
+
+Engine_Multithread::~Engine_Multithread()
+{
+#ifdef ENABLE_DEBUG_TIME
+ NS_Engine_Multithread::DBG().cout() << "Engine_Multithread::~Engine_Multithread()" << endl;
+ std::map<boost::thread::id, std::vector<double> >::iterator it;
+ for (it=m_timer_list.begin(); it!=m_timer_list.end(); it++)
+ {
+ NS_Engine_Multithread::DBG().cout() << "*** DEBUG Thread: " << it->first << std::endl;
+ std::vector<double>::iterator it2;
+ for (it2=it->second.begin(); it2<it->second.end();)
+ {
+ NS_Engine_Multithread::DBG().cout() << "after voltage update, before barrier1: " << fixed << setprecision(6) << *(it2++) << std::endl;
+ NS_Engine_Multithread::DBG().cout() << "after barrier1, before barrier2: " << fixed << setprecision(6) << *(it2++) << std::endl;
+ NS_Engine_Multithread::DBG().cout() << "after barrier2, before current update: " << fixed << setprecision(6) << *(it2++) << std::endl;
+ NS_Engine_Multithread::DBG().cout() << "after current update, before barrier3: " << fixed << setprecision(6) << *(it2++) << std::endl;
+ NS_Engine_Multithread::DBG().cout() << "after barrier3: " << fixed << setprecision(6) << *(it2++) << std::endl;
+ }
+ }
+#endif
+
+ Reset();
+}
+
+void Engine_Multithread::setNumThreads( unsigned int numThreads )
+{
+ m_numThreads = numThreads;
+}
+
+void Engine_Multithread::Init()
+{
+ m_stopThreads = true;
+ ENGINE_MULTITHREAD_BASE::Init();
+
+ // initialize threads
+ m_stopThreads = false;
+ if (m_numThreads == 0)
+ m_numThreads = boost::thread::hardware_concurrency();
+
+ vector<unsigned int> m_Start_Lines;
+ vector<unsigned int> m_Stop_Lines;
+ m_Op_MT->CalcStartStopLines( m_numThreads, m_Start_Lines, m_Stop_Lines );
+
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Multithreaded engine using " << m_numThreads << " threads. Utilization: (";
+ m_IterateBarrier = new boost::barrier(m_numThreads); // numThread workers
+
+ m_startBarrier = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+ m_stopBarrier = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+#ifdef MPI_SUPPORT
+ m_MPI_Barrier = 0;
+#endif
+
+ for (unsigned int n=0; n<m_numThreads; n++)
+ {
+ unsigned int start = m_Start_Lines.at(n);
+ unsigned int stop = m_Stop_Lines.at(n);
+ unsigned int stop_h = stop;
+ if (n == m_numThreads-1)
+ {
+ // last thread
+ stop_h = stop-1;
+ if (g_settings.GetVerboseLevel()>0)
+ cout << stop-start+1 << ")" << endl;
+ }
+ else
+ if (g_settings.GetVerboseLevel()>0)
+ cout << stop-start+1 << ";";
+// NS_Engine_Multithread::DBG().cout() << "###DEBUG## Thread " << n << ": start=" << start << " stop=" << stop << " stop_h=" << stop_h << std::endl;
+ boost::thread *t = new boost::thread( NS_Engine_Multithread::thread(this,start,stop,stop_h,n) );
+ m_thread_group.add_thread( t );
+ }
+
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ m_Eng_exts.at(n)->SetNumberOfThreads(m_numThreads);
+}
+
+void Engine_Multithread::Reset()
+{
+ if (!m_stopThreads) // prevent multiple invocations
+ {
+ ClearExtensions(); //prevent extensions from interfering with thread reset...
+
+ // stop the threads
+ //NS_Engine_Multithread::DBG().cout() << "stopping all threads" << endl;
+ m_iterTS = 1;
+ m_startBarrier->wait(); // start the threads
+ m_stopThreads = true;
+ m_stopBarrier->wait(); // wait for the threads to finish
+ m_thread_group.join_all(); // wait for termination
+ delete m_IterateBarrier;
+ m_IterateBarrier = 0;
+ delete m_startBarrier;
+ m_startBarrier = 0;
+ delete m_stopBarrier;
+ m_stopBarrier = 0;
+ }
+
+ ENGINE_MULTITHREAD_BASE::Reset();
+}
+
+bool Engine_Multithread::IterateTS(unsigned int iterTS)
+{
+ m_iterTS = iterTS;
+
+ //cout << "bool Engine_Multithread::IterateTS(): starting threads ...";
+ m_startBarrier->wait(); // start the threads
+
+ //cout << "... threads started";
+
+ m_stopBarrier->wait(); // wait for the threads to finish <iterTS> time steps
+ return true;
+}
+
+void Engine_Multithread::DoPreVoltageUpdates(int threadID)
+{
+ //execute extensions in reverse order -> highest priority gets access to the voltages last
+ for (int n=m_Eng_exts.size()-1; n>=0; --n)
+ {
+ m_Eng_exts.at(n)->DoPreVoltageUpdates(threadID);
+ m_IterateBarrier->wait();
+ }
+
+}
+
+void Engine_Multithread::DoPostVoltageUpdates(int threadID)
+{
+ //execute extensions in normal order -> highest priority gets access to the voltages first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ {
+ m_Eng_exts.at(n)->DoPostVoltageUpdates(threadID);
+ m_IterateBarrier->wait();
+ }
+}
+
+void Engine_Multithread::Apply2Voltages(int threadID)
+{
+ //execute extensions in normal order -> highest priority gets access to the voltages first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ {
+ m_Eng_exts.at(n)->Apply2Voltages(threadID);
+ m_IterateBarrier->wait();
+ }
+}
+
+void Engine_Multithread::DoPreCurrentUpdates(int threadID)
+{
+ //execute extensions in reverse order -> highest priority gets access to the currents last
+ for (int n=m_Eng_exts.size()-1; n>=0; --n)
+ {
+ m_Eng_exts.at(n)->DoPreCurrentUpdates(threadID);
+ m_IterateBarrier->wait();
+ }
+}
+
+void Engine_Multithread::DoPostCurrentUpdates(int threadID)
+{
+ //execute extensions in normal order -> highest priority gets access to the currents first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ {
+ m_Eng_exts.at(n)->DoPostCurrentUpdates(threadID);
+ m_IterateBarrier->wait();
+ }
+}
+
+void Engine_Multithread::Apply2Current(int threadID)
+{
+ //execute extensions in normal order -> highest priority gets access to the currents first
+ for (size_t n=0; n<m_Eng_exts.size(); ++n)
+ {
+ m_Eng_exts.at(n)->Apply2Current(threadID);
+ m_IterateBarrier->wait();
+ }
+}
+
+//
+// *************************************************************************************************************************
+//
+namespace NS_Engine_Multithread
+{
+
+thread::thread( Engine_Multithread* ptr, unsigned int start, unsigned int stop, unsigned int stop_h, unsigned int threadID )
+{
+ m_enginePtr = ptr;
+ m_start = start;
+ m_stop = stop;
+ m_stop_h = stop_h;
+ m_threadID = threadID;
+}
+
+void thread::operator()()
+{
+ //std::cout << "thread::operator() Parameters: " << m_start << " " << m_stop << std::endl;
+ //DBG().cout() << "Thread " << m_threadID << " (" << boost::this_thread::get_id() << ") started." << endl;
+
+ // speed up the calculation of denormal floating point values (flush-to-zero)
+#ifndef SSE_CORRECT_DENORMALS
+ unsigned int oldMXCSR = _mm_getcsr(); //read the old MXCSR setting
+ unsigned int newMXCSR = oldMXCSR | 0x8040; // set DAZ and FZ bits
+ _mm_setcsr( newMXCSR ); //write the new MXCSR setting to the MXCSR
+#endif
+
+ while (!m_enginePtr->m_stopThreads)
+ {
+ // wait for start
+ //DBG().cout() << "Thread " << m_threadID << " (" << boost::this_thread::get_id() << ") waiting..." << endl;
+ m_enginePtr->m_startBarrier->wait();
+ //cout << "Thread " << boost::this_thread::get_id() << " waiting... started." << endl;
+
+ DEBUG_TIME( Timer timer1 );
+
+ for (unsigned int iter=0; iter<m_enginePtr->m_iterTS; ++iter)
+ {
+ // pre voltage stuff...
+ m_enginePtr->DoPreVoltageUpdates(m_threadID);
+
+ //voltage updates
+ m_enginePtr->UpdateVoltages(m_start,m_stop-m_start+1);
+
+ // record time
+ DEBUG_TIME( m_enginePtr->m_timer_list[boost::this_thread::get_id()].push_back( timer1.elapsed() ); )
+
+ //cout << "Thread " << boost::this_thread::get_id() << " m_barrier1 waiting..." << endl;
+ m_enginePtr->m_IterateBarrier->wait();
+
+ // record time
+ DEBUG_TIME( m_enginePtr->m_timer_list[boost::this_thread::get_id()].push_back( timer1.elapsed() ); )
+
+ //post voltage stuff...
+ m_enginePtr->DoPostVoltageUpdates(m_threadID);
+ m_enginePtr->Apply2Voltages(m_threadID);
+
+#ifdef MPI_SUPPORT
+ if (m_threadID==0)
+ {
+ if (m_enginePtr->m_MPI_Barrier)
+ m_enginePtr->m_MPI_Barrier->wait();
+ m_enginePtr->SendReceiveVoltages();
+ }
+ m_enginePtr->m_IterateBarrier->wait();
+#endif
+
+ // record time
+ DEBUG_TIME( m_enginePtr->m_timer_list[boost::this_thread::get_id()].push_back( timer1.elapsed() ); )
+
+ //pre current stuff
+ m_enginePtr->DoPreCurrentUpdates(m_threadID);
+
+ //current updates
+ m_enginePtr->UpdateCurrents(m_start,m_stop_h-m_start+1);
+
+ // record time
+ DEBUG_TIME( m_enginePtr->m_timer_list[boost::this_thread::get_id()].push_back( timer1.elapsed() ); )
+ m_enginePtr->m_IterateBarrier->wait();
+
+ // record time
+ DEBUG_TIME( m_enginePtr->m_timer_list[boost::this_thread::get_id()].push_back( timer1.elapsed() ); )
+
+ //post current stuff
+ m_enginePtr->DoPostCurrentUpdates(m_threadID);
+ m_enginePtr->Apply2Current(m_threadID);
+
+#ifdef MPI_SUPPORT
+ if (m_threadID==0)
+ {
+ if (m_enginePtr->m_MPI_Barrier)
+ m_enginePtr->m_MPI_Barrier->wait();
+ m_enginePtr->SendReceiveCurrents();
+ }
+ m_enginePtr->m_IterateBarrier->wait();
+#endif
+
+ if (m_threadID == 0)
+ ++m_enginePtr->numTS; // only the first thread increments numTS
+ }
+
+ m_enginePtr->m_stopBarrier->wait();
+ }
+
+ //DBG().cout() << "Thread " << m_threadID << " (" << boost::this_thread::get_id() << ") finished." << endl;
+}
+
+} // namespace
+
diff --git a/openEMS/FDTD/engine_multithread.h b/openEMS/FDTD/engine_multithread.h
new file mode 100644
index 0000000..20e7073
--- /dev/null
+++ b/openEMS/FDTD/engine_multithread.h
@@ -0,0 +1,127 @@
+/*
+* Copyright (C) 2010 Sebastian Held (sebastian.held@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_MULTITHREAD_H
+#define ENGINE_MULTITHREAD_H
+
+#include "operator_multithread.h"
+#include "engine_sse_compressed.h"
+
+#include <boost/thread.hpp>
+#include <boost/fusion/include/list.hpp>
+#include <boost/fusion/container/list/list_fwd.hpp>
+#include <boost/fusion/include/list_fwd.hpp>
+
+//#ifdef WIN32
+//#include <Winsock2.h> // for struct timeval
+//#endif
+
+#include <sys/time.h>
+
+#ifdef MPI_SUPPORT
+ #define ENGINE_MULTITHREAD_BASE Engine_MPI
+ #include "engine_mpi.h"
+#else
+ #define ENGINE_MULTITHREAD_BASE Engine_SSE_Compressed
+#endif
+
+
+class Engine_Multithread;
+
+namespace NS_Engine_Multithread
+{
+
+class DBG // debug
+{
+public:
+ DBG() {}
+ ~DBG() { std::cout << os.str();}
+ std::ostringstream& cout() {return os;}
+protected:
+ std::ostringstream os;
+};
+
+class Timer //debug
+{
+public:
+ Timer() {gettimeofday(&t1,NULL);}
+ double elapsed() {gettimeofday(&t2,NULL); return (t2.tv_sec-t1.tv_sec) + (t2.tv_usec-t1.tv_usec)*1e-6;}
+protected:
+ timeval t1,t2;
+};
+
+class thread
+{
+public:
+ thread( Engine_Multithread* ptr, unsigned int start, unsigned int stop, unsigned int stop_h, unsigned int threadID );
+ void operator()();
+
+protected:
+ unsigned int m_start, m_stop, m_stop_h, m_threadID;
+ Engine_Multithread *m_enginePtr;
+};
+} // namespace
+
+
+class Engine_Multithread : public ENGINE_MULTITHREAD_BASE
+{
+ friend class NS_Engine_Multithread::thread;
+ friend class Engine_CylinderMultiGrid;
+public:
+ static Engine_Multithread* New(const Operator_Multithread* op, unsigned int numThreads = 0);
+ virtual ~Engine_Multithread();
+
+ virtual void setNumThreads( unsigned int numThreads );
+ virtual void Init();
+ virtual void Reset();
+
+ //! Iterate \a iterTS number of timesteps
+ virtual bool IterateTS(unsigned int iterTS);
+
+ virtual void DoPreVoltageUpdates(int threadID);
+ virtual void DoPostVoltageUpdates(int threadID);
+ virtual void Apply2Voltages(int threadID);
+
+ virtual void DoPreCurrentUpdates(int threadID);
+ virtual void DoPostCurrentUpdates(int threadID);
+ virtual void Apply2Current(int threadID);
+
+protected:
+ Engine_Multithread(const Operator_Multithread* op);
+ const Operator_Multithread* m_Op_MT;
+ boost::thread_group m_thread_group;
+ boost::barrier *m_startBarrier, *m_stopBarrier;
+ boost::barrier *m_IterateBarrier;
+ volatile unsigned int m_iterTS;
+ unsigned int m_numThreads; //!< number of worker threads
+ volatile bool m_stopThreads;
+
+#ifdef MPI_SUPPORT
+ /*! Workaround needed for subgridding scheme... (see Engine_CylinderMultiGrid)
+ Some engines may need an additional barrier for synchronizing MPI communication.
+ This engine will not initialize or cleanup this barrier, but check for it and wait before executing any MPI sync.
+ Make sure to cleanup (delete) this barriere before Engine_Multithread::Reset() is called.
+ */
+ boost::barrier *m_MPI_Barrier;
+#endif
+
+#ifdef ENABLE_DEBUG_TIME
+ std::map<boost::thread::id, std::vector<double> > m_timer_list;
+#endif
+};
+
+#endif // ENGINE_MULTITHREAD_H
diff --git a/openEMS/FDTD/engine_sse.cpp b/openEMS/FDTD/engine_sse.cpp
new file mode 100644
index 0000000..660e6d6
--- /dev/null
+++ b/openEMS/FDTD/engine_sse.cpp
@@ -0,0 +1,176 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <xmmintrin.h>
+#include "engine_sse.h"
+
+//! \brief construct an Engine_sse instance
+//! it's the responsibility of the caller to free the returned pointer
+Engine_sse* Engine_sse::New(const Operator_sse* op)
+{
+ cout << "Create FDTD engine (SSE)" << endl;
+ Engine_sse* e = new Engine_sse(op);
+ e->Init();
+ return e;
+}
+
+Engine_sse::Engine_sse(const Operator_sse* op) : Engine(op)
+{
+ m_type = SSE;
+ Op = op;
+ f4_volt = 0;
+ f4_curr = 0;
+ numVectors = ceil((double)numLines[2]/4.0);
+
+ // speed up the calculation of denormal floating point values (flush-to-zero)
+#ifndef SSE_CORRECT_DENORMALS
+ unsigned int oldMXCSR = _mm_getcsr(); //read the old MXCSR setting
+ unsigned int newMXCSR = oldMXCSR | 0x8040; // set DAZ and FZ bits
+ _mm_setcsr( newMXCSR ); //write the new MXCSR setting to the MXCSR
+#endif
+}
+
+Engine_sse::~Engine_sse()
+{
+ //_mm_setcsr( oldMXCSR ); // restore old setting
+ Reset();
+}
+
+void Engine_sse::Init()
+{
+ Engine::Init();
+
+ Delete_N_3DArray(volt,numLines);
+ volt=NULL; // not used
+ Delete_N_3DArray(curr,numLines);
+ curr=NULL; // not used
+
+ f4_volt = Create_N_3DArray_v4sf(numLines);
+ f4_curr = Create_N_3DArray_v4sf(numLines);
+}
+
+void Engine_sse::Reset()
+{
+ Engine::Reset();
+ Delete_N_3DArray_v4sf(f4_volt,numLines);
+ f4_volt = 0;
+ Delete_N_3DArray_v4sf(f4_curr,numLines);
+ f4_curr = 0;
+}
+
+void Engine_sse::UpdateVoltages(unsigned int startX, unsigned int numX)
+{
+ unsigned int pos[3];
+ bool shift[2];
+ f4vector temp;
+
+ pos[0] = startX;
+ for (unsigned int posX=0; posX<numX; ++posX)
+ {
+ shift[0]=pos[0];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ shift[1]=pos[1];
+ for (pos[2]=1; pos[2]<numVectors; ++pos[2])
+ {
+ // x-polarization
+ f4_volt[0][pos[0]][pos[1]][pos[2]].v *= Op->f4_vv[0][pos[0]][pos[1]][pos[2]].v;
+ f4_volt[0][pos[0]][pos[1]][pos[2]].v += Op->f4_vi[0][pos[0]][pos[1]][pos[2]].v * ( f4_curr[2][pos[0]][pos[1]][pos[2]].v - f4_curr[2][pos[0]][pos[1]-shift[1]][pos[2]].v - f4_curr[1][pos[0]][pos[1]][pos[2]].v + f4_curr[1][pos[0]][pos[1]][pos[2]-1].v );
+
+ // y-polarization
+ f4_volt[1][pos[0]][pos[1]][pos[2]].v *= Op->f4_vv[1][pos[0]][pos[1]][pos[2]].v;
+ f4_volt[1][pos[0]][pos[1]][pos[2]].v += Op->f4_vi[1][pos[0]][pos[1]][pos[2]].v * ( f4_curr[0][pos[0]][pos[1]][pos[2]].v - f4_curr[0][pos[0]][pos[1]][pos[2]-1].v - f4_curr[2][pos[0]][pos[1]][pos[2]].v + f4_curr[2][pos[0]-shift[0]][pos[1]][pos[2]].v);
+
+ // z-polarization
+ f4_volt[2][pos[0]][pos[1]][pos[2]].v *= Op->f4_vv[2][pos[0]][pos[1]][pos[2]].v;
+ f4_volt[2][pos[0]][pos[1]][pos[2]].v += Op->f4_vi[2][pos[0]][pos[1]][pos[2]].v * ( f4_curr[1][pos[0]][pos[1]][pos[2]].v - f4_curr[1][pos[0]-shift[0]][pos[1]][pos[2]].v - f4_curr[0][pos[0]][pos[1]][pos[2]].v + f4_curr[0][pos[0]][pos[1]-shift[1]][pos[2]].v);
+ }
+
+ // for pos[2] = 0
+ // x-polarization
+ temp.f[0] = 0;
+ temp.f[1] = f4_curr[1][pos[0]][pos[1]][numVectors-1].f[0];
+ temp.f[2] = f4_curr[1][pos[0]][pos[1]][numVectors-1].f[1];
+ temp.f[3] = f4_curr[1][pos[0]][pos[1]][numVectors-1].f[2];
+ f4_volt[0][pos[0]][pos[1]][0].v *= Op->f4_vv[0][pos[0]][pos[1]][0].v;
+ f4_volt[0][pos[0]][pos[1]][0].v += Op->f4_vi[0][pos[0]][pos[1]][0].v * ( f4_curr[2][pos[0]][pos[1]][0].v - f4_curr[2][pos[0]][pos[1]-shift[1]][0].v - f4_curr[1][pos[0]][pos[1]][0].v + temp.v );
+
+ // y-polarization
+ temp.f[0] = 0;
+ temp.f[1] = f4_curr[0][pos[0]][pos[1]][numVectors-1].f[0];
+ temp.f[2] = f4_curr[0][pos[0]][pos[1]][numVectors-1].f[1];
+ temp.f[3] = f4_curr[0][pos[0]][pos[1]][numVectors-1].f[2];
+ f4_volt[1][pos[0]][pos[1]][0].v *= Op->f4_vv[1][pos[0]][pos[1]][0].v;
+ f4_volt[1][pos[0]][pos[1]][0].v += Op->f4_vi[1][pos[0]][pos[1]][0].v * ( f4_curr[0][pos[0]][pos[1]][0].v - temp.v - f4_curr[2][pos[0]][pos[1]][0].v + f4_curr[2][pos[0]-shift[0]][pos[1]][0].v);
+
+ // z-polarization
+ f4_volt[2][pos[0]][pos[1]][0].v *= Op->f4_vv[2][pos[0]][pos[1]][0].v;
+ f4_volt[2][pos[0]][pos[1]][0].v += Op->f4_vi[2][pos[0]][pos[1]][0].v * ( f4_curr[1][pos[0]][pos[1]][0].v - f4_curr[1][pos[0]-shift[0]][pos[1]][0].v - f4_curr[0][pos[0]][pos[1]][0].v + f4_curr[0][pos[0]][pos[1]-shift[1]][0].v);
+ }
+ ++pos[0];
+ }
+}
+
+void Engine_sse::UpdateCurrents(unsigned int startX, unsigned int numX)
+{
+ unsigned int pos[5];
+ f4vector temp;
+
+ pos[0] = startX;
+ for (unsigned int posX=0; posX<numX; ++posX)
+ {
+ for (pos[1]=0; pos[1]<numLines[1]-1; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numVectors-1; ++pos[2])
+ {
+ // x-pol
+ f4_curr[0][pos[0]][pos[1]][pos[2]].v *= Op->f4_ii[0][pos[0]][pos[1]][pos[2]].v;
+ f4_curr[0][pos[0]][pos[1]][pos[2]].v += Op->f4_iv[0][pos[0]][pos[1]][pos[2]].v * ( f4_volt[2][pos[0]][pos[1]][pos[2]].v - f4_volt[2][pos[0]][pos[1]+1][pos[2]].v - f4_volt[1][pos[0]][pos[1]][pos[2]].v + f4_volt[1][pos[0]][pos[1]][pos[2]+1].v);
+
+ // y-pol
+ f4_curr[1][pos[0]][pos[1]][pos[2]].v *= Op->f4_ii[1][pos[0]][pos[1]][pos[2]].v;
+ f4_curr[1][pos[0]][pos[1]][pos[2]].v += Op->f4_iv[1][pos[0]][pos[1]][pos[2]].v * ( f4_volt[0][pos[0]][pos[1]][pos[2]].v - f4_volt[0][pos[0]][pos[1]][pos[2]+1].v - f4_volt[2][pos[0]][pos[1]][pos[2]].v + f4_volt[2][pos[0]+1][pos[1]][pos[2]].v);
+
+ // z-pol
+ f4_curr[2][pos[0]][pos[1]][pos[2]].v *= Op->f4_ii[2][pos[0]][pos[1]][pos[2]].v;
+ f4_curr[2][pos[0]][pos[1]][pos[2]].v += Op->f4_iv[2][pos[0]][pos[1]][pos[2]].v * ( f4_volt[1][pos[0]][pos[1]][pos[2]].v - f4_volt[1][pos[0]+1][pos[1]][pos[2]].v - f4_volt[0][pos[0]][pos[1]][pos[2]].v + f4_volt[0][pos[0]][pos[1]+1][pos[2]].v);
+ }
+
+ // for pos[2] = numVectors-1
+ // x-pol
+ temp.f[0] = f4_volt[1][pos[0]][pos[1]][0].f[1];
+ temp.f[1] = f4_volt[1][pos[0]][pos[1]][0].f[2];
+ temp.f[2] = f4_volt[1][pos[0]][pos[1]][0].f[3];
+ temp.f[3] = 0;
+ f4_curr[0][pos[0]][pos[1]][numVectors-1].v *= Op->f4_ii[0][pos[0]][pos[1]][numVectors-1].v;
+ f4_curr[0][pos[0]][pos[1]][numVectors-1].v += Op->f4_iv[0][pos[0]][pos[1]][numVectors-1].v * ( f4_volt[2][pos[0]][pos[1]][numVectors-1].v - f4_volt[2][pos[0]][pos[1]+1][numVectors-1].v - f4_volt[1][pos[0]][pos[1]][numVectors-1].v + temp.v);
+
+ // y-pol
+ temp.f[0] = f4_volt[0][pos[0]][pos[1]][0].f[1];
+ temp.f[1] = f4_volt[0][pos[0]][pos[1]][0].f[2];
+ temp.f[2] = f4_volt[0][pos[0]][pos[1]][0].f[3];
+ temp.f[3] = 0;
+ f4_curr[1][pos[0]][pos[1]][numVectors-1].v *= Op->f4_ii[1][pos[0]][pos[1]][numVectors-1].v;
+ f4_curr[1][pos[0]][pos[1]][numVectors-1].v += Op->f4_iv[1][pos[0]][pos[1]][numVectors-1].v * ( f4_volt[0][pos[0]][pos[1]][numVectors-1].v - temp.v - f4_volt[2][pos[0]][pos[1]][numVectors-1].v + f4_volt[2][pos[0]+1][pos[1]][numVectors-1].v);
+
+ // z-pol
+ f4_curr[2][pos[0]][pos[1]][numVectors-1].v *= Op->f4_ii[2][pos[0]][pos[1]][numVectors-1].v;
+ f4_curr[2][pos[0]][pos[1]][numVectors-1].v += Op->f4_iv[2][pos[0]][pos[1]][numVectors-1].v * ( f4_volt[1][pos[0]][pos[1]][numVectors-1].v - f4_volt[1][pos[0]+1][pos[1]][numVectors-1].v - f4_volt[0][pos[0]][pos[1]][numVectors-1].v + f4_volt[0][pos[0]][pos[1]+1][numVectors-1].v);
+ }
+ ++pos[0];
+ }
+}
diff --git a/openEMS/FDTD/engine_sse.h b/openEMS/FDTD/engine_sse.h
new file mode 100644
index 0000000..9389f84
--- /dev/null
+++ b/openEMS/FDTD/engine_sse.h
@@ -0,0 +1,60 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_SSE_H
+#define ENGINE_SSE_H
+
+#include "engine.h"
+#include "operator_sse.h"
+
+class Engine_sse : public Engine
+{
+public:
+ static Engine_sse* New(const Operator_sse* op);
+ virtual ~Engine_sse();
+
+ virtual void Init();
+ virtual void Reset();
+
+ virtual unsigned int GetNumberOfTimesteps() {return numTS;};
+
+ //this access functions muss be overloaded by any new engine using a different storage model
+ inline virtual FDTD_FLOAT GetVolt( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return f4_volt[n][x][y][z%numVectors].f[z/numVectors]; }
+ inline virtual FDTD_FLOAT GetVolt( unsigned int n, const unsigned int pos[3] ) const { return f4_volt[n][pos[0]][pos[1]][pos[2]%numVectors].f[pos[2]/numVectors]; }
+ inline virtual FDTD_FLOAT GetCurr( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return f4_curr[n][x][y][z%numVectors].f[z/numVectors]; }
+ inline virtual FDTD_FLOAT GetCurr( unsigned int n, const unsigned int pos[3] ) const { return f4_curr[n][pos[0]][pos[1]][pos[2]%numVectors].f[pos[2]/numVectors]; }
+
+ inline virtual void SetVolt( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value) { f4_volt[n][x][y][z%numVectors].f[z/numVectors]=value; }
+ inline virtual void SetVolt( unsigned int n, const unsigned int pos[3], FDTD_FLOAT value ) { f4_volt[n][pos[0]][pos[1]][pos[2]%numVectors].f[pos[2]/numVectors]=value; }
+ inline virtual void SetCurr( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value) { f4_curr[n][x][y][z%numVectors].f[z/numVectors]=value; }
+ inline virtual void SetCurr( unsigned int n, const unsigned int pos[3], FDTD_FLOAT value ) { f4_curr[n][pos[0]][pos[1]][pos[2]%numVectors].f[pos[2]/numVectors]=value; }
+
+protected:
+ Engine_sse(const Operator_sse* op);
+ const Operator_sse* Op;
+
+ virtual void UpdateVoltages(unsigned int startX, unsigned int numX);
+ virtual void UpdateCurrents(unsigned int startX, unsigned int numX);
+
+ unsigned int numVectors;
+
+public: //public access to the sse arrays for efficient extensions access... use careful...
+ f4vector**** f4_volt;
+ f4vector**** f4_curr;
+};
+
+#endif // ENGINE_SSE_H
diff --git a/openEMS/FDTD/engine_sse_compressed.cpp b/openEMS/FDTD/engine_sse_compressed.cpp
new file mode 100644
index 0000000..8e83387
--- /dev/null
+++ b/openEMS/FDTD/engine_sse_compressed.cpp
@@ -0,0 +1,163 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_sse_compressed.h"
+#ifdef __SSE2__
+#include <emmintrin.h>
+#endif
+
+Engine_SSE_Compressed* Engine_SSE_Compressed::New(const Operator_SSE_Compressed* op)
+{
+ cout << "Create FDTD engine (compressed SSE)" << endl;
+ Engine_SSE_Compressed* e = new Engine_SSE_Compressed(op);
+ e->Init();
+ return e;
+}
+
+Engine_SSE_Compressed::Engine_SSE_Compressed(const Operator_SSE_Compressed* op) : Engine_sse(op)
+{
+ Op = op;
+}
+
+Engine_SSE_Compressed::~Engine_SSE_Compressed()
+{
+}
+
+void Engine_SSE_Compressed::UpdateVoltages(unsigned int startX, unsigned int numX)
+{
+ unsigned int pos[3];
+ bool shift[2];
+ f4vector temp;
+
+ pos[0] = startX;
+ unsigned int index=0;
+ for (unsigned int posX=0; posX<numX; ++posX)
+ {
+ shift[0]=pos[0];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ shift[1]=pos[1];
+ for (pos[2]=1; pos[2]<numVectors; ++pos[2])
+ {
+ index = Op->m_Op_index[pos[0]][pos[1]][pos[2]];
+ // x-polarization
+ f4_volt[0][pos[0]][pos[1]][pos[2]].v *= Op->f4_vv_Compressed[0][index].v;
+ f4_volt[0][pos[0]][pos[1]][pos[2]].v += Op->f4_vi_Compressed[0][index].v * ( f4_curr[2][pos[0]][pos[1]][pos[2]].v - f4_curr[2][pos[0]][pos[1]-shift[1]][pos[2]].v - f4_curr[1][pos[0]][pos[1]][pos[2]].v + f4_curr[1][pos[0]][pos[1]][pos[2]-1].v );
+
+ // y-polarization
+ f4_volt[1][pos[0]][pos[1]][pos[2]].v *= Op->f4_vv_Compressed[1][index].v;
+ f4_volt[1][pos[0]][pos[1]][pos[2]].v += Op->f4_vi_Compressed[1][index].v * ( f4_curr[0][pos[0]][pos[1]][pos[2]].v - f4_curr[0][pos[0]][pos[1]][pos[2]-1].v - f4_curr[2][pos[0]][pos[1]][pos[2]].v + f4_curr[2][pos[0]-shift[0]][pos[1]][pos[2]].v);
+
+ // z-polarization
+ f4_volt[2][pos[0]][pos[1]][pos[2]].v *= Op->f4_vv_Compressed[2][index].v;
+ f4_volt[2][pos[0]][pos[1]][pos[2]].v += Op->f4_vi_Compressed[2][index].v * ( f4_curr[1][pos[0]][pos[1]][pos[2]].v - f4_curr[1][pos[0]-shift[0]][pos[1]][pos[2]].v - f4_curr[0][pos[0]][pos[1]][pos[2]].v + f4_curr[0][pos[0]][pos[1]-shift[1]][pos[2]].v);
+ }
+
+ // for pos[2] = 0
+ // x-polarization
+ index = Op->m_Op_index[pos[0]][pos[1]][0];
+#ifdef __SSE2__
+ temp.v = (__m128)_mm_slli_si128( (__m128i)f4_curr[1][pos[0]][pos[1]][numVectors-1].v, 4 );
+#else
+ temp.f[0] = 0;
+ temp.f[1] = f4_curr[1][pos[0]][pos[1]][numVectors-1].f[0];
+ temp.f[2] = f4_curr[1][pos[0]][pos[1]][numVectors-1].f[1];
+ temp.f[3] = f4_curr[1][pos[0]][pos[1]][numVectors-1].f[2];
+#endif
+ f4_volt[0][pos[0]][pos[1]][0].v *= Op->f4_vv_Compressed[0][index].v;
+ f4_volt[0][pos[0]][pos[1]][0].v += Op->f4_vi_Compressed[0][index].v * ( f4_curr[2][pos[0]][pos[1]][0].v - f4_curr[2][pos[0]][pos[1]-shift[1]][0].v - f4_curr[1][pos[0]][pos[1]][0].v + temp.v );
+
+ // y-polarization
+#ifdef __SSE2__
+ temp.v = (__m128)_mm_slli_si128( (__m128i)f4_curr[0][pos[0]][pos[1]][numVectors-1].v, 4 );
+#else
+ temp.f[0] = 0;
+ temp.f[1] = f4_curr[0][pos[0]][pos[1]][numVectors-1].f[0];
+ temp.f[2] = f4_curr[0][pos[0]][pos[1]][numVectors-1].f[1];
+ temp.f[3] = f4_curr[0][pos[0]][pos[1]][numVectors-1].f[2];
+#endif
+ f4_volt[1][pos[0]][pos[1]][0].v *= Op->f4_vv_Compressed[1][index].v;
+ f4_volt[1][pos[0]][pos[1]][0].v += Op->f4_vi_Compressed[1][index].v * ( f4_curr[0][pos[0]][pos[1]][0].v - temp.v - f4_curr[2][pos[0]][pos[1]][0].v + f4_curr[2][pos[0]-shift[0]][pos[1]][0].v);
+
+ // z-polarization
+ f4_volt[2][pos[0]][pos[1]][0].v *= Op->f4_vv_Compressed[2][index].v;
+ f4_volt[2][pos[0]][pos[1]][0].v += Op->f4_vi_Compressed[2][index].v * ( f4_curr[1][pos[0]][pos[1]][0].v - f4_curr[1][pos[0]-shift[0]][pos[1]][0].v - f4_curr[0][pos[0]][pos[1]][0].v + f4_curr[0][pos[0]][pos[1]-shift[1]][0].v);
+ }
+ ++pos[0];
+ }
+}
+
+void Engine_SSE_Compressed::UpdateCurrents(unsigned int startX, unsigned int numX)
+{
+ unsigned int pos[3];
+ f4vector temp;
+
+ pos[0] = startX;
+ unsigned int index;
+ for (unsigned int posX=0; posX<numX; ++posX)
+ {
+ for (pos[1]=0; pos[1]<numLines[1]-1; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numVectors-1; ++pos[2])
+ {
+ index = Op->m_Op_index[pos[0]][pos[1]][pos[2]];
+ // x-pol
+ f4_curr[0][pos[0]][pos[1]][pos[2]].v *= Op->f4_ii_Compressed[0][index].v;
+ f4_curr[0][pos[0]][pos[1]][pos[2]].v += Op->f4_iv_Compressed[0][index].v * ( f4_volt[2][pos[0]][pos[1]][pos[2]].v - f4_volt[2][pos[0]][pos[1]+1][pos[2]].v - f4_volt[1][pos[0]][pos[1]][pos[2]].v + f4_volt[1][pos[0]][pos[1]][pos[2]+1].v);
+
+ // y-pol
+ f4_curr[1][pos[0]][pos[1]][pos[2]].v *= Op->f4_ii_Compressed[1][index].v;
+ f4_curr[1][pos[0]][pos[1]][pos[2]].v += Op->f4_iv_Compressed[1][index].v * ( f4_volt[0][pos[0]][pos[1]][pos[2]].v - f4_volt[0][pos[0]][pos[1]][pos[2]+1].v - f4_volt[2][pos[0]][pos[1]][pos[2]].v + f4_volt[2][pos[0]+1][pos[1]][pos[2]].v);
+
+ // z-pol
+ f4_curr[2][pos[0]][pos[1]][pos[2]].v *= Op->f4_ii_Compressed[2][index].v;
+ f4_curr[2][pos[0]][pos[1]][pos[2]].v += Op->f4_iv_Compressed[2][index].v * ( f4_volt[1][pos[0]][pos[1]][pos[2]].v - f4_volt[1][pos[0]+1][pos[1]][pos[2]].v - f4_volt[0][pos[0]][pos[1]][pos[2]].v + f4_volt[0][pos[0]][pos[1]+1][pos[2]].v);
+ }
+
+ index = Op->m_Op_index[pos[0]][pos[1]][numVectors-1];
+ // for pos[2] = numVectors-1
+ // x-pol
+#ifdef __SSE2__
+ temp.v = (__m128)_mm_srli_si128( (__m128i)f4_volt[1][pos[0]][pos[1]][0].v, 4 );
+#else
+ temp.f[0] = f4_volt[1][pos[0]][pos[1]][0].f[1];
+ temp.f[1] = f4_volt[1][pos[0]][pos[1]][0].f[2];
+ temp.f[2] = f4_volt[1][pos[0]][pos[1]][0].f[3];
+ temp.f[3] = 0;
+#endif
+ f4_curr[0][pos[0]][pos[1]][numVectors-1].v *= Op->f4_ii_Compressed[0][index].v;
+ f4_curr[0][pos[0]][pos[1]][numVectors-1].v += Op->f4_iv_Compressed[0][index].v * ( f4_volt[2][pos[0]][pos[1]][numVectors-1].v - f4_volt[2][pos[0]][pos[1]+1][numVectors-1].v - f4_volt[1][pos[0]][pos[1]][numVectors-1].v + temp.v);
+
+ // y-pol
+#ifdef __SSE2__
+ temp.v = (__m128)_mm_srli_si128( (__m128i)f4_volt[0][pos[0]][pos[1]][0].v, 4 );
+#else
+ temp.f[0] = f4_volt[0][pos[0]][pos[1]][0].f[1];
+ temp.f[1] = f4_volt[0][pos[0]][pos[1]][0].f[2];
+ temp.f[2] = f4_volt[0][pos[0]][pos[1]][0].f[3];
+ temp.f[3] = 0;
+#endif
+ f4_curr[1][pos[0]][pos[1]][numVectors-1].v *= Op->f4_ii_Compressed[1][index].v;
+ f4_curr[1][pos[0]][pos[1]][numVectors-1].v += Op->f4_iv_Compressed[1][index].v * ( f4_volt[0][pos[0]][pos[1]][numVectors-1].v - temp.v - f4_volt[2][pos[0]][pos[1]][numVectors-1].v + f4_volt[2][pos[0]+1][pos[1]][numVectors-1].v);
+
+ // z-pol
+ f4_curr[2][pos[0]][pos[1]][numVectors-1].v *= Op->f4_ii_Compressed[2][index].v;
+ f4_curr[2][pos[0]][pos[1]][numVectors-1].v += Op->f4_iv_Compressed[2][index].v * ( f4_volt[1][pos[0]][pos[1]][numVectors-1].v - f4_volt[1][pos[0]+1][pos[1]][numVectors-1].v - f4_volt[0][pos[0]][pos[1]][numVectors-1].v + f4_volt[0][pos[0]][pos[1]+1][numVectors-1].v);
+ }
+ ++pos[0];
+ }
+}
diff --git a/openEMS/FDTD/engine_sse_compressed.h b/openEMS/FDTD/engine_sse_compressed.h
new file mode 100644
index 0000000..ab86cc8
--- /dev/null
+++ b/openEMS/FDTD/engine_sse_compressed.h
@@ -0,0 +1,38 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_SSE_COMPRESSED_H
+#define ENGINE_SSE_COMPRESSED_H
+
+#include "engine_sse.h"
+#include "operator_sse_compressed.h"
+
+class Engine_SSE_Compressed : public Engine_sse
+{
+public:
+ static Engine_SSE_Compressed* New(const Operator_SSE_Compressed* op);
+ virtual ~Engine_SSE_Compressed();
+
+protected:
+ Engine_SSE_Compressed(const Operator_SSE_Compressed* op);
+ const Operator_SSE_Compressed* Op;
+
+ virtual void UpdateVoltages(unsigned int startX, unsigned int numX);
+ virtual void UpdateCurrents(unsigned int startX, unsigned int numX);
+};
+
+#endif // ENGINE_SSE_COMPRESSED_H
diff --git a/openEMS/FDTD/excitation.cpp b/openEMS/FDTD/excitation.cpp
new file mode 100644
index 0000000..f095b53
--- /dev/null
+++ b/openEMS/FDTD/excitation.cpp
@@ -0,0 +1,304 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tools/array_ops.h"
+#include "tools/useful.h"
+#include <iostream>
+#include <fstream>
+#include "fparser.hh"
+#include "excitation.h"
+
+using namespace std;
+
+Excitation::Excitation()
+{
+ Signal_volt = 0;
+ Signal_curr = 0;
+
+ this->Reset(0);
+
+ m_Excit_Type = Excitation::UNDEFINED;
+ m_SignalPeriod = 0;
+}
+
+Excitation::~Excitation()
+{
+ this->Reset(0);
+}
+
+void Excitation::Reset( double timestep )
+{
+ delete[] Signal_volt;
+ Signal_volt = 0;
+ delete[] Signal_curr;
+ Signal_curr = 0;
+
+ dT = timestep;
+ m_nyquistTS = 0;
+ m_f_max = 0;
+ m_foi = 0;
+}
+
+bool Excitation::SetupGaussianPulse(double f0, double fc)
+{
+ m_Excit_Type = Excitation::GaissianPulse;
+ m_f0 = f0;
+ m_fc = fc;
+ m_f_max = f0+fc;
+ m_SignalPeriod = 0;
+}
+
+bool Excitation::SetupSinusoidal(double f0)
+{
+ m_Excit_Type = Excitation::Sinusoidal;
+ m_f0 = f0;
+ m_f_max = f0;
+ m_SignalPeriod = 1/f0;
+}
+
+bool Excitation::SetupDiracPulse(double fmax)
+{
+ m_Excit_Type = Excitation::DiracPulse;
+ m_SignalPeriod = 0;
+ m_f_max = fmax;
+}
+
+bool Excitation::SetupStepExcite(double fmax)
+{
+ m_Excit_Type = Excitation::Step;
+ m_SignalPeriod = 0;
+ m_f_max = fmax;
+}
+
+bool Excitation::SetupCustomExcite(string str, double f0, double fmax)
+{
+ m_Excit_Type = Excitation::CustomExcite;
+ m_CustomExc_Str = str;
+ m_f0 = f0;
+ m_SignalPeriod = 0;
+ m_f_max = fmax;
+}
+
+bool Excitation::buildExcitationSignal(unsigned int maxTS)
+{
+ if (dT<=0)
+ {
+ cerr << "Excitation::setupExcitation: Error, invalid timestep... " << endl;
+ return false;
+ }
+
+ switch (m_Excit_Type)
+ {
+ case Excitation::GaissianPulse:
+ CalcGaussianPulsExcitation(m_f0,m_fc,maxTS);
+ break;
+ case Excitation::Sinusoidal:
+ CalcSinusExcitation(m_f0,maxTS);
+ break;
+ case Excitation::DiracPulse:
+ CalcDiracPulsExcitation();
+ break;
+ case Excitation::Step:
+ CalcStepExcitation();
+ break;
+ case Excitation::CustomExcite:
+ CalcCustomExcitation(m_f0,maxTS,m_CustomExc_Str);
+ break;
+ default:
+ cerr << "Excitation::buildExcitationSignal: Unknown excitation type: \"" << m_Excit_Type<< "\" !!" << endl;
+ m_Excit_Type = Excitation::UNDEFINED;
+ return false;
+ }
+
+ if (GetNyquistNum() == 0)
+ {
+ cerr << "Excitation::buildExcitationSignal: Unknown error... excitation setup failed!!" << endl;
+ return false;
+ }
+
+ return true;
+}
+
+unsigned int Excitation::GetMaxExcitationTimestep() const
+{
+ FDTD_FLOAT maxAmp=0;
+ unsigned int maxStep=0;
+ for (unsigned int n=1; n<Length+1; ++n)
+ {
+ if (fabs(Signal_volt[n])>maxAmp)
+ {
+ maxAmp = fabs(Signal_volt[n]);
+ maxStep = n;
+ }
+ }
+ return maxStep;
+}
+
+void Excitation::CalcGaussianPulsExcitation(double f0, double fc, int nTS)
+{
+ if (dT==0) return;
+
+ Length = (unsigned int)(2.0 * 9.0/(2.0*PI*fc) / dT);
+ if (Length>(unsigned int)nTS)
+ {
+ cerr << "Operator::CalcGaussianPulsExcitation: Requested excitation pusle would be " << Length << " timesteps or " << Length * dT << " s long. Cutting to max number of timesteps!" << endl;
+ Length=(unsigned int)nTS;
+ }
+ delete[] Signal_volt;
+ delete[] Signal_curr;
+ Signal_volt = new FDTD_FLOAT[Length+1];
+ Signal_curr = new FDTD_FLOAT[Length+1];
+ Signal_volt[0]=0.0;
+ Signal_curr[0]=0.0;
+ for (unsigned int n=1; n<Length+1; ++n)
+ {
+ double t = (n-1)*dT;
+ Signal_volt[n] = cos(2.0*PI*f0*(t-9.0/(2.0*PI*fc)))*exp(-1*pow(2.0*PI*fc*t/3.0-3,2));
+ t += 0.5*dT;
+ Signal_curr[n] = cos(2.0*PI*f0*(t-9.0/(2.0*PI*fc)))*exp(-1*pow(2.0*PI*fc*t/3.0-3,2));
+ }
+
+ m_foi = f0;
+ m_f_max = f0+fc;
+
+ SetNyquistNum( CalcNyquistNum(f0+fc,dT) );
+}
+
+void Excitation::CalcDiracPulsExcitation()
+{
+ if (dT==0) return;
+
+ Length = 1;
+// cerr << "Operator::CalcDiracPulsExcitation: Length of the excite signal: " << ExciteLength << " timesteps" << endl;
+ delete[] Signal_volt;
+ delete[] Signal_curr;
+ Signal_volt = new FDTD_FLOAT[Length+1];
+ Signal_curr = new FDTD_FLOAT[Length+1];
+ Signal_volt[0]=0.0;
+ Signal_volt[1]=1.0;
+ Signal_curr[0]=0.0;
+ Signal_curr[1]=1.0;
+
+ m_foi = 0;
+ m_f_max = 0;
+
+ SetNyquistNum( 1 );
+}
+
+void Excitation::CalcStepExcitation()
+{
+ if (dT==0) return;
+
+ Length = 1;
+ delete[] Signal_volt;
+ delete[] Signal_curr;
+ Signal_volt = new FDTD_FLOAT[Length+1];
+ Signal_curr = new FDTD_FLOAT[Length+1];
+ Signal_volt[0]=1.0;
+ Signal_volt[1]=1.0;
+ Signal_curr[0]=1.0;
+ Signal_curr[1]=1.0;
+
+ m_foi = 0;
+ m_f_max = 0;
+
+ SetNyquistNum( 1 );
+}
+
+void Excitation::CalcCustomExcitation(double f0, int nTS, string signal)
+{
+ if (dT==0) return;
+ if (nTS<=0) return;
+
+ Length = (unsigned int)(nTS);
+// cerr << "Operator::CalcSinusExcitation: Length of the excite signal: " << ExciteLength << " timesteps" << endl;
+ delete[] Signal_volt;
+ delete[] Signal_curr;
+ Signal_volt = new FDTD_FLOAT[Length+1];
+ Signal_curr = new FDTD_FLOAT[Length+1];
+ Signal_volt[0]=0.0;
+ Signal_curr[0]=0.0;
+ FunctionParser fParse;
+ fParse.AddConstant("pi", 3.14159265358979323846);
+ fParse.AddConstant("e", 2.71828182845904523536);
+ fParse.Parse(signal,"t");
+ if (fParse.GetParseErrorType()!=FunctionParser::FP_NO_ERROR)
+ {
+ cerr << "Operator::CalcCustomExcitation: Function Parser error: " << fParse.ErrorMsg() << endl;
+ exit(1);
+ }
+ double vars[1];
+ for (unsigned int n=1; n<Length+1; ++n)
+ {
+ vars[0] = (n-1)*dT;
+ Signal_volt[n] = fParse.Eval(vars);
+ vars[0] += 0.5*dT;
+ Signal_curr[n] = fParse.Eval(vars);
+ }
+
+ m_f_max = f0;
+ m_foi = f0;
+ SetNyquistNum( CalcNyquistNum(f0,dT) );
+}
+
+void Excitation::CalcSinusExcitation(double f0, int nTS)
+{
+ if (dT==0) return;
+ if (nTS<=0) return;
+
+ Length = (unsigned int)(2.0/f0/dT);
+ //cerr << "Operator::CalcSinusExcitation: Length of the excite signal: " << Length << " timesteps " << Length*dT << "s" << endl;
+ delete[] Signal_volt;
+ delete[] Signal_curr;
+ Signal_volt = new FDTD_FLOAT[Length+1];
+ Signal_curr = new FDTD_FLOAT[Length+1];
+ Signal_volt[0]=0.0;
+ Signal_curr[0]=0.0;
+ for (unsigned int n=1; n<Length+1; ++n)
+ {
+ double t = (n-1)*dT;
+ Signal_volt[n] = sin(2.0*PI*f0*t);
+ t += 0.5*dT;
+ Signal_curr[n] = sin(2.0*PI*f0*t);
+ }
+ m_f_max = f0;
+ m_foi = f0;
+ SetNyquistNum( CalcNyquistNum(f0,dT) );
+}
+
+void Excitation::DumpVoltageExcite(string filename)
+{
+ ofstream file;
+ file.open( filename.c_str() );
+ if (file.fail())
+ return;
+ for (unsigned int n=1; n<Length+1; ++n)
+ file << (n-1)*dT << "\t" << Signal_volt[n] << "\n";
+ file.close();
+}
+
+void Excitation::DumpCurrentExcite(string filename)
+{
+ ofstream file;
+ file.open( filename.c_str() );
+ if (file.fail())
+ return;
+ for (unsigned int n=1; n<Length+1; ++n)
+ file << (n-1)*dT + 0.5*dT << "\t" << Signal_curr[n] << "\n";
+ file.close();
+}
+
diff --git a/openEMS/FDTD/excitation.h b/openEMS/FDTD/excitation.h
new file mode 100644
index 0000000..8ae3a5b
--- /dev/null
+++ b/openEMS/FDTD/excitation.h
@@ -0,0 +1,115 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef EXCITATION_H
+#define EXCITATION_H
+
+#include <vector>
+#include <string>
+#include "tools/constants.h"
+
+class Excitation
+{
+public:
+ enum ExciteTypes {UNDEFINED=-1, GaissianPulse=0, Sinusoidal=1, DiracPulse=2, Step=3, CustomExcite=10};
+ Excitation();
+ virtual ~Excitation();
+
+ virtual void Reset( double timestep );
+
+ bool SetupGaussianPulse(double f0, double fc);
+ bool SetupSinusoidal(double f0);
+ bool SetupDiracPulse(double fmax);
+ bool SetupStepExcite(double fmax);
+ bool SetupCustomExcite(std::string str, double f0, double fmax);
+
+ double GetCenterFreq() {return m_f0;}
+ double GetCutOffFreq() {return m_fc;}
+ double GetMaxFreq() {return m_f_max;}
+
+ bool buildExcitationSignal(unsigned int maxTS);
+
+ //! Get the excitation timestep with the (first) max amplitude
+ virtual unsigned int GetMaxExcitationTimestep() const;
+
+ void SetNyquistNum(unsigned int nyquist) {m_nyquistTS=nyquist;}
+ unsigned int GetNyquistNum() const {return m_nyquistTS;}
+
+ //! Dump voltage excitation signal to ASCII file
+ void DumpVoltageExcite(std::string filename);
+
+ //! Dump current excitation signal to ASCII file
+ void DumpCurrentExcite(std::string filename);
+
+ //! Get the used timestep
+ double GetTimestep() const {return dT;}
+
+ //! Get the type of excitation
+ int GetExciteType() const {return m_Excit_Type;}
+
+ //! Get the length of the excitation signal
+ unsigned int GetLength() const {return Length;}
+
+ //! Get the max frequeny excited by this signal
+ double GetMaxFrequency() const {return m_f_max;}
+
+ //! Get the frequency of interest
+ double GetFrequencyOfInterest() const {return m_foi;}
+
+ //! Get the signal period, 0 if not a periodical signal
+ double GetSignalPeriod() const {return m_SignalPeriod;}
+
+ FDTD_FLOAT* GetVoltageSignal() const {return Signal_volt;}
+ FDTD_FLOAT* GetCurrentSignal() const {return Signal_curr;}
+
+protected:
+ double dT;
+ unsigned int m_nyquistTS;
+ double m_SignalPeriod;
+ ExciteTypes m_Excit_Type;
+
+ //Excitation time-signal
+ unsigned int Length;
+ FDTD_FLOAT* Signal_volt;
+ FDTD_FLOAT* Signal_curr;
+
+ // center frequency
+ double m_f0;
+
+ // cutoff-frequency (Gaussian pulse only)
+ double m_fc;
+
+ std::string m_CustomExc_Str;
+
+ // max frequency
+ double m_f_max;
+ // frequency of interest
+ double m_foi;
+
+ //! Calculate a custom signal
+ virtual void CalcCustomExcitation(double f0, int nTS, std::string signal);
+ //! Calculate an excitation with center of \a f0 and the half bandwidth \a fc
+ virtual void CalcGaussianPulsExcitation(double f0, double fc, int nTS);
+ //! Calculate a sinusoidal excitation with frequency \a f0 and a duration of \a nTS number of timesteps
+ virtual void CalcSinusExcitation(double f0, int nTS);
+ //! Calculate a dirac impuls excitation
+ virtual void CalcDiracPulsExcitation();
+ //! Calculate a step excitation
+ virtual void CalcStepExcitation();
+};
+
+#endif // EXCITATION_H
diff --git a/openEMS/FDTD/extensions/CMakeLists.txt b/openEMS/FDTD/extensions/CMakeLists.txt
new file mode 100644
index 0000000..3566944
--- /dev/null
+++ b/openEMS/FDTD/extensions/CMakeLists.txt
@@ -0,0 +1,32 @@
+
+#INCLUDE_DIRECTORIES( ${openEMS_SOURCE_DIR} )
+#INCLUDE_DIRECTORIES( ${CSXCAD_SOURCE_DIR}/src )
+
+set(SOURCES
+ ${SOURCES}
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_extension.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_dispersive.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_lorentzmaterial.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_conductingsheet.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_dispersive.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_lorentzmaterial.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_cylindermultigrid.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_upml.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_upml.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_extension.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_mur_abc.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_mur_abc.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_cylinder.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_cylinder.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_excitation.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_excitation.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_tfsf.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_tfsf.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/operator_ext_steadystate.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/engine_ext_steadystate.cpp
+ PARENT_SCOPE
+)
+
+# FDTD/extensions lib
+#add_library( extensions STATIC ${SOURCES} )
+
diff --git a/openEMS/FDTD/extensions/OptimizeCondSheetParameter.m b/openEMS/FDTD/extensions/OptimizeCondSheetParameter.m
new file mode 100644
index 0000000..12ac8ec
--- /dev/null
+++ b/openEMS/FDTD/extensions/OptimizeCondSheetParameter.m
@@ -0,0 +1,107 @@
+function OptimizeCondSheetParameter
+% function OptimizeCondSheetParameter
+%
+% internal openEMS function to create the "cond_sheet_parameter.h" header
+% file containing optimized parameter values for the conducting sheet model
+%
+% (c) 2012: Thorsten Liebig, thorsten.liebig@gmx.de
+
+
+close all
+clear
+clc
+
+
+X = [1 1 1 1 1];
+lb = zeros(size(X));
+ub = ones(size(X))*1000;
+
+
+Omega = linspace(0,20,51);
+Omega = Omega(2:end);
+
+Omega_fine = linspace(0,20,15001);
+Omega_fine = Omega_fine(2:end);
+
+options = optimset('fzero');
+% options = optimset(options,'Display','iter')
+options = optimset(options,'MaxFunEvals',5000);
+options = optimset(options,'MaxIter',5000);
+
+omg_stop_str = [];
+omg_critical_20 = [];
+omg_critical_5 = [];
+g_str = [];
+r1_str= [];
+r2_str= [];
+l1_str= [];
+l2_str= [];
+
+numPara = 30;
+factor = 1.5;
+
+for p = 1:numPara
+
+ X = lsqnonlin(@(X)CalcYDiff(Omega,X),X,lb,ub,options);
+
+ omg_stop_str = [omg_stop_str num2str(Omega(end),10) ','];
+ g_str = [g_str num2str(X(1),10) ','];
+ r1_str = [r1_str num2str(X(2),10) ','];
+ l1_str = [l1_str num2str(X(3),10) ','];
+ r2_str = [r2_str num2str(X(4),10) ','];
+ l2_str = [l2_str num2str(X(5),10) ','];
+
+ Ys = tanh((1+1j)*sqrt(Omega_fine))/(1+1j)./sqrt(Omega_fine);
+
+ err = (CalcYDiff(Omega_fine,X))./real(1./Ys);
+
+ fc = Omega_fine(find(abs(err)>0.2,1,'last'));
+ if (isempty(fc))
+ fc = 0;
+ end
+ omg_critical_20 = [omg_critical_20 num2str(fc,10) ','];
+
+ fc = Omega_fine(find(abs(err)>0.05,1,'last'));
+ if (isempty(fc))
+ fc = 0;
+ end
+ omg_critical_5 = [omg_critical_5 num2str(fc,10) ','];
+
+% disp(['max error: ' num2str(max(abs(err)*100)) ])
+% figure
+% plot(Omega_fine,err*100,'g--');
+
+ Omega_fine = Omega_fine*factor;
+ Omega = Omega*factor;
+end
+
+%% write to file
+fid = fopen('cond_sheet_parameter.h','w');
+
+fprintf(fid,'// This is a list of conducting sheet model parameter for different ranges of omega = w/w0\n');
+fprintf(fid,'// This file was created automatically using Matlab: OptimizeCondSheetParameter.m \n');
+fprintf(fid,'// Do not change this file! \n');
+fprintf(fid,'// Creation: %s \n\n',datestr(now));
+
+
+
+fprintf(fid,'unsigned int numOptPara=%d;\n',numPara);
+
+fprintf(fid,'double omega_stop[%d]={%s};\n',numPara,omg_stop_str(1:end-1));
+fprintf(fid,'double omega_critical_5[%d]={%s};\n',numPara,omg_critical_5(1:end-1));
+fprintf(fid,'double omega_critical_20[%d]={%s};\n',numPara,omg_critical_20(1:end-1));
+fprintf(fid,'double g[%d]={%s};\n',numPara,g_str(1:end-1));
+fprintf(fid,'double r1[%d]={%s};\n',numPara,r1_str(1:end-1));
+fprintf(fid,'double l1[%d]={%s};\n',numPara,l1_str(1:end-1));
+fprintf(fid,'double r2[%d]={%s};\n',numPara,r2_str(1:end-1));
+fprintf(fid,'double l2[%d]={%s};\n',numPara,l2_str(1:end-1));
+
+fclose(fid);
+
+function Ydiff = CalcYDiff(omega, X)
+
+Ys = tanh((1+1j)*sqrt(omega))/(1+1j)./sqrt(omega);
+
+Y = X(1) + 1./(X(2)+1j*omega*X(3)) + 1./(X(4)+1j*omega*X(5));
+
+Ydiff = real(1./Ys)-real(1./Y); \ No newline at end of file
diff --git a/openEMS/FDTD/extensions/cond_sheet_parameter.h b/openEMS/FDTD/extensions/cond_sheet_parameter.h
new file mode 100644
index 0000000..b3fc77b
--- /dev/null
+++ b/openEMS/FDTD/extensions/cond_sheet_parameter.h
@@ -0,0 +1,14 @@
+// This is a list of conducting sheet model parameter for different ranges of omega = w/w0
+// This file was created automatically using Matlab: OptimizeCondSheetParameter.m
+// Do not change this file!
+// Creation: 08-May-2012 09:49:53
+
+unsigned int numOptPara=30;
+double omega_stop[30]={20,30,45,67.5,101.25,151.875,227.8125,341.71875,512.578125,768.8671875,1153.300781,1729.951172,2594.926758,3892.390137,5838.585205,8757.877808,13136.81671,19705.22507,29557.8376,44336.7564,66505.1346,99757.7019,149636.5529,224454.8293,336682.2439,505023.3659,757535.0488,1136302.573,1704453.86,2556680.79};
+double omega_critical_5[30]={0,0,0,1.566,6.8445,10.4085,15.1419375,22.30284375,33.45426562,50.28391406,75.42587109,113.1388066,169.70821,254.5623149,381.8434724,572.7652086,859.1478129,1288.721719,1933.082579,2899.623869,4349.435803,6524.153704,9786.230557,14679.34583,22019.01875,33028.52813,35503.14262,119084.5097,180444.8486,704280.3349};
+double omega_critical_20[30]={0,0,0,0,1.41075,2.7135,4.100625,5.90034375,8.6113125,12.86571094,19.37545312,29.06317969,43.59476953,65.3921543,98.08823145,147.1323472,220.6985208,331.0477811,496.5716717,744.8575075,1117.286261,1675.929392,2513.894088,3770.841132,5656.261698,8484.392547,10504.48601,11363.02573,11135.76522,7499.596983};
+double g[30]={0.1370843401,0.1244327709,0.1087425925,0.09215450299,0.07639249525,0.06239206861,0.05068701937,0.04124161681,0.03364925947,0.0274825647,0.02244156564,0.01832317373,0.01496080786,0.01221545053,0.009973874666,0.008143635713,0.006649251918,0.005429092739,0.00443283702,0.003619397792,0.002955227653,0.002412935361,0.001970156167,0.001608629812,0.001313423397,0.001072422468,0.0009031383439,0.0007674973627,0.0006482579571,0.0005450699565};
+double r1[30]={1.302754546,1.2992612,1.320033314,1.41829213,1.674326257,2.138770494,2.769126112,3.498802047,4.311446869,5.266204065,6.443980095,7.893402541,9.667414736,11.84010502,14.50110421,17.76014698,21.75163911,26.64019322,32.6274156,39.96021835,48.94100192,59.94011376,73.41109983,89.90930992,110.1195785,134.8631576,149.2770459,153.5258961,148.9373215,119.3522908};
+double l1[30]={0.9542567116,0.9412051444,0.8999655165,0.8189903271,0.702028543,0.5718817624,0.4577262324,0.3689027719,0.3004106661,0.2455514861,0.2005633225,0.1637496639,0.1337010005,0.1091664663,0.0891340699,0.07277768839,0.05942276018,0.04851850861,0.03961522618,0.03234573021,0.02641021614,0.02156389712,0.0176069076,0.01437606898,0.0117376269,0.009584103516,0.008750848841,0.008547706786,0.00854127488,0.008801399365};
+double r2[30]={10.62245057,10.21952962,10.24755832,10.99147713,12.70450822,15.59830718,19.55714986,24.32580904,29.88733852,36.55680626,44.75374078,54.81575133,67.13533424,82.22360504,100.7029064,123.3353165,151.0542147,185.0027444,226.5809553,277.5035137,339.8704104,416.2534638,509.8022059,624.3729288,764.7279941,936.5525496,1000,999.9999981,999.999984,999.9999985};
+double l2[30]={0.7925524826,0.6926195458,0.5814718257,0.4784644339,0.3916667501,0.3204661897,0.2620413998,0.2140939121,0.1748272154,0.1427375388,0.1165424396,0.09515681664,0.07769522035,0.06343788358,0.05179681795,0.04229192785,0.03453121766,0.02819462457,0.0230208182,0.01879642336,0.01534721999,0.01253095815,0.01023149158,0.008353988465,0.006820957973,0.005569332359,0.004553963932,0.003696380632,0.002978504727,0.002391295771};
diff --git a/openEMS/FDTD/extensions/engine_ext_cylinder.cpp b/openEMS/FDTD/extensions/engine_ext_cylinder.cpp
new file mode 100644
index 0000000..e240f1b
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_cylinder.cpp
@@ -0,0 +1,101 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "FDTD/engine.h"
+#include "engine_ext_cylinder.h"
+#include "operator_ext_cylinder.h"
+#include "FDTD/engine_sse.h"
+
+Engine_Ext_Cylinder::Engine_Ext_Cylinder(Operator_Ext_Cylinder* op_ext) : Engine_Extension(op_ext)
+{
+ cyl_Op = op_ext;
+ m_Eng_SSE = NULL;
+
+ CC_closedAlpha = op_ext->CC_closedAlpha;
+ CC_R0_included = op_ext->CC_R0_included;
+
+ for (int n=0; n<3; ++n)
+ numLines[n] = op_ext->m_Op->GetNumberOfLines(n,true);
+
+ //this cylindrical extension should be executed first?
+ m_Priority = ENG_EXT_PRIO_CYLINDER;
+}
+
+void Engine_Ext_Cylinder::SetEngine(Engine* eng)
+{
+ Engine_Extension::SetEngine(eng);
+ m_Eng_SSE = dynamic_cast<Engine_sse*>(m_Eng);
+}
+
+void Engine_Ext_Cylinder::DoPostVoltageUpdates()
+{
+ if (CC_closedAlpha==false) return;
+
+ if (CC_R0_included)
+ {
+ unsigned int pos[3];
+ pos[0] = 0;
+ FDTD_FLOAT volt=0;
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ volt =m_Eng_SSE->Engine_sse::GetVolt(2,0,0,pos[2])*cyl_Op->vv_R0[pos[2]];
+ for (pos[1]=0; pos[1]<numLines[1]-1; ++pos[1])
+ volt +=cyl_Op->vi_R0[pos[2]] * m_Eng_SSE->Engine_sse::GetCurr(1,0,pos[1],pos[2]);
+ m_Eng_SSE->Engine_sse::SetVolt(2,0,0,pos[2], volt);
+ }
+
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ m_Eng_SSE->Engine_sse::SetVolt(1,0,pos[1],pos[2], 0); //no voltage in alpha-direction at r=0
+ m_Eng_SSE->Engine_sse::SetVolt(2,0,pos[1],pos[2], m_Eng_SSE->Engine_sse::GetVolt(2,0,0,pos[2]) );
+ }
+ }
+ }
+
+ //close alpha
+ unsigned int pos[3];
+ // copy tangential voltages from last alpha-plane to first
+ unsigned int last_A_Line = numLines[1]-2;
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ m_Eng_SSE->Engine_sse::SetVolt(0,pos[0],0,pos[2], m_Eng_SSE->Engine_sse::GetVolt(0,pos[0],last_A_Line,pos[2]) );
+ m_Eng_SSE->Engine_sse::SetVolt(2,pos[0],0,pos[2], m_Eng_SSE->Engine_sse::GetVolt(2,pos[0],last_A_Line,pos[2]) );
+ }
+ }
+}
+
+void Engine_Ext_Cylinder::DoPostCurrentUpdates()
+{
+ if (CC_closedAlpha==false) return;
+
+ //close alpha
+ unsigned int pos[3];
+ // copy tangential currents from first alpha-plane to last
+ for (pos[0]=0; pos[0]<numLines[0]-1; ++pos[0])
+ {
+ unsigned int last_A_Line = numLines[1]-2;
+ for (pos[2]=0; pos[2]<numLines[2]-1; ++pos[2])
+ {
+ m_Eng_SSE->Engine_sse::SetCurr(0,pos[0],last_A_Line,pos[2], m_Eng_SSE->Engine_sse::GetCurr(0,pos[0],0,pos[2]) );
+ m_Eng_SSE->Engine_sse::SetCurr(2,pos[0],last_A_Line,pos[2], m_Eng_SSE->Engine_sse::GetCurr(2,pos[0],0,pos[2]) );
+ }
+ }
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_cylinder.h b/openEMS/FDTD/extensions/engine_ext_cylinder.h
new file mode 100644
index 0000000..c996a9d
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_cylinder.h
@@ -0,0 +1,49 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_CYLINDER_H
+#define ENGINE_CYLINDER_H
+
+#include "FDTD/engine.h"
+#include "engine_extension.h"
+#include "FDTD/operator_cylinder.h"
+
+class Operator_Ext_Cylinder;
+class Engine_sse;
+
+class Engine_Ext_Cylinder : public Engine_Extension
+{
+public:
+ Engine_Ext_Cylinder(Operator_Ext_Cylinder* op_ext);
+
+ virtual void DoPostVoltageUpdates();
+
+ virtual void DoPostCurrentUpdates();
+
+ virtual void SetEngine(Engine* eng);
+
+protected:
+ Operator_Ext_Cylinder* cyl_Op;
+ Engine_sse* m_Eng_SSE;
+
+ unsigned int numLines[3];
+
+ bool CC_closedAlpha;
+ bool CC_R0_included;
+};
+
+#endif // ENGINE_CYLINDER_H
diff --git a/openEMS/FDTD/extensions/engine_ext_cylindermultigrid.cpp b/openEMS/FDTD/extensions/engine_ext_cylindermultigrid.cpp
new file mode 100644
index 0000000..eca2c9e
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_cylindermultigrid.cpp
@@ -0,0 +1,165 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "FDTD/engine.h"
+#include "engine_ext_cylindermultigrid.h"
+#include "FDTD/engine_cylindermultigrid.h"
+
+Engine_Ext_CylinderMultiGrid::Engine_Ext_CylinderMultiGrid(Operator_Extension* op_ext, bool isBase) : Engine_Extension(op_ext)
+{
+ m_IsBase = isBase;
+ m_Eng_MG = NULL;
+
+ // the multi-grid should be applies last?
+ m_Priority = ENG_EXT_PRIO_CYLINDERMULTIGRID;
+}
+
+Engine_Ext_CylinderMultiGrid::~Engine_Ext_CylinderMultiGrid()
+{
+}
+
+void Engine_Ext_CylinderMultiGrid::SetBarrier(boost::barrier* waitBase, boost::barrier* waitChild, boost::barrier* waitSync)
+{
+ m_WaitOnBase = waitBase;
+ m_WaitOnChild = waitChild;
+ m_WaitOnSync = waitSync;
+}
+
+void Engine_Ext_CylinderMultiGrid::SetEngine(Engine* eng)
+{
+ m_Eng_MG = dynamic_cast<Engine_CylinderMultiGrid*>(eng);
+ if (m_Eng_MG==NULL)
+ {
+ cerr << "Engine_Ext_CylinderMultiGrid::SetEngine(): Error" << endl;
+ exit(0);
+ }
+}
+
+void Engine_Ext_CylinderMultiGrid::DoPreVoltageUpdates()
+{
+ //cerr << "Engine_Ext_CylinderMultiGrid::DoPreVoltageUpdates() for " << m_IsBase << endl;
+ if (!m_IsBase)
+ {
+ //cerr << "child: volt wait on base " << endl;
+ m_WaitOnBase->wait(); //wait on base to finisch current sync and/or to finisch voltage updates, than start child voltage updates
+ }
+}
+
+void Engine_Ext_CylinderMultiGrid::DoPostVoltageUpdates()
+{
+
+}
+
+void Engine_Ext_CylinderMultiGrid::Apply2Voltages()
+{
+ if (m_IsBase)
+ {
+ m_WaitOnBase->wait(); //base voltage updates are done, tell child to start its voltage updates
+ m_WaitOnChild->wait(); //wait for child to finisch its updates
+ SyncVoltages(); //child is finisch, run sync and go to current updates next
+ m_WaitOnSync->wait(); //sync is done... move on and tell child to move on...
+ }
+ else
+ {
+ m_WaitOnChild->wait(); //child is finished voltage updates, will tell base to run sync
+ m_WaitOnSync->wait(); //wait for base to finisch sync before going to wait for current updates
+ }
+}
+
+void Engine_Ext_CylinderMultiGrid::SyncVoltages()
+{
+ if (m_Eng_MG==NULL)
+ {
+ cerr << "Engine_Ext_CylinderMultiGrid::SyncVoltages: Error engine is NULL" << endl;
+ return;
+ }
+
+ unsigned int* numLines = m_Eng_MG->numLines;
+
+ Engine_Multithread* m_InnerEng = m_Eng_MG->m_InnerEngine;
+
+ //interpolate voltages from base engine to child engine...
+ unsigned int pos[3];
+ pos[0] = m_Eng_MG->Op_CMG->GetSplitPos()-1;
+ unsigned int pos1_half = 0;
+ f4vector v_null;
+ v_null.f[0] = 0;
+ v_null.f[1] = 0;
+ v_null.f[2] = 0;
+ v_null.f[3] = 0;
+ for (pos[1]=0; pos[1]<numLines[1]-1; pos[1]+=2)
+ {
+ pos1_half = pos[1]/2;
+ for (pos[2]=0; pos[2]<m_Eng_MG->numVectors; ++pos[2])
+ {
+ //r - direczion
+ m_InnerEng->f4_volt[0][pos[0]][pos1_half][pos[2]].v = v_null.v;
+
+ //z - direction
+ m_InnerEng->f4_volt[2][pos[0]][pos1_half][pos[2]].v = m_Eng_MG->f4_volt[2][pos[0]][pos[1]][pos[2]].v;
+
+ //alpha - direction
+ m_InnerEng->f4_volt[1][pos[0]][pos1_half][pos[2]].v = m_Eng_MG->f4_volt[1][pos[0]][pos[1]][pos[2]].v;
+ m_InnerEng->f4_volt[1][pos[0]][pos1_half][pos[2]].v += m_Eng_MG->f4_volt[1][pos[0]][pos[1]+1][pos[2]].v;
+ }
+ }
+}
+
+void Engine_Ext_CylinderMultiGrid::DoPreCurrentUpdates()
+{
+ //cerr << "Engine_Ext_CylinderMultiGrid::DoPreCurrentUpdates() for " << m_IsBase << endl;
+ if (!m_IsBase)
+ {
+ //cerr << "child: curr wait on base " << endl;
+ m_WaitOnBase->wait(); //wait on base to finisch voltage sync and current updates, than start child current updates
+ }
+}
+
+void Engine_Ext_CylinderMultiGrid::DoPostCurrentUpdates()
+{
+
+}
+
+void Engine_Ext_CylinderMultiGrid::Apply2Current()
+{
+ if (m_IsBase)
+ {
+ //cerr << "Base: curr wait on base done, wait on sync" << endl;
+ m_WaitOnBase->wait(); //base current updates are done, tell child to start its current updates
+ m_WaitOnChild->wait(); //wait for child to finisch its updates
+ SyncCurrents(); //child is finisch, run sync and go to voltage updates next
+ m_WaitOnSync->wait(); //sync is done... move on and tell child to move on...
+ }
+ else
+ {
+ m_WaitOnChild->wait(); //child is finished current updates, will tell base to run sync...
+ m_WaitOnSync->wait(); //wait for base to finisch sync before going to wait for next voltage updates
+ //cerr << "Child: curr done, wait on sync" << endl;
+ }
+}
+
+void Engine_Ext_CylinderMultiGrid::SyncCurrents()
+{
+ if (m_Eng_MG==NULL)
+ {
+ cerr << "Engine_Ext_CylinderMultiGrid::SyncCurrents: Error engine is NULL" << endl;
+ return;
+ }
+
+ m_Eng_MG->InterpolCurrChild2Base(m_Eng_MG->Op_CMG->GetSplitPos()-2);
+ return;
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_cylindermultigrid.h b/openEMS/FDTD/extensions/engine_ext_cylindermultigrid.h
new file mode 100644
index 0000000..e9226f5
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_cylindermultigrid.h
@@ -0,0 +1,58 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_CYLINDERMULTIGRID_H
+#define ENGINE_EXT_CYLINDERMULTIGRID_H
+
+#include "FDTD/engine_cylindermultigrid.h"
+#include "engine_extension.h"
+#include "FDTD/operator_cylindermultigrid.h"
+
+class Operator_Ext_CylinderMultiGrid;
+
+class Engine_Ext_CylinderMultiGrid : public Engine_Extension
+{
+public:
+ Engine_Ext_CylinderMultiGrid(Operator_Extension* op_ext, bool isBase);
+ virtual ~Engine_Ext_CylinderMultiGrid();
+
+ void SetBarrier(boost::barrier* waitBase, boost::barrier* waitChild, boost::barrier* waitSync);
+
+ virtual void DoPreVoltageUpdates();
+ virtual void DoPostVoltageUpdates();
+ virtual void Apply2Voltages();
+
+ virtual void DoPreCurrentUpdates();
+ virtual void DoPostCurrentUpdates();
+ virtual void Apply2Current();
+
+ virtual void SetEngine(Engine* eng);
+
+protected:
+ void SyncVoltages();
+ void SyncCurrents();
+
+ Engine_CylinderMultiGrid* m_Eng_MG;
+
+ boost::barrier *m_WaitOnBase;
+ boost::barrier *m_WaitOnChild;
+ boost::barrier *m_WaitOnSync;
+
+ bool m_IsBase;
+};
+
+#endif // ENGINE_EXT_CYLINDERMULTIGRID_H
diff --git a/openEMS/FDTD/extensions/engine_ext_dispersive.cpp b/openEMS/FDTD/extensions/engine_ext_dispersive.cpp
new file mode 100644
index 0000000..d9c431b
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_dispersive.cpp
@@ -0,0 +1,162 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_dispersive.h"
+#include "operator_ext_dispersive.h"
+#include "FDTD/engine_sse.h"
+
+Engine_Ext_Dispersive::Engine_Ext_Dispersive(Operator_Ext_Dispersive* op_ext_disp) : Engine_Extension(op_ext_disp)
+{
+ m_Op_Ext_Disp = op_ext_disp;
+ int order = m_Op_Ext_Disp->m_Order;
+ curr_ADE = new FDTD_FLOAT**[order];
+ volt_ADE = new FDTD_FLOAT**[order];
+ for (int o=0;o<order;++o)
+ {
+ curr_ADE[o] = new FDTD_FLOAT*[3];
+ volt_ADE[o] = new FDTD_FLOAT*[3];
+ for (int n=0; n<3; ++n)
+ {
+ if (m_Op_Ext_Disp->m_curr_ADE_On[o]==true)
+ {
+ curr_ADE[o][n] = new FDTD_FLOAT[m_Op_Ext_Disp->m_LM_Count[o]];
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count[o]; ++i)
+ curr_ADE[o][n][i]=0.0;
+ }
+ else
+ curr_ADE[o][n] = NULL;
+ if (m_Op_Ext_Disp->m_volt_ADE_On[o]==true)
+ {
+ volt_ADE[o][n] = new FDTD_FLOAT[m_Op_Ext_Disp->m_LM_Count[o]];
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count[o]; ++i)
+ volt_ADE[o][n][i]=0.0;
+ }
+ else
+ volt_ADE[o][n] = NULL;
+ }
+ }
+}
+
+Engine_Ext_Dispersive::~Engine_Ext_Dispersive()
+{
+ if (curr_ADE==NULL && volt_ADE==NULL)
+ return;
+
+ for (int o=0;o<m_Op_Ext_Disp->m_Order;++o)
+ {
+ for (int n=0; n<3; ++n)
+ {
+ delete[] curr_ADE[o][n];
+ delete[] volt_ADE[o][n];
+ }
+ delete[] curr_ADE[o];
+ delete[] volt_ADE[o];
+ }
+ delete[] curr_ADE;
+ curr_ADE=NULL;
+
+ delete[] volt_ADE;
+ volt_ADE=NULL;
+}
+
+void Engine_Ext_Dispersive::Apply2Voltages()
+{
+ for (int o=0;o<m_Op_Ext_Disp->m_Order;++o)
+ {
+ if (m_Op_Ext_Disp->m_volt_ADE_On[o]==false) continue;
+
+ unsigned int **pos = m_Op_Ext_Disp->m_LM_pos[o];
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count.at(o); ++i)
+ {
+ m_Eng->Engine::SetVolt(0,pos[0][i],pos[1][i],pos[2][i], m_Eng->Engine::GetVolt(0,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][0][i]);
+ m_Eng->Engine::SetVolt(1,pos[0][i],pos[1][i],pos[2][i], m_Eng->Engine::GetVolt(1,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][1][i]);
+ m_Eng->Engine::SetVolt(2,pos[0][i],pos[1][i],pos[2][i], m_Eng->Engine::GetVolt(2,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][2][i]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*)m_Eng;
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count.at(o); ++i)
+ {
+ eng_sse->Engine_sse::SetVolt(0,pos[0][i],pos[1][i],pos[2][i], eng_sse->Engine_sse::GetVolt(0,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][0][i]);
+ eng_sse->Engine_sse::SetVolt(1,pos[0][i],pos[1][i],pos[2][i], eng_sse->Engine_sse::GetVolt(1,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][1][i]);
+ eng_sse->Engine_sse::SetVolt(2,pos[0][i],pos[1][i],pos[2][i], eng_sse->Engine_sse::GetVolt(2,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][2][i]);
+ }
+ break;
+ }
+ default:
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count.at(o); ++i)
+ {
+ m_Eng->SetVolt(0,pos[0][i],pos[1][i],pos[2][i], m_Eng->GetVolt(0,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][0][i]);
+ m_Eng->SetVolt(1,pos[0][i],pos[1][i],pos[2][i], m_Eng->GetVolt(1,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][1][i]);
+ m_Eng->SetVolt(2,pos[0][i],pos[1][i],pos[2][i], m_Eng->GetVolt(2,pos[0][i],pos[1][i],pos[2][i]) - volt_ADE[o][2][i]);
+ }
+ break;
+ }
+ }
+}
+
+void Engine_Ext_Dispersive::Apply2Current()
+{
+ for (int o=0;o<m_Op_Ext_Disp->m_Order;++o)
+ {
+ if (m_Op_Ext_Disp->m_curr_ADE_On[o]==false) continue;
+
+ unsigned int **pos = m_Op_Ext_Disp->m_LM_pos[o];
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count.at(o); ++i)
+ {
+ m_Eng->Engine::SetCurr(0,pos[0][i],pos[1][i],pos[2][i], m_Eng->Engine::GetCurr(0,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][0][i]);
+ m_Eng->Engine::SetCurr(1,pos[0][i],pos[1][i],pos[2][i], m_Eng->Engine::GetCurr(1,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][1][i]);
+ m_Eng->Engine::SetCurr(2,pos[0][i],pos[1][i],pos[2][i], m_Eng->Engine::GetCurr(2,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][2][i]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*)m_Eng;
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count.at(o); ++i)
+ {
+ eng_sse->Engine_sse::SetCurr(0,pos[0][i],pos[1][i],pos[2][i], eng_sse->Engine_sse::GetCurr(0,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][0][i]);
+ eng_sse->Engine_sse::SetCurr(1,pos[0][i],pos[1][i],pos[2][i], eng_sse->Engine_sse::GetCurr(1,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][1][i]);
+ eng_sse->Engine_sse::SetCurr(2,pos[0][i],pos[1][i],pos[2][i], eng_sse->Engine_sse::GetCurr(2,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][2][i]);
+ }
+ break;
+ }
+ default:
+ for (unsigned int i=0; i<m_Op_Ext_Disp->m_LM_Count.at(o); ++i)
+ {
+ m_Eng->SetCurr(0,pos[0][i],pos[1][i],pos[2][i], m_Eng->GetCurr(0,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][0][i]);
+ m_Eng->SetCurr(1,pos[0][i],pos[1][i],pos[2][i], m_Eng->GetCurr(1,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][1][i]);
+ m_Eng->SetCurr(2,pos[0][i],pos[1][i],pos[2][i], m_Eng->GetCurr(2,pos[0][i],pos[1][i],pos[2][i]) - curr_ADE[o][2][i]);
+ }
+ break;
+ }
+ }
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_dispersive.h b/openEMS/FDTD/extensions/engine_ext_dispersive.h
new file mode 100644
index 0000000..c1b84ea
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_dispersive.h
@@ -0,0 +1,51 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_DISPERSIVE_H
+#define ENGINE_EXT_DISPERSIVE_H
+
+#include "engine_extension.h"
+#include "FDTD/engine.h"
+#include "FDTD/operator.h"
+
+class Operator_Ext_Dispersive;
+
+class Engine_Ext_Dispersive : public Engine_Extension
+{
+public:
+ Engine_Ext_Dispersive(Operator_Ext_Dispersive* op_ext_disp);
+ virtual ~Engine_Ext_Dispersive();
+
+ virtual void Apply2Voltages();
+ virtual void Apply2Current();
+
+protected:
+ Operator_Ext_Dispersive* m_Op_Ext_Disp;
+
+ //! Dispersive order
+ int m_Order;
+
+ //! ADE currents
+ // Array setup: curr_ADE[N_order][direction][mesh_pos]
+ FDTD_FLOAT ***curr_ADE;
+
+ //! ADE voltages
+ // Array setup: volt_ADE[N_order][direction][mesh_pos]
+ FDTD_FLOAT ***volt_ADE;
+};
+
+#endif // ENGINE_EXT_DISPERSIVE_H
diff --git a/openEMS/FDTD/extensions/engine_ext_excitation.cpp b/openEMS/FDTD/extensions/engine_ext_excitation.cpp
new file mode 100644
index 0000000..b5bd8bd
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_excitation.cpp
@@ -0,0 +1,170 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_excitation.h"
+#include "operator_ext_excitation.h"
+#include "FDTD/engine_sse.h"
+
+Engine_Ext_Excitation::Engine_Ext_Excitation(Operator_Ext_Excitation* op_ext) : Engine_Extension(op_ext)
+{
+ m_Op_Exc = op_ext;
+ m_Priority = ENG_EXT_PRIO_EXCITATION;
+}
+
+Engine_Ext_Excitation::~Engine_Ext_Excitation()
+{
+
+}
+
+void Engine_Ext_Excitation::Apply2Voltages()
+{
+ //soft voltage excitation here (E-field excite)
+ int exc_pos;
+ unsigned int ny;
+ unsigned int pos[3];
+ int numTS = m_Eng->GetNumberOfTimesteps();
+ unsigned int length = m_Op_Exc->m_Exc->GetLength();
+ FDTD_FLOAT* exc_volt = m_Op_Exc->m_Exc->GetVoltageSignal();
+
+ int p = numTS+1;
+ if (m_Op_Exc->m_Exc->GetSignalPeriod()>0)
+ p = int(m_Op_Exc->m_Exc->GetSignalPeriod()/m_Op_Exc->m_Exc->GetTimestep());
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int n=0; n<m_Op_Exc->Volt_Count; ++n)
+ {
+ exc_pos = numTS - (int)m_Op_Exc->Volt_delay[n];
+ exc_pos *= (exc_pos>0);
+ exc_pos %= p;
+ exc_pos *= (exc_pos<=(int)length);
+ ny = m_Op_Exc->Volt_dir[n];
+ pos[0]=m_Op_Exc->Volt_index[0][n];
+ pos[1]=m_Op_Exc->Volt_index[1][n];
+ pos[2]=m_Op_Exc->Volt_index[2][n];
+ m_Eng->Engine::SetVolt(ny,pos, m_Eng->Engine::GetVolt(ny,pos) + m_Op_Exc->Volt_amp[n]*exc_volt[exc_pos]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ for (unsigned int n=0; n<m_Op_Exc->Volt_Count; ++n)
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ exc_pos = numTS - (int)m_Op_Exc->Volt_delay[n];
+ exc_pos *= (exc_pos>0);
+ exc_pos %= p;
+ exc_pos *= (exc_pos<=(int)length);
+ ny = m_Op_Exc->Volt_dir[n];
+ pos[0]=m_Op_Exc->Volt_index[0][n];
+ pos[1]=m_Op_Exc->Volt_index[1][n];
+ pos[2]=m_Op_Exc->Volt_index[2][n];
+ eng_sse->Engine_sse::SetVolt(ny,pos, eng_sse->Engine_sse::GetVolt(ny,pos) + m_Op_Exc->Volt_amp[n]*exc_volt[exc_pos]);
+ }
+ break;
+ }
+ default:
+ {
+ for (unsigned int n=0; n<m_Op_Exc->Volt_Count; ++n)
+ {
+ exc_pos = numTS - (int)m_Op_Exc->Volt_delay[n];
+ exc_pos *= (exc_pos>0);
+ exc_pos %= p;
+ exc_pos *= (exc_pos<=(int)length);
+ ny = m_Op_Exc->Volt_dir[n];
+ pos[0]=m_Op_Exc->Volt_index[0][n];
+ pos[1]=m_Op_Exc->Volt_index[1][n];
+ pos[2]=m_Op_Exc->Volt_index[2][n];
+ m_Eng->SetVolt(ny,pos, m_Eng->GetVolt(ny,pos) + m_Op_Exc->Volt_amp[n]*exc_volt[exc_pos]);
+ }
+ break;
+ }
+ }
+}
+
+void Engine_Ext_Excitation::Apply2Current()
+{
+ //soft current excitation here (H-field excite)
+
+ int exc_pos;
+ unsigned int ny;
+ unsigned int pos[3];
+ int numTS = m_Eng->GetNumberOfTimesteps();
+ unsigned int length = m_Op_Exc->m_Exc->GetLength();
+ FDTD_FLOAT* exc_curr = m_Op_Exc->m_Exc->GetCurrentSignal();
+
+ int p = numTS+1;
+ if (m_Op_Exc->m_Exc->GetSignalPeriod()>0)
+ p = int(m_Op_Exc->m_Exc->GetSignalPeriod()/m_Op_Exc->m_Exc->GetTimestep());
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int n=0; n<m_Op_Exc->Curr_Count; ++n)
+ {
+ exc_pos = numTS - (int)m_Op_Exc->Curr_delay[n];
+ exc_pos *= (exc_pos>0);
+ exc_pos %= p;
+ exc_pos *= (exc_pos<=(int)length);
+ ny = m_Op_Exc->Curr_dir[n];
+ pos[0]=m_Op_Exc->Curr_index[0][n];
+ pos[1]=m_Op_Exc->Curr_index[1][n];
+ pos[2]=m_Op_Exc->Curr_index[2][n];
+ m_Eng->Engine::SetCurr(ny,pos, m_Eng->Engine::GetCurr(ny,pos) + m_Op_Exc->Curr_amp[n]*exc_curr[exc_pos]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ for (unsigned int n=0; n<m_Op_Exc->Curr_Count; ++n)
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ exc_pos = numTS - (int)m_Op_Exc->Curr_delay[n];
+ exc_pos *= (exc_pos>0);
+ exc_pos %= p;
+ exc_pos *= (exc_pos<=(int)length);
+ ny = m_Op_Exc->Curr_dir[n];
+ pos[0]=m_Op_Exc->Curr_index[0][n];
+ pos[1]=m_Op_Exc->Curr_index[1][n];
+ pos[2]=m_Op_Exc->Curr_index[2][n];
+ eng_sse->Engine_sse::SetCurr(ny,pos, eng_sse->Engine_sse::GetCurr(ny,pos) + m_Op_Exc->Curr_amp[n]*exc_curr[exc_pos]);
+ }
+ break;
+ }
+ default:
+ {
+ for (unsigned int n=0; n<m_Op_Exc->Curr_Count; ++n)
+ {
+ exc_pos = numTS - (int)m_Op_Exc->Curr_delay[n];
+ exc_pos *= (exc_pos>0);
+ exc_pos %= p;
+ exc_pos *= (exc_pos<=(int)length);
+ ny = m_Op_Exc->Curr_dir[n];
+ pos[0]=m_Op_Exc->Curr_index[0][n];
+ pos[1]=m_Op_Exc->Curr_index[1][n];
+ pos[2]=m_Op_Exc->Curr_index[2][n];
+ m_Eng->SetCurr(ny,pos, m_Eng->GetCurr(ny,pos) + m_Op_Exc->Curr_amp[n]*exc_curr[exc_pos]);
+ }
+ break;
+ }
+ }
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_excitation.h b/openEMS/FDTD/extensions/engine_ext_excitation.h
new file mode 100644
index 0000000..aae58a0
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_excitation.h
@@ -0,0 +1,40 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_EXCITATION_H
+#define ENGINE_EXT_EXCITATION_H
+
+#include "engine_extension.h"
+#include "FDTD/engine.h"
+#include "FDTD/operator.h"
+
+class Operator_Ext_Excitation;
+
+class Engine_Ext_Excitation : public Engine_Extension
+{
+public:
+ Engine_Ext_Excitation(Operator_Ext_Excitation* op_ext);
+ virtual ~Engine_Ext_Excitation();
+
+ virtual void Apply2Voltages();
+ virtual void Apply2Current();
+
+protected:
+ Operator_Ext_Excitation* m_Op_Exc;
+};
+
+#endif // ENGINE_EXT_EXCITATION_H
diff --git a/openEMS/FDTD/extensions/engine_ext_lorentzmaterial.cpp b/openEMS/FDTD/extensions/engine_ext_lorentzmaterial.cpp
new file mode 100644
index 0000000..9aaa1ff
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_lorentzmaterial.cpp
@@ -0,0 +1,322 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_lorentzmaterial.h"
+#include "operator_ext_lorentzmaterial.h"
+#include "FDTD/engine_sse.h"
+
+Engine_Ext_LorentzMaterial::Engine_Ext_LorentzMaterial(Operator_Ext_LorentzMaterial* op_ext_lorentz) : Engine_Ext_Dispersive(op_ext_lorentz)
+{
+ m_Op_Ext_Lor = op_ext_lorentz;
+ m_Order = m_Op_Ext_Lor->GetDispersionOrder();
+ int order = m_Op_Ext_Lor->m_Order;
+
+ curr_Lor_ADE = new FDTD_FLOAT**[order];
+ volt_Lor_ADE = new FDTD_FLOAT**[order];
+ for (int o=0;o<order;++o)
+ {
+ curr_Lor_ADE[o] = new FDTD_FLOAT*[3];
+ volt_Lor_ADE[o] = new FDTD_FLOAT*[3];
+ for (int n=0; n<3; ++n)
+ {
+ if (m_Op_Ext_Lor->m_curr_Lor_ADE_On[o]==true)
+ {
+ curr_Lor_ADE[o][n] = new FDTD_FLOAT[m_Op_Ext_Lor->m_LM_Count[o]];
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count[o]; ++i)
+ curr_Lor_ADE[o][n][i]=0.0;
+ }
+ else
+ curr_Lor_ADE[o][n] = NULL;
+
+ if (m_Op_Ext_Lor->m_volt_Lor_ADE_On[o]==true)
+ {
+ volt_Lor_ADE[o][n] = new FDTD_FLOAT[m_Op_Ext_Lor->m_LM_Count[o]];
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count[o]; ++i)
+ volt_Lor_ADE[o][n][i]=0.0;
+ }
+ else
+ volt_Lor_ADE[o][n] = NULL;
+ }
+ }
+}
+
+Engine_Ext_LorentzMaterial::~Engine_Ext_LorentzMaterial()
+{
+ if (curr_Lor_ADE==NULL && volt_Lor_ADE==NULL)
+ return;
+
+ for (int o=0;o<m_Op_Ext_Lor->m_Order;++o)
+ {
+ for (int n=0; n<3; ++n)
+ {
+ delete[] curr_Lor_ADE[o][n];
+ delete[] volt_Lor_ADE[o][n];
+ }
+ delete[] curr_Lor_ADE[o];
+ delete[] volt_Lor_ADE[o];
+ }
+ delete[] curr_Lor_ADE;
+ curr_Lor_ADE=NULL;
+
+ delete[] volt_Lor_ADE;
+ volt_Lor_ADE=NULL;
+}
+
+void Engine_Ext_LorentzMaterial::DoPreVoltageUpdates()
+{
+ for (int o=0;o<m_Order;++o)
+ {
+ if (m_Op_Ext_Lor->m_volt_ADE_On[o]==false) continue;
+
+ unsigned int **pos = m_Op_Ext_Lor->m_LM_pos[o];
+
+ if (m_Op_Ext_Lor->m_volt_Lor_ADE_On[o])
+ {
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ volt_Lor_ADE[o][0][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][0][i]*volt_ADE[o][0][i];
+ volt_ADE[o][0][i] *= m_Op_Ext_Lor->v_int_ADE[o][0][i];
+ volt_ADE[o][0][i] += m_Op_Ext_Lor->v_ext_ADE[o][0][i] * (m_Eng->Engine::GetVolt(0,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][0][i]);
+
+ volt_Lor_ADE[o][1][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][1][i]*volt_ADE[o][1][i];
+ volt_ADE[o][1][i] *= m_Op_Ext_Lor->v_int_ADE[o][1][i];
+ volt_ADE[o][1][i] += m_Op_Ext_Lor->v_ext_ADE[o][1][i] * (m_Eng->Engine::GetVolt(1,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][2][i]);
+
+ volt_Lor_ADE[o][2][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][2][i]*volt_ADE[o][2][i];
+ volt_ADE[o][2][i] *= m_Op_Ext_Lor->v_int_ADE[o][2][i];
+ volt_ADE[o][2][i] += m_Op_Ext_Lor->v_ext_ADE[o][2][i] * (m_Eng->Engine::GetVolt(2,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][2][i]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*)m_Eng;
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ volt_Lor_ADE[o][0][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][0][i]*volt_ADE[o][0][i];
+ volt_ADE[o][0][i] *= m_Op_Ext_Lor->v_int_ADE[o][0][i];
+ volt_ADE[o][0][i] += m_Op_Ext_Lor->v_ext_ADE[o][0][i] * (eng_sse->Engine_sse::GetVolt(0,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][0][i]);
+
+ volt_Lor_ADE[o][1][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][1][i]*volt_ADE[o][1][i];
+ volt_ADE[o][1][i] *= m_Op_Ext_Lor->v_int_ADE[o][1][i];
+ volt_ADE[o][1][i] += m_Op_Ext_Lor->v_ext_ADE[o][1][i] * (eng_sse->Engine_sse::GetVolt(1,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][1][i]);
+
+ volt_Lor_ADE[o][2][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][2][i]*volt_ADE[o][2][i];
+ volt_ADE[o][2][i] *= m_Op_Ext_Lor->v_int_ADE[o][2][i];
+ volt_ADE[o][2][i] += m_Op_Ext_Lor->v_ext_ADE[o][2][i] * (eng_sse->Engine_sse::GetVolt(2,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][2][i]);
+ }
+ break;
+ }
+ default:
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ volt_Lor_ADE[o][0][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][0][i]*volt_ADE[o][0][i];
+ volt_ADE[o][0][i] *= m_Op_Ext_Lor->v_int_ADE[o][0][i];
+ volt_ADE[o][0][i] += m_Op_Ext_Lor->v_ext_ADE[o][0][i] * (m_Eng->GetVolt(0,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][0][i]);
+
+ volt_Lor_ADE[o][1][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][1][i]*volt_ADE[o][1][i];
+ volt_ADE[o][1][i] *= m_Op_Ext_Lor->v_int_ADE[o][1][i];
+ volt_ADE[o][1][i] += m_Op_Ext_Lor->v_ext_ADE[o][1][i] * (m_Eng->GetVolt(1,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][1][i]);
+
+ volt_Lor_ADE[o][2][i]+=m_Op_Ext_Lor->v_Lor_ADE[o][2][i]*volt_ADE[o][2][i];
+ volt_ADE[o][2][i] *= m_Op_Ext_Lor->v_int_ADE[o][2][i];
+ volt_ADE[o][2][i] += m_Op_Ext_Lor->v_ext_ADE[o][2][i] * (m_Eng->GetVolt(2,pos[0][i],pos[1][i],pos[2][i])-volt_Lor_ADE[o][2][i]);
+ }
+ break;
+ }
+ }
+ else
+ {
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ volt_ADE[o][0][i] *= m_Op_Ext_Lor->v_int_ADE[o][0][i];
+ volt_ADE[o][0][i] += m_Op_Ext_Lor->v_ext_ADE[o][0][i] * m_Eng->Engine::GetVolt(0,pos[0][i],pos[1][i],pos[2][i]);
+
+ volt_ADE[o][1][i] *= m_Op_Ext_Lor->v_int_ADE[o][1][i];
+ volt_ADE[o][1][i] += m_Op_Ext_Lor->v_ext_ADE[o][1][i] * m_Eng->Engine::GetVolt(1,pos[0][i],pos[1][i],pos[2][i]);
+
+ volt_ADE[o][2][i] *= m_Op_Ext_Lor->v_int_ADE[o][2][i];
+ volt_ADE[o][2][i] += m_Op_Ext_Lor->v_ext_ADE[o][2][i] * m_Eng->Engine::GetVolt(2,pos[0][i],pos[1][i],pos[2][i]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*)m_Eng;
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ volt_ADE[o][0][i] *= m_Op_Ext_Lor->v_int_ADE[o][0][i];
+ volt_ADE[o][0][i] += m_Op_Ext_Lor->v_ext_ADE[o][0][i] * eng_sse->Engine_sse::GetVolt(0,pos[0][i],pos[1][i],pos[2][i]);
+
+ volt_ADE[o][1][i] *= m_Op_Ext_Lor->v_int_ADE[o][1][i];
+ volt_ADE[o][1][i] += m_Op_Ext_Lor->v_ext_ADE[o][1][i] * eng_sse->Engine_sse::GetVolt(1,pos[0][i],pos[1][i],pos[2][i]);
+
+ volt_ADE[o][2][i] *= m_Op_Ext_Lor->v_int_ADE[o][2][i];
+ volt_ADE[o][2][i] += m_Op_Ext_Lor->v_ext_ADE[o][2][i] * eng_sse->Engine_sse::GetVolt(2,pos[0][i],pos[1][i],pos[2][i]);
+ }
+ break;
+ }
+ default:
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ volt_ADE[o][0][i] *= m_Op_Ext_Lor->v_int_ADE[o][0][i];
+ volt_ADE[o][0][i] += m_Op_Ext_Lor->v_ext_ADE[o][0][i] * m_Eng->GetVolt(0,pos[0][i],pos[1][i],pos[2][i]);
+
+ volt_ADE[o][1][i] *= m_Op_Ext_Lor->v_int_ADE[o][1][i];
+ volt_ADE[o][1][i] += m_Op_Ext_Lor->v_ext_ADE[o][1][i] * m_Eng->GetVolt(1,pos[0][i],pos[1][i],pos[2][i]);
+
+ volt_ADE[o][2][i] *= m_Op_Ext_Lor->v_int_ADE[o][2][i];
+ volt_ADE[o][2][i] += m_Op_Ext_Lor->v_ext_ADE[o][2][i] * m_Eng->GetVolt(2,pos[0][i],pos[1][i],pos[2][i]);
+ }
+ break;
+ }
+ }
+ }
+}
+
+void Engine_Ext_LorentzMaterial::DoPreCurrentUpdates()
+{
+ for (int o=0;o<m_Order;++o)
+ {
+ if (m_Op_Ext_Lor->m_curr_ADE_On[o]==false) continue;
+
+ unsigned int **pos = m_Op_Ext_Lor->m_LM_pos[o];
+
+ if (m_Op_Ext_Lor->m_curr_Lor_ADE_On[o])
+ {
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ curr_Lor_ADE[o][0][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][0][i]*curr_ADE[o][0][i];
+ curr_ADE[o][0][i] *= m_Op_Ext_Lor->i_int_ADE[o][0][i];
+ curr_ADE[o][0][i] += m_Op_Ext_Lor->i_ext_ADE[o][0][i] * (m_Eng->Engine::GetCurr(0,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][0][i]);
+
+ curr_Lor_ADE[o][1][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][1][i]*curr_ADE[o][1][i];
+ curr_ADE[o][1][i] *= m_Op_Ext_Lor->i_int_ADE[o][1][i];
+ curr_ADE[o][1][i] += m_Op_Ext_Lor->i_ext_ADE[o][1][i] * (m_Eng->Engine::GetCurr(1,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][1][i]);
+
+ curr_Lor_ADE[o][2][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][2][i]*curr_ADE[o][2][i];
+ curr_ADE[o][2][i] *= m_Op_Ext_Lor->i_int_ADE[o][2][i];
+ curr_ADE[o][2][i] += m_Op_Ext_Lor->i_ext_ADE[o][2][i] * (m_Eng->Engine::GetCurr(2,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][2][i]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*)m_Eng;
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ curr_Lor_ADE[o][0][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][0][i]*curr_ADE[o][0][i];
+ curr_ADE[o][0][i] *= m_Op_Ext_Lor->i_int_ADE[o][0][i];
+ curr_ADE[o][0][i] += m_Op_Ext_Lor->i_ext_ADE[o][0][i] * (eng_sse->Engine_sse::GetCurr(0,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][0][i]);
+
+ curr_Lor_ADE[o][1][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][1][i]*curr_ADE[o][1][i];
+ curr_ADE[o][1][i] *= m_Op_Ext_Lor->i_int_ADE[o][1][i];
+ curr_ADE[o][1][i] += m_Op_Ext_Lor->i_ext_ADE[o][1][i] * (eng_sse->Engine_sse::GetCurr(1,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][1][i]);
+
+ curr_Lor_ADE[o][2][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][2][i]*curr_ADE[o][2][i];
+ curr_ADE[o][2][i] *= m_Op_Ext_Lor->i_int_ADE[o][2][i];
+ curr_ADE[o][2][i] += m_Op_Ext_Lor->i_ext_ADE[o][2][i] * (eng_sse->Engine_sse::GetCurr(2,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][2][i]);
+ }
+ break;
+ }
+ default:
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ curr_Lor_ADE[o][0][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][0][i]*curr_ADE[o][0][i];
+ curr_ADE[o][0][i] *= m_Op_Ext_Lor->i_int_ADE[o][0][i];
+ curr_ADE[o][0][i] += m_Op_Ext_Lor->i_ext_ADE[o][0][i] * (m_Eng->GetCurr(0,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][0][i]);
+
+ curr_Lor_ADE[o][1][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][1][i]*curr_ADE[o][1][i];
+ curr_ADE[o][1][i] *= m_Op_Ext_Lor->i_int_ADE[o][1][i];
+ curr_ADE[o][1][i] += m_Op_Ext_Lor->i_ext_ADE[o][1][i] * (m_Eng->GetCurr(1,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][1][i]);
+
+ curr_Lor_ADE[o][2][i]+=m_Op_Ext_Lor->i_Lor_ADE[o][2][i]*curr_ADE[o][2][i];
+ curr_ADE[o][2][i] *= m_Op_Ext_Lor->i_int_ADE[o][2][i];
+ curr_ADE[o][2][i] += m_Op_Ext_Lor->i_ext_ADE[o][2][i] * (m_Eng->GetCurr(2,pos[0][i],pos[1][i],pos[2][i])-curr_Lor_ADE[o][2][i]);
+ }
+ break;
+ }
+ }
+ else
+ {
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ curr_ADE[o][0][i] *= m_Op_Ext_Lor->i_int_ADE[o][0][i];
+ curr_ADE[o][0][i] += m_Op_Ext_Lor->i_ext_ADE[o][0][i] * m_Eng->Engine::GetCurr(0,pos[0][i],pos[1][i],pos[2][i]);
+
+ curr_ADE[o][1][i] *= m_Op_Ext_Lor->i_int_ADE[o][1][i];
+ curr_ADE[o][1][i] += m_Op_Ext_Lor->i_ext_ADE[o][1][i] * m_Eng->Engine::GetCurr(1,pos[0][i],pos[1][i],pos[2][i]);
+
+ curr_ADE[o][2][i] *= m_Op_Ext_Lor->i_int_ADE[o][2][i];
+ curr_ADE[o][2][i] += m_Op_Ext_Lor->i_ext_ADE[o][2][i] * m_Eng->Engine::GetCurr(2,pos[0][i],pos[1][i],pos[2][i]);
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*)m_Eng;
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ curr_ADE[o][0][i] *= m_Op_Ext_Lor->i_int_ADE[o][0][i];
+ curr_ADE[o][0][i] += m_Op_Ext_Lor->i_ext_ADE[o][0][i] * eng_sse->Engine_sse::GetCurr(0,pos[0][i],pos[1][i],pos[2][i]);
+
+ curr_ADE[o][1][i] *= m_Op_Ext_Lor->i_int_ADE[o][1][i];
+ curr_ADE[o][1][i] += m_Op_Ext_Lor->i_ext_ADE[o][1][i] * eng_sse->Engine_sse::GetCurr(1,pos[0][i],pos[1][i],pos[2][i]);
+
+ curr_ADE[o][2][i] *= m_Op_Ext_Lor->i_int_ADE[o][2][i];
+ curr_ADE[o][2][i] += m_Op_Ext_Lor->i_ext_ADE[o][2][i] * eng_sse->Engine_sse::GetCurr(2,pos[0][i],pos[1][i],pos[2][i]);
+ }
+ break;
+ }
+ default:
+ for (unsigned int i=0; i<m_Op_Ext_Lor->m_LM_Count.at(o); ++i)
+ {
+ curr_ADE[o][0][i] *= m_Op_Ext_Lor->i_int_ADE[o][0][i];
+ curr_ADE[o][0][i] += m_Op_Ext_Lor->i_ext_ADE[o][0][i] * m_Eng->GetCurr(0,pos[0][i],pos[1][i],pos[2][i]);
+
+ curr_ADE[o][1][i] *= m_Op_Ext_Lor->i_int_ADE[o][1][i];
+ curr_ADE[o][1][i] += m_Op_Ext_Lor->i_ext_ADE[o][1][i] * m_Eng->GetCurr(1,pos[0][i],pos[1][i],pos[2][i]);
+
+ curr_ADE[o][2][i] *= m_Op_Ext_Lor->i_int_ADE[o][2][i];
+ curr_ADE[o][2][i] += m_Op_Ext_Lor->i_ext_ADE[o][2][i] * m_Eng->GetCurr(2,pos[0][i],pos[1][i],pos[2][i]);
+ }
+ break;
+ }
+ }
+ }
+}
+
diff --git a/openEMS/FDTD/extensions/engine_ext_lorentzmaterial.h b/openEMS/FDTD/extensions/engine_ext_lorentzmaterial.h
new file mode 100644
index 0000000..804f49a
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_lorentzmaterial.h
@@ -0,0 +1,48 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_LORENTZMATERIAL_H
+#define ENGINE_EXT_LORENTZMATERIAL_H
+
+#include "engine_ext_dispersive.h"
+
+class Operator_Ext_LorentzMaterial;
+
+class Engine_Ext_LorentzMaterial : public Engine_Ext_Dispersive
+{
+public:
+ Engine_Ext_LorentzMaterial(Operator_Ext_LorentzMaterial* op_ext_lorentz);
+ virtual ~Engine_Ext_LorentzMaterial();
+
+ virtual void DoPreVoltageUpdates();
+
+ virtual void DoPreCurrentUpdates();
+
+protected:
+ Operator_Ext_LorentzMaterial* m_Op_Ext_Lor;
+
+ //! ADE Lorentz voltages
+ // Array setup: volt_Lor_ADE[N_order][direction][mesh_pos]
+ FDTD_FLOAT ***volt_Lor_ADE;
+
+ //! ADE Lorentz currents
+ // Array setup: curr_Lor_ADE[N_order][direction][mesh_pos]
+ FDTD_FLOAT ***curr_Lor_ADE;
+
+};
+
+#endif // ENGINE_EXT_LORENTZMATERIAL_H
diff --git a/openEMS/FDTD/extensions/engine_ext_mur_abc.cpp b/openEMS/FDTD/extensions/engine_ext_mur_abc.cpp
new file mode 100644
index 0000000..d9f1b17
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_mur_abc.cpp
@@ -0,0 +1,263 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_mur_abc.h"
+#include "operator_ext_mur_abc.h"
+#include "FDTD/engine.h"
+#include "FDTD/engine_sse.h"
+#include "tools/array_ops.h"
+#include "tools/useful.h"
+#include "operator_ext_excitation.h"
+
+Engine_Ext_Mur_ABC::Engine_Ext_Mur_ABC(Operator_Ext_Mur_ABC* op_ext) : Engine_Extension(op_ext)
+{
+ m_Op_mur = op_ext;
+ m_numLines[0] = m_Op_mur->m_numLines[0];
+ m_numLines[1] = m_Op_mur->m_numLines[1];
+ m_ny = m_Op_mur->m_ny;
+ m_nyP = m_Op_mur->m_nyP;
+ m_nyPP = m_Op_mur->m_nyPP;
+ m_LineNr = m_Op_mur->m_LineNr;
+ m_LineNr_Shift = m_Op_mur->m_LineNr_Shift;
+
+ m_Mur_Coeff_nyP = m_Op_mur->m_Mur_Coeff_nyP;
+ m_Mur_Coeff_nyPP = m_Op_mur->m_Mur_Coeff_nyPP;
+
+ m_volt_nyP = Create2DArray<FDTD_FLOAT>(m_numLines);
+ m_volt_nyPP = Create2DArray<FDTD_FLOAT>(m_numLines);
+
+ //find if some excitation is on this mur-abc and find the max length of this excite, so that the abc can start after the excitation is done...
+ int maxDelay=-1;
+ Operator_Ext_Excitation* Exc_ext = m_Op_mur->m_Op->GetExcitationExtension();
+ for (unsigned int n=0; n<Exc_ext->GetVoltCount(); ++n)
+ {
+ if ( ((Exc_ext->Volt_dir[n]==m_nyP) || (Exc_ext->Volt_dir[n]==m_nyPP)) && (Exc_ext->Volt_index[m_ny][n]==m_LineNr) )
+ {
+ if ((int)Exc_ext->Volt_delay[n]>maxDelay)
+ maxDelay = (int)Exc_ext->Volt_delay[n];
+ }
+ }
+ m_start_TS = 0;
+ if (maxDelay>=0)
+ {
+ m_start_TS = maxDelay + m_Op_mur->m_Op->GetExcitationSignal()->GetLength() + 10; //give it some extra timesteps, for the excitation to travel at least one cell away
+ cerr << "Engine_Ext_Mur_ABC::Engine_Ext_Mur_ABC: Warning: Excitation inside the Mur-ABC #" << m_ny << "-" << (int)(m_LineNr>0) << " found!!!! Mur-ABC will be switched on after excitation is done at " << m_start_TS << " timesteps!!! " << endl;
+ }
+
+ SetNumberOfThreads(1);
+}
+
+Engine_Ext_Mur_ABC::~Engine_Ext_Mur_ABC()
+{
+ Delete2DArray(m_volt_nyP,m_numLines);
+ m_volt_nyP = NULL;
+ Delete2DArray(m_volt_nyPP,m_numLines);
+ m_volt_nyPP = NULL;
+}
+
+
+void Engine_Ext_Mur_ABC::SetNumberOfThreads(int nrThread)
+{
+ Engine_Extension::SetNumberOfThreads(nrThread);
+
+ m_numX = AssignJobs2Threads(m_numLines[0],m_NrThreads,false);
+ m_start.resize(m_NrThreads,0);
+ m_start.at(0)=0;
+ for (size_t n=1; n<m_numX.size(); ++n)
+ m_start.at(n) = m_start.at(n-1) + m_numX.at(n-1);
+}
+
+
+void Engine_Ext_Mur_ABC::DoPreVoltageUpdates(int threadID)
+{
+ if (IsActive()==false) return;
+ if (m_Eng==NULL) return;
+ if (threadID>=m_NrThreads)
+ return;
+ unsigned int pos[] = {0,0,0};
+ unsigned int pos_shift[] = {0,0,0};
+ pos[m_ny] = m_LineNr;
+ pos_shift[m_ny] = m_LineNr_Shift;
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ pos_shift[m_nyP] = pos[m_nyP];
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ pos_shift[m_nyPP] = pos[m_nyPP];
+ m_volt_nyP[pos[m_nyP]][pos[m_nyPP]] = m_Eng->Engine::GetVolt(m_nyP,pos_shift) - m_Op_mur->m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->Engine::GetVolt(m_nyP,pos);
+ m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]] = m_Eng->Engine::GetVolt(m_nyPP,pos_shift) - m_Op_mur->m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->Engine::GetVolt(m_nyPP,pos);
+ }
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ pos_shift[m_nyP] = pos[m_nyP];
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ pos_shift[m_nyPP] = pos[m_nyPP];
+ m_volt_nyP[pos[m_nyP]][pos[m_nyPP]] = eng_sse->Engine_sse::GetVolt(m_nyP,pos_shift) - m_Op_mur->m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] * eng_sse->Engine_sse::GetVolt(m_nyP,pos);
+ m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]] = eng_sse->Engine_sse::GetVolt(m_nyPP,pos_shift) - m_Op_mur->m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] * eng_sse->Engine_sse::GetVolt(m_nyPP,pos);
+ }
+ }
+ break;
+ }
+ default:
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ pos_shift[m_nyP] = pos[m_nyP];
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ pos_shift[m_nyPP] = pos[m_nyPP];
+ m_volt_nyP[pos[m_nyP]][pos[m_nyPP]] = m_Eng->GetVolt(m_nyP,pos_shift) - m_Op_mur->m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->GetVolt(m_nyP,pos);
+ m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]] = m_Eng->GetVolt(m_nyPP,pos_shift) - m_Op_mur->m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->GetVolt(m_nyPP,pos);
+ }
+ }
+ break;
+ }
+}
+
+void Engine_Ext_Mur_ABC::DoPostVoltageUpdates(int threadID)
+{
+ if (IsActive()==false) return;
+ if (m_Eng==NULL) return;
+ if (threadID>=m_NrThreads)
+ return;
+ unsigned int pos[] = {0,0,0};
+ unsigned int pos_shift[] = {0,0,0};
+ pos[m_ny] = m_LineNr;
+ pos_shift[m_ny] = m_LineNr_Shift;
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ pos_shift[m_nyP] = pos[m_nyP];
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ pos_shift[m_nyPP] = pos[m_nyPP];
+ m_volt_nyP[pos[m_nyP]][pos[m_nyPP]] += m_Op_mur->m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->Engine::GetVolt(m_nyP,pos_shift);
+ m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]] += m_Op_mur->m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->Engine::GetVolt(m_nyPP,pos_shift);
+ }
+ }
+ break;
+ }
+
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ pos_shift[m_nyP] = pos[m_nyP];
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ pos_shift[m_nyPP] = pos[m_nyPP];
+ m_volt_nyP[pos[m_nyP]][pos[m_nyPP]] += m_Op_mur->m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] * eng_sse->Engine_sse::GetVolt(m_nyP,pos_shift);
+ m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]] += m_Op_mur->m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] * eng_sse->Engine_sse::GetVolt(m_nyPP,pos_shift);
+ }
+ }
+ break;
+ }
+
+ default:
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ pos_shift[m_nyP] = pos[m_nyP];
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ pos_shift[m_nyPP] = pos[m_nyPP];
+ m_volt_nyP[pos[m_nyP]][pos[m_nyPP]] += m_Op_mur->m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->GetVolt(m_nyP,pos_shift);
+ m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]] += m_Op_mur->m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] * m_Eng->GetVolt(m_nyPP,pos_shift);
+ }
+ }
+ break;
+ }
+}
+
+void Engine_Ext_Mur_ABC::Apply2Voltages(int threadID)
+{
+ if (IsActive()==false) return;
+ if (threadID>=m_NrThreads)
+ return;
+ if (m_Eng==NULL) return;
+ unsigned int pos[] = {0,0,0};
+ pos[m_ny] = m_LineNr;
+
+ //switch for different engine types to access faster inline engine functions
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ m_Eng->Engine::SetVolt(m_nyP,pos, m_volt_nyP[pos[m_nyP]][pos[m_nyPP]]);
+ m_Eng->Engine::SetVolt(m_nyPP,pos, m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]]);
+ }
+ }
+ break;
+ }
+
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ eng_sse->Engine_sse::SetVolt(m_nyP,pos, m_volt_nyP[pos[m_nyP]][pos[m_nyPP]]);
+ eng_sse->Engine_sse::SetVolt(m_nyPP,pos, m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]]);
+ }
+ }
+ break;
+ }
+
+ default:
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ pos[m_nyP]=lineX+m_start.at(threadID);
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ m_Eng->SetVolt(m_nyP,pos, m_volt_nyP[pos[m_nyP]][pos[m_nyPP]]);
+ m_Eng->SetVolt(m_nyPP,pos, m_volt_nyPP[pos[m_nyP]][pos[m_nyPP]]);
+ }
+ }
+ break;
+ }
+
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_mur_abc.h b/openEMS/FDTD/extensions/engine_ext_mur_abc.h
new file mode 100644
index 0000000..aadb2fd
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_mur_abc.h
@@ -0,0 +1,63 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_MUR_ABC_H
+#define ENGINE_EXT_MUR_ABC_H
+
+#include "engine_extension.h"
+#include "FDTD/engine.h"
+#include "FDTD/operator.h"
+
+class Operator_Ext_Mur_ABC;
+
+class Engine_Ext_Mur_ABC : public Engine_Extension
+{
+public:
+ Engine_Ext_Mur_ABC(Operator_Ext_Mur_ABC* op_ext);
+ virtual ~Engine_Ext_Mur_ABC();
+
+ virtual void SetNumberOfThreads(int nrThread);
+
+ virtual void DoPreVoltageUpdates() {Engine_Ext_Mur_ABC::DoPreVoltageUpdates(0);}
+ virtual void DoPreVoltageUpdates(int threadID);
+ virtual void DoPostVoltageUpdates() {Engine_Ext_Mur_ABC::DoPostVoltageUpdates(0);}
+ virtual void DoPostVoltageUpdates(int threadID);
+ virtual void Apply2Voltages() {Engine_Ext_Mur_ABC::Apply2Voltages(0);}
+ virtual void Apply2Voltages(int threadID);
+
+protected:
+ Operator_Ext_Mur_ABC* m_Op_mur;
+
+ inline bool IsActive() {if (m_Eng->GetNumberOfTimesteps()<m_start_TS) return false; return true;}
+ unsigned int m_start_TS;
+
+ int m_ny;
+ int m_nyP,m_nyPP;
+ unsigned int m_LineNr;
+ int m_LineNr_Shift;
+ unsigned int m_numLines[2];
+
+ vector<unsigned int> m_start;
+ vector<unsigned int> m_numX;
+
+ FDTD_FLOAT** m_Mur_Coeff_nyP;
+ FDTD_FLOAT** m_Mur_Coeff_nyPP;
+ FDTD_FLOAT** m_volt_nyP; //n+1 direction
+ FDTD_FLOAT** m_volt_nyPP; //n+2 direction
+};
+
+#endif // ENGINE_EXT_MUR_ABC_H
diff --git a/openEMS/FDTD/extensions/engine_ext_steadystate.cpp b/openEMS/FDTD/extensions/engine_ext_steadystate.cpp
new file mode 100644
index 0000000..9e5d0ce
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_steadystate.cpp
@@ -0,0 +1,112 @@
+/*
+* Copyright (C) 2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_steadystate.h"
+#include "operator_ext_steadystate.h"
+#include "FDTD/engine_sse.h"
+#include "FDTD/engine_interface_fdtd.h"
+
+Engine_Ext_SteadyState::Engine_Ext_SteadyState(Operator_Ext_SteadyState* op_ext): Engine_Extension(op_ext)
+{
+ m_Op_SS = op_ext;
+ m_Priority = ENG_EXT_PRIO_STEADYSTATE;
+
+ for (size_t n=0;n<m_Op_SS->m_E_probe_dir.size();++n)
+ {
+ double* rec = new double[m_Op_SS->m_TS_period*2];
+ m_E_records.push_back(rec);
+ }
+ m_last_max_diff = 1;
+ last_total_energy = 0;
+ m_Eng_Interface = NULL;
+}
+
+Engine_Ext_SteadyState::~Engine_Ext_SteadyState()
+{
+ for (size_t n=0;n<m_E_records.size();++n)
+ {
+ delete[] m_E_records.at(n);
+ m_E_records.at(n) = NULL;
+ }
+ m_E_records.clear();
+ delete m_Eng_Interface;
+ m_Eng_Interface = NULL;
+}
+
+void Engine_Ext_SteadyState::Apply2Voltages()
+{
+ unsigned int p = m_Op_SS->m_TS_period;
+ unsigned int TS = m_Eng->GetNumberOfTimesteps();
+ unsigned int rel_pos = m_Eng->GetNumberOfTimesteps()%(2*p);
+ for (size_t n=0;n<m_E_records.size();++n)
+ m_E_records.at(n)[rel_pos] = m_Eng->GetVolt(m_Op_SS->m_E_probe_dir.at(n), m_Op_SS->m_E_probe_pos[0].at(n), m_Op_SS->m_E_probe_pos[1].at(n), m_Op_SS->m_E_probe_pos[2].at(n));
+ if ((TS%(m_Op_SS->m_TS_period)==0) && (TS>=2*p))
+ {
+ bool no_valid = true;
+ m_last_max_diff = 0;
+ double curr_total_energy = m_Eng_Interface->CalcFastEnergy();
+ if (last_total_energy>0)
+ {
+ m_last_max_diff = abs(curr_total_energy-last_total_energy)/last_total_energy;
+ no_valid = false;
+ }
+ //cerr << curr_total_energy << "/" << last_total_energy << "=" << abs(curr_total_energy-last_total_energy)/last_total_energy << endl;
+ last_total_energy = curr_total_energy;
+ unsigned int old_pos = 0;
+ unsigned int new_pos = p;
+ if (rel_pos<=p)
+ {
+ new_pos = 0;
+ old_pos = p;
+ }
+ //cerr << TS << "/" << rel_pos << ": one period complete, new_pos" << new_pos << " old pos: " << old_pos << endl;
+ double *curr_pow = new double[m_E_records.size()];
+ double *diff_pow = new double[m_E_records.size()];
+ double max_pow = 0;
+ for (size_t n=0;n<m_E_records.size();++n)
+ {
+ double *buf = m_E_records.at(n);
+ curr_pow[n] = 0;
+ diff_pow[n] = 0;
+ for (unsigned int nt=0;nt<p;++nt)
+ {
+ curr_pow[n] += buf[nt+new_pos]*buf[nt+new_pos];
+ diff_pow[n] += (buf[nt+old_pos]-buf[nt+new_pos])*(buf[nt+old_pos]-buf[nt+new_pos]);
+ }
+ max_pow = max(max_pow, curr_pow[n]);
+ }
+ for (size_t n=0;n<m_E_records.size();++n)
+ {
+ //cerr << "curr_pow: " << curr_pow[n] << " diff_pow: " << diff_pow[n] << " diff: " << diff_pow[n]/curr_pow[n] << endl;
+ if (curr_pow[n]>max_pow*1e-2)
+ {
+ m_last_max_diff = max(m_last_max_diff, diff_pow[n]/curr_pow[n]);
+ //cerr << m_last_max_diff << endl;
+ no_valid = false;
+ }
+ }
+ if ((no_valid) || (m_last_max_diff>1))
+ m_last_max_diff = 1;
+ delete[] curr_pow; curr_pow = NULL;
+ //cerr << m_last_max_diff << endl;
+ }
+}
+
+void Engine_Ext_SteadyState::Apply2Current()
+{
+
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_steadystate.h b/openEMS/FDTD/extensions/engine_ext_steadystate.h
new file mode 100644
index 0000000..b66596e
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_steadystate.h
@@ -0,0 +1,51 @@
+/*
+* Copyright (C) 2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_STEADYSTATE_H
+#define ENGINE_EXT_STEADYSTATE_H
+
+#include "engine_extension.h"
+#include "FDTD/engine.h"
+#include "FDTD/operator.h"
+
+class Operator_Ext_SteadyState;
+class Engine_Interface_FDTD;
+
+class Engine_Ext_SteadyState : public Engine_Extension
+{
+public:
+ Engine_Ext_SteadyState(Operator_Ext_SteadyState* op_ext);
+ virtual ~Engine_Ext_SteadyState();
+
+ virtual void Apply2Voltages();
+ virtual void Apply2Current();
+
+ void SetEngineInterface(Engine_Interface_FDTD* eng_if) {m_Eng_Interface=eng_if;}
+ double GetLastDiff() {return m_last_max_diff;}
+
+protected:
+ Operator_Ext_SteadyState* m_Op_SS;
+ double m_last_max_diff;
+ vector<double*> m_E_records;
+ vector<double*> m_H_records;
+
+ double last_total_energy;
+ Engine_Interface_FDTD* m_Eng_Interface;
+};
+
+
+#endif // ENGINE_EXT_STEADYSTATE_H
diff --git a/openEMS/FDTD/extensions/engine_ext_tfsf.cpp b/openEMS/FDTD/extensions/engine_ext_tfsf.cpp
new file mode 100644
index 0000000..cd3b107
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_tfsf.cpp
@@ -0,0 +1,215 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_tfsf.h"
+#include "operator_ext_tfsf.h"
+#include "FDTD/engine_sse.h"
+
+Engine_Ext_TFSF::Engine_Ext_TFSF(Operator_Ext_TFSF* op_ext) : Engine_Extension(op_ext)
+{
+ m_Op_TFSF = op_ext;
+ m_Priority = ENG_EXT_PRIO_TFSF;
+
+ m_DelayLookup = new unsigned int[m_Op_TFSF->m_maxDelay+1];
+}
+
+Engine_Ext_TFSF::~Engine_Ext_TFSF()
+{
+ delete[] m_DelayLookup;
+ m_DelayLookup = NULL;
+}
+
+void Engine_Ext_TFSF::DoPostVoltageUpdates()
+{
+ unsigned int numTS = m_Eng->GetNumberOfTimesteps();
+ unsigned int length = m_Op_TFSF->m_Exc->GetLength();
+
+ int p = int(m_Op_TFSF->m_Exc->GetSignalPeriod()/m_Op_TFSF->m_Exc->GetTimestep());
+
+ for (unsigned int n=0;n<=m_Op_TFSF->m_maxDelay;++n)
+ {
+ if ( numTS < n )
+ m_DelayLookup[n]=0;
+ else if ((numTS-n > length) && (p==0))
+ m_DelayLookup[n]=0;
+ else
+ m_DelayLookup[n] = numTS - n;
+ if (p>0)
+ m_DelayLookup[n] = (m_DelayLookup[n] % p);
+ }
+
+ //get the current signal since an H-field is added ...
+ FDTD_FLOAT* signal = m_Op_TFSF->m_Exc->GetCurrentSignal();
+
+ int nP,nPP;
+ unsigned int ui_pos;
+ unsigned int pos[3];
+ for (int n=0;n<3;++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+
+ // lower plane
+ pos[nP] = m_Op_TFSF->m_Start[nP];
+ ui_pos = 0;
+ if (m_Op_TFSF->m_ActiveDir[n][0])
+ {
+
+ for (unsigned int i=0;i<m_Op_TFSF->m_numLines[nP];++i)
+ {
+ pos[nPP] = m_Op_TFSF->m_Start[nPP];
+ for (unsigned int j=0;j<m_Op_TFSF->m_numLines[nPP];++j)
+ {
+ // current updates
+ pos[n] = m_Op_TFSF->m_Start[n];
+
+ m_Eng->SetVolt(nP,pos, m_Eng->GetVolt(nP,pos)
+ + (1.0-m_Op_TFSF->m_VoltDelayDelta[n][0][0][ui_pos])*m_Op_TFSF->m_VoltAmp[n][0][0][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_VoltDelay[n][0][0][ui_pos]]]
+ + m_Op_TFSF->m_VoltDelayDelta[n][0][0][ui_pos] *m_Op_TFSF->m_VoltAmp[n][0][0][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_VoltDelay[n][0][0][ui_pos]]] );
+
+ m_Eng->SetVolt(nPP,pos, m_Eng->GetVolt(nPP,pos)
+ + (1.0-m_Op_TFSF->m_VoltDelayDelta[n][0][1][ui_pos])*m_Op_TFSF->m_VoltAmp[n][0][1][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_VoltDelay[n][0][1][ui_pos]]]
+ + m_Op_TFSF->m_VoltDelayDelta[n][0][1][ui_pos] *m_Op_TFSF->m_VoltAmp[n][0][1][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_VoltDelay[n][0][1][ui_pos]]] );
+
+ ++pos[nPP];
+ ++ui_pos;
+ }
+ ++pos[nP];
+ }
+ }
+
+ // upper plane
+ pos[nP] = m_Op_TFSF->m_Start[nP];
+ ui_pos = 0;
+ if (m_Op_TFSF->m_ActiveDir[n][1])
+ {
+
+ for (unsigned int i=0;i<m_Op_TFSF->m_numLines[nP];++i)
+ {
+ pos[nPP] = m_Op_TFSF->m_Start[nPP];
+ for (unsigned int j=0;j<m_Op_TFSF->m_numLines[nPP];++j)
+ {
+ // current updates
+ pos[n] = m_Op_TFSF->m_Stop[n];
+
+ m_Eng->SetVolt(nP,pos, m_Eng->GetVolt(nP,pos)
+ + (1.0-m_Op_TFSF->m_VoltDelayDelta[n][1][0][ui_pos])*m_Op_TFSF->m_VoltAmp[n][1][0][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_VoltDelay[n][1][0][ui_pos]]]
+ + m_Op_TFSF->m_VoltDelayDelta[n][1][0][ui_pos] *m_Op_TFSF->m_VoltAmp[n][1][0][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_VoltDelay[n][1][0][ui_pos]]] );
+
+ m_Eng->SetVolt(nPP,pos, m_Eng->GetVolt(nPP,pos)
+ + (1.0-m_Op_TFSF->m_VoltDelayDelta[n][1][1][ui_pos])*m_Op_TFSF->m_VoltAmp[n][1][1][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_VoltDelay[n][1][1][ui_pos]]]
+ + m_Op_TFSF->m_VoltDelayDelta[n][1][1][ui_pos] *m_Op_TFSF->m_VoltAmp[n][1][1][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_VoltDelay[n][1][1][ui_pos]]] );
+
+ ++pos[nPP];
+ ++ui_pos;
+ }
+ ++pos[nP];
+ }
+ }
+ }
+}
+
+void Engine_Ext_TFSF::DoPostCurrentUpdates()
+{
+ unsigned int numTS = m_Eng->GetNumberOfTimesteps();
+ unsigned int length = m_Op_TFSF->m_Exc->GetLength();
+
+ int p = int(m_Op_TFSF->m_Exc->GetSignalPeriod()/m_Op_TFSF->m_Exc->GetTimestep());
+
+ for (unsigned int n=0;n<m_Op_TFSF->m_maxDelay;++n)
+ {
+ if ( numTS < n )
+ m_DelayLookup[n]=0;
+ else if ((numTS-n > length) && (p==0))
+ m_DelayLookup[n]=0;
+ else
+ m_DelayLookup[n] = numTS - n;
+ if (p>0)
+ m_DelayLookup[n] = (m_DelayLookup[n] % p);
+ }
+
+ //get the current signal since an E-field is added ...
+ FDTD_FLOAT* signal = m_Op_TFSF->m_Exc->GetVoltageSignal();
+
+ int nP,nPP;
+ unsigned int ui_pos;
+ unsigned int pos[3];
+ for (int n=0;n<3;++n)
+ {
+ if (!m_Op_TFSF->m_ActiveDir[n][0] && !m_Op_TFSF->m_ActiveDir[n][1])
+ continue;
+
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+
+ // lower plane
+ pos[nP] = m_Op_TFSF->m_Start[nP];
+ ui_pos = 0;
+ if (m_Op_TFSF->m_ActiveDir[n][0])
+ {
+ for (unsigned int i=0;i<m_Op_TFSF->m_numLines[nP];++i)
+ {
+ pos[nPP] = m_Op_TFSF->m_Start[nPP];
+ for (unsigned int j=0;j<m_Op_TFSF->m_numLines[nPP];++j)
+ {
+ // current updates
+ pos[n] = m_Op_TFSF->m_Start[n]-1;
+
+ m_Eng->SetCurr(nP,pos, m_Eng->GetCurr(nP,pos)
+ + (1.0-m_Op_TFSF->m_CurrDelayDelta[n][0][0][ui_pos])*m_Op_TFSF->m_CurrAmp[n][0][0][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_CurrDelay[n][0][0][ui_pos]]]
+ + m_Op_TFSF->m_CurrDelayDelta[n][0][0][ui_pos] *m_Op_TFSF->m_CurrAmp[n][0][0][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_CurrDelay[n][0][0][ui_pos]]] );
+
+ m_Eng->SetCurr(nPP,pos, m_Eng->GetCurr(nPP,pos)
+ + (1.0-m_Op_TFSF->m_CurrDelayDelta[n][0][1][ui_pos])*m_Op_TFSF->m_CurrAmp[n][0][1][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_CurrDelay[n][0][1][ui_pos]]]
+ + m_Op_TFSF->m_CurrDelayDelta[n][0][1][ui_pos] *m_Op_TFSF->m_CurrAmp[n][0][1][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_CurrDelay[n][0][1][ui_pos]]] );
+
+ ++pos[nPP];
+ ++ui_pos;
+ }
+ ++pos[nP];
+ }
+ }
+
+ // upper plane
+ pos[nP] = m_Op_TFSF->m_Start[nP];
+ ui_pos = 0;
+ if (m_Op_TFSF->m_ActiveDir[n][1])
+ {
+ for (unsigned int i=0;i<m_Op_TFSF->m_numLines[nP];++i)
+ {
+ pos[nPP] = m_Op_TFSF->m_Start[nPP];
+ for (unsigned int j=0;j<m_Op_TFSF->m_numLines[nPP];++j)
+ {
+ // current updates
+ pos[n] = m_Op_TFSF->m_Stop[n];
+
+ m_Eng->SetCurr(nP,pos, m_Eng->GetCurr(nP,pos)
+ + (1.0-m_Op_TFSF->m_CurrDelayDelta[n][1][0][ui_pos])*m_Op_TFSF->m_CurrAmp[n][1][0][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_CurrDelay[n][1][0][ui_pos]]]
+ + m_Op_TFSF->m_CurrDelayDelta[n][1][0][ui_pos] *m_Op_TFSF->m_CurrAmp[n][1][0][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_CurrDelay[n][1][0][ui_pos]]] );
+
+ m_Eng->SetCurr(nPP,pos, m_Eng->GetCurr(nPP,pos)
+ + (1.0-m_Op_TFSF->m_CurrDelayDelta[n][1][1][ui_pos])*m_Op_TFSF->m_CurrAmp[n][1][1][ui_pos]*signal[m_DelayLookup[ m_Op_TFSF->m_CurrDelay[n][1][1][ui_pos]]]
+ + m_Op_TFSF->m_CurrDelayDelta[n][1][1][ui_pos] *m_Op_TFSF->m_CurrAmp[n][1][1][ui_pos]*signal[m_DelayLookup[1+m_Op_TFSF->m_CurrDelay[n][1][1][ui_pos]]] );
+
+ ++pos[nPP];
+ ++ui_pos;
+ }
+ ++pos[nP];
+ }
+ }
+ }
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_tfsf.h b/openEMS/FDTD/extensions/engine_ext_tfsf.h
new file mode 100644
index 0000000..d4e662a
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_tfsf.h
@@ -0,0 +1,40 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_TFSF_H
+#define ENGINE_EXT_TFSF_H
+
+#include "engine_extension.h"
+
+class Operator_Ext_TFSF;
+
+class Engine_Ext_TFSF : public Engine_Extension
+{
+public:
+ Engine_Ext_TFSF(Operator_Ext_TFSF* op_ext);
+ virtual ~Engine_Ext_TFSF();
+
+ virtual void DoPostVoltageUpdates();
+ virtual void DoPostCurrentUpdates();
+
+protected:
+ Operator_Ext_TFSF* m_Op_TFSF;
+
+ unsigned int* m_DelayLookup;
+};
+
+#endif // ENGINE_EXT_TFSF_H
diff --git a/openEMS/FDTD/extensions/engine_ext_upml.cpp b/openEMS/FDTD/extensions/engine_ext_upml.cpp
new file mode 100644
index 0000000..8cb365f
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_upml.cpp
@@ -0,0 +1,493 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_ext_upml.h"
+#include "operator_ext_upml.h"
+#include "FDTD/engine.h"
+#include "FDTD/engine_sse.h"
+#include "tools/array_ops.h"
+#include "tools/useful.h"
+
+Engine_Ext_UPML::Engine_Ext_UPML(Operator_Ext_UPML* op_ext) : Engine_Extension(op_ext)
+{
+ m_Op_UPML = op_ext;
+
+ //this ABC extension should be executed first!
+ m_Priority = ENG_EXT_PRIO_UPML;
+
+ volt_flux = Create_N_3DArray<FDTD_FLOAT>(m_Op_UPML->m_numLines);
+ curr_flux = Create_N_3DArray<FDTD_FLOAT>(m_Op_UPML->m_numLines);
+
+ SetNumberOfThreads(1);
+}
+
+Engine_Ext_UPML::~Engine_Ext_UPML()
+{
+ Delete_N_3DArray<FDTD_FLOAT>(volt_flux,m_Op_UPML->m_numLines);
+ volt_flux=NULL;
+ Delete_N_3DArray<FDTD_FLOAT>(curr_flux,m_Op_UPML->m_numLines);
+ curr_flux=NULL;
+}
+
+void Engine_Ext_UPML::SetNumberOfThreads(int nrThread)
+{
+ Engine_Extension::SetNumberOfThreads(nrThread);
+
+ m_numX = AssignJobs2Threads(m_Op_UPML->m_numLines[0],m_NrThreads,false);
+ m_start.resize(m_NrThreads,0);
+ m_start.at(0)=0;
+ for (size_t n=1; n<m_numX.size(); ++n)
+ m_start.at(n) = m_start.at(n-1) + m_numX.at(n-1);
+}
+
+
+void Engine_Ext_UPML::DoPreVoltageUpdates(int threadID)
+{
+ if (m_Eng==NULL)
+ return;
+
+ if (threadID>=m_NrThreads)
+ return;
+
+ unsigned int pos[3];
+ unsigned int loc_pos[3];
+ FDTD_FLOAT f_help;
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = m_Op_UPML->vv[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->Engine::GetVolt(0,pos)
+ - m_Op_UPML->vvfo[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->Engine::SetVolt(0,pos, volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->vv[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->Engine::GetVolt(1,pos)
+ - m_Op_UPML->vvfo[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->Engine::SetVolt(1,pos, volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->vv[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->Engine::GetVolt(2,pos)
+ - m_Op_UPML->vvfo[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->Engine::SetVolt(2,pos, volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+ }
+ }
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = m_Op_UPML->vv[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * eng_sse->Engine_sse::GetVolt(0,pos)
+ - m_Op_UPML->vvfo[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ eng_sse->Engine_sse::SetVolt(0,pos, volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->vv[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * eng_sse->Engine_sse::GetVolt(1,pos)
+ - m_Op_UPML->vvfo[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ eng_sse->Engine_sse::SetVolt(1,pos, volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->vv[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * eng_sse->Engine_sse::GetVolt(2,pos)
+ - m_Op_UPML->vvfo[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ eng_sse->Engine_sse::SetVolt(2,pos, volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+ }
+ }
+ }
+ break;
+ }
+ default:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = m_Op_UPML->vv[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->GetVolt(0,pos)
+ - m_Op_UPML->vvfo[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->SetVolt(0,pos, volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->vv[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->GetVolt(1,pos)
+ - m_Op_UPML->vvfo[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->SetVolt(1,pos, volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->vv[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->GetVolt(2,pos)
+ - m_Op_UPML->vvfo[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->SetVolt(2,pos, volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+ }
+ }
+ }
+ break;
+ }
+ }
+
+}
+
+void Engine_Ext_UPML::DoPostVoltageUpdates(int threadID)
+{
+ if (m_Eng==NULL)
+ return;
+ if (threadID>=m_NrThreads)
+ return;
+
+ unsigned int pos[3];
+ unsigned int loc_pos[3];
+ FDTD_FLOAT f_help;
+
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->Engine::GetVolt(0,pos);
+ m_Eng->Engine::SetVolt(0,pos, f_help + m_Op_UPML->vvfn[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->Engine::GetVolt(1,pos);
+ m_Eng->Engine::SetVolt(1,pos, f_help + m_Op_UPML->vvfn[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->Engine::GetVolt(2,pos);
+ m_Eng->Engine::SetVolt(2,pos, f_help + m_Op_UPML->vvfn[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ }
+ }
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = eng_sse->Engine_sse::GetVolt(0,pos);
+ eng_sse->Engine_sse::SetVolt(0,pos, f_help + m_Op_UPML->vvfn[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = eng_sse->Engine_sse::GetVolt(1,pos);
+ eng_sse->Engine_sse::SetVolt(1,pos, f_help + m_Op_UPML->vvfn[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = eng_sse->Engine_sse::GetVolt(2,pos);
+ eng_sse->Engine_sse::SetVolt(2,pos, f_help + m_Op_UPML->vvfn[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ }
+ }
+ }
+ break;
+ }
+ default:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->GetVolt(0,pos);
+ m_Eng->SetVolt(0,pos, f_help + m_Op_UPML->vvfn[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->GetVolt(1,pos);
+ m_Eng->SetVolt(1,pos, f_help + m_Op_UPML->vvfn[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->GetVolt(2,pos);
+ m_Eng->SetVolt(2,pos, f_help + m_Op_UPML->vvfn[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * volt_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ }
+ }
+ }
+ break;
+ }
+ }
+
+}
+
+void Engine_Ext_UPML::DoPreCurrentUpdates(int threadID)
+{
+ if (m_Eng==NULL)
+ return;
+ if (threadID>=m_NrThreads)
+ return;
+
+ unsigned int pos[3];
+ unsigned int loc_pos[3];
+ FDTD_FLOAT f_help;
+
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = m_Op_UPML->ii[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->Engine::GetCurr(0,pos)
+ - m_Op_UPML->iifo[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->Engine::SetCurr(0,pos, curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->ii[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->Engine::GetCurr(1,pos)
+ - m_Op_UPML->iifo[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->Engine::SetCurr(1,pos, curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->ii[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->Engine::GetCurr(2,pos)
+ - m_Op_UPML->iifo[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->Engine::SetCurr(2,pos, curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+ }
+ }
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = m_Op_UPML->ii[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * eng_sse->Engine_sse::GetCurr(0,pos)
+ - m_Op_UPML->iifo[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ eng_sse->Engine_sse::SetCurr(0,pos, curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->ii[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * eng_sse->Engine_sse::GetCurr(1,pos)
+ - m_Op_UPML->iifo[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ eng_sse->Engine_sse::SetCurr(1,pos, curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->ii[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * eng_sse->Engine_sse::GetCurr(2,pos)
+ - m_Op_UPML->iifo[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ eng_sse->Engine_sse::SetCurr(2,pos, curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ }
+ }
+ }
+ break;
+ }
+ default:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = m_Op_UPML->ii[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->GetCurr(0,pos)
+ - m_Op_UPML->iifo[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->SetCurr(0,pos, curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->ii[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->GetCurr(1,pos)
+ - m_Op_UPML->iifo[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->SetCurr(1,pos, curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+
+ f_help = m_Op_UPML->ii[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * m_Eng->GetCurr(2,pos)
+ - m_Op_UPML->iifo[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ m_Eng->SetCurr(2,pos, curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = f_help;
+ }
+ }
+ }
+ break;
+ }
+ }
+}
+
+void Engine_Ext_UPML::DoPostCurrentUpdates(int threadID)
+{
+ if (m_Eng==NULL)
+ return;
+ if (threadID>=m_NrThreads)
+ return;
+
+ unsigned int pos[3];
+ unsigned int loc_pos[3];
+ FDTD_FLOAT f_help;
+
+ switch (m_Eng->GetType())
+ {
+ case Engine::BASIC:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->Engine::GetCurr(0,pos);
+ m_Eng->Engine::SetCurr(0,pos, f_help + m_Op_UPML->iifn[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->Engine::GetCurr(1,pos);
+ m_Eng->Engine::SetCurr(1,pos, f_help + m_Op_UPML->iifn[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->Engine::GetCurr(2,pos);
+ m_Eng->Engine::SetCurr(2,pos, f_help + m_Op_UPML->iifn[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ }
+ }
+ }
+ break;
+ }
+ case Engine::SSE:
+ {
+ Engine_sse* eng_sse = (Engine_sse*) m_Eng;
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = eng_sse->Engine_sse::GetCurr(0,pos);
+ eng_sse->Engine_sse::SetCurr(0,pos, f_help + m_Op_UPML->iifn[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = eng_sse->Engine_sse::GetCurr(1,pos);
+ eng_sse->Engine_sse::SetCurr(1,pos, f_help + m_Op_UPML->iifn[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = eng_sse->Engine_sse::GetCurr(2,pos);
+ eng_sse->Engine_sse::SetCurr(2,pos, f_help + m_Op_UPML->iifn[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ }
+ }
+ }
+ break;
+ }
+ default:
+ {
+ for (unsigned int lineX=0; lineX<m_numX.at(threadID); ++lineX)
+ {
+ loc_pos[0]=lineX+m_start.at(threadID);
+ pos[0] = loc_pos[0] + m_Op_UPML->m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_Op_UPML->m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_Op_UPML->m_StartPos[1];
+ for (loc_pos[2]=0; loc_pos[2]<m_Op_UPML->m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_Op_UPML->m_StartPos[2];
+
+ f_help = curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->GetCurr(0,pos);
+ m_Eng->SetCurr(0,pos, f_help + m_Op_UPML->iifn[0][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[0][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->GetCurr(1,pos);
+ m_Eng->SetCurr(1,pos, f_help + m_Op_UPML->iifn[1][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[1][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+
+ f_help = curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]];
+ curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] = m_Eng->GetCurr(2,pos);
+ m_Eng->SetCurr(2,pos, f_help + m_Op_UPML->iifn[2][loc_pos[0]][loc_pos[1]][loc_pos[2]] * curr_flux[2][loc_pos[0]][loc_pos[1]][loc_pos[2]]);
+ }
+ }
+ }
+ break;
+ }
+ }
+}
diff --git a/openEMS/FDTD/extensions/engine_ext_upml.h b/openEMS/FDTD/extensions/engine_ext_upml.h
new file mode 100644
index 0000000..283c886
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_ext_upml.h
@@ -0,0 +1,55 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXT_UPML_H
+#define ENGINE_EXT_UPML_H
+
+#include "engine_extension.h"
+#include "FDTD/engine.h"
+#include "FDTD/operator.h"
+
+class Operator_Ext_UPML;
+
+class Engine_Ext_UPML : public Engine_Extension
+{
+public:
+ Engine_Ext_UPML(Operator_Ext_UPML* op_ext);
+ virtual ~Engine_Ext_UPML();
+
+ virtual void SetNumberOfThreads(int nrThread);
+
+ virtual void DoPreVoltageUpdates() {Engine_Ext_UPML::DoPreVoltageUpdates(0);};
+ virtual void DoPreVoltageUpdates(int threadID);
+ virtual void DoPostVoltageUpdates() {Engine_Ext_UPML::DoPostVoltageUpdates(0);};
+ virtual void DoPostVoltageUpdates(int threadID);
+
+ virtual void DoPreCurrentUpdates() {Engine_Ext_UPML::DoPreCurrentUpdates(0);};
+ virtual void DoPreCurrentUpdates(int threadID);
+ virtual void DoPostCurrentUpdates() {Engine_Ext_UPML::DoPostCurrentUpdates(0);};
+ virtual void DoPostCurrentUpdates(int threadID);
+
+protected:
+ Operator_Ext_UPML* m_Op_UPML;
+
+ vector<unsigned int> m_start;
+ vector<unsigned int> m_numX;
+
+ FDTD_FLOAT**** volt_flux;
+ FDTD_FLOAT**** curr_flux;
+};
+
+#endif // ENGINE_EXT_UPML_H
diff --git a/openEMS/FDTD/extensions/engine_extension.cpp b/openEMS/FDTD/extensions/engine_extension.cpp
new file mode 100644
index 0000000..6f688a3
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_extension.cpp
@@ -0,0 +1,95 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_extension.h"
+#include "operator_extension.h"
+
+#include "FDTD/engine.h"
+
+Engine_Extension::Engine_Extension(Operator_Extension* op_ext)
+{
+ m_Op_ext = op_ext;
+ m_Eng = NULL;
+ m_Priority = ENG_EXT_PRIO_DEFAULT;
+ m_NrThreads = 1;
+}
+
+Engine_Extension::~Engine_Extension()
+{
+}
+
+void Engine_Extension::SetNumberOfThreads(int nrThread)
+{
+ if (nrThread<1)
+ return;
+ m_NrThreads=nrThread;
+}
+
+string Engine_Extension::GetExtensionName() const
+{
+ if (m_Op_ext)
+ return m_Op_ext->GetExtensionName();
+ else
+ return "Unknown Extension";
+}
+
+void Engine_Extension::DoPreVoltageUpdates(int threadID)
+{
+ //if this method gets called the derived extension obviously doesn't support multithrading, calling non-MT method...
+ if (threadID==0)
+ DoPreVoltageUpdates();
+}
+
+void Engine_Extension::DoPostVoltageUpdates(int threadID)
+{
+ //if this method gets called the derived extension obviously doesn't support multithrading, calling non-MT method...
+ if (threadID==0)
+ DoPostVoltageUpdates();
+}
+
+void Engine_Extension::Apply2Voltages(int threadID)
+{
+ //if this method gets called the derived extension obviously doesn't support multithrading, calling non-MT method...
+ if (threadID==0)
+ Apply2Voltages();
+}
+
+void Engine_Extension::DoPreCurrentUpdates(int threadID)
+{
+ //if this method gets called the derived extension obviously doesn't support multithrading, calling non-MT method...
+ if (threadID==0)
+ DoPreCurrentUpdates();
+}
+
+void Engine_Extension::DoPostCurrentUpdates(int threadID)
+{
+ //if this method gets called the derived extension obviously doesn't support multithrading, calling non-MT method...
+ if (threadID==0)
+ DoPostCurrentUpdates();
+}
+
+void Engine_Extension::Apply2Current(int threadID)
+{
+ //if this method gets called the derived extension obviously doesn't support multithrading, calling non-MT method...
+ if (threadID==0)
+ Apply2Current();
+}
+
+bool Engine_Extension::operator< (const Engine_Extension& other)
+{
+ return (GetPriority()<other.GetPriority());
+}
diff --git a/openEMS/FDTD/extensions/engine_extension.h b/openEMS/FDTD/extensions/engine_extension.h
new file mode 100644
index 0000000..12ef712
--- /dev/null
+++ b/openEMS/FDTD/extensions/engine_extension.h
@@ -0,0 +1,88 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ENGINE_EXTENSION_H
+#define ENGINE_EXTENSION_H
+
+#define ENG_EXT_PRIO_DEFAULT 0 //default engine extension priority
+
+// priority definitions for some important extensions
+#define ENG_EXT_PRIO_STEADYSTATE +2e6 //steady state extension priority
+#define ENG_EXT_PRIO_UPML +1e6 //unaxial pml extension priority
+#define ENG_EXT_PRIO_CYLINDER +1e5 //cylindrial extension priority
+#define ENG_EXT_PRIO_TFSF +5e4 //total-field/scattered-field extension priority
+#define ENG_EXT_PRIO_EXCITATION -1000 //excitation priority
+#define ENG_EXT_PRIO_CYLINDERMULTIGRID -3000 //cylindrial multi-grid extension priority
+
+#include <string>
+
+class Operator_Extension;
+class Engine;
+
+//! Abstract base-class for all engine extensions
+class Engine_Extension
+{
+public:
+ virtual ~Engine_Extension();
+
+ virtual void SetNumberOfThreads(int nrThread);
+
+ //! This methode will be called __before__ the main engine does the usual voltage updates. This methode may __not__ change the engine voltages!!!
+ virtual void DoPreVoltageUpdates() {}
+ virtual void DoPreVoltageUpdates(int threadID);
+ //! This methode will be called __after__ the main engine does the usual voltage updates. This methode may __not__ change the engine voltages!!!
+ virtual void DoPostVoltageUpdates() {}
+ virtual void DoPostVoltageUpdates(int threadID);
+ //! This methode will be called __after__ all updates to the voltages and extensions and may add/set its results to the engine voltages, but may __not__ rely on the current value of the engine voltages!!!
+ virtual void Apply2Voltages() {}
+ virtual void Apply2Voltages(int threadID);
+
+ //! This methode will be called __before__ the main engine does the usual current updates. This methode may __not__ change the engine current!!!
+ virtual void DoPreCurrentUpdates() {}
+ virtual void DoPreCurrentUpdates(int threadID);
+ //! This methode will be called __after__ the main engine does the usual current updates. This methode may __not__ change the engine current!!!
+ virtual void DoPostCurrentUpdates() {}
+ virtual void DoPostCurrentUpdates(int threadID);
+ //! This methode will be called __after__ all updates to the current and extensions and may add/set its results to the engine current, but may __not__ rely on the current value of the engine current!!!
+ virtual void Apply2Current() {}
+ virtual void Apply2Current(int threadID);
+
+ //! Set the Engine to this extention. This will usually done automatically by Engine::AddExtension
+ virtual void SetEngine(Engine* eng) {m_Eng=eng;}
+
+ //! Get the priority for this extension
+ virtual int GetPriority() const {return m_Priority;}
+
+ //! Set the priority for this extension
+ virtual void SetPriority(int val) {m_Priority=val;}
+
+ virtual bool operator< (const Engine_Extension& other);
+
+ virtual std::string GetExtensionName() const;
+
+protected:
+ Engine_Extension(Operator_Extension* op_ext);
+
+ Operator_Extension* m_Op_ext;
+ Engine* m_Eng;
+
+ int m_Priority;
+
+ int m_NrThreads;
+};
+
+#endif // ENGINE_EXTENSION_H
diff --git a/openEMS/FDTD/extensions/operator_ext_conductingsheet.cpp b/openEMS/FDTD/extensions/operator_ext_conductingsheet.cpp
new file mode 100644
index 0000000..28c51bb
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_conductingsheet.cpp
@@ -0,0 +1,261 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_conductingsheet.h"
+#include "tools/array_ops.h"
+#include "tools/constants.h"
+#include "cond_sheet_parameter.h"
+
+#include "CSPropConductingSheet.h"
+
+Operator_Ext_ConductingSheet::Operator_Ext_ConductingSheet(Operator* op, double f_max) : Operator_Ext_LorentzMaterial(op)
+{
+ m_f_max = f_max;
+}
+
+Operator_Ext_ConductingSheet::Operator_Ext_ConductingSheet(Operator* op, Operator_Ext_ConductingSheet* op_ext) : Operator_Ext_LorentzMaterial(op, op_ext)
+{
+ m_f_max = op_ext->m_f_max;
+}
+
+Operator_Extension* Operator_Ext_ConductingSheet::Clone(Operator* op)
+{
+ if (dynamic_cast<Operator_Ext_ConductingSheet*>(this)==NULL)
+ return NULL;
+ return new Operator_Ext_ConductingSheet(op, this);
+}
+
+bool Operator_Ext_ConductingSheet::BuildExtension()
+{
+ double dT = m_Op->GetTimestep();
+ unsigned int pos[] = {0,0,0};
+ double coord[3];
+ unsigned int numLines[3] = {m_Op->GetNumberOfLines(0,true),m_Op->GetNumberOfLines(1,true),m_Op->GetNumberOfLines(2,true)};
+
+ m_Order = 0;
+ vector<unsigned int> v_pos[3];
+ int ****tanDir = Create_N_3DArray<int>(numLines);
+ float ****Conductivity = Create_N_3DArray<float>(numLines);
+ float ****Thickness = Create_N_3DArray<float>(numLines);
+
+ CSPrimitives* cs_sheet = NULL;
+ double box[6];
+ int nP, nPP;
+ bool b_pos_on;
+ bool disable_pos;
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ vector<CSPrimitives*> vPrims = m_Op->GetPrimitivesBoundBox(pos[0], pos[1], -1, (CSProperties::PropertyType)(CSProperties::MATERIAL | CSProperties::METAL));
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ b_pos_on = false;
+ disable_pos = false;
+ // disable conducting sheet model inside the boundary conditions, especially inside a pml
+ for (int m=0;m<3;++m)
+ if ((pos[m]<=(unsigned int)m_Op->GetBCSize(2*m)) || (pos[m]>=(numLines[m]-m_Op->GetBCSize(2*m+1)-1)))
+ disable_pos = true;
+
+ for (int n=0; n<3; ++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+
+ tanDir[n][pos[0]][pos[1]][pos[2]] = -1; //deactivate by default
+ Conductivity[n][pos[0]][pos[1]][pos[2]] = 0; //deactivate by default
+ Thickness[n][pos[0]][pos[1]][pos[2]] = 0; //deactivate by default
+
+ if (m_Op->GetYeeCoords(n,pos,coord,false)==false)
+ continue;
+
+ // Ez at r==0 not supported --> set to PEC
+ if (m_CC_R0_included && (n==2) && (pos[0]==0))
+ disable_pos = true;
+
+// CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord,(CSProperties::PropertyType)(CSProperties::METAL | CSProperties::MATERIAL), false, &cs_sheet);
+ CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord, vPrims, false, &cs_sheet);
+ CSPropConductingSheet* cs_prop = dynamic_cast<CSPropConductingSheet*>(prop);
+ if (cs_prop)
+ {
+ if (cs_sheet==NULL)
+ return false; //sanity check, this should never happen
+ if (cs_sheet->GetDimension()!=2)
+ {
+ cerr << "Operator_Ext_ConductingSheet::BuildExtension: A conducting sheet primitive (ID: " << cs_sheet->GetID() << ") with dimension: " << cs_sheet->GetDimension() << " found, fallback to PEC!" << endl;
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], 0 );
+ m_Op->SetVI(n,pos[0],pos[1],pos[2], 0 );
+ ++m_Op->m_Nr_PEC[n];
+ continue;
+ }
+ cs_sheet->SetPrimitiveUsed(true);
+
+ if (disable_pos)
+ {
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], 0 );
+ m_Op->SetVI(n,pos[0],pos[1],pos[2], 0 );
+ ++m_Op->m_Nr_PEC[n];
+ continue;
+ }
+
+ Conductivity[n][pos[0]][pos[1]][pos[2]] = cs_prop->GetConductivity();
+ Thickness[n][pos[0]][pos[1]][pos[2]] = cs_prop->GetThickness();
+
+ if ((Conductivity[n][pos[0]][pos[1]][pos[2]]<=0) || (Thickness[n][pos[0]][pos[1]][pos[2]]<=0))
+ {
+ cerr << "Operator_Ext_ConductingSheet::BuildExtension: Warning: Zero conductivity or thickness detected... fallback to PEC!" << endl;
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], 0 );
+ m_Op->SetVI(n,pos[0],pos[1],pos[2], 0 );
+ ++m_Op->m_Nr_PEC[n];
+ continue;
+ }
+
+ cs_sheet->GetBoundBox(box);
+ if (box[2*nP]!=box[2*nP+1])
+ tanDir[n][pos[0]][pos[1]][pos[2]] = nP;
+ if (box[2*nPP]!=box[2*nPP+1])
+ tanDir[n][pos[0]][pos[1]][pos[2]] = nPP;
+ b_pos_on = true;
+ }
+ }
+ if (b_pos_on)
+ {
+ for (int n=0; n<3; ++n)
+ v_pos[n].push_back(pos[n]);
+ }
+ }
+ }
+ }
+
+ size_t numCS = v_pos[0].size();
+ if (numCS==0)
+ return false;
+
+ m_LM_Count.push_back(numCS);
+ m_LM_Count.push_back(numCS);
+
+ m_Order = 2;
+ m_volt_ADE_On = new bool[m_Order];
+ m_volt_ADE_On[0] = m_volt_ADE_On[1]=true;
+ m_curr_ADE_On = new bool[m_Order];
+ m_curr_ADE_On[0] = m_curr_ADE_On[1]=false;
+
+ m_volt_Lor_ADE_On = new bool[m_Order];
+ m_volt_Lor_ADE_On[0] = m_volt_Lor_ADE_On[1]=false;
+ m_curr_Lor_ADE_On = new bool[m_Order];
+ m_curr_Lor_ADE_On[0] = m_curr_Lor_ADE_On[1]=false;
+
+ m_LM_pos = new unsigned int**[m_Order];
+ m_LM_pos[0] = new unsigned int*[3];
+ m_LM_pos[1] = new unsigned int*[3];
+
+ v_int_ADE = new FDTD_FLOAT**[m_Order];
+ v_ext_ADE = new FDTD_FLOAT**[m_Order];
+
+ v_int_ADE[0] = new FDTD_FLOAT*[3];
+ v_ext_ADE[0] = new FDTD_FLOAT*[3];
+ v_int_ADE[1] = new FDTD_FLOAT*[3];
+ v_ext_ADE[1] = new FDTD_FLOAT*[3];
+
+ for (int n=0; n<3; ++n)
+ {
+ m_LM_pos[0][n] = new unsigned int[numCS];
+ m_LM_pos[1][n] = new unsigned int[numCS];
+ for (unsigned int i=0; i<numCS; ++i)
+ {
+ m_LM_pos[0][n][i] = v_pos[n].at(i);
+ m_LM_pos[1][n][i] = v_pos[n].at(i);
+ }
+ v_int_ADE[0][n] = new FDTD_FLOAT[numCS];
+ v_int_ADE[1][n] = new FDTD_FLOAT[numCS];
+ v_ext_ADE[0][n] = new FDTD_FLOAT[numCS];
+ v_ext_ADE[1][n] = new FDTD_FLOAT[numCS];
+ }
+
+ unsigned int index;
+ float w_stop = m_f_max*2*PI;
+ float Omega_max=0;
+ float G,L1,L2,R1,R2,Lmin;
+ float G0, w0;
+ float wtl; //width to length factor
+ float factor=1;
+ int t_dir=0; //tangential sheet direction
+ unsigned int tpos[] = {0,0,0};
+ unsigned int optParaPos;
+ for (unsigned int i=0;i<numCS;++i)
+ {
+ pos[0]=m_LM_pos[0][0][i];pos[1]=m_LM_pos[0][1][i];pos[2]=m_LM_pos[0][2][i];
+ tpos[0]=pos[0];tpos[1]=pos[1];tpos[2]=pos[2];
+ index = m_Op->MainOp->SetPos(pos[0],pos[1],pos[2]);
+ for (int n=0;n<3;++n)
+ {
+ tpos[0]=pos[0];tpos[1]=pos[1];tpos[2]=pos[2];
+ t_dir = tanDir[n][pos[0]][pos[1]][pos[2]];
+ G0 = Conductivity[n][pos[0]][pos[1]][pos[2]]*Thickness[n][pos[0]][pos[1]][pos[2]];
+ w0 = 8.0/ G0 / Thickness[n][pos[0]][pos[1]][pos[2]]/__MUE0__;
+ Omega_max = w_stop/w0;
+ for (optParaPos=0;optParaPos<numOptPara;++optParaPos)
+ if (omega_stop[optParaPos]>Omega_max)
+ break;
+ if (optParaPos>=numOptPara)
+ {
+ cerr << "Operator_Ext_ConductingSheet::BuildExtension(): Error, conductor thickness, conductivity or max. simulation frequency of interest is too high! Check parameter!" << endl;
+ cerr << " --> max f: " << m_f_max << "Hz, Conductivity: " << Conductivity[n][pos[0]][pos[1]][pos[2]] << "S/m, Thickness " << Thickness[n][pos[0]][pos[1]][pos[2]]*1e6 << "um" << endl;
+ optParaPos = numOptPara-1;
+ }
+ v_int_ADE[0][n][i]=0;
+ v_ext_ADE[0][n][i]=0;
+ v_int_ADE[1][n][i]=0;
+ v_ext_ADE[1][n][i]=0;
+ if (t_dir>=0)
+ {
+ wtl = m_Op->GetEdgeLength(n,pos)/m_Op->GetNodeWidth(t_dir,pos);
+ factor = 1;
+ if (tanDir[t_dir][tpos[0]][tpos[1]][tpos[2]]<0)
+ factor = 2;
+ --tpos[t_dir];
+ if (tanDir[t_dir][tpos[0]][tpos[1]][tpos[2]]<0)
+ factor = 2;
+
+ L1 = l1[optParaPos]/G0/w0*factor;
+ L2 = l2[optParaPos]/G0/w0*factor;
+ R1 = r1[optParaPos]/G0*factor;
+ R2 = r2[optParaPos]/G0*factor;
+ G = G0*g[optParaPos]/factor;
+
+ L1*=wtl;
+ L2*=wtl;
+ R1*=wtl;
+ R2*=wtl;
+ G/=wtl;
+
+ Lmin = L1;
+ if (L2<L1)
+ Lmin = L2;
+ m_Op->EC_G[n][index]= G;
+ m_Op->EC_C[n][index]= dT*dT/4.0*(16.0/Lmin + 1/L1 + 1/L2);
+ m_Op->Calc_ECOperatorPos(n,pos);
+
+ v_int_ADE[0][n][i]=(2.0*L1-dT*R1)/(2.0*L1+dT*R1);
+ v_ext_ADE[0][n][i]=dT/(L1+dT*R1/2.0)*m_Op->GetVI(n,pos[0],pos[1],pos[2]);
+ v_int_ADE[1][n][i]=(2.0*L2-dT*R2)/(2.0*L2+dT*R2);
+ v_ext_ADE[1][n][i]=dT/(L2+dT*R2/2.0)*m_Op->GetVI(n,pos[0],pos[1],pos[2]);
+ }
+ }
+ }
+ return true;
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_conductingsheet.h b/openEMS/FDTD/extensions/operator_ext_conductingsheet.h
new file mode 100644
index 0000000..f84dc4b
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_conductingsheet.h
@@ -0,0 +1,51 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_CONDUCTINGSHEET_H
+#define OPERATOR_EXT_CONDUCTINGSHEET_H
+
+#include "FDTD/operator.h"
+#include "operator_ext_lorentzmaterial.h"
+
+/*!
+ FDTD extension for a conducting sheet model as described in:
+ Lauer, A.; Wolff, I.; , "A conducting sheet model for efficient wide band FDTD analysis of planar waveguides and circuits," Microwave Symposium Digest, 1999 IEEE MTT-S International , vol.4, no., pp.1589-1592 vol.4, 1999
+ doi: 10.1109/MWSYM.1999.780262
+ URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=780262&isnumber=16934
+ */
+class Operator_Ext_ConductingSheet : public Operator_Ext_LorentzMaterial
+{
+public:
+ Operator_Ext_ConductingSheet(Operator* op, double f_max);
+
+ virtual Operator_Extension* Clone(Operator* op);
+
+ virtual bool BuildExtension();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return true;}
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return true;}
+ virtual bool IsMPISave() const {return true;}
+
+ virtual string GetExtensionName() const {return string("Conducting Sheet Extension");}
+
+protected:
+ //! Copy constructor
+ Operator_Ext_ConductingSheet(Operator* op, Operator_Ext_ConductingSheet* op_ext);
+ double m_f_max;
+};
+
+#endif // OPERATOR_EXT_CONDUCTINGSHEET_H
diff --git a/openEMS/FDTD/extensions/operator_ext_cylinder.cpp b/openEMS/FDTD/extensions/operator_ext_cylinder.cpp
new file mode 100644
index 0000000..d400bf8
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_cylinder.cpp
@@ -0,0 +1,114 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_cylinder.h"
+#include "FDTD/operator_cylinder.h"
+#include "engine_ext_cylinder.h"
+
+Operator_Ext_Cylinder::Operator_Ext_Cylinder(Operator_Cylinder* op) : Operator_Extension(op)
+{
+ m_Op_Cyl = op;
+
+ CC_R0_included=m_Op_Cyl->GetR0Included();
+ CC_closedAlpha=m_Op_Cyl->GetClosedAlpha();
+
+ vv_R0 = NULL;
+ vi_R0 = NULL;
+}
+
+Operator_Ext_Cylinder::~Operator_Ext_Cylinder()
+{
+ delete[] vv_R0;
+ vv_R0=NULL;
+ delete[] vi_R0;
+ vi_R0=NULL;
+}
+
+bool Operator_Ext_Cylinder::BuildExtension()
+{
+ delete[] vv_R0;
+ vv_R0=NULL;
+ delete[] vi_R0;
+ vi_R0=NULL;
+
+ //if r=0 is not included -> obviously no special treatment for r=0
+ //if alpha direction is not closed, PEC-BC at r=0 necessary and already set...
+ if (CC_R0_included==false)
+ return true;
+
+ vv_R0 = new FDTD_FLOAT[m_Op->GetNumberOfLines(2,true)];
+ vi_R0 = new FDTD_FLOAT[m_Op->GetNumberOfLines(2,true)];
+
+ unsigned int pos[3];
+ double coord[3];
+ double inEC[4];
+ double dT = m_Op->GetTimestep();
+ pos[0]=0;
+ vector<CSPrimitives*> vPrims_metal = m_Op->GetPrimitivesBoundBox(pos[0], -1, -1, (CSProperties::PropertyType)(CSProperties::MATERIAL | CSProperties::METAL));
+ for (pos[2]=0; pos[2]<m_Op->GetNumberOfLines(2,true); ++pos[2])
+ {
+ double C=0;
+ double G=0;
+ vector<CSPrimitives*> vPrims_mat = m_Op->GetPrimitivesBoundBox(pos[0], -1, pos[2], CSProperties::MATERIAL);
+ for (pos[1]=0; pos[1]<m_Op->GetNumberOfLines(1,true)-2; ++pos[1])
+ {
+ m_Op_Cyl->Calc_ECPos(2,pos,inEC,vPrims_mat);
+ C+=inEC[0];
+ G+=inEC[1];
+ }
+ m_Op->SetVV(2,0,0,pos[2], 1);
+ vv_R0[pos[2]] = (1-dT*G/2/C)/(1+dT*G/2/C);
+ vi_R0[pos[2]] = (dT/C)/(1+dT*G/2/C);
+
+ for (unsigned int i=0; i<m_Op->GetNumberOfLines(1,true); ++i)
+ {
+ m_Op->EC_C[2][m_Op->MainOp->SetPos(0,i,pos[2])] = C;
+ m_Op->EC_G[2][m_Op->MainOp->SetPos(0,i,pos[2])] = G;
+ }
+
+ //search for metal on z-axis
+ m_Op_Cyl->GetYeeCoords(2,pos,coord,false);
+ CSProperties* prop = m_Op->CSX->GetPropertyByCoordPriority(coord, vPrims_metal, true);
+ if (prop)
+ {
+ if (prop->GetType()==CSProperties::METAL) //set to PEC
+ {
+ m_Op->SetVV(2,0,0,pos[2], 0);
+ vv_R0[pos[2]] = 0;
+ vi_R0[pos[2]] = 0;
+ m_Op->EC_C[2][m_Op->MainOp->SetPos(0,0,pos[2])] = 0;
+ m_Op->EC_G[2][m_Op->MainOp->SetPos(0,0,pos[2])] = 0;
+ }
+ }
+ }
+ return true;
+}
+
+Engine_Extension* Operator_Ext_Cylinder::CreateEngineExtention()
+{
+ Engine_Ext_Cylinder* eng_ext = new Engine_Ext_Cylinder(this);
+ return eng_ext;
+}
+
+
+void Operator_Ext_Cylinder::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ string On_Off[2] = {"Off", "On"};
+ ostr << " Zeroth Radius\t\t: " << On_Off[CC_R0_included] << endl;
+ ostr << " Closed Rotation\t: " << On_Off[CC_closedAlpha] << endl;
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_cylinder.h b/openEMS/FDTD/extensions/operator_ext_cylinder.h
new file mode 100644
index 0000000..c8dff2d
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_cylinder.h
@@ -0,0 +1,60 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_CYLINDER_H
+#define OPERATOR_EXT_CYLINDER_H
+
+#include "operator_extension.h"
+#include "FDTD/operator.h"
+
+class Operator_Cylinder;
+
+class Operator_Ext_Cylinder : public Operator_Extension
+{
+ friend class Engine_Ext_Cylinder;
+ friend class Operator_Ext_LorentzMaterial;
+public:
+ Operator_Ext_Cylinder(Operator_Cylinder* op);
+ ~Operator_Ext_Cylinder();
+
+ virtual bool BuildExtension();
+
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return true;}
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return true;}
+
+ // FIXME, this extension is not save or unknown to be save to use with MPI
+ virtual bool IsMPISave() const {return false;}
+
+ virtual std::string GetExtensionName() const {return std::string("Extension for the Cylinder-Coords Operator");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+protected:
+ Operator_Cylinder* m_Op_Cyl;
+
+ bool CC_closedAlpha;
+ bool CC_R0_included;
+
+ //special EC operator for R0
+ FDTD_FLOAT* vv_R0; //calc new voltage from old voltage
+ FDTD_FLOAT* vi_R0; //calc new voltage from old current
+
+};
+
+#endif // OPERATOR_EXT_CYLINDER_H
diff --git a/openEMS/FDTD/extensions/operator_ext_dispersive.cpp b/openEMS/FDTD/extensions/operator_ext_dispersive.cpp
new file mode 100644
index 0000000..ed01f1d
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_dispersive.cpp
@@ -0,0 +1,78 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_dispersive.h"
+
+#include "tools/array_ops.h"
+
+using namespace std;
+
+Operator_Ext_Dispersive::Operator_Ext_Dispersive(Operator* op) : Operator_Extension(op)
+{
+ m_curr_ADE_On = NULL;
+ m_volt_ADE_On = NULL;
+
+ m_LM_pos=NULL;
+ m_curr_ADE_On=NULL;
+ m_volt_ADE_On=NULL;
+
+ m_Order = 0;
+}
+
+Operator_Ext_Dispersive::Operator_Ext_Dispersive(Operator* op, Operator_Ext_Dispersive* op_ext) : Operator_Extension(op,op_ext)
+{
+ m_curr_ADE_On = NULL;
+ m_volt_ADE_On = NULL;
+
+ m_LM_pos=NULL;
+ m_curr_ADE_On=NULL;
+ m_volt_ADE_On=NULL;
+
+ m_Order = 0;
+}
+
+Operator_Ext_Dispersive::~Operator_Ext_Dispersive()
+{
+ delete[] m_curr_ADE_On;
+ delete[] m_volt_ADE_On;
+ m_curr_ADE_On=NULL;
+ m_volt_ADE_On=NULL;
+
+ for (int n=0;n<m_Order;++n)
+ {
+ delete[] m_LM_pos[n][0];
+ delete[] m_LM_pos[n][1];
+ delete[] m_LM_pos[n][2];
+ }
+ delete[] m_LM_pos;
+ m_LM_pos=NULL;
+ m_Order=0;
+ m_LM_Count.clear();
+}
+
+void Operator_Ext_Dispersive::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ string On_Off[2] = {"Off", "On"};
+ ostr << " Max. Dispersion Order N = " << m_Order << endl;
+ for (int i=0;i<m_Order;++i)
+ {
+ ostr << " N=" << i << ":\t Active cells\t\t: " << m_LM_Count.at(i) << endl;
+ ostr << " N=" << i << ":\t Voltage ADE is \t: " << On_Off[m_volt_ADE_On[i]] << endl;
+ ostr << " N=" << i << ":\t Current ADE is \t: " << On_Off[m_curr_ADE_On[i]] << endl;
+ }
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_dispersive.h b/openEMS/FDTD/extensions/operator_ext_dispersive.h
new file mode 100644
index 0000000..fab354c
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_dispersive.h
@@ -0,0 +1,56 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_DISPERSIVE_H
+#define OPERATOR_EXT_DISPERSIVE_H
+
+//#include "operator.h"
+#include "operator_extension.h"
+#include "vector"
+
+//! Abstract base class for all dispersive material models, based on an ADE (additional differential equation)
+class Operator_Ext_Dispersive : public Operator_Extension
+{
+ friend class Engine_Ext_Dispersive;
+public:
+ virtual ~Operator_Ext_Dispersive();
+
+ virtual int GetDispersionOrder() {return m_Order;}
+
+ virtual std::string GetExtensionName() const {return std::string("Dispersive Material Abstract Base class");}
+
+ virtual void ShowStat(std::ostream &ostr) const;
+
+protected:
+ Operator_Ext_Dispersive(Operator* op);
+ //! Copy constructor
+ Operator_Ext_Dispersive(Operator* op, Operator_Ext_Dispersive* op_ext);
+
+ //! Dispersive order
+ int m_Order;
+
+ //! Dispersive material count
+ std::vector<unsigned int> m_LM_Count;
+ //! Index with dispersive material
+ // Array setup: m_LM_pos[N_order][direction][mesh_pos]
+ unsigned int ***m_LM_pos;
+
+ bool *m_curr_ADE_On;
+ bool *m_volt_ADE_On;
+};
+
+#endif // OPERATOR_EXT_DISPERSIVE_H
diff --git a/openEMS/FDTD/extensions/operator_ext_excitation.cpp b/openEMS/FDTD/extensions/operator_ext_excitation.cpp
new file mode 100644
index 0000000..d2085ff
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_excitation.cpp
@@ -0,0 +1,372 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_excitation.h"
+#include "engine_ext_excitation.h"
+#include "FDTD/excitation.h"
+#include "ContinuousStructure.h"
+
+#include "CSPrimCurve.h"
+#include "CSPropExcitation.h"
+
+Operator_Ext_Excitation::Operator_Ext_Excitation(Operator* op) : Operator_Extension(op)
+{
+ Init();
+}
+
+Operator_Ext_Excitation::~Operator_Ext_Excitation()
+{
+ Reset();
+}
+
+Operator_Extension* Operator_Ext_Excitation::Clone(Operator* op)
+{
+ Operator_Ext_Excitation* clone = new Operator_Ext_Excitation(op, this);
+ return clone;
+}
+
+void Operator_Ext_Excitation::Init()
+{
+ Operator_Extension::Init();
+ Volt_delay = 0;
+ Volt_amp = 0;
+ Volt_dir = 0;
+ Volt_Count = 0;
+ Curr_delay = 0;
+ Curr_amp = 0;
+ Curr_dir = 0;
+ Curr_Count = 0;
+
+ for (int n=0; n<3; ++n)
+ {
+ Volt_index[n] = 0;
+ Curr_index[n] = 0;
+ Volt_Count_Dir[n] = 0;
+ Curr_Count_Dir[n] = 0;
+ }
+ m_Exc = 0;
+}
+
+void Operator_Ext_Excitation::Reset()
+{
+ Operator_Extension::Reset();
+ delete[] Volt_delay;
+ Volt_delay = 0;
+ delete[] Volt_dir;
+ Volt_dir = 0;
+ delete[] Volt_amp;
+ Volt_amp = 0;
+ delete[] Curr_delay;
+ Curr_delay = 0;
+ delete[] Curr_dir;
+ Curr_dir = 0;
+ delete[] Curr_amp;
+ Curr_amp = 0;
+
+ Volt_Count = 0;
+ Curr_Count = 0;
+
+ for (int n=0; n<3; ++n)
+ {
+ delete[] Volt_index[n];
+ Volt_index[n] = 0;
+ delete[] Curr_index[n];
+ Curr_index[n] = 0;
+
+ Volt_Count_Dir[n] = 0;
+ Curr_Count_Dir[n] = 0;
+ }
+}
+
+
+Operator_Ext_Excitation::Operator_Ext_Excitation(Operator* op, Operator_Ext_Excitation* op_ext) : Operator_Extension(op, op_ext)
+{
+ Init();
+}
+
+bool Operator_Ext_Excitation::BuildExtension()
+{
+ m_Exc = m_Op->GetExcitationSignal();
+ double dT = m_Op->GetTimestep();
+ if (dT==0)
+ return false;
+ if (m_Exc==0)
+ return false;
+
+ Reset();
+ ContinuousStructure* CSX = m_Op->GetGeometryCSX();
+
+ unsigned int pos[3];
+ double amp=0;
+
+ vector<unsigned int> volt_vIndex[3];
+ vector<FDTD_FLOAT> volt_vExcit;
+ vector<unsigned int> volt_vDelay;
+ vector<unsigned int> volt_vDir;
+ double volt_coord[3];
+
+ vector<unsigned int> curr_vIndex[3];
+ vector<FDTD_FLOAT> curr_vExcit;
+ vector<unsigned int> curr_vDelay;
+ vector<unsigned int> curr_vDir;
+ double curr_coord[3];
+
+ vector<CSProperties*> vec_prop = CSX->GetPropertyByType(CSProperties::EXCITATION);
+
+ if (vec_prop.size()==0)
+ {
+ cerr << "Operator::CalcFieldExcitation: Warning, no excitation properties found" << endl;
+ return false;
+ }
+
+ CSPropExcitation* elec=NULL;
+ CSProperties* prop=NULL;
+ int priority=0;
+
+ unsigned int numLines[] = {m_Op->GetNumberOfLines(0,true),m_Op->GetNumberOfLines(1,true),m_Op->GetNumberOfLines(2,true)};
+
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ //electric field excite
+ for (int n=0; n<3; ++n)
+ {
+ if (m_Op->GetYeeCoords(n,pos,volt_coord,false)==false)
+ continue;
+ if (m_CC_R0_included && (n==2) && (pos[0]==0))
+ volt_coord[1] = m_Op->GetDiscLine(1,0);
+
+ if (m_CC_R0_included && (n==1) && (pos[0]==0))
+ continue;
+
+ for (size_t p=0; p<vec_prop.size(); ++p)
+ {
+ prop = vec_prop.at(p);
+ elec = prop->ToExcitation();
+ if (elec==NULL)
+ continue;
+ if (prop->CheckCoordInPrimitive(volt_coord,priority,true))
+ {
+ if ((elec->GetActiveDir(n)) && ( (elec->GetExcitType()==0) || (elec->GetExcitType()==1) ))//&& (pos[n]<numLines[n]-1))
+ {
+ amp = elec->GetWeightedExcitation(n,volt_coord)*m_Op->GetEdgeLength(n,pos);// delta[n]*gridDelta;
+ if (amp!=0)
+ {
+ volt_vExcit.push_back(amp);
+ volt_vDelay.push_back((unsigned int)(elec->GetDelay()/dT));
+ volt_vDir.push_back(n);
+ volt_vIndex[0].push_back(pos[0]);
+ volt_vIndex[1].push_back(pos[1]);
+ volt_vIndex[2].push_back(pos[2]);
+ }
+ if (elec->GetExcitType()==1) //hard excite
+ {
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], 0 );
+ m_Op->SetVI(n,pos[0],pos[1],pos[2], 0 );
+ }
+ }
+ }
+ }
+ }
+
+ //magnetic field excite
+ for (int n=0; n<3; ++n)
+ {
+ if ((pos[0]>=numLines[0]-1) || (pos[1]>=numLines[1]-1) || (pos[2]>=numLines[2]-1))
+ continue; //skip the last H-Line which is outside the FDTD-domain
+ if (m_Op->GetYeeCoords(n,pos,curr_coord,true)==false)
+ continue;
+ for (size_t p=0; p<vec_prop.size(); ++p)
+ {
+ prop = vec_prop.at(p);
+ elec = prop->ToExcitation();
+ if (elec==NULL)
+ continue;
+ if (prop->CheckCoordInPrimitive(curr_coord,priority,true))
+ {
+ if ((elec->GetActiveDir(n)) && ( (elec->GetExcitType()==2) || (elec->GetExcitType()==3) ))
+ {
+ amp = elec->GetWeightedExcitation(n,curr_coord)*m_Op->GetEdgeLength(n,pos,true);// delta[n]*gridDelta;
+ if (amp!=0)
+ {
+ curr_vExcit.push_back(amp);
+ curr_vDelay.push_back((unsigned int)(elec->GetDelay()/dT));
+ curr_vDir.push_back(n);
+ curr_vIndex[0].push_back(pos[0]);
+ curr_vIndex[1].push_back(pos[1]);
+ curr_vIndex[2].push_back(pos[2]);
+ }
+ if (elec->GetExcitType()==3) //hard excite
+ {
+ m_Op->SetII(n,pos[0],pos[1],pos[2], 0 );
+ m_Op->SetIV(n,pos[0],pos[1],pos[2], 0 );
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ }
+
+ //special treatment for primitives of type curve (treated as wires) see also Calc_PEC
+ double p1[3];
+ double p2[3];
+ Grid_Path path;
+ for (size_t p=0; p<vec_prop.size(); ++p)
+ {
+ prop = vec_prop.at(p);
+ elec = prop->ToExcitation();
+ for (size_t n=0; n<prop->GetQtyPrimitives(); ++n)
+ {
+ CSPrimitives* prim = prop->GetPrimitive(n);
+ CSPrimCurve* curv = prim->ToCurve();
+ if (curv)
+ {
+ for (size_t i=1; i<curv->GetNumberOfPoints(); ++i)
+ {
+ curv->GetPoint(i-1,p1,m_Op->m_MeshType);
+ curv->GetPoint(i,p2,m_Op->m_MeshType);
+ path = m_Op->FindPath(p1,p2);
+ if (path.dir.size()>0)
+ prim->SetPrimitiveUsed(true);
+ for (size_t t=0; t<path.dir.size(); ++t)
+ {
+ n = path.dir.at(t);
+ pos[0] = path.posPath[0].at(t);
+ pos[1] = path.posPath[1].at(t);
+ pos[2] = path.posPath[2].at(t);
+ m_Op->GetYeeCoords(n,pos,volt_coord,false);
+ if (elec!=NULL)
+ {
+ if ((elec->GetActiveDir(n)) && (pos[n]<numLines[n]-1) && ( (elec->GetExcitType()==0) || (elec->GetExcitType()==1) ))
+ {
+ amp = elec->GetWeightedExcitation(n,volt_coord)*m_Op->GetEdgeLength(n,pos);
+ if (amp!=0)
+ {
+ volt_vExcit.push_back(amp);
+ volt_vDelay.push_back((unsigned int)(elec->GetDelay()/dT));
+ volt_vDir.push_back(n);
+ volt_vIndex[0].push_back(pos[0]);
+ volt_vIndex[1].push_back(pos[1]);
+ volt_vIndex[2].push_back(pos[2]);
+ }
+ if (elec->GetExcitType()==1) //hard excite
+ {
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], 0 );
+ m_Op->SetVI(n,pos[0],pos[1],pos[2], 0 );
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // set voltage excitations
+ setupVoltageExcitation( volt_vIndex, volt_vExcit, volt_vDelay, volt_vDir );
+
+ // set current excitations
+ setupCurrentExcitation( curr_vIndex, curr_vExcit, curr_vDelay, curr_vDir );
+
+ return true;
+}
+
+void Operator_Ext_Excitation::setupVoltageExcitation( vector<unsigned int> const volt_vIndex[3], vector<FDTD_FLOAT> const& volt_vExcit,
+ vector<unsigned int> const& volt_vDelay, vector<unsigned int> const& volt_vDir )
+{
+ Volt_Count = volt_vIndex[0].size();
+ for (int n=0; n<3; n++)
+ {
+ Volt_Count_Dir[n]=0;
+ delete[] Volt_index[n];
+ Volt_index[n] = new unsigned int[Volt_Count];
+ }
+ delete[] Volt_delay;
+ delete[] Volt_amp;
+ delete[] Volt_dir;
+ Volt_delay = new unsigned int[Volt_Count];
+ Volt_amp = new FDTD_FLOAT[Volt_Count];
+ Volt_dir = new unsigned short[Volt_Count];
+
+// cerr << "Excitation::setupVoltageExcitation(): Number of voltage excitation points: " << Volt_Count << endl;
+// if (Volt_Count==0)
+// cerr << "No E-Field/voltage excitation found!" << endl;
+ for (int n=0; n<3; n++)
+ for (unsigned int i=0; i<Volt_Count; i++)
+ Volt_index[n][i] = volt_vIndex[n].at(i);
+ for (unsigned int i=0; i<Volt_Count; i++)
+ {
+ Volt_delay[i] = volt_vDelay.at(i);
+ Volt_amp[i] = volt_vExcit.at(i);
+ Volt_dir[i] = volt_vDir.at(i);
+ ++Volt_Count_Dir[Volt_dir[i]];
+ }
+}
+
+void Operator_Ext_Excitation::setupCurrentExcitation( vector<unsigned int> const curr_vIndex[3], vector<FDTD_FLOAT> const& curr_vExcit,
+ vector<unsigned int> const& curr_vDelay, vector<unsigned int> const& curr_vDir )
+{
+ Curr_Count = curr_vIndex[0].size();
+ for (int n=0; n<3; n++)
+ {
+ Curr_Count_Dir[n]=0;
+ delete[] Curr_index[n];
+ Curr_index[n] = new unsigned int[Curr_Count];
+ }
+ delete[] Curr_delay;
+ delete[] Curr_amp;
+ delete[] Curr_dir;
+ Curr_delay = new unsigned int[Curr_Count];
+ Curr_amp = new FDTD_FLOAT[Curr_Count];
+ Curr_dir = new unsigned short[Curr_Count];
+
+// cerr << "Excitation::setupCurrentExcitation(): Number of current excitation points: " << Curr_Count << endl;
+// if (Curr_Count==0)
+// cerr << "No H-Field/current excitation found!" << endl;
+ for (int n=0; n<3; ++n)
+ for (unsigned int i=0; i<Curr_Count; i++)
+ Curr_index[n][i] = curr_vIndex[n].at(i);
+ for (unsigned int i=0; i<Curr_Count; i++)
+ {
+ Curr_delay[i] = curr_vDelay.at(i);
+ Curr_amp[i] = curr_vExcit.at(i);
+ Curr_dir[i] = curr_vDir.at(i);
+ ++Curr_Count_Dir[Curr_dir[i]];
+ }
+
+}
+
+Engine_Extension* Operator_Ext_Excitation::CreateEngineExtention()
+{
+ return new Engine_Ext_Excitation(this);
+}
+
+void Operator_Ext_Excitation::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ cout << "Voltage excitations\t: " << Volt_Count << "\t (" << Volt_Count_Dir[0] << ", " << Volt_Count_Dir[1] << ", " << Volt_Count_Dir[2] << ")" << endl;
+ cout << "Current excitations\t: " << Curr_Count << "\t (" << Curr_Count_Dir[0] << ", " << Curr_Count_Dir[1] << ", " << Curr_Count_Dir[2] << ")" << endl;
+ cout << "Excitation Length (TS)\t: " << m_Exc->GetLength() << endl;
+ cout << "Excitation Length (s)\t: " << m_Exc->GetLength()*m_Op->GetTimestep() << endl;
+}
+
diff --git a/openEMS/FDTD/extensions/operator_ext_excitation.h b/openEMS/FDTD/extensions/operator_ext_excitation.h
new file mode 100644
index 0000000..2abcef0
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_excitation.h
@@ -0,0 +1,84 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_EXCITATION_H
+#define OPERATOR_EXT_EXCITATION_H
+
+#include "operator_extension.h"
+#include "FDTD/operator.h"
+
+class Excitation;
+
+class Operator_Ext_Excitation : public Operator_Extension
+{
+ friend class Engine_Ext_Excitation;
+ friend class Engine_Ext_Mur_ABC;
+ friend class Operator;
+public:
+ Operator_Ext_Excitation(Operator* op);
+ ~Operator_Ext_Excitation();
+
+ virtual Operator_Extension* Clone(Operator* op);
+
+ virtual bool BuildExtension();
+
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return true;}
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return true;}
+ virtual bool IsMPISave() const {return true;}
+
+ virtual string GetExtensionName() const {return string("Excitation Extension");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+ virtual void Init();
+ virtual void Reset();
+
+ unsigned int GetVoltCount() const {return Volt_Count;}
+ unsigned int GetVoltCount(int ny) const {return Volt_Count_Dir[ny];}
+
+ unsigned int GetCurrCount() const {return Curr_Count;}
+ unsigned int GetCurrCount(int ny) const {return Curr_Count_Dir[ny];}
+
+protected:
+ Operator_Ext_Excitation(Operator* op, Operator_Ext_Excitation* op_ext);
+
+ Excitation* m_Exc;
+
+ void setupVoltageExcitation( vector<unsigned int> const volt_vIndex[3], vector<FDTD_FLOAT> const& volt_vExcit,
+ vector<unsigned int> const& volt_vDelay, vector<unsigned int> const& volt_vDir );
+ void setupCurrentExcitation( vector<unsigned int> const curr_vIndex[3], vector<FDTD_FLOAT> const& curr_vExcit,
+ vector<unsigned int> const& curr_vDelay, vector<unsigned int> const& curr_vDir );
+ //E-Field/voltage Excitation
+ unsigned int Volt_Count;
+ unsigned int Volt_Count_Dir[3];
+ unsigned int* Volt_index[3];
+ unsigned short* Volt_dir;
+ FDTD_FLOAT* Volt_amp; //represented as edge-voltages!!
+ unsigned int* Volt_delay;
+
+ //H-Field/current Excitation
+ unsigned int Curr_Count;
+ unsigned int Curr_Count_Dir[3];
+ unsigned int* Curr_index[3];
+ unsigned short* Curr_dir;
+ FDTD_FLOAT* Curr_amp; //represented as edge-currents!!
+ unsigned int* Curr_delay;
+};
+
+#endif // OPERATOR_EXT_EXCITATION_H
diff --git a/openEMS/FDTD/extensions/operator_ext_lorentzmaterial.cpp b/openEMS/FDTD/extensions/operator_ext_lorentzmaterial.cpp
new file mode 100644
index 0000000..9f386fc
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_lorentzmaterial.cpp
@@ -0,0 +1,453 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_lorentzmaterial.h"
+#include "engine_ext_lorentzmaterial.h"
+#include "operator_ext_cylinder.h"
+#include "../operator_cylinder.h"
+
+#include "CSPropLorentzMaterial.h"
+#include "CSPropDebyeMaterial.h"
+
+Operator_Ext_LorentzMaterial::Operator_Ext_LorentzMaterial(Operator* op) : Operator_Ext_Dispersive(op)
+{
+ v_int_ADE = NULL;
+ v_ext_ADE = NULL;
+ i_int_ADE = NULL;
+ i_ext_ADE = NULL;
+
+ v_Lor_ADE = NULL;
+ i_Lor_ADE = NULL;
+
+ m_curr_Lor_ADE_On = NULL;
+ m_curr_Lor_ADE_On = NULL;
+}
+
+Operator_Ext_LorentzMaterial::Operator_Ext_LorentzMaterial(Operator* op, Operator_Ext_LorentzMaterial* op_ext) : Operator_Ext_Dispersive(op,op_ext)
+{
+ v_int_ADE = NULL;
+ v_ext_ADE = NULL;
+ i_int_ADE = NULL;
+ i_ext_ADE = NULL;
+
+ v_Lor_ADE = NULL;
+ i_Lor_ADE = NULL;
+
+ m_curr_Lor_ADE_On = NULL;
+ m_curr_Lor_ADE_On = NULL;
+}
+
+Operator_Ext_LorentzMaterial::~Operator_Ext_LorentzMaterial()
+{
+ for (int i=0;i<m_Order;++i)
+ {
+ for (int n=0; n<3; ++n)
+ {
+ if (m_volt_ADE_On[i])
+ {
+ delete[] v_int_ADE[i][n];
+ delete[] v_ext_ADE[i][n];
+ }
+ if (m_curr_ADE_On[i])
+ {
+ delete[] i_int_ADE[i][n];
+ delete[] i_ext_ADE[i][n];
+ }
+ if (m_volt_Lor_ADE_On[i])
+ delete[] v_Lor_ADE[i][n];
+ if (m_curr_Lor_ADE_On[i])
+ delete[] i_Lor_ADE[i][n];
+ }
+ if (m_volt_ADE_On[i])
+ {
+ delete[] v_int_ADE[i];
+ delete[] v_ext_ADE[i];
+ }
+ if (m_curr_ADE_On[i])
+ {
+ delete[] i_int_ADE[i];
+ delete[] i_ext_ADE[i];
+ }
+ if (m_volt_Lor_ADE_On[i])
+ delete[] v_Lor_ADE[i];
+ if (m_curr_Lor_ADE_On[i])
+ delete[] i_Lor_ADE[i];
+ }
+ delete[] v_int_ADE;
+ delete[] v_ext_ADE;
+ delete[] i_int_ADE;
+ delete[] i_ext_ADE;
+ v_int_ADE = NULL;
+ v_ext_ADE = NULL;
+ i_int_ADE = NULL;
+ i_ext_ADE = NULL;
+
+ delete[] v_Lor_ADE;
+ delete[] i_Lor_ADE;
+ v_Lor_ADE = NULL;
+ i_Lor_ADE = NULL;
+
+ delete[] m_curr_Lor_ADE_On;
+ delete[] m_volt_Lor_ADE_On;
+ m_curr_Lor_ADE_On = NULL;
+ m_curr_Lor_ADE_On = NULL;
+}
+
+Operator_Extension* Operator_Ext_LorentzMaterial::Clone(Operator* op)
+{
+ if (dynamic_cast<Operator_Ext_LorentzMaterial*>(this)==NULL)
+ return NULL;
+ return new Operator_Ext_LorentzMaterial(op, this);
+}
+
+bool Operator_Ext_LorentzMaterial::BuildExtension()
+{
+ double dT = m_Op->GetTimestep();
+ unsigned int pos[] = {0,0,0};
+ double coord[3];
+ unsigned int numLines[3] = {m_Op->GetNumberOfLines(0,true),m_Op->GetNumberOfLines(1,true),m_Op->GetNumberOfLines(2,true)};
+ CSPropLorentzMaterial* mat = NULL;
+ CSPropDebyeMaterial* debye_mat = NULL;
+
+ bool warn_once = true;
+
+ bool b_pos_on;
+ vector<unsigned int> v_pos[3];
+
+ // drude material parameter
+ double w_plasma,t_relax;
+ double L_D[3], C_D[3];
+ double R_D[3], G_D[3];
+ vector<double> v_int[3];
+ vector<double> v_ext[3];
+ vector<double> i_int[3];
+ vector<double> i_ext[3];
+
+ //additional Dorentz material parameter
+ double w_Lor_Pol;
+ double C_L[3];
+ double L_L[3];
+ vector<double> v_Lor[3];
+ vector<double> i_Lor[3];
+
+ m_Order = 0;
+ vector<CSProperties*> LD_props = m_Op->CSX->GetPropertyByType(CSProperties::LORENTZMATERIAL);
+ for (size_t n=0;n<LD_props.size();++n)
+ {
+ CSPropLorentzMaterial* LorMat = dynamic_cast<CSPropLorentzMaterial*>(LD_props.at(n));
+ if (LorMat==NULL)
+ return false; //sanity check, this should not happen
+ if (LorMat->GetDispersionOrder()>m_Order)
+ m_Order=LorMat->GetDispersionOrder();
+ }
+ LD_props = m_Op->CSX->GetPropertyByType(CSProperties::DEBYEMATERIAL);
+ for (size_t n=0;n<LD_props.size();++n)
+ {
+ CSPropDebyeMaterial* DebyeMat = dynamic_cast<CSPropDebyeMaterial*>(LD_props.at(n));
+ if (DebyeMat==NULL)
+ return false; //sanity check, this should not happen
+ if (DebyeMat->GetDispersionOrder()>m_Order)
+ m_Order=DebyeMat->GetDispersionOrder();
+ }
+
+ m_LM_pos = new unsigned int**[m_Order];
+
+ m_volt_ADE_On = new bool[m_Order];
+ m_curr_ADE_On = new bool[m_Order];
+ m_volt_Lor_ADE_On = new bool[m_Order];
+ m_curr_Lor_ADE_On = new bool[m_Order];
+
+ v_int_ADE = new FDTD_FLOAT**[m_Order];
+ v_ext_ADE = new FDTD_FLOAT**[m_Order];
+ i_int_ADE = new FDTD_FLOAT**[m_Order];
+ i_ext_ADE = new FDTD_FLOAT**[m_Order];
+
+ v_Lor_ADE = new FDTD_FLOAT**[m_Order];
+ i_Lor_ADE = new FDTD_FLOAT**[m_Order];
+
+ for (int order=0;order<m_Order;++order)
+ {
+ m_volt_ADE_On[order]=false;
+ m_curr_ADE_On[order]=false;
+
+ m_volt_Lor_ADE_On[order]=false;
+ m_curr_Lor_ADE_On[order]=false;
+
+ for (int n=0;n<3;++n)
+ {
+ v_pos[n].clear();
+
+ v_int[n].clear();
+ v_ext[n].clear();
+ i_int[n].clear();
+ i_ext[n].clear();
+
+ v_Lor[n].clear();
+ i_Lor[n].clear();
+ }
+
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ vector<CSPrimitives*> vPrims = m_Op->GetPrimitivesBoundBox(pos[0], pos[1], -1, (CSProperties::PropertyType)(CSProperties::MATERIAL | CSProperties::METAL));
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ unsigned int index = m_Op->MainOp->SetPos(pos[0],pos[1],pos[2]);
+ //calc epsilon lorentz material
+ b_pos_on = false;
+ for (int n=0; n<3; ++n)
+ {
+ L_D[n]=0;
+ R_D[n]=0;
+ C_L[n]=0;
+ if (m_Op->GetYeeCoords(n,pos,coord,false)==false)
+ continue;
+ if (m_CC_R0_included && (n==2) && (pos[0]==0))
+ coord[1] = m_Op->GetDiscLine(1,0);
+
+ if (m_Op->GetVI(n,pos[0],pos[1],pos[2])==0)
+ continue;
+
+// CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord,(CSProperties::PropertyType)(CSProperties::METAL | CSProperties::MATERIAL), true);
+ CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord, vPrims, true);
+ if ((mat = prop->ToLorentzMaterial()))
+ {
+ w_plasma = mat->GetEpsPlasmaFreqWeighted(order,n,coord) * 2 * PI;
+ if ((w_plasma>0) && (m_Op->EC_C[n][index]>0))
+ {
+ b_pos_on = true;
+ m_volt_ADE_On[order] = true;
+ L_D[n] = 1/(w_plasma*w_plasma*m_Op->EC_C[n][index]);
+ }
+ t_relax = mat->GetEpsRelaxTimeWeighted(order,n,coord);
+ if ((t_relax>0) && m_volt_ADE_On[order])
+ {
+ R_D[n] = L_D[n]/t_relax;
+ }
+ w_Lor_Pol = mat->GetEpsLorPoleFreqWeighted(order,n,coord) * 2 * PI;
+ if ((w_Lor_Pol>0) && (L_D[n]>0))
+ {
+ m_volt_Lor_ADE_On[order] = true;
+ C_L[n] = 1/(w_Lor_Pol*w_Lor_Pol*L_D[n]);
+ }
+ }
+ if ((debye_mat = prop->ToDebyeMaterial()))
+ {
+ C_L[n] = 8.85418781762e-12*debye_mat->GetEpsDeltaWeighted(order,n,coord) * m_Op->GetEdgeArea(n, pos) / m_Op->GetEdgeLength(n,pos);
+ t_relax = debye_mat->GetEpsRelaxTimeWeighted(order,n,coord);
+ if ((t_relax<2.0*dT) && warn_once)
+ {
+ warn_once = false;
+ cerr << "Operator_Ext_LorentzMaterial::BuildExtension(): Warning, debye relaxation time is to small, skipping..." << endl;
+ }
+ if ((C_L[n]>0) && (t_relax>0) && (t_relax>2.0*dT))
+ {
+ R_D[n] = t_relax/C_L[n];
+ b_pos_on = true;
+ m_volt_ADE_On[order] = true;
+ m_volt_Lor_ADE_On[order] = true;
+ }
+ }
+ }
+
+ for (int n=0; n<3; ++n)
+ {
+ C_D[n]=0;
+ G_D[n]=0;
+ L_L[n]=0;
+ if (m_Op->GetYeeCoords(n,pos,coord,true)==false)
+ continue;
+ if (m_Op->GetIV(n,pos[0],pos[1],pos[2])==0)
+ continue;
+
+// CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord,(CSProperties::PropertyType)(CSProperties::METAL | CSProperties::MATERIAL), true);
+ CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord, vPrims, true);
+ if ((mat = prop->ToLorentzMaterial()))
+ {
+ w_plasma = mat->GetMuePlasmaFreqWeighted(order,n,coord) * 2 * PI;
+ if ((w_plasma>0) && (m_Op->EC_L[n][index]>0))
+ {
+ b_pos_on = true;
+ m_curr_ADE_On[order] = true;
+ C_D[n] = 1/(w_plasma*w_plasma*m_Op->EC_L[n][index]);
+ }
+ t_relax = mat->GetMueRelaxTimeWeighted(order,n,coord);
+ if ((t_relax>0) && m_curr_ADE_On[order])
+ {
+ G_D[n] = C_D[n]/t_relax;
+ }
+ w_Lor_Pol = mat->GetMueLorPoleFreqWeighted(order,n,coord) * 2 * PI;
+ if ((w_Lor_Pol>0) && (C_D[n]>0))
+ {
+ m_curr_Lor_ADE_On[order] = true;
+ L_L[n] = 1/(w_Lor_Pol*w_Lor_Pol*C_D[n]);
+ }
+ }
+ }
+
+ if (b_pos_on) //this position has active drude material
+ {
+ for (unsigned int n=0; n<3; ++n)
+ {
+ v_pos[n].push_back(pos[n]);
+ if (L_D[n]>0)
+ {
+ v_int[n].push_back((2.0*L_D[n]-dT*R_D[n])/(2.0*L_D[n]+dT*R_D[n]));
+ // check for r==0 in clyindrical coords and get special VI cooefficient
+ if (m_CC_R0_included && n==2 && pos[0]==0)
+ v_ext[n].push_back(dT/(L_D[n]+dT*R_D[n]/2.0)*m_Op_Cyl->m_Cyl_Ext->vi_R0[pos[2]]);
+ else
+ v_ext[n].push_back(dT/(L_D[n]+dT*R_D[n]/2.0)*m_Op->GetVI(n,pos[0],pos[1],pos[2]));
+ }
+ else if ((R_D[n]>0) && (C_L[n]>0))
+ {
+ v_int[n].push_back((2.0*dT-R_D[n]*C_L[n])/(C_L[n]*R_D[n]));
+ v_ext[n].push_back(2.0/R_D[n]*m_Op->GetVI(n,pos[0],pos[1],pos[2]));
+ }
+ else
+ {
+ v_int[n].push_back(1);
+ v_ext[n].push_back(0);
+ }
+ if (C_D[n]>0)
+ {
+ i_int[n].push_back((2.0*C_D[n]-dT*G_D[n])/(2.0*C_D[n]+dT*G_D[n]));
+ i_ext[n].push_back(dT/(C_D[n]+dT*G_D[n]/2.0)*m_Op->GetIV(n,pos[0],pos[1],pos[2]));
+ }
+ else
+ {
+ i_int[n].push_back(1);
+ i_ext[n].push_back(0);
+ }
+ if (C_L[n]>0)
+ v_Lor[n].push_back(dT/C_L[n]/m_Op->GetVI(n,pos[0],pos[1],pos[2]));
+ else
+ v_Lor[n].push_back(0);
+ if (L_L[n]>0)
+ i_Lor[n].push_back(dT/L_L[n]/m_Op->GetIV(n,pos[0],pos[1],pos[2]));
+ else
+ i_Lor[n].push_back(0);
+ }
+ }
+ }
+ }
+ }
+
+ //copy all vectors into the array's
+ m_LM_Count.push_back(v_pos[0].size());
+
+ m_LM_pos[order] = new unsigned int*[3];
+
+ if (m_volt_ADE_On[order])
+ {
+ v_int_ADE[order] = new FDTD_FLOAT*[3];
+ v_ext_ADE[order] = new FDTD_FLOAT*[3];
+ }
+ else
+ {
+ v_int_ADE[order] = NULL;
+ v_ext_ADE[order] = NULL;
+ }
+
+ if (m_curr_ADE_On[order])
+ {
+ i_int_ADE[order] = new FDTD_FLOAT*[3];
+ i_ext_ADE[order] = new FDTD_FLOAT*[3];
+ }
+ else
+ {
+ i_int_ADE[order] = NULL;
+ i_ext_ADE[order] = NULL;
+ }
+
+ if (m_volt_Lor_ADE_On[order])
+ v_Lor_ADE[order] = new FDTD_FLOAT*[3];
+ else
+ v_Lor_ADE[order] = NULL;
+
+ if (m_curr_Lor_ADE_On[order])
+ i_Lor_ADE[order] = new FDTD_FLOAT*[3];
+ else
+ i_Lor_ADE[order] = NULL;
+
+ for (int n=0; n<3; ++n)
+ {
+ m_LM_pos[order][n] = new unsigned int[m_LM_Count.at(order)];
+ for (unsigned int i=0; i<m_LM_Count.at(order); ++i)
+ m_LM_pos[order][n][i] = v_pos[n].at(i);
+ if (m_volt_ADE_On[order])
+ {
+ v_int_ADE[order][n] = new FDTD_FLOAT[m_LM_Count.at(order)];
+ v_ext_ADE[order][n] = new FDTD_FLOAT[m_LM_Count.at(order)];
+
+ for (unsigned int i=0; i<m_LM_Count.at(order); ++i)
+ {
+ v_int_ADE[order][n][i] = v_int[n].at(i);
+ v_ext_ADE[order][n][i] = v_ext[n].at(i);
+ }
+ }
+ if (m_curr_ADE_On[order])
+ {
+ i_int_ADE[order][n] = new FDTD_FLOAT[m_LM_Count.at(order)];
+ i_ext_ADE[order][n] = new FDTD_FLOAT[m_LM_Count.at(order)];
+
+ for (unsigned int i=0; i<m_LM_Count.at(order); ++i)
+ {
+ i_int_ADE[order][n][i] = i_int[n].at(i);
+ i_ext_ADE[order][n][i] = i_ext[n].at(i);
+ }
+ }
+
+ if (m_volt_Lor_ADE_On[order])
+ {
+ v_Lor_ADE[order][n] = new FDTD_FLOAT[m_LM_Count.at(order)];
+ for (unsigned int i=0; i<m_LM_Count.at(order); ++i)
+ v_Lor_ADE[order][n][i] = v_Lor[n].at(i);
+ }
+ if (m_curr_Lor_ADE_On[order])
+ {
+ i_Lor_ADE[order][n] = new FDTD_FLOAT[m_LM_Count.at(order)];
+ for (unsigned int i=0; i<m_LM_Count.at(order); ++i)
+ i_Lor_ADE[order][n][i] = i_Lor[n].at(i);
+ }
+ }
+ }
+
+ return true;
+}
+
+Engine_Extension* Operator_Ext_LorentzMaterial::CreateEngineExtention()
+{
+ Engine_Ext_LorentzMaterial* eng_ext_lor = new Engine_Ext_LorentzMaterial(this);
+ return eng_ext_lor;
+}
+
+void Operator_Ext_LorentzMaterial::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ string On_Off[2] = {"Off", "On"};
+ ostr << " Max. Dispersion Order N = " << m_Order << endl;
+ for (int i=0;i<m_Order;++i)
+ {
+ ostr << " N=" << i << ":\t Active cells\t\t: " << m_LM_Count.at(i) << endl;
+ ostr << " N=" << i << ":\t Voltage ADE is \t: " << On_Off[m_volt_ADE_On[i]] << endl;
+ ostr << " N=" << i << ":\t Voltage Lor-ADE is \t: " << On_Off[m_volt_Lor_ADE_On[i]] << endl;
+ ostr << " N=" << i << ":\t Current ADE is \t: " << On_Off[m_curr_ADE_On[i]] << endl;
+ ostr << " N=" << i << ":\t Current Lor-ADE is \t: " << On_Off[m_curr_Lor_ADE_On[i]] << endl;
+ }
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_lorentzmaterial.h b/openEMS/FDTD/extensions/operator_ext_lorentzmaterial.h
new file mode 100644
index 0000000..d9e600b
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_lorentzmaterial.h
@@ -0,0 +1,62 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_LORENTZMATERIAL_H
+#define OPERATOR_EXT_LORENTZMATERIAL_H
+
+#include "FDTD/operator.h"
+#include "operator_ext_dispersive.h"
+
+class Operator_Ext_LorentzMaterial : public Operator_Ext_Dispersive
+{
+ friend class Engine_Ext_LorentzMaterial;
+public:
+ Operator_Ext_LorentzMaterial(Operator* op);
+ virtual ~Operator_Ext_LorentzMaterial();
+
+ virtual Operator_Extension* Clone(Operator* op);
+
+ virtual bool BuildExtension();
+
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return true;}
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return true;}
+ virtual bool IsMPISave() const {return true;}
+
+ virtual string GetExtensionName() const {return string("Drude/Lorentz Dispersive Material Extension");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+protected:
+ //! Copy constructor
+ Operator_Ext_LorentzMaterial(Operator* op, Operator_Ext_LorentzMaterial* op_ext);
+
+ //ADE update coefficients, array setup: coeff[N_order][direction][mesh_pos_index]
+ FDTD_FLOAT ***v_int_ADE;
+ FDTD_FLOAT ***v_ext_ADE;
+ FDTD_FLOAT ***i_int_ADE;
+ FDTD_FLOAT ***i_ext_ADE;
+
+ bool *m_curr_Lor_ADE_On;
+ bool *m_volt_Lor_ADE_On;
+
+ FDTD_FLOAT ***v_Lor_ADE;
+ FDTD_FLOAT ***i_Lor_ADE;
+};
+
+#endif // OPERATOR_EXT_LORENTZMATERIAL_H
diff --git a/openEMS/FDTD/extensions/operator_ext_mur_abc.cpp b/openEMS/FDTD/extensions/operator_ext_mur_abc.cpp
new file mode 100644
index 0000000..1df8583
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_mur_abc.cpp
@@ -0,0 +1,210 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_mur_abc.h"
+#include "engine_ext_mur_abc.h"
+
+#include "tools/array_ops.h"
+
+#include "CSPropMaterial.h"
+
+Operator_Ext_Mur_ABC::Operator_Ext_Mur_ABC(Operator* op) : Operator_Extension(op)
+{
+ Initialize();
+}
+
+Operator_Ext_Mur_ABC::~Operator_Ext_Mur_ABC()
+{
+ Delete2DArray(m_Mur_Coeff_nyP,m_numLines);
+ m_Mur_Coeff_nyP = NULL;
+ Delete2DArray(m_Mur_Coeff_nyPP,m_numLines);
+ m_Mur_Coeff_nyPP = NULL;
+}
+
+Operator_Ext_Mur_ABC::Operator_Ext_Mur_ABC(Operator* op, Operator_Ext_Mur_ABC* op_ext) : Operator_Extension(op, op_ext)
+{
+ Initialize();
+ m_v_phase = op_ext->m_v_phase;
+ SetDirection(op_ext->m_ny,op_ext->m_top);
+}
+
+Operator_Extension* Operator_Ext_Mur_ABC::Clone(Operator* op)
+{
+ if (dynamic_cast<Operator_Ext_Mur_ABC*>(this)==NULL)
+ return NULL;
+ return new Operator_Ext_Mur_ABC(op, this);
+}
+
+bool Operator_Ext_Mur_ABC::IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const
+{
+ if ((m_ny==0) && (!m_top) && (R0_included || closedAlpha))
+ return false;
+ if ((m_ny==1) && (closedAlpha))
+ return false;
+ return true;
+}
+
+bool Operator_Ext_Mur_ABC::IsCylindricalMultiGridSave(bool child) const
+{
+ if (m_ny==2) //always allow in z-direction
+ return true;
+ if ((m_ny==0) && (m_top) && (!child)) //if top r-direction and is not a child grid allow Mur...
+ return true;
+ //in all other cases this ABC is not save to use in CylindricalMultiGrid
+ return false;
+}
+
+void Operator_Ext_Mur_ABC::Initialize()
+{
+ m_ny = -1;
+ m_nyP = -1;
+ m_nyPP = -1;
+ m_LineNr = 0;
+ m_LineNr_Shift = 0;
+
+ m_v_phase = 0.0;
+
+ m_Mur_Coeff_nyP = NULL;
+ m_Mur_Coeff_nyPP = NULL;
+
+ m_numLines[0]=0;
+ m_numLines[1]=0;
+}
+
+void Operator_Ext_Mur_ABC::SetDirection(int ny, bool top_ny)
+{
+ if ((ny<0) || (ny>2))
+ return;
+
+ Delete2DArray(m_Mur_Coeff_nyP,m_numLines);
+ Delete2DArray(m_Mur_Coeff_nyPP,m_numLines);
+
+ m_ny = ny;
+ m_top = top_ny;
+ m_nyP = (ny+1)%3;
+ m_nyPP = (ny+2)%3;
+ if (!top_ny)
+ {
+ m_LineNr = 0;
+ m_LineNr_Shift = 1;
+ }
+ else
+ {
+ m_LineNr = m_Op->GetNumberOfLines(m_ny,true)-1;
+ m_LineNr_Shift = m_Op->GetNumberOfLines(m_ny,true) - 2;
+ }
+
+ m_numLines[0] = m_Op->GetNumberOfLines(m_nyP,true);
+ m_numLines[1] = m_Op->GetNumberOfLines(m_nyPP,true);
+
+ m_Mur_Coeff_nyP = Create2DArray<FDTD_FLOAT>(m_numLines);
+ m_Mur_Coeff_nyPP = Create2DArray<FDTD_FLOAT>(m_numLines);
+
+}
+
+bool Operator_Ext_Mur_ABC::BuildExtension()
+{
+ if (m_ny<0)
+ {
+ cerr << "Operator_Ext_Mur_ABC::BuildExtension: Warning, Extension not initialized! Use SetDirection!! Abort build!!" << endl;
+ return false;
+ }
+ double dT = m_Op->GetTimestep();
+ unsigned int pos[] = {0,0,0};
+ pos[m_ny] = m_LineNr;
+ double delta = fabs(m_Op->GetEdgeLength(m_ny,pos));
+ double coord[] = {0,0,0};
+ coord[0] = m_Op->GetDiscLine(0,pos[0]);
+ coord[1] = m_Op->GetDiscLine(1,pos[1]);
+ coord[2] = m_Op->GetDiscLine(2,pos[2]);
+
+ double eps,mue;
+ double c0t;
+
+ if (m_LineNr==0)
+ coord[m_ny] = m_Op->GetDiscLine(m_ny,pos[m_ny]) + delta/2 / m_Op->GetGridDelta();
+ else
+ coord[m_ny] = m_Op->GetDiscLine(m_ny,pos[m_ny]) - delta/2 / m_Op->GetGridDelta();
+
+ int posBB[3];
+ posBB[m_ny] =pos[m_ny];
+ posBB[m_nyPP]=-1;
+
+ for (pos[m_nyP]=0; pos[m_nyP]<m_numLines[0]; ++pos[m_nyP])
+ {
+ posBB[m_nyP]=pos[m_nyP];
+ vector<CSPrimitives*> vPrims = m_Op->GetPrimitivesBoundBox(posBB[0], posBB[1], posBB[2], CSProperties::MATERIAL);
+ coord[m_nyP] = m_Op->GetDiscLine(m_nyP,pos[m_nyP]);
+ for (pos[m_nyPP]=0; pos[m_nyPP]<m_numLines[1]; ++pos[m_nyPP])
+ {
+ coord[m_nyPP] = m_Op->GetDiscLine(m_nyPP,pos[m_nyPP]);
+// CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord, CSProperties::MATERIAL, false);
+ CSProperties* prop = m_Op->GetGeometryCSX()->GetPropertyByCoordPriority(coord, vPrims, false);
+ if (prop)
+ {
+ CSPropMaterial* mat = prop->ToMaterial();
+
+ //nP
+ eps = mat->GetEpsilonWeighted(m_nyP,coord);
+ mue = mat->GetMueWeighted(m_nyP,coord);
+ if (m_v_phase>0.0)
+ c0t = m_v_phase * dT;
+ else
+ c0t = __C0__ * dT / sqrt(eps*mue);
+ m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] = (c0t - delta) / (c0t + delta);
+
+ //nPP
+ eps = mat->GetEpsilonWeighted(m_nyPP,coord);
+ mue = mat->GetMueWeighted(m_nyPP,coord);
+ if (m_v_phase>0.0)
+ c0t = m_v_phase * dT;
+ else
+ c0t = __C0__ * dT / sqrt(eps*mue);
+ m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] = (c0t - delta) / (c0t + delta);
+
+ }
+ else
+ {
+ if (m_v_phase>0.0)
+ c0t = m_v_phase * dT;
+ else
+ c0t = __C0__ / sqrt(m_Op->GetBackgroundEpsR()*m_Op->GetBackgroundMueR()) * dT;
+ m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] = (c0t - delta) / (c0t + delta);
+ m_Mur_Coeff_nyPP[pos[m_nyP]][pos[m_nyPP]] = m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]];
+ }
+// cerr << m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] << " : " << m_Mur_Coeff_nyP[pos[m_nyP]][pos[m_nyPP]] << endl;
+ }
+ }
+// cerr << "Operator_Ext_Mur_ABC::BuildExtension(): " << m_ny << " @ " << m_LineNr << endl;
+ return true;
+}
+
+Engine_Extension* Operator_Ext_Mur_ABC::CreateEngineExtention()
+{
+ Engine_Ext_Mur_ABC* eng_ext = new Engine_Ext_Mur_ABC(this);
+ return eng_ext;
+}
+
+
+void Operator_Ext_Mur_ABC::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ string XYZ[3] = {"x","y","z"};
+ ostr << " Active direction\t: " << XYZ[m_ny] << " at line: " << m_LineNr << endl;
+ if (m_v_phase>0.0)
+ ostr << " Used phase velocity\t: " << m_v_phase << " (" << m_v_phase/__C0__ << " * c_0)" <<endl;
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_mur_abc.h b/openEMS/FDTD/extensions/operator_ext_mur_abc.h
new file mode 100644
index 0000000..ddc43c1
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_mur_abc.h
@@ -0,0 +1,68 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_MUR_ABC_H
+#define OPERATOR_EXT_MUR_ABC_H
+
+#include "FDTD/operator.h"
+#include "operator_extension.h"
+
+class Operator_Ext_Mur_ABC : public Operator_Extension
+{
+ friend class Engine_Ext_Mur_ABC;
+public:
+ Operator_Ext_Mur_ABC(Operator* op);
+ ~Operator_Ext_Mur_ABC();
+
+ virtual Operator_Extension* Clone(Operator* op);
+
+ //! Define the direction of this ABC: \a ny=0,1,2 -> x,y,z and if at bottom_ny -> e.g. x=0 or x=end
+ void SetDirection(int ny, bool top_ny);
+
+ //! Set (override) the expected phase velocity of the incoming wave
+ void SetPhaseVelocity(double c_phase) {m_v_phase=c_phase;};
+
+ virtual bool BuildExtension();
+
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const;
+ virtual bool IsCylindricalMultiGridSave(bool child) const;
+ virtual bool IsMPISave() const {return true;}
+
+ virtual string GetExtensionName() const {return string("Mur ABC Extension");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+protected:
+ Operator_Ext_Mur_ABC(Operator* op, Operator_Ext_Mur_ABC* op_ext);
+ void Initialize();
+ int m_ny;
+ int m_nyP,m_nyPP;
+ bool m_top;
+ unsigned int m_LineNr;
+ int m_LineNr_Shift;
+
+ double m_v_phase;
+
+ unsigned int m_numLines[2];
+
+ FDTD_FLOAT** m_Mur_Coeff_nyP;
+ FDTD_FLOAT** m_Mur_Coeff_nyPP;
+};
+
+#endif // OPERATOR_EXT_MUR_ABC_H
diff --git a/openEMS/FDTD/extensions/operator_ext_steadystate.cpp b/openEMS/FDTD/extensions/operator_ext_steadystate.cpp
new file mode 100644
index 0000000..b8395a8
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_steadystate.cpp
@@ -0,0 +1,104 @@
+/*
+* Copyright (C) 2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_steadystate.h"
+#include "engine_ext_steadystate.h"
+
+Operator_Ext_SteadyState::Operator_Ext_SteadyState(Operator* op, double period): Operator_Extension(op)
+{
+ this->Reset();
+ m_T_period = period;
+}
+
+Operator_Ext_SteadyState::Operator_Ext_SteadyState(Operator* op, Operator_Ext_SteadyState* op_ext): Operator_Extension(op, op_ext)
+{
+ this->Reset();
+ m_T_period = op_ext->m_T_period;
+}
+
+Operator_Ext_SteadyState::~Operator_Ext_SteadyState()
+{
+}
+
+Operator_Extension* Operator_Ext_SteadyState::Clone(Operator* op)
+{
+ //disable cloning, only the main operator needs to have a steady state detection
+ UNUSED(op);
+ return NULL;
+}
+
+bool Operator_Ext_SteadyState::BuildExtension()
+{
+ double dT = m_Op->GetTimestep();
+ m_TS_period = round(m_T_period/dT);
+ m_T_period = m_TS_period*dT;
+ return true;
+}
+
+void Operator_Ext_SteadyState::Reset()
+{
+ for (int n=0;n<3;++n)
+ {
+ m_E_probe_pos[n].clear();
+ m_H_probe_pos[n].clear();
+ }
+ m_E_probe_dir.clear();
+ m_H_probe_dir.clear();
+ m_T_period = 0;
+ m_TS_period = 0;
+}
+
+bool Operator_Ext_SteadyState::Add_E_Probe(unsigned int pos[3], int dir)
+{
+ if ((dir<0) || (dir>2))
+ return false;
+ for (int n=0;n<3;++n)
+ if (pos[n]>=m_Op->GetNumberOfLines(n))
+ return false;
+ for (int n=0;n<3;++n)
+ m_E_probe_pos[n].push_back(pos[n]);
+ m_E_probe_dir.push_back(dir);
+ return true;
+}
+
+bool Operator_Ext_SteadyState::Add_H_Probe(unsigned int pos[3], int dir)
+{
+ if ((dir<0) || (dir>2))
+ return false;
+ for (int n=0;n<3;++n)
+ if (pos[n]>=m_Op->GetNumberOfLines(n))
+ return false;
+ for (int n=0;n<3;++n)
+ m_H_probe_pos[n].push_back(pos[n]);
+ m_H_probe_dir.push_back(dir);
+ return true;
+}
+
+Engine_Extension* Operator_Ext_SteadyState::CreateEngineExtention()
+{
+ m_Eng_Ext = new Engine_Ext_SteadyState(this);
+ return m_Eng_Ext;
+}
+
+void Operator_Ext_SteadyState::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ cout << "Period time (s): " << m_T_period << "\t Period TS: " << m_TS_period << endl;
+ cout << "Number of E probes\t: " << m_E_probe_dir.size() << endl;
+ cout << "Number of H probes\t: " << m_H_probe_dir.size() << endl;
+}
+
diff --git a/openEMS/FDTD/extensions/operator_ext_steadystate.h b/openEMS/FDTD/extensions/operator_ext_steadystate.h
new file mode 100644
index 0000000..b735ca3
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_steadystate.h
@@ -0,0 +1,61 @@
+/*
+* Copyright (C) 2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_STEADYSTATE_H
+#define OPERATOR_EXT_STEADYSTATE_H
+
+#include "operator_extension.h"
+#include "FDTD/operator.h"
+
+class Engine_Ext_SteadyState;
+
+class Operator_Ext_SteadyState : public Operator_Extension
+{
+ friend class Engine_Ext_SteadyState;
+public:
+ Operator_Ext_SteadyState(Operator* op, double period);
+ virtual ~Operator_Ext_SteadyState();
+
+ virtual Operator_Extension* Clone(Operator* op);
+
+ virtual bool BuildExtension();
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return true;}
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return true;}
+ virtual bool IsMPISave() const {return true;}
+
+ virtual string GetExtensionName() const {return string("Steady-State Detection Extension");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+ virtual void Reset();
+
+ bool Add_E_Probe(unsigned int pos[3], int dir);
+ bool Add_H_Probe(unsigned int pos[3], int dir);
+
+protected:
+ Operator_Ext_SteadyState(Operator* op, Operator_Ext_SteadyState* op_ext);
+ double m_T_period;
+ unsigned int m_TS_period;
+ vector<unsigned int> m_E_probe_pos[3];
+ vector<unsigned int> m_E_probe_dir;
+ vector<unsigned int> m_H_probe_pos[3];
+ vector<unsigned int> m_H_probe_dir;
+};
+
+#endif // OPERATOR_EXT_STEADYSTATE_H
diff --git a/openEMS/FDTD/extensions/operator_ext_tfsf.cpp b/openEMS/FDTD/extensions/operator_ext_tfsf.cpp
new file mode 100644
index 0000000..663dc1f
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_tfsf.cpp
@@ -0,0 +1,429 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_tfsf.h"
+#include "engine_ext_tfsf.h"
+#include <cmath>
+
+#include "CSPrimBox.h"
+#include "CSPropExcitation.h"
+
+Operator_Ext_TFSF::Operator_Ext_TFSF(Operator* op) : Operator_Extension(op)
+{
+ Init();
+}
+
+Operator_Ext_TFSF::~Operator_Ext_TFSF()
+{
+ Reset();
+}
+
+void Operator_Ext_TFSF::Init()
+{
+ for (int n=0;n<3;++n)
+ for (int l=0;l<2;++l)
+ for (int c=0;c<2;++c)
+ {
+ m_VoltDelay[n][l][c]=NULL;
+ m_VoltDelayDelta[n][l][c]=NULL;
+ m_VoltAmp[n][l][c]=NULL;
+ m_CurrDelay[n][l][c]=NULL;
+ m_CurrDelayDelta[n][l][c]=NULL;
+ m_CurrAmp[n][l][c]=NULL;
+ }
+
+ m_Frequency = 0.0;
+ m_PhVel = __C0__;
+ Operator_Extension::Init();
+}
+
+void Operator_Ext_TFSF::Reset()
+{
+ for (int n=0;n<3;++n)
+ for (int l=0;l<2;++l)
+ for (int c=0;c<2;++c)
+ {
+ delete[] m_VoltDelay[n][l][c];
+ m_VoltDelay[n][l][c]=NULL;
+ delete[] m_VoltDelayDelta[n][l][c];
+ m_VoltDelayDelta[n][l][c]=NULL;
+ delete[] m_VoltAmp[n][l][c];
+ m_VoltAmp[n][l][c]=NULL;
+ delete[] m_CurrDelay[n][l][c];
+ m_CurrDelay[n][l][c]=NULL;
+ delete[] m_CurrDelayDelta[n][l][c];
+ m_CurrDelayDelta[n][l][c]=NULL;
+ delete[] m_CurrAmp[n][l][c];
+ m_CurrAmp[n][l][c]=NULL;
+ }
+ Operator_Extension::Reset();
+}
+
+Operator_Extension* Operator_Ext_TFSF::Clone(Operator* op)
+{
+ UNUSED(op);
+ return NULL;
+}
+
+bool Operator_Ext_TFSF::BuildExtension()
+{
+ m_Exc = m_Op->GetExcitationSignal();
+ double dT = m_Op->GetTimestep();
+ if (dT==0)
+ return false;
+ if (m_Exc==0)
+ return false;
+
+ Reset();
+ ContinuousStructure* CSX = m_Op->GetGeometryCSX();
+
+ vector<CSProperties*> vec_prop = CSX->GetPropertyByType(CSProperties::EXCITATION);
+
+ if (vec_prop.size()==0)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, no excitation properties found" << endl;
+ SetActive(false);
+ return false;
+ }
+
+ double ref_index = sqrt(m_Op->GetBackgroundEpsR()*m_Op->GetBackgroundMueR());
+ m_PhVel = __C0__/ref_index;
+ CSPropExcitation* elec=NULL;
+ CSProperties* prop=NULL;
+ CSPrimitives* prim=NULL;
+ CSPrimBox* box=NULL;
+ for (size_t p=0; p<vec_prop.size(); ++p)
+ {
+ prop = vec_prop.at(p);
+ elec = prop->ToExcitation();
+ if (elec->GetExcitType()!=10)
+ continue;
+ if (prop->GetQtyPrimitives()!=1)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, plane wave excitation found with more (or less) than one primitive, skipping..." << endl;
+ continue;
+ }
+ prim = prop->GetPrimitive(0);
+ if (prim->GetType()!=CSPrimitives::BOX)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, plane wave excitation found with false non-Box primitive, skipping..." << endl;
+ continue;
+ }
+ box = prim->ToBox();
+ if (box==NULL) //sanity check, should not happen!
+ {
+ SetActive(false);
+ return false;
+ }
+
+ // found a plane-wave excite with exactly one box
+ for (int n=0;n<3;++n)
+ m_PropDir[n] = elec->GetPropagationDir(n);
+ double dir_norm = sqrt(m_PropDir[0]*m_PropDir[0]+m_PropDir[1]*m_PropDir[1]+m_PropDir[2]*m_PropDir[2]);
+ if (dir_norm==0)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, plane wave direction is zero, skipping..." << endl;
+ SetActive(false);
+ return false;
+ }
+
+ //make it a unit vector
+ m_PropDir[0]/=dir_norm;m_PropDir[1]/=dir_norm;m_PropDir[2]/=dir_norm;
+
+ if (m_Op->SnapBox2Mesh(box->GetStartCoord()->GetNativeCoords(), box->GetStopCoord()->GetNativeCoords(), m_Start, m_Stop)!=3)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, plane wave box dimension is invalid, skipping..." << endl;
+ SetActive(false);
+ return false;
+ }
+
+ m_Frequency = elec->GetFrequency();
+// if (m_Frequency<=0)
+// m_Frequency = m_Op->GetExcitationSignal()->GetFrequencyOfInterest();
+ if (m_Frequency<=0)
+ m_PhVel=__C0__/ref_index;
+ else
+ m_PhVel=m_Op->CalcNumericPhaseVelocity(m_Start,m_Stop,m_PropDir,m_Frequency);
+
+ if ((m_PhVel<0) || (m_PhVel>__C0__/ref_index) || isnan(m_PhVel))
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, invalid phase velocity found, resetting to c0! " << endl;
+ m_PhVel = __C0__/ref_index;
+ }
+
+ double origin[3];
+ unsigned int ui_origin[3];
+ for (int n=0;n<3;++n)
+ {
+ m_E_Amp[n] = elec->GetExcitation(n);
+ m_numLines[n] = m_Stop[n]-m_Start[n]+1;
+ m_IncLow[n] = m_PropDir[n]>=0;
+
+ if (m_Start[n]==0)
+ m_ActiveDir[n][0]=false;
+ else
+ m_ActiveDir[n][0]=true;
+ if (m_Stop[n]==m_Op->GetNumberOfLines(n,true)-1)
+ m_ActiveDir[n][1]=false;
+ else
+ m_ActiveDir[n][1]=true;
+
+ if (m_IncLow[n])
+ {
+ ui_origin[n] = m_Start[n]-1;
+ }
+ else
+ {
+ ui_origin[n] = m_Stop[n]+1;
+ }
+ origin[n] = m_Op->GetDiscLine(n,ui_origin[n]);
+ }
+
+ double dotEk = (m_E_Amp[0]*m_PropDir[0] + m_E_Amp[1]*m_PropDir[1] + m_E_Amp[2]*m_PropDir[2]);
+ double angle = acos( dotEk / (m_E_Amp[0]*m_E_Amp[0] + m_E_Amp[1]*m_E_Amp[1] + m_E_Amp[2]*m_E_Amp[2]) ) / PI * 180;
+
+ if (angle==0)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, plane wave direction and polarization is identical, skipping..." << endl;
+ SetActive(false);
+ return false;
+ }
+ if (angle!=90)
+ {
+ cerr << "Operator_Ext_TFSF::BuildExtension: Warning, angle between propagation direction and polarization is not 90deg, resetting E-polarization to : (";
+ for (int n=0;n<3;++n)
+ m_E_Amp[n]-=m_PropDir[n]*dotEk;
+ cerr << m_E_Amp[0] << "," << m_E_Amp[1] << "," << m_E_Amp[2] << ")" << endl;
+ }
+
+ int nP,nPP;
+ for (int n=0;n<3;++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ m_H_Amp[n] = m_PropDir[nP]*m_E_Amp[nPP] - m_PropDir[nPP]*m_E_Amp[nP];
+ m_H_Amp[n] /= __Z0__*sqrt(m_Op->GetBackgroundMueR()/m_Op->GetBackgroundEpsR());
+ }
+
+ double coord[3];
+ double unit = m_Op->GetGridDelta();
+ double delay;
+ double dist;
+ unsigned int pos[3];
+ unsigned int numP, ui_pos;
+ m_maxDelay = 0;
+ for (int n=0;n<3;++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ pos[n] = 0; //unused
+ pos[nP] = m_Start[nP];
+
+ numP = m_numLines[nP]*m_numLines[nPP];
+
+ if (!m_ActiveDir[n][0] && !m_ActiveDir[n][1])
+ continue;
+
+ for (int l=0;l<2;++l)
+ for (int c=0;c<2;++c)
+ {
+ if (m_ActiveDir[n][l])
+ {
+ m_VoltDelay[n][l][c]=new unsigned int[numP];
+ m_VoltDelayDelta[n][l][c]=new FDTD_FLOAT[numP];
+ m_VoltAmp[n][l][c]=new FDTD_FLOAT[numP];
+
+ m_CurrDelay[n][l][c]=new unsigned int[numP];
+ m_CurrDelayDelta[n][l][c]=new FDTD_FLOAT[numP];
+ m_CurrAmp[n][l][c]=new FDTD_FLOAT[numP];
+ }
+ }
+
+ ui_pos = 0;
+ for (unsigned int i=0;i<m_numLines[nP];++i)
+ {
+ pos[nPP] = m_Start[nPP];
+ for (unsigned int j=0;j<m_numLines[nPP];++j)
+ {
+ // current updates
+ pos[n] = m_Start[n];
+
+ if (m_ActiveDir[n][0])
+ {
+ m_Op->GetYeeCoords(nP,pos,coord,false);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_CurrDelay[n][0][1][ui_pos] = floor(delay);
+ m_CurrDelayDelta[n][0][1][ui_pos] = delay - floor(delay);
+ m_CurrAmp[n][0][1][ui_pos] = m_E_Amp[nP]*m_Op->GetEdgeLength(nP,pos);
+
+ m_Op->GetYeeCoords(nPP,pos,coord,false);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_CurrDelay[n][0][0][ui_pos] = floor(delay);
+ m_CurrDelayDelta[n][0][0][ui_pos] = delay - floor(delay);
+ m_CurrAmp[n][0][0][ui_pos] = m_E_Amp[nPP]*m_Op->GetEdgeLength(nPP,pos);
+
+ --pos[n];
+ m_CurrAmp[n][0][0][ui_pos]*=m_Op->GetIV(nP,pos);
+ m_CurrAmp[n][0][1][ui_pos]*=m_Op->GetIV(nPP,pos);
+ }
+
+ if (m_ActiveDir[n][1])
+ {
+ pos[n] = m_Stop[n];
+ m_Op->GetYeeCoords(nP,pos,coord,false);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_CurrDelay[n][1][1][ui_pos] = floor(delay);
+ m_CurrDelayDelta[n][1][1][ui_pos] = delay - floor(delay);
+ m_CurrAmp[n][1][1][ui_pos] = m_E_Amp[nP]*m_Op->GetEdgeLength(nP,pos);
+
+ m_Op->GetYeeCoords(nPP,pos,coord,false);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_CurrDelay[n][1][0][ui_pos] = floor(delay);
+ m_CurrDelayDelta[n][1][0][ui_pos] = delay - floor(delay);
+ m_CurrAmp[n][1][0][ui_pos] = m_E_Amp[nPP]*m_Op->GetEdgeLength(nPP,pos);
+
+ m_CurrAmp[n][1][0][ui_pos]*=m_Op->GetIV(nP,pos);
+ m_CurrAmp[n][1][1][ui_pos]*=m_Op->GetIV(nPP,pos);
+ }
+
+ if (m_ActiveDir[n][0])
+ m_CurrAmp[n][0][0][ui_pos]*=-1;
+ if (m_ActiveDir[n][1])
+ m_CurrAmp[n][1][1][ui_pos]*=-1;
+
+ if (pos[nP]==m_Stop[nP])
+ {
+ if (m_ActiveDir[n][0])
+ m_CurrAmp[n][0][1][ui_pos]=0;
+ if (m_ActiveDir[n][1])
+ m_CurrAmp[n][1][1][ui_pos]=0;
+ }
+ if (pos[nPP]==m_Stop[nPP])
+ {
+ if (m_ActiveDir[n][0])
+ m_CurrAmp[n][0][0][ui_pos]=0;
+ if (m_ActiveDir[n][1])
+ m_CurrAmp[n][1][0][ui_pos]=0;
+ }
+
+ // voltage updates
+ pos[n] = m_Start[n]-1;
+ if (m_ActiveDir[n][0])
+ {
+ m_Op->GetYeeCoords(nP,pos,coord,true);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT + 1.0;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_VoltDelay[n][0][1][ui_pos] = floor(delay);
+ m_VoltDelayDelta[n][0][1][ui_pos] = delay - floor(delay);
+ m_VoltAmp[n][0][1][ui_pos] = m_H_Amp[nP]*m_Op->GetEdgeLength(nP,pos,true);
+
+ m_Op->GetYeeCoords(nPP,pos,coord,true);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT + 1.0;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_VoltDelay[n][0][0][ui_pos] = floor(delay);
+ m_VoltDelayDelta[n][0][0][ui_pos] = delay - floor(delay);
+ m_VoltAmp[n][0][0][ui_pos] = m_H_Amp[nPP]*m_Op->GetEdgeLength(nPP,pos,true);
+
+ ++pos[n];
+ m_VoltAmp[n][0][0][ui_pos]*=m_Op->GetVI(nP,pos);
+ m_VoltAmp[n][0][1][ui_pos]*=m_Op->GetVI(nPP,pos);
+ }
+
+ pos[n] = m_Stop[n];
+ if (m_ActiveDir[n][1])
+ {
+ m_Op->GetYeeCoords(nP,pos,coord,true);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT + 1.0;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_VoltDelay[n][1][1][ui_pos] = floor(delay);
+ m_VoltDelayDelta[n][1][1][ui_pos] = delay - floor(delay);
+ m_VoltAmp[n][1][1][ui_pos] = m_H_Amp[nP]*m_Op->GetEdgeLength(nP,pos,true);
+
+ m_Op->GetYeeCoords(nPP,pos,coord,true);
+ dist = fabs((coord[0]-origin[0])*m_PropDir[0])+fabs((coord[1]-origin[1])*m_PropDir[1])+fabs((coord[2]-origin[2])*m_PropDir[2]);
+ delay = dist*unit/m_PhVel/dT + 1.0;
+ m_maxDelay = max((unsigned int)delay,m_maxDelay);
+ m_VoltDelay[n][1][0][ui_pos] = floor(delay);
+ m_VoltDelayDelta[n][1][0][ui_pos] = delay - floor(delay);
+ m_VoltAmp[n][1][0][ui_pos] = m_H_Amp[nPP]*m_Op->GetEdgeLength(nPP,pos,true);
+
+ m_VoltAmp[n][1][0][ui_pos]*=m_Op->GetVI(nP,pos);
+ m_VoltAmp[n][1][1][ui_pos]*=m_Op->GetVI(nPP,pos);
+ }
+
+ if (m_ActiveDir[n][1])
+ m_VoltAmp[n][1][0][ui_pos]*=-1;
+ if (m_ActiveDir[n][0])
+ m_VoltAmp[n][0][1][ui_pos]*=-1;
+
+ if (pos[nP]==m_Stop[nP])
+ {
+ if (m_ActiveDir[n][0])
+ m_VoltAmp[n][0][0][ui_pos]=0;
+ if (m_ActiveDir[n][1])
+ m_VoltAmp[n][1][0][ui_pos]=0;
+ }
+ if (pos[nPP]==m_Stop[nPP])
+ {
+ if (m_ActiveDir[n][0])
+ m_VoltAmp[n][0][1][ui_pos]=0;
+ if (m_ActiveDir[n][1])
+ m_VoltAmp[n][1][1][ui_pos]=0;
+ }
+
+ ++pos[nPP];
+ ++ui_pos;
+ }
+ ++pos[nP];
+ }
+ }
+ ++m_maxDelay;
+ return true;
+ }
+ SetActive(false);
+ return false;
+}
+
+Engine_Extension* Operator_Ext_TFSF::CreateEngineExtention()
+{
+ return new Engine_Ext_TFSF(this);
+}
+
+void Operator_Ext_TFSF::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+ cout << "Active directions\t: " << "(" << m_ActiveDir[0][0] << "/" << m_ActiveDir[0][1] << ", " << m_ActiveDir[1][0] << "/" << m_ActiveDir[1][1] << ", " << m_ActiveDir[2][0] << "/" << m_ActiveDir[2][1] << ")" << endl;
+ cout << "Propagation direction\t: " << "(" << m_PropDir[0] << ", " << m_PropDir[1] << ", " << m_PropDir[2] << ")" << endl;
+ cout << "Rel. propagation speed\t: " << m_PhVel/__C0__ << "*c0 @ " << m_Frequency << " Hz" << endl;
+ cout << "E-field amplitude (V/m)\t: " << "(" << m_E_Amp[0] << ", " << m_E_Amp[1] << ", " << m_E_Amp[2] << ")" << endl;
+ cout << "H-field amplitude (A/m)\t: " << "(" << m_H_Amp[0] << ", " << m_H_Amp[1] << ", " << m_H_Amp[2] << ")" << endl;
+ cout << "Box Dimensions\t\t: " << m_numLines[0] << " x " << m_numLines[1] << " x " << m_numLines[2] << endl;
+ cout << "Max. Delay (TS)\t\t: " << m_maxDelay << endl;
+ int dirs = m_ActiveDir[0][0] + m_ActiveDir[0][1] + m_ActiveDir[1][0] + m_ActiveDir[1][1] + m_ActiveDir[2][0] + m_ActiveDir[2][1] ;
+ cout << "Memory usage (est.)\t: ~" << m_numLines[0] * m_numLines[1] * m_numLines[2] * dirs * 4 * 4 / 1024 << " kiB" << endl;
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_tfsf.h b/openEMS/FDTD/extensions/operator_ext_tfsf.h
new file mode 100644
index 0000000..e1e714e
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_tfsf.h
@@ -0,0 +1,82 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_TFSF_H
+#define OPERATOR_EXT_TFSF_H
+
+#include "operator_extension.h"
+#include "FDTD/operator.h"
+#include "tools/constants.h"
+
+class Excitation;
+
+class Operator_Ext_TFSF : public Operator_Extension
+{
+ friend class Engine_Ext_TFSF;
+public:
+ Operator_Ext_TFSF(Operator* op);
+ ~Operator_Ext_TFSF();
+
+ virtual Operator_Extension* Clone(Operator* op);
+
+ virtual bool BuildExtension();
+
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return false;}
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return false;}
+
+ // FIXME, this extension is not save to use with MPI
+ virtual bool IsMPISave() const {return false;}
+
+ virtual string GetExtensionName() const {return string("Total-Field/Scattered-Field Extension");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+ virtual void Init();
+ virtual void Reset();
+
+protected:
+ Excitation* m_Exc;
+
+ bool m_IncLow[3];
+ bool m_ActiveDir[3][2]; // m_ActiveDir[direction][low/high]
+ unsigned int m_Start[3];
+ unsigned int m_Stop[3];
+ unsigned int m_numLines[3];
+
+ double m_PropDir[3];
+ double m_E_Amp[3];
+ double m_H_Amp[3];
+
+ double m_Frequency;
+ double m_PhVel;
+
+ unsigned int m_maxDelay;
+
+ // array setup [direction][low/high][component][ <mesh_position> ]
+ unsigned int* m_VoltDelay[3][2][2];
+ FDTD_FLOAT* m_VoltDelayDelta[3][2][2];
+ FDTD_FLOAT* m_VoltAmp[3][2][2];
+
+ unsigned int* m_CurrDelay[3][2][2];
+ FDTD_FLOAT* m_CurrDelayDelta[3][2][2];
+ FDTD_FLOAT* m_CurrAmp[3][2][2];
+
+};
+
+#endif // OPERATOR_EXT_TFSF_H
diff --git a/openEMS/FDTD/extensions/operator_ext_upml.cpp b/openEMS/FDTD/extensions/operator_ext_upml.cpp
new file mode 100644
index 0000000..fc46d85
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_upml.cpp
@@ -0,0 +1,478 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_ext_upml.h"
+#include "FDTD/operator_cylindermultigrid.h"
+#include "engine_ext_upml.h"
+#include "tools/array_ops.h"
+#include "fparser.hh"
+
+using namespace std;
+
+Operator_Ext_UPML::Operator_Ext_UPML(Operator* op) : Operator_Extension(op)
+{
+ m_GradingFunction = new FunctionParser();
+ //default grading function
+ SetGradingFunction(" -log(1e-6)*log(2.5)/(2*dl*Z*(pow(2.5,W/dl)-1)) * pow(2.5, D/dl) ");
+
+ for (int n=0; n<6; ++n)
+ {
+ m_BC[n]=0;
+ m_Size[n]=0;
+ }
+ for (int n=0; n<3; ++n)
+ {
+ m_StartPos[n]=0;
+ m_numLines[n]=0;
+ }
+
+ vv = NULL;
+ vvfo = NULL;
+ vvfn = NULL;
+ ii = NULL;
+ iifo = NULL;
+ iifn = NULL;
+}
+
+Operator_Ext_UPML::~Operator_Ext_UPML()
+{
+ delete m_GradingFunction;
+ m_GradingFunction = NULL;
+ DeleteOp();
+}
+
+void Operator_Ext_UPML::SetBoundaryCondition(const int* BCs, const unsigned int size[6])
+{
+ for (int n=0; n<6; ++n)
+ {
+ m_BC[n]=BCs[n];
+ m_Size[n]=size[n];
+ }
+}
+
+void Operator_Ext_UPML::SetRange(const unsigned int start[3], const unsigned int stop[3])
+{
+ for (int n=0; n<3; ++n)
+ {
+ m_StartPos[n]=start[n];
+ m_numLines[n]=stop[n]-start[n]+1;
+ }
+}
+
+bool Operator_Ext_UPML::Create_UPML(Operator* op, const int ui_BC[6], const unsigned int ui_size[6], string gradFunc)
+{
+ int BC[6]={ui_BC[0],ui_BC[1],ui_BC[2],ui_BC[3],ui_BC[4],ui_BC[5]};
+ unsigned int size[6]={ui_size[0],ui_size[1],ui_size[2],ui_size[3],ui_size[4],ui_size[5]};
+
+ //check if mesh is large enough to support the pml
+ for (int n=0; n<3; ++n)
+ if ( (size[2*n]*(BC[2*n]==3)+size[2*n+1]*(BC[2*n+1]==3)) >= op->GetNumberOfLines(n,true) )
+ {
+ cerr << "Operator_Ext_UPML::Create_UPML: Warning: Not enough lines in direction: " << n << ", resetting to PEC" << endl;
+ BC[2*n]=0;
+ size[2*n]=0;
+ BC[2*n+1]=0;
+ size[2*n+1]=0;
+ }
+
+ //check cylindrical coord compatiblility
+ Operator_Cylinder* op_cyl = dynamic_cast<Operator_Cylinder*>(op);
+ if (op_cyl)
+ {
+ if ((BC[0]==3) && (op_cyl->GetClosedAlpha() || op_cyl->GetR0Included()))
+ {
+ BC[0]=0;
+ size[0]=0;
+ cerr << "Operator_Ext_UPML::Create_UPML: Warning: An upml in r-min direction is not possible, resetting to PEC..." << endl;
+ }
+ if ( (BC[2]==3) && (op_cyl->GetClosedAlpha()) )
+ {
+ BC[2]=0;
+ size[2]=0;
+ cerr << "Operator_Ext_UPML::Create_UPML: Warning: An upml in alpha-min direction is not possible, resetting to PEC..." << endl;
+ }
+ if ( (BC[3]==3) && (op_cyl->GetClosedAlpha()) )
+ {
+ BC[3]=0;
+ size[3]=0;
+ cerr << "Operator_Ext_UPML::Create_UPML: Warning: An upml in alpha-max direction is not possible, resetting to PEC..." << endl;
+ }
+ }
+
+ //check cylindrical coord compatiblility
+ if (dynamic_cast<Operator_CylinderMultiGrid*>(op))
+ {
+ if (BC[2]==3)
+ {
+ BC[2]=0;
+ size[2]=0;
+ cerr << "Operator_Ext_UPML::Create_UPML: Warning: An upml in alpha direction is not possible for a cylindrical multi-grid, resetting to PEC..." << endl;
+ }
+ if (BC[3]==3)
+ {
+ BC[3]=0;
+ size[3]=0;
+ cerr << "Operator_Ext_UPML::Create_UPML: Warning: An upml in alpha direction is not possible for a cylindrical multi-grid, resetting to PEC..." << endl;
+ }
+ }
+
+
+ Operator_Ext_UPML* op_ext_upml=NULL;
+ unsigned int start[3]={0 ,0 ,0};
+ unsigned int stop[3] ={op->GetNumberOfLines(0,true)-1,op->GetNumberOfLines(1,true)-1,op->GetNumberOfLines(2,true)-1};
+
+ //create a pml in x-direction over the full width of yz-space
+ if (BC[0]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[0]=0;
+ stop[0] =size[0];
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op->AddExtension(op_ext_upml);
+ }
+ if (BC[1]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[0]=op->GetNumberOfLines(0,true)-1-size[1];
+ stop[0] =op->GetNumberOfLines(0,true)-1;
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op->AddExtension(op_ext_upml);
+ }
+
+ //create a pml in y-direction over the xz-space (if a pml in x-direction already exists, skip that corner regions)
+ start[0]=(size[0]+1)*(BC[0]==3);
+ stop[0] =op->GetNumberOfLines(0,true)-1-(size[0]+1)*(BC[1]==3);
+
+ if (BC[2]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[1]=0;
+ stop[1] =size[2];
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op->AddExtension(op_ext_upml);
+ }
+ if (BC[3]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[1]=op->GetNumberOfLines(1,true)-1-size[3];
+ stop[1] =op->GetNumberOfLines(1,true)-1;
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op->AddExtension(op_ext_upml);
+ }
+
+ //create a pml in z-direction over the xy-space (if a pml in x- and/or y-direction already exists, skip that corner/edge regions)
+ start[1]=(size[2]+1)*(BC[2]==3);
+ stop[1] =op->GetNumberOfLines(1,true)-1-(size[3]+1)*(BC[3]==3);
+
+ //exclude x-lines that does not belong to the base multi-grid operator;
+ Operator_CylinderMultiGrid* op_cyl_MG = dynamic_cast<Operator_CylinderMultiGrid*>(op);
+ if (op_cyl_MG)
+ start[0] = op_cyl_MG->GetSplitPos()-1;
+
+ if (BC[4]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[2]=0;
+ stop[2] =size[4];
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op->AddExtension(op_ext_upml);
+ }
+ if (BC[5]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[2]=op->GetNumberOfLines(2,true)-1-size[5];
+ stop[2] =op->GetNumberOfLines(2,true)-1;
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op->AddExtension(op_ext_upml);
+ }
+
+ BC[1]=0;
+ size[1]=0;
+ //create pml extensions (in z-direction only) for child operators in cylindrical multigrid operators
+ while (op_cyl_MG)
+ {
+ Operator_Cylinder* op_child = op_cyl_MG->GetInnerOperator();
+ op_cyl_MG = dynamic_cast<Operator_CylinderMultiGrid*>(op_child);
+ for (int n=0; n<2; ++n)
+ {
+ start[n]=0;
+ stop[n]=op_child->GetNumberOfLines(n,true)-1;
+ }
+
+ if (op_cyl_MG)
+ start[0] = op_cyl_MG->GetSplitPos()-1;
+
+ if (BC[4]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op_child);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[2]=0;
+ stop[2] =size[4];
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op_child->AddExtension(op_ext_upml);
+ }
+ if (BC[5]==3)
+ {
+ op_ext_upml = new Operator_Ext_UPML(op_child);
+ op_ext_upml->SetGradingFunction(gradFunc);
+ start[2]=op->GetNumberOfLines(2,true)-1-size[5];
+ stop[2] =op->GetNumberOfLines(2,true)-1;
+ op_ext_upml->SetBoundaryCondition(BC, size);
+ op_ext_upml->SetRange(start,stop);
+ op_child->AddExtension(op_ext_upml);
+ }
+ }
+
+ return true;
+}
+
+
+void Operator_Ext_UPML::DeleteOp()
+{
+ Delete_N_3DArray<FDTD_FLOAT>(vv,m_numLines);
+ vv = NULL;
+ Delete_N_3DArray<FDTD_FLOAT>(vvfo,m_numLines);
+ vvfo = NULL;
+ Delete_N_3DArray<FDTD_FLOAT>(vvfn,m_numLines);
+ vvfn = NULL;
+ Delete_N_3DArray<FDTD_FLOAT>(ii,m_numLines);
+ ii = NULL;
+ Delete_N_3DArray<FDTD_FLOAT>(iifo,m_numLines);
+ iifo = NULL;
+ Delete_N_3DArray<FDTD_FLOAT>(iifn,m_numLines);
+ iifn = NULL;
+}
+
+
+bool Operator_Ext_UPML::SetGradingFunction(string func)
+{
+ if (func.empty())
+ return true;
+
+ m_GradFunc = func;
+ int res = m_GradingFunction->Parse(m_GradFunc.c_str(), "D,dl,W,Z,N");
+ if (res < 0) return true;
+
+ cerr << "Operator_Ext_UPML::SetGradingFunction: Warning, an error occured parsing the pml grading function (see below) ..." << endl;
+ cerr << func << "\n" << string(res, ' ') << "^\n" << m_GradingFunction->ErrorMsg() << "\n";
+ return false;
+}
+
+void Operator_Ext_UPML::CalcGradingKappa(int ny, unsigned int pos[3], double Zm, double kappa_v[3], double kappa_i[3])
+{
+ double depth=0;
+ double width=0;
+ for (int n=0; n<3; ++n)
+ {
+ if ((pos[n] <= m_Size[2*n]) && (m_BC[2*n]==3)) //lower pml in n-dir
+ {
+ width = (m_Op->GetDiscLine(n,m_Size[2*n]) - m_Op->GetDiscLine(n,0))*m_Op->GetGridDelta();
+ depth = width - (m_Op->GetDiscLine(n,pos[n]) - m_Op->GetDiscLine(n,0))*m_Op->GetGridDelta();
+
+ if ((m_Op_Cyl) && (n==1))
+ {
+ width *= m_Op_Cyl->GetDiscLine(0,pos[0]);
+ depth *= m_Op_Cyl->GetDiscLine(0,pos[0]);
+ }
+
+ if (n==ny)
+ depth-=m_Op->GetEdgeLength(n,pos)/2;
+ double vars[5] = {depth, width/m_Size[2*n], width, Zm, (double)m_Size[2*n]};
+ if (depth>0)
+ kappa_v[n] = m_GradingFunction->Eval(vars);
+ else
+ kappa_v[n]=0;
+ if (n==ny)
+ depth+=m_Op->GetEdgeLength(n,pos)/2;
+
+ if (n!=ny)
+ depth-=m_Op->GetEdgeLength(n,pos)/2;
+ if (depth<0)
+ depth=0;
+ vars[0]=depth;
+ if (depth>0)
+ kappa_i[n] = m_GradingFunction->Eval(vars);
+ else
+ kappa_i[n] = 0;
+ }
+ else if ((pos[n] >= m_Op->GetNumberOfLines(n,true) -1 -m_Size[2*n+1]) && (m_BC[2*n+1]==3)) //upper pml in n-dir
+ {
+ width = (m_Op->GetDiscLine(n,m_Op->GetNumberOfLines(n,true)-1) - m_Op->GetDiscLine(n,m_Op->GetNumberOfLines(n,true)-m_Size[2*n+1]-1))*m_Op->GetGridDelta();
+ depth = width - (m_Op->GetDiscLine(n,m_Op->GetNumberOfLines(n,true)-1) - m_Op->GetDiscLine(n,pos[n]))*m_Op->GetGridDelta();
+
+ if ((m_Op_Cyl) && (n==1))
+ {
+ width *= m_Op_Cyl->GetDiscLine(0,pos[0]);
+ depth *= m_Op_Cyl->GetDiscLine(0,pos[0]);
+ }
+
+ if (n==ny)
+ depth+=m_Op->GetEdgeLength(n,pos)/2;
+ double vars[5] = {depth, width/(m_Size[2*n]), width, Zm, (double)m_Size[2*n]};
+ if (depth>0)
+ kappa_v[n] = m_GradingFunction->Eval(vars);
+ else
+ kappa_v[n]=0;
+ if (n==ny)
+ depth-=m_Op->GetEdgeLength(n,pos)/2;
+
+ if (n!=ny)
+ depth+=m_Op->GetEdgeLength(n,pos)/2;
+ if (depth>width)
+ depth=0;
+ vars[0]=depth;
+ if (depth>0)
+ kappa_i[n] = m_GradingFunction->Eval(vars);
+ else
+ kappa_i[n]=0;
+ }
+ else
+ {
+ kappa_v[n] = 0;
+ kappa_i[n] = 0;
+ }
+ }
+}
+
+bool Operator_Ext_UPML::BuildExtension()
+{
+ /*Calculate the upml coefficients as defined in:
+ Allen Taflove, computational electrodynamics - the FDTD method, third edition, chapter 7.8, pages 297-300
+ - modified by Thorsten Liebig to match the equivalent circuit (EC) FDTD method
+ - kappa is used for conductivities (instead of sigma)
+ */
+ if (m_Op==NULL)
+ return false;
+
+ DeleteOp();
+ vv = Create_N_3DArray<FDTD_FLOAT>(m_numLines);
+ vvfo = Create_N_3DArray<FDTD_FLOAT>(m_numLines);
+ vvfn = Create_N_3DArray<FDTD_FLOAT>(m_numLines);
+ ii = Create_N_3DArray<FDTD_FLOAT>(m_numLines);
+ iifo = Create_N_3DArray<FDTD_FLOAT>(m_numLines);
+ iifn = Create_N_3DArray<FDTD_FLOAT>(m_numLines);
+
+ unsigned int pos[3];
+ unsigned int loc_pos[3];
+ int nP,nPP;
+ double kappa_v[3]={0,0,0};
+ double kappa_i[3]={0,0,0};
+ double eff_Mat[4];
+ double dT = m_Op->GetTimestep();
+
+ for (loc_pos[0]=0; loc_pos[0]<m_numLines[0]; ++loc_pos[0])
+ {
+ pos[0] = loc_pos[0] + m_StartPos[0];
+ for (loc_pos[1]=0; loc_pos[1]<m_numLines[1]; ++loc_pos[1])
+ {
+ pos[1] = loc_pos[1] + m_StartPos[1];
+ vector<CSPrimitives*> vPrims = m_Op->GetPrimitivesBoundBox(pos[0], pos[1], -1, CSProperties::MATERIAL);
+ for (loc_pos[2]=0; loc_pos[2]<m_numLines[2]; ++loc_pos[2])
+ {
+ pos[2] = loc_pos[2] + m_StartPos[2];
+ for (int n=0; n<3; ++n)
+ {
+ m_Op->Calc_EffMatPos(n,pos,eff_Mat,vPrims);
+ CalcGradingKappa(n, pos,__Z0__ ,kappa_v ,kappa_i);
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ if ((kappa_v[0]+kappa_v[1]+kappa_v[2])!=0)
+ {
+ //check if pos is on PEC
+ if ( (m_Op->GetVV(n,pos[0],pos[1],pos[2]) + m_Op->GetVI(n,pos[0],pos[1],pos[2])) != 0 )
+ {
+ //modify the original operator to perform eq. (7.85) by the main engine (EC-FDTD: equation is multiplied by delta_n)
+ //the engine extension will replace the original voltages with the "voltage flux" (volt*eps0) prior to the voltage updates
+ //after the updates are done the extension will calculate the new voltages (see below) and place them back into the main field domain
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], (2*__EPS0__ - kappa_v[nP]*dT) / (2*__EPS0__ + kappa_v[nP]*dT) );
+ m_Op->SetVI(n,pos[0],pos[1],pos[2], (2*__EPS0__*dT) / (2*__EPS0__ + kappa_v[nP]*dT) * m_Op->GetEdgeLength(n,pos) / m_Op->GetEdgeArea(n,pos) );
+
+
+ //operators needed by eq. (7.88) to calculate new voltages from old voltages and old and new "voltage fluxes"
+ GetVV(n,loc_pos) = (2*__EPS0__ - kappa_v[nPP]*dT) / (2*__EPS0__ + kappa_v[nPP]*dT);
+ GetVVFN(n,loc_pos) = (2*__EPS0__ + kappa_v[n]*dT) / (2*__EPS0__ + kappa_v[nPP]*dT)/eff_Mat[0];
+ GetVVFO(n,loc_pos) = (2*__EPS0__ - kappa_v[n]*dT) / (2*__EPS0__ + kappa_v[nPP]*dT)/eff_Mat[0];
+ }
+ }
+ else
+ {
+ //disable upml
+ GetVV(n,loc_pos) = m_Op->GetVV(n,pos[0],pos[1],pos[2]);
+ m_Op->SetVV(n,pos[0],pos[1],pos[2], 0 );
+ GetVVFO(n,loc_pos) = 0;
+ GetVVFN(n,loc_pos) = 1;
+ }
+
+ if ((kappa_i[0]+kappa_i[1]+kappa_i[2])!=0)
+ {
+ //check if pos is on PMC
+ if ( (m_Op->GetII(n,pos[0],pos[1],pos[2]) + m_Op->GetIV(n,pos[0],pos[1],pos[2])) != 0 )
+ {
+ //modify the original operator to perform eq. (7.89) by the main engine (EC-FDTD: equation is multiplied by delta_n)
+ //the engine extension will replace the original currents with the "current flux" (curr*mu0) prior to the current updates
+ //after the updates are done the extension will calculate the new currents (see below) and place them back into the main field domain
+ m_Op->SetII(n,pos[0],pos[1],pos[2], (2*__EPS0__ - kappa_i[nP]*dT) / (2*__EPS0__ + kappa_i[nP]*dT) );
+ m_Op->SetIV(n,pos[0],pos[1],pos[2], (2*__EPS0__*dT) / (2*__EPS0__ + kappa_i[nP]*dT) * m_Op->GetEdgeLength(n,pos,true) / m_Op->GetEdgeArea(n,pos,true) );
+
+ //operators needed by eq. (7.90) to calculate new currents from old currents and old and new "current fluxes"
+ GetII(n,loc_pos) = (2*__EPS0__ - kappa_i[nPP]*dT) / (2*__EPS0__ + kappa_i[nPP]*dT);
+ GetIIFN(n,loc_pos) = (2*__EPS0__ + kappa_i[n]*dT) / (2*__EPS0__ + kappa_i[nPP]*dT)/eff_Mat[2];
+ GetIIFO(n,loc_pos) = (2*__EPS0__ - kappa_i[n]*dT) / (2*__EPS0__ + kappa_i[nPP]*dT)/eff_Mat[2];
+ }
+ }
+ else
+ {
+ //disable upml
+ GetII(n,loc_pos) = m_Op->GetII(n,pos[0],pos[1],pos[2]);
+ m_Op->SetII(n,pos[0],pos[1],pos[2], 0 );
+ GetIIFO(n,loc_pos) = 0;
+ GetIIFN(n,loc_pos) = 1;
+ }
+ }
+ }
+ }
+ }
+ return true;
+}
+
+Engine_Extension* Operator_Ext_UPML::CreateEngineExtention()
+{
+ Engine_Ext_UPML* eng_ext = new Engine_Ext_UPML(this);
+ return eng_ext;
+}
+
+void Operator_Ext_UPML::ShowStat(ostream &ostr) const
+{
+ Operator_Extension::ShowStat(ostr);
+
+ ostr << " PML range\t\t: " << "[" << m_StartPos[0]<< "," << m_StartPos[1]<< "," << m_StartPos[2]<< "] to ["
+ << m_StartPos[0]+m_numLines[0]-1 << "," << m_StartPos[1]+m_numLines[1]-1 << "," << m_StartPos[2]+m_numLines[2]-1 << "]" << endl;
+ ostr << " Grading function\t: \"" << m_GradFunc << "\"" << endl;
+}
diff --git a/openEMS/FDTD/extensions/operator_ext_upml.h b/openEMS/FDTD/extensions/operator_ext_upml.h
new file mode 100644
index 0000000..5256655
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_ext_upml.h
@@ -0,0 +1,106 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXT_UPML_H
+#define OPERATOR_EXT_UPML_H
+
+#include "FDTD/operator.h"
+#include "operator_extension.h"
+
+class FunctionParser;
+
+//! Operator extension implemention an uniaxial perfectly matched layer (upml)
+/*
+ The priority for this extension should be the highest of all extensions since this operator will use the main engine to perform vital parts in the upml implementation.
+ Therefore the voltages and currents as well as the operator are replaced during these update process.
+ This extension is propably incompatible with the most other extensions operating in the same regions.
+ */
+class Operator_Ext_UPML : public Operator_Extension
+{
+ friend class Engine_Ext_UPML;
+public:
+ virtual ~Operator_Ext_UPML();
+
+ //! Returns always true, Create_UPML method will take care of creating a valid pml for the cylindrical fdtd
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const { UNUSED(closedAlpha); UNUSED(R0_included); return true;}
+
+ //! Returns always true if base grid, Create_UPML will create proper child pml extensions.
+ virtual bool IsCylindricalMultiGridSave(bool child) const {if (child) return false; return true;}
+
+ virtual bool IsMPISave() const {return true;}
+
+ void SetBoundaryCondition(const int* BCs, const unsigned int size[6]);
+
+ void SetRange(const unsigned int start[3], const unsigned int stop[3]);
+
+ //! Set the grading function for the pml
+ /*!
+ Define the pml grading grading function.
+ Predefined variables in this grading function are:
+ D = depth in the pml in meter
+ dl = mesh delta inside the pml in meter
+ W = width (length) of the pml in meter
+ N = number of cells for the pml
+ Z = wave impedance at the current depth and position
+ example: SetGradingFunction(" -log(1e-6)*log(2.5)/(2*dl*Z*(pow(2.5,W/dl)-1)) * pow(2.5, D/dl) ");
+
+ An empty function string will be ignored.
+ */
+ virtual bool SetGradingFunction(string func);
+
+ virtual bool BuildExtension();
+
+ virtual Engine_Extension* CreateEngineExtention();
+
+ virtual string GetExtensionName() const {return string("Uniaxial PML Extension");}
+
+ virtual void ShowStat(ostream &ostr) const;
+
+ //! Create the UPML
+ static bool Create_UPML(Operator* op, const int ui_BC[6], const unsigned int ui_size[6], const string gradFunc);
+
+protected:
+ Operator_Ext_UPML(Operator* op);
+ int m_BC[6];
+ unsigned int m_Size[6];
+
+ unsigned int m_StartPos[3];
+ unsigned int m_numLines[3];
+
+ string m_GradFunc;
+ FunctionParser* m_GradingFunction;
+
+ void CalcGradingKappa(int ny, unsigned int pos[3], double Zm, double kappa_v[3], double kappa_i[3]);
+
+ void DeleteOp();
+
+ virtual FDTD_FLOAT& GetVV(int ny, unsigned int pos[3]) {return vv[ny][pos[0]][pos[1]][pos[2]];}
+ virtual FDTD_FLOAT& GetVVFO(int ny, unsigned int pos[3]) {return vvfo[ny][pos[0]][pos[1]][pos[2]];}
+ virtual FDTD_FLOAT& GetVVFN(int ny, unsigned int pos[3]) {return vvfn[ny][pos[0]][pos[1]][pos[2]];}
+ virtual FDTD_FLOAT& GetII(int ny, unsigned int pos[3]) {return ii[ny][pos[0]][pos[1]][pos[2]];}
+ virtual FDTD_FLOAT& GetIIFO(int ny, unsigned int pos[3]) {return iifo[ny][pos[0]][pos[1]][pos[2]];}
+ virtual FDTD_FLOAT& GetIIFN(int ny, unsigned int pos[3]) {return iifn[ny][pos[0]][pos[1]][pos[2]];}
+
+ FDTD_FLOAT**** vv; //calc new voltage from old voltage
+ FDTD_FLOAT**** vvfo; //calc new voltage from old voltage flux
+ FDTD_FLOAT**** vvfn; //calc new voltage from new voltage flux
+ FDTD_FLOAT**** ii; //calc new current from old current
+ FDTD_FLOAT**** iifo; //calc new current from old current flux
+ FDTD_FLOAT**** iifn; //calc new current from new current flux
+};
+
+#endif // OPERATOR_EXT_UPML_H
diff --git a/openEMS/FDTD/extensions/operator_extension.cpp b/openEMS/FDTD/extensions/operator_extension.cpp
new file mode 100644
index 0000000..50e7068
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_extension.cpp
@@ -0,0 +1,54 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_extension.h"
+#include "FDTD/operator.h"
+#include "FDTD/operator_cylinder.h"
+
+using namespace std;
+
+Operator_Extension::Operator_Extension(Operator* op)
+{
+ m_Op = op;
+ m_Active = true;
+
+ m_CC_R0_included = false;
+ m_Op_Cyl = dynamic_cast<Operator_Cylinder*>(op);
+ if (m_Op_Cyl)
+ m_CC_R0_included=m_Op_Cyl->GetR0Included();
+ m_Eng_Ext = NULL;
+}
+
+Operator_Extension::~Operator_Extension()
+{
+}
+
+Operator_Extension::Operator_Extension(Operator* op, Operator_Extension* op_ext)
+{
+ UNUSED(op_ext);
+ m_Op = op;
+ m_Op_Cyl = dynamic_cast<Operator_Cylinder*>(op);
+ m_Active = op_ext->m_Active;
+ if (m_Op_Cyl)
+ m_CC_R0_included=m_Op_Cyl->GetR0Included();
+ m_Eng_Ext = NULL;
+}
+
+void Operator_Extension::ShowStat(ostream &ostr) const
+{
+ ostr << "--- " << GetExtensionName() << " ---" << endl;
+}
diff --git a/openEMS/FDTD/extensions/operator_extension.h b/openEMS/FDTD/extensions/operator_extension.h
new file mode 100644
index 0000000..21e42af
--- /dev/null
+++ b/openEMS/FDTD/extensions/operator_extension.h
@@ -0,0 +1,87 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_EXTENSION_H
+#define OPERATOR_EXTENSION_H
+
+#include <string>
+
+#include <iostream>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "tools/global.h"
+
+class Operator;
+class Operator_Cylinder;
+class Engine_Extension;
+
+//! Abstract base-class for all operator extensions
+class Operator_Extension
+{
+ friend class Engine_Extension;
+public:
+ virtual ~Operator_Extension();
+
+ //! Create a clone of this extension, will return NULL if this is impossible
+ /*!
+ Create a clone of this extension, will return NULL if this is impossible (e.g. derived extension has no clone method and copy-constructor)...
+ BuildExtension has to be called separatly!
+ */
+ virtual Operator_Extension* Clone(Operator* op) {UNUSED(op); return NULL;}
+
+ virtual bool BuildExtension() {return true;}
+
+ virtual Engine_Extension* CreateEngineExtention() {return 0;}
+ virtual Engine_Extension* GetEngineExtention() {return m_Eng_Ext;}
+
+ //! The cylindrical operator will check whether the extension is save to use. Default is false. Derive this method to override.
+ virtual bool IsCylinderCoordsSave(bool closedAlpha, bool R0_included) const {UNUSED(closedAlpha); UNUSED(R0_included); return false;}
+
+ //! The cylindrical multi grid operator will check whether the extension is save to use. Default is false. Derive this method to override.
+ virtual bool IsCylindricalMultiGridSave(bool child) const {UNUSED(child); return false;}
+
+ //! The MPI operator (if enabled) will check whether the extension is compatible with MPI. Default is false. Derive this method to override.
+ virtual bool IsMPISave() const {return false;}
+
+ virtual std::string GetExtensionName() const {return std::string("Abstract Operator Extension Base Class");}
+
+ virtual void ShowStat(std::ostream &ostr) const;
+
+ virtual bool IsActive() const {return m_Active;}
+ virtual void SetActive(bool active=true) {m_Active=active;}
+
+ virtual void Init() {}
+ virtual void Reset() {}
+
+protected:
+ Operator_Extension(Operator* op);
+ //! Copy constructor
+ Operator_Extension(Operator* op, Operator_Extension* op_ext);
+
+ bool m_Active;
+
+ //FDTD Operator
+ Operator* m_Op;
+ Engine_Extension* m_Eng_Ext;
+
+ //Cylindrical FDTD Operator (not NULL if a cylindrical FDTD is used)
+ Operator_Cylinder* m_Op_Cyl;
+ bool m_CC_R0_included;
+};
+
+#endif // OPERATOR_EXTENSION_H
diff --git a/openEMS/FDTD/openems_fdtd_mpi.cpp b/openEMS/FDTD/openems_fdtd_mpi.cpp
new file mode 100644
index 0000000..eaab59a
--- /dev/null
+++ b/openEMS/FDTD/openems_fdtd_mpi.cpp
@@ -0,0 +1,545 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "openems_fdtd_mpi.h"
+#include "FDTD/engine_interface_fdtd.h"
+#include "FDTD/operator_mpi.h"
+#include "FDTD/operator_cylinder.h"
+#include "FDTD/engine_mpi.h"
+#include "Common/processfields.h"
+#include "Common/processintegral.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <iostream>
+#include <sstream>
+#include <vector>
+#include <iomanip>
+#include <string.h>
+#include <sys/time.h>
+#include <time.h>
+#include "mpi.h"
+#include "tools/useful.h"
+#include "tinyxml.h"
+
+openEMS_FDTD_MPI::openEMS_FDTD_MPI(bool m_MPI_Debug) : openEMS()
+{
+ m_MyID = MPI::COMM_WORLD.Get_rank();
+ m_NumProc = MPI::COMM_WORLD.Get_size();
+
+ m_MaxEnergy = 0;
+ m_EnergyDecrement = 1;
+ m_MPI_Op = NULL;
+
+ if (m_NumProc>1)
+ m_MPI_Enabled=true;
+ else
+ m_MPI_Enabled=false;
+
+ if (m_MyID==0)
+ {
+ m_Gather_Buffer = new int[m_NumProc];
+ m_Energy_Buffer = new double[m_NumProc];
+ }
+ else
+ {
+ m_Gather_Buffer = NULL;
+ m_Energy_Buffer = NULL;
+ }
+
+ m_MPI_Elem = NULL;
+ m_Original_Grid = NULL;
+
+ //redirect output to file for all ranks > 0
+ if ((m_MyID>0) && (m_MPI_Debug==false))
+ {
+ stringstream out_name;
+ out_name << "ID" << m_MyID << "_" << "output.txt";
+ m_Output = new ofstream();
+ m_Output->open(out_name.str().c_str());
+ cout.rdbuf(m_Output->rdbuf());
+ cerr.rdbuf(m_Output->rdbuf());
+ }
+ else
+ m_Output = NULL;
+}
+
+openEMS_FDTD_MPI::~openEMS_FDTD_MPI()
+{
+ delete[] m_Gather_Buffer;
+ m_Gather_Buffer = NULL;
+ delete[] m_Energy_Buffer;
+ m_Energy_Buffer = NULL;
+ delete m_Original_Grid;
+ m_Original_Grid = NULL;
+ delete m_Output;
+ m_Output=NULL;
+}
+
+string openEMS_FDTD_MPI::GetExtLibsInfo()
+{
+ stringstream str;
+
+ str << openEMS::GetExtLibsInfo();
+
+ // MPI
+ str << "\t\t" << "MPI -- Version: " << MPI_VERSION << "." << MPI_SUBVERSION << endl;
+ str << "\t\t" << " compiled against: ";
+#ifdef MPICH2_VERSION
+ str << "MPICH2 " << MPICH2_VERSION << endl;
+#endif
+
+#ifdef OMPI_MAJOR_VERSION
+ str << "openMPI" << OMPI_MAJOR_VERSION << "." << OMPI_MINOR_VERSION << "." << OMPI_RELEASE_VERSION << endl;
+#endif
+
+ return str.str();
+}
+
+
+bool openEMS_FDTD_MPI::parseCommandLineArgument( const char *argv )
+{
+ if (!argv)
+ return false;
+
+ bool ret = openEMS::parseCommandLineArgument( argv );
+
+ if (ret)
+ return ret;
+
+ if (strcmp(argv,"--engine=MPI")==0)
+ {
+ cout << "openEMS_FDTD_MPI - enabled MPI parallel processing" << endl;
+ m_engine = EngineType_MPI;
+ return true;
+ }
+
+ return false;
+}
+
+bool openEMS_FDTD_MPI::Parse_XML_FDTDSetup(TiXmlElement* FDTD_Opts)
+{
+ m_MPI_Elem = FDTD_Opts->FirstChildElement("MPI");
+ if (!m_MPI_Enabled)
+ {
+ if ((m_MPI_Elem!=NULL))
+ cerr << "openEMS_FDTD_MPI::SetupMPI: Warning: Number of MPI processes is 1, skipping MPI engine... " << endl;
+ return openEMS::Parse_XML_FDTDSetup(FDTD_Opts);
+ }
+
+ if (m_MPI_Elem==NULL)
+ {
+ MPI_Barrier(MPI_COMM_WORLD);
+ if (m_MyID==0)
+ cerr << "openEMS_FDTD_MPI::SetupMPI: Error: no MPI settings found, exiting MPI engine... " << endl;
+ exit(-1);
+ }
+
+ CSRectGrid* grid = m_CSX->GetGrid();
+ delete m_Original_Grid;
+ m_Original_Grid = CSRectGrid::Clone(grid);
+
+ string arg_Pos_Names[] = {"SplitPos_X", "SplitPos_Y", "SplitPos_Z"};
+ string arg_N_Names[] = {"SplitN_X", "SplitN_Y", "SplitN_Z"};
+ const char* tmp = NULL;
+ for (int n=0;n<3;++n)
+ {
+ m_SplitNumber[n].clear();
+ m_SplitNumber[n].push_back(0);
+ tmp = m_MPI_Elem->Attribute(arg_Pos_Names[n].c_str());
+ if (tmp) //check if a split position is requested
+ {
+ vector<double> SplitLines = SplitString2Double(tmp, ',');
+ bool inside;
+ unsigned int line;
+ for (size_t lineN = 0; lineN<SplitLines.size();++lineN)
+ {
+ line = m_Original_Grid->Snap2LineNumber(n, SplitLines.at(lineN), inside);
+ if (inside)
+ m_SplitNumber[n].push_back(line);
+ }
+ }
+ else //check if a number of splits is requested
+ {
+ int SplitN=0;
+ if (m_MPI_Elem->QueryIntAttribute( arg_N_Names[n].c_str(), &SplitN) == TIXML_SUCCESS)
+ {
+ if (SplitN>1)
+ {
+
+ vector<unsigned int> jobs = AssignJobs2Threads(m_Original_Grid->GetQtyLines(n)-1, SplitN, true);
+ unsigned int line=0;
+ for (size_t i = 0; i<jobs.size()-1;++i)
+ {
+ line += jobs.at(i);
+ m_SplitNumber[n].push_back(line);
+ }
+ }
+ }
+ }
+
+ m_SplitNumber[n].push_back(m_Original_Grid->GetQtyLines(n)-1);
+ unique(m_SplitNumber[n].begin(), m_SplitNumber[n].end());
+ }
+
+ return openEMS::Parse_XML_FDTDSetup(FDTD_Opts);
+}
+
+bool openEMS_FDTD_MPI::SetupMPI()
+{
+ if (!m_MPI_Enabled)
+ return true;
+
+ MPI_Barrier(MPI_COMM_WORLD);
+
+ //validate number of processes
+ unsigned int numProcs = (m_SplitNumber[0].size()-1)*(m_SplitNumber[1].size()-1)*(m_SplitNumber[2].size()-1);
+ if (numProcs!=m_NumProc)
+ {
+ if (m_MyID==0)
+ cerr << "openEMS_FDTD_MPI::SetupMPI: Error: Requested splits require " << numProcs << " processes, but only " << m_NumProc << " were found! Exit! " << endl;
+ exit(10);
+ }
+
+ //create process table
+ unsigned int procN = 0;
+ unsigned int splits[] = {(unsigned int)m_SplitNumber[0].size()-1, (unsigned int)m_SplitNumber[1].size()-1, (unsigned int)m_SplitNumber[2].size()-1};
+ m_MPI_Op->SetSplitNumbers(0,splits[0]);
+ m_MPI_Op->SetSplitNumbers(1,splits[1]);
+ m_MPI_Op->SetSplitNumbers(2,splits[2]);
+ unsigned int*** procTable=Create3DArray<unsigned int>(splits);
+ for (size_t i=0;i<m_SplitNumber[0].size()-1;++i)
+ for (size_t j=0;j<m_SplitNumber[1].size()-1;++j)
+ for (size_t k=0;k<m_SplitNumber[2].size()-1;++k)
+ {
+ procTable[i][j][k] = procN;
+ ++procN;
+ }
+ m_MPI_Op->SetProcessTable(procTable);
+
+ CSRectGrid* grid = m_CSX->GetGrid();
+ //assign mesh and neighbors to this process
+ for (size_t i=0;i<m_SplitNumber[0].size()-1;++i)
+ {
+ for (size_t j=0;j<m_SplitNumber[1].size()-1;++j)
+ {
+ for (size_t k=0;k<m_SplitNumber[2].size()-1;++k)
+ {
+ if (procTable[i][j][k] == m_MyID)
+ {
+ m_MPI_Op->SetProcessTablePosition(0,i);
+ m_MPI_Op->SetProcessTablePosition(1,j);
+ m_MPI_Op->SetProcessTablePosition(2,k);
+
+ grid->ClearLines(0);
+ grid->ClearLines(1);
+ grid->ClearLines(2);
+
+ for (unsigned int n=m_SplitNumber[0].at(i);n<=m_SplitNumber[0].at(i+1);++n)
+ grid->AddDiscLine(0, m_Original_Grid->GetLine(0,n) );
+ for (unsigned int n=m_SplitNumber[1].at(j);n<=m_SplitNumber[1].at(j+1);++n)
+ grid->AddDiscLine(1, m_Original_Grid->GetLine(1,n) );
+ for (unsigned int n=m_SplitNumber[2].at(k);n<=m_SplitNumber[2].at(k+1);++n)
+ grid->AddDiscLine(2, m_Original_Grid->GetLine(2,n) );
+
+ m_MPI_Op->SetSplitPos(0,m_SplitNumber[0].at(i));
+ m_MPI_Op->SetSplitPos(1,m_SplitNumber[1].at(i));
+ m_MPI_Op->SetSplitPos(2,m_SplitNumber[2].at(i));
+
+ if (i>0)
+ m_MPI_Op->SetNeighborDown(0,procTable[i-1][j][k]);
+ if (i<m_SplitNumber[0].size()-2)
+ {
+ //add one additional line
+ grid->AddDiscLine(0, m_Original_Grid->GetLine(0,m_SplitNumber[0].at(i+1)+1 ));
+ m_MPI_Op->SetNeighborUp(0,procTable[i+1][j][k]);
+ }
+
+ if (j>0)
+ m_MPI_Op->SetNeighborDown(1,procTable[i][j-1][k]);
+ if (j<m_SplitNumber[1].size()-2)
+ {
+ //add one additional line
+ grid->AddDiscLine(1, m_Original_Grid->GetLine(1,m_SplitNumber[1].at(j+1)+1 ));
+ m_MPI_Op->SetNeighborUp(1,procTable[i][j+1][k]);
+ }
+
+ if (k>0)
+ m_MPI_Op->SetNeighborDown(2,procTable[i][j][k-1]);
+ if (k<m_SplitNumber[2].size()-2)
+ {
+ //add one additional line
+ grid->AddDiscLine(2, m_Original_Grid->GetLine(2,m_SplitNumber[2].at(k+1)+1 ));
+ m_MPI_Op->SetNeighborUp(2,procTable[i][j][k+1]);
+ }
+
+ }
+ }
+ }
+ }
+
+ m_MPI_Op->SetOriginalMesh(m_Original_Grid);
+
+ m_MPI_Op->SetTag(0);
+
+ return true;
+}
+
+
+bool openEMS_FDTD_MPI::SetupOperator()
+{
+ bool ret = true;
+ if (m_engine == EngineType_MPI)
+ {
+ FDTD_Op = Operator_MPI::New();
+ }
+ else
+ {
+ ret = openEMS::SetupOperator();
+ }
+
+ m_MPI_Op = dynamic_cast<Operator_MPI*>(FDTD_Op);
+
+ if ((m_MPI_Enabled) && (m_MPI_Op==NULL))
+ {
+ cerr << "openEMS_FDTD_MPI::SetupOperator: Error: MPI is enabled but requested engine does not support MPI... EXIT!!!" << endl;
+ MPI_Barrier(MPI_COMM_WORLD);
+ exit(0);
+ }
+
+ ret &= SetupMPI();
+
+ return ret;
+}
+
+unsigned int openEMS_FDTD_MPI::GetNextStep()
+{
+ //start processing and get local next step
+ int step=PA->Process();
+ double currTS = FDTD_Eng->GetNumberOfTimesteps();
+ if ((step<0) || (step>(int)(NrTS - currTS))) step=NrTS - currTS;
+
+ int local_step=step;
+
+ //find the smallest next step requestes by all processings
+ MPI_Reduce(&local_step, &step, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
+ //send the smallest next step to all
+ MPI_Bcast(&step, 1, MPI_INT, 0, MPI_COMM_WORLD);
+
+ return step;
+}
+
+bool openEMS_FDTD_MPI::CheckEnergyCalc()
+{
+ int local_Check = (int)m_ProcField->CheckTimestep();
+ int result;
+
+ //check if some process request an energy calculation --> the sum is larger than 0
+ MPI_Reduce(&local_Check, &result, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
+ //send result to all
+ MPI_Bcast(&result, 1, MPI_INT, 0, MPI_COMM_WORLD);
+
+ //calc energy if result is non-zero
+ return result>0;
+}
+
+double openEMS_FDTD_MPI::CalcEnergy()
+{
+ double energy = 0;
+ double loc_energy= m_ProcField->CalcTotalEnergyEstimate();
+
+ //calc the sum of all local energies
+ MPI_Reduce(&loc_energy, &energy, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
+ //send sum-energy to all processes
+ MPI_Bcast(&energy, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
+
+ if (energy>m_MaxEnergy)
+ m_MaxEnergy = energy;
+ if (m_MaxEnergy)
+ m_EnergyDecrement = energy/m_MaxEnergy;
+
+ return energy;
+}
+
+bool openEMS_FDTD_MPI::SetupProcessing()
+{
+ bool ret = openEMS::SetupProcessing();
+
+ //search for active processings in different processes
+ size_t numProc = PA->GetNumberOfProcessings();
+ int active=0;
+ bool deactivate = false;
+ bool rename = false;
+ for (size_t n=0;n<numProc;++n)
+ {
+ Processing* proc = PA->GetProcessing(n);
+ int isActive = (int)proc->GetEnable();
+ //sum of all active processings
+ MPI_Reduce(&isActive, &active, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
+ deactivate = false;
+ rename = false;
+ if ((m_MyID==0) && (active>1)) //more than one active processing...
+ {
+ deactivate = true; //default
+ if (dynamic_cast<ProcessIntegral*>(proc)!=NULL)
+ {
+ //type is integral processing --> disable! Needs to be fixed!
+ cerr << "openEMS_FDTD_MPI::SetupProcessing(): Warning: Processing: " << proc->GetName() << " occures multiple times and is being deactivated..." << endl;
+ deactivate = true;
+ rename = false;
+ }
+ if (dynamic_cast<ProcessFields*>(proc)!=NULL)
+ {
+ //type is field processing --> renameing! Needs to be fixed!
+ cerr << "openEMS_FDTD_MPI::SetupProcessing(): Warning: Processing: " << proc->GetName() << " occures multiple times and is being renamed..." << endl;
+ deactivate = false;
+ rename = true;
+ }
+ }
+ //broadcast informations to all
+ MPI_Bcast(&deactivate, 1, MPI::BOOL, 0, MPI_COMM_WORLD);
+ MPI_Bcast(&rename, 1, MPI::BOOL, 0, MPI_COMM_WORLD);
+ if (deactivate)
+ proc->SetEnable(false);
+ if (rename)
+ {
+ ProcessFields* ProcField = dynamic_cast<ProcessFields*>(proc);
+ if (ProcField)
+ {
+ stringstream name_ss;
+ name_ss << "ID" << m_MyID << "_" << ProcField->GetName();
+ ProcField->SetName(name_ss.str());
+ ProcField->SetFileName(name_ss.str());
+ }
+ }
+ }
+ return ret;
+}
+
+int openEMS_FDTD_MPI::SetupFDTD()
+{
+ return openEMS::SetupFDTD();
+}
+
+void openEMS_FDTD_MPI::RunFDTD()
+{
+ if (!m_MPI_Enabled)
+ return openEMS::RunFDTD();
+
+ cout << "Running MPI-FDTD engine... this may take a while... grab a cup of coffee?!?" << endl;
+
+ //get the sum of all cells
+ unsigned int local_NrCells=FDTD_Op->GetNumberCells();
+ MPI_Reduce(&local_NrCells, &m_NumberCells, 1, MPI_UNSIGNED, MPI_SUM, 0, MPI_COMM_WORLD);
+ MPI_Bcast(&m_NumberCells, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
+
+ //special handling of a field processing, needed to realize the end criteria...
+ m_ProcField = new ProcessFields(NewEngineInterface());
+ PA->AddProcessing(m_ProcField);
+
+ //init processings
+ PA->InitAll();
+
+ double currE=0;
+
+ //add all timesteps to end-crit field processing with max excite amplitude
+ unsigned int maxExcite = FDTD_Op->GetExcitationSignal()->GetMaxExcitationTimestep();
+// for (unsigned int n=0; n<FDTD_Op->Exc->Volt_Count; ++n)
+// m_ProcField->AddStep(FDTD_Op->Exc->Volt_delay[n]+maxExcite);
+ m_ProcField->AddStep(maxExcite);
+
+ int prevTS=0,currTS=0;
+ double numCells = FDTD_Op->GetNumberCells();
+ double speed = 0;
+ double t_diff;
+ double t_run;
+
+ timeval currTime;
+ gettimeofday(&currTime,NULL);
+ timeval startTime = currTime;
+ timeval prevTime= currTime;
+
+ if (m_DumpStats)
+ InitRunStatistics(__OPENEMS_RUN_STAT_FILE__);
+ //*************** simulate ************//
+ PA->PreProcess();
+ int step = GetNextStep();
+
+ while ((step>0) && !CheckAbortCond())
+ {
+ FDTD_Eng->IterateTS(step);
+ step = GetNextStep();
+
+ currTS = FDTD_Eng->GetNumberOfTimesteps();
+
+ currE = 0;
+ gettimeofday(&currTime,NULL);
+ t_diff = CalcDiffTime(currTime,prevTime);
+
+ if (CheckEnergyCalc())
+ currE = CalcEnergy();
+
+ //make sure all processes are at the same simulation time
+ MPI_Bcast(&t_diff, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
+
+ if (t_diff>4)
+ {
+ if (currE==0)
+ currE = CalcEnergy();
+ if (m_MyID==0)
+ {
+ t_run = CalcDiffTime(currTime,startTime);
+ speed = numCells*(currTS-prevTS)/t_diff;
+ cout << "[@" << FormatTime(t_run) << "] Timestep: " << setw(12) << currTS ;
+ cout << " || Speed: " << setw(6) << setprecision(1) << std::fixed << speed*1e-6 << " MC/s (" << setw(4) << setprecision(3) << std::scientific << t_diff/(currTS-prevTS) << " s/TS)" ;
+ cout << " || Energy: ~" << setw(6) << setprecision(2) << std::scientific << currE << " (-" << setw(5) << setprecision(2) << std::fixed << fabs(10.0*log10(m_EnergyDecrement)) << "dB)" << endl;
+
+ //set step to zero to abort simulation and send to all
+ if (m_EnergyDecrement<endCrit)
+ step=0;
+
+ if (m_DumpStats)
+ DumpRunStatistics(__OPENEMS_RUN_STAT_FILE__, t_run, currTS, speed, currE);
+ }
+
+ MPI_Bcast(&step, 1, MPI_INT, 0, MPI_COMM_WORLD);
+
+ prevTime=currTime;
+ prevTS=currTS;
+
+ PA->FlushNext();
+ }
+ }
+ if ((m_MyID==0) && (m_EnergyDecrement>endCrit) && (FDTD_Op->GetExcitationSignal()->GetExciteType()==0))
+ cerr << "RunFDTD: max. number of timesteps was reached before the end-criteria of -" << fabs(10.0*log10(endCrit)) << "dB was reached... " << endl << \
+ "\tYou may want to choose a higher number of max. timesteps... " << endl;
+
+ gettimeofday(&currTime,NULL);
+
+ t_diff = CalcDiffTime(currTime,startTime);
+
+ if (m_MyID==0)
+ {
+ cout << "Time for " << FDTD_Eng->GetNumberOfTimesteps() << " iterations with " << FDTD_Op->GetNumberCells() << " cells : " << t_diff << " sec" << endl;
+ cout << "Speed: " << numCells*(double)FDTD_Eng->GetNumberOfTimesteps()/t_diff*1e-6 << " MCells/s " << endl;
+
+ if (m_DumpStats)
+ DumpStatistics(__OPENEMS_STAT_FILE__, t_diff);
+ }
+
+ //*************** postproc ************//
+ PA->PostProcess();
+}
diff --git a/openEMS/FDTD/openems_fdtd_mpi.h b/openEMS/FDTD/openems_fdtd_mpi.h
new file mode 100644
index 0000000..efb1f00
--- /dev/null
+++ b/openEMS/FDTD/openems_fdtd_mpi.h
@@ -0,0 +1,72 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPENEMS_FDTD_MPI_H
+#define OPENEMS_FDTD_MPI_H
+
+#include "openems.h"
+
+class ProcessFields;
+class Operator_MPI;
+class CSRectGrid;
+
+class openEMS_FDTD_MPI : public openEMS
+{
+public:
+ openEMS_FDTD_MPI(bool m_MPI_Debug=false);
+ virtual ~openEMS_FDTD_MPI();
+
+ virtual bool Parse_XML_FDTDSetup(TiXmlElement* FDTD_Opts);
+ virtual int SetupFDTD();
+ virtual void RunFDTD();
+
+ virtual bool parseCommandLineArgument( const char *argv );
+
+ static std::string GetExtLibsInfo();
+
+protected:
+ Operator_MPI* m_MPI_Op;
+ CSRectGrid* m_Original_Grid;
+ unsigned int m_MyID;
+ unsigned int m_NumProc;
+ bool m_MPI_Enabled;
+ unsigned int m_NumberCells;
+
+ std::vector<unsigned int> m_SplitNumber[3];
+ TiXmlElement* m_MPI_Elem;
+ virtual bool SetupMPI();
+ virtual bool SetupOperator();
+
+ int* m_Gather_Buffer;
+ unsigned int GetNextStep();
+
+ ProcessFields* m_ProcField;
+ double m_MaxEnergy;
+ double m_EnergyDecrement;
+ double* m_Energy_Buffer;
+ //! Check if energy calc is requested...
+ bool CheckEnergyCalc();
+ //! Calc energy in all processes and add up
+ double CalcEnergy();
+
+ virtual bool SetupProcessing();
+
+ //output redirection to file for ranks > 0
+ std::ofstream* m_Output;
+};
+
+#endif // OPENEMS_FDTD_MPI_H
diff --git a/openEMS/FDTD/operator.cpp b/openEMS/FDTD/operator.cpp
new file mode 100644
index 0000000..a7582aa
--- /dev/null
+++ b/openEMS/FDTD/operator.cpp
@@ -0,0 +1,2131 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <fstream>
+#include <algorithm>
+#include "operator.h"
+#include "engine.h"
+#include "extensions/operator_extension.h"
+#include "extensions/operator_ext_excitation.h"
+#include "Common/processfields.h"
+#include "tools/array_ops.h"
+#include "tools/vtk_file_writer.h"
+#include "fparser.hh"
+#include "extensions/operator_ext_excitation.h"
+
+#include "vtkPolyData.h"
+#include "vtkCellArray.h"
+#include "vtkPoints.h"
+#include "vtkXMLPolyDataWriter.h"
+#include "CSPrimBox.h"
+#include "CSPrimCurve.h"
+
+#include "CSPropMaterial.h"
+#include "CSPropLumpedElement.h"
+
+Operator* Operator::New()
+{
+ cout << "Create FDTD operator" << endl;
+ Operator* op = new Operator();
+ op->Init();
+ return op;
+}
+
+Operator::Operator() : Operator_Base()
+{
+ m_Exc = 0;
+ m_InvaildTimestep = false;
+ m_TimeStepVar = 3;
+}
+
+Operator::~Operator()
+{
+ for (size_t n=0; n<m_Op_exts.size(); ++n)
+ delete m_Op_exts.at(n);
+ m_Op_exts.clear();
+
+ Delete();
+}
+
+Engine* Operator::CreateEngine()
+{
+ m_Engine = Engine::New(this);
+ return m_Engine;
+}
+
+void Operator::Init()
+{
+ CSX = NULL;
+ m_Engine = NULL;
+
+ Operator_Base::Init();
+
+ vv=NULL;
+ vi=NULL;
+ iv=NULL;
+ ii=NULL;
+
+ m_epsR=NULL;
+ m_kappa=NULL;
+ m_mueR=NULL;
+ m_sigma=NULL;
+
+ MainOp=NULL;
+
+ for (int n=0; n<3; ++n)
+ {
+ EC_C[n]=NULL;
+ EC_G[n]=NULL;
+ EC_L[n]=NULL;
+ EC_R[n]=NULL;
+ }
+
+ m_Exc = 0;
+ m_TimeStepFactor = 1;
+ SetMaterialAvgMethod(QuarterCell);
+}
+
+void Operator::Delete()
+{
+ CSX = NULL;
+
+ Delete_N_3DArray(vv,numLines);
+ Delete_N_3DArray(vi,numLines);
+ Delete_N_3DArray(iv,numLines);
+ Delete_N_3DArray(ii,numLines);
+ vv=vi=iv=ii=0;
+ delete MainOp; MainOp=0;
+ for (int n=0; n<3; ++n)
+ {
+ delete[] EC_C[n];EC_C[n]=0;
+ delete[] EC_G[n];EC_G[n]=0;
+ delete[] EC_L[n];EC_L[n]=0;
+ delete[] EC_R[n];EC_R[n]=0;
+ }
+
+ Delete_N_3DArray(m_epsR,numLines);
+ m_epsR=0;
+ Delete_N_3DArray(m_kappa,numLines);
+ m_kappa=0;
+ Delete_N_3DArray(m_mueR,numLines);
+ m_mueR=0;
+ Delete_N_3DArray(m_sigma,numLines);
+ m_sigma=0;
+}
+
+void Operator::Reset()
+{
+ Delete();
+ Operator_Base::Reset();
+}
+
+double Operator::GetDiscLine(int n, unsigned int pos, bool dualMesh) const
+{
+ if ((n<0) || (n>2)) return 0.0;
+ if (pos>=numLines[n]) return 0.0;
+ if (dualMesh==false)
+ return discLines[n][pos];
+
+ // return dual mesh node
+ if (pos<numLines[n]-1)
+ return 0.5*(discLines[n][pos] + discLines[n][pos+1]);
+
+ // dual node for the last line (outside the field domain)
+ return discLines[n][pos] + 0.5*(discLines[n][pos] - discLines[n][pos-1]);
+}
+
+double Operator::GetDiscDelta(int n, unsigned int pos, bool dualMesh) const
+{
+ if ((n<0) || (n>2)) return 0.0;
+ if (pos>=numLines[n]) return 0.0;
+ double delta=0;
+ if (dualMesh==false)
+ {
+ if (pos<numLines[n]-1)
+ delta = GetDiscLine(n,pos+1,false) - GetDiscLine(n,pos,false);
+ else
+ delta = GetDiscLine(n,pos,false) - GetDiscLine(n,pos-1,false);
+ return delta;
+ }
+ else
+ {
+ if (pos>0)
+ delta = GetDiscLine(n,pos,true) - GetDiscLine(n,pos-1,true);
+ else
+ delta = GetDiscLine(n,1,false) - GetDiscLine(n,0,false);
+ return delta;
+ }
+}
+
+bool Operator::GetYeeCoords(int ny, unsigned int pos[3], double* coords, bool dualMesh) const
+{
+ for (int n=0;n<3;++n)
+ coords[n]=GetDiscLine(n,pos[n],dualMesh);
+ coords[ny]=GetDiscLine(ny,pos[ny],!dualMesh);
+
+ //check if position is inside the FDTD domain
+ if (dualMesh==false) //main grid
+ {
+ if (pos[ny]>=numLines[ny]-1)
+ return false;
+ }
+ else //dual grid
+ {
+ int nP = (ny+1)%3;
+ int nPP = (ny+2)%3;
+ if ((pos[nP]>=numLines[nP]-1) || (pos[nPP]>=numLines[nPP]-1))
+ return false;
+ }
+ return true;
+}
+
+bool Operator::GetNodeCoords(const unsigned int pos[3], double* coords, bool dualMesh, CoordinateSystem c_system) const
+{
+ for (int n=0;n<3;++n)
+ coords[n]=GetDiscLine(n,pos[n],dualMesh);
+ TransformCoordSystem(coords,coords,m_MeshType,c_system);
+ return true;
+}
+
+double Operator::GetEdgeLength(int n, const unsigned int* pos, bool dualMesh) const
+{
+ return GetDiscDelta(n,pos[n],dualMesh)*gridDelta;
+}
+
+double Operator::GetCellVolume(const unsigned int pos[3], bool dualMesh) const
+{
+ double vol=1;
+ for (int n=0;n<3;++n)
+ vol*=GetEdgeLength(n,pos,dualMesh);
+ return vol;
+}
+
+double Operator::GetNodeWidth(int ny, const int pos[3], bool dualMesh) const
+{
+ if ( (pos[0]<0) || (pos[1]<0) || (pos[2]<0) )
+ return 0.0;
+
+ //call the unsigned int version of GetNodeWidth
+ unsigned int uiPos[]={(unsigned int)pos[0],(unsigned int)pos[1],(unsigned int)pos[2]};
+ return GetNodeWidth(ny, uiPos, dualMesh);
+}
+
+double Operator::GetNodeArea(int ny, const unsigned int pos[3], bool dualMesh) const
+{
+ int nyP = (ny+1)%3;
+ int nyPP = (ny+2)%3;
+ return GetNodeWidth(nyP,pos,dualMesh) * GetNodeWidth(nyPP,pos,dualMesh);
+}
+
+double Operator::GetNodeArea(int ny, const int pos[3], bool dualMesh) const
+{
+ if ( (pos[0]<0) || (pos[1]<0) || (pos[2]<0) )
+ return 0.0;
+
+ //call the unsigned int version of GetNodeArea
+ unsigned int uiPos[]={(unsigned int)pos[0],(unsigned int)pos[1],(unsigned int)pos[2]};
+ return GetNodeArea(ny, uiPos, dualMesh);
+}
+
+unsigned int Operator::SnapToMeshLine(int ny, double coord, bool &inside, bool dualMesh, bool fullMesh) const
+{
+ inside = false;
+ if ((ny<0) || (ny>2))
+ return 0;
+ if (coord<GetDiscLine(ny,0))
+ return 0;
+ unsigned int numLines = GetNumberOfLines(ny, fullMesh);
+ if (coord>GetDiscLine(ny,numLines-1))
+ return numLines-1;
+ inside=true;
+ if (dualMesh==false)
+ {
+ for (unsigned int n=0;n<numLines;++n)
+ {
+ if (coord<=GetDiscLine(ny,n,true))
+ return n;
+ }
+ }
+ else
+ {
+ for (unsigned int n=1;n<numLines;++n)
+ {
+ if (coord<=GetDiscLine(ny,n,false))
+ return n-1;
+ }
+ }
+ //should not happen
+ return 0;
+}
+
+bool Operator::SnapToMesh(const double* dcoord, unsigned int* uicoord, bool dualMesh, bool fullMesh, bool* inside) const
+{
+ bool meshInside=false;
+ bool ok=true;
+ for (int n=0; n<3; ++n)
+ {
+ uicoord[n] = SnapToMeshLine(n,dcoord[n],meshInside,dualMesh,fullMesh);
+ ok &= meshInside;
+ if (inside)
+ inside[n]=meshInside;
+ }
+ return ok;
+}
+
+int Operator::SnapBox2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh, bool fullMesh, int SnapMethod, bool* bStartIn, bool* bStopIn) const
+{
+ double l_start[3], l_stop[3];
+ for (int n=0;n<3;++n)
+ {
+ l_start[n] = fmin(start[n],stop[n]);
+ l_stop[n] = fmax(start[n], stop[n]);
+ double min = GetDiscLine(n,0);
+ double max = GetDiscLine(n,GetNumberOfLines(n, fullMesh)-1);
+ if ( ((l_start[n]<min) && (l_stop[n]<min)) || ((l_start[n]>max) && (l_stop[n]>max)) )
+ {
+ return -2;
+ }
+ }
+
+ SnapToMesh(l_start, uiStart, dualMesh, fullMesh, bStartIn);
+ SnapToMesh(l_stop, uiStop, dualMesh, fullMesh, bStopIn);
+ int iDim = 0;
+
+ if (SnapMethod==0)
+ {
+ for (int n=0;n<3;++n)
+ if (uiStop[n]>uiStart[n])
+ ++iDim;
+ return iDim;
+ }
+ else if (SnapMethod==1)
+ {
+ for (int n=0;n<3;++n)
+ {
+ if (uiStop[n]>uiStart[n])
+ {
+ if ((GetDiscLine( n, uiStart[n], dualMesh ) > l_start[n]) && (uiStart[n]>0))
+ --uiStart[n];
+ if ((GetDiscLine( n, uiStop[n], dualMesh ) < l_stop[n]) && (uiStop[n]<GetNumberOfLines(n, fullMesh)-1))
+ ++uiStop[n];
+ }
+ if (uiStop[n]>uiStart[n])
+ ++iDim;
+ }
+ return iDim;
+ }
+ else if (SnapMethod==2)
+ {
+ for (int n=0;n<3;++n)
+ {
+ if (uiStop[n]>uiStart[n])
+ {
+ if ((GetDiscLine( n, uiStart[n], dualMesh ) < l_start[n]) && (uiStart[n]<GetNumberOfLines(n, fullMesh)-1))
+ ++uiStart[n];
+ if ((GetDiscLine( n, uiStop[n], dualMesh ) > l_stop[n]) && (uiStop[n]>0))
+ --uiStop[n];
+ }
+ if (uiStop[n]>uiStart[n])
+ ++iDim;
+ }
+ return iDim;
+ }
+ else
+ cerr << "Operator::SnapBox2Mesh: Unknown snapping method!" << endl;
+ return -1;
+}
+
+int Operator::SnapLine2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh, bool fullMesh) const
+{
+ bool bStartIn[3];
+ bool bStopIn[3];
+ SnapToMesh(start, uiStart, dualMesh, fullMesh, bStartIn);
+ SnapToMesh(stop, uiStop, dualMesh, fullMesh, bStopIn);
+
+ for (int n=0;n<3;++n)
+ {
+ if ((start[n]<GetDiscLine(n,0)) && (stop[n]<GetDiscLine(n,0)))
+ return -1; //lower bound violation
+ if ((start[n]>GetDiscLine(n,GetNumberOfLines(n,true)-1)) && (stop[n]>GetDiscLine(n,GetNumberOfLines(n,true)-1)))
+ return -1; //upper bound violation
+ }
+
+ int ret = 0;
+ if (!(bStartIn[0] && bStartIn[1] && bStartIn[2]))
+ ret = ret + 1;
+ if (!(bStopIn[0] && bStopIn[1] && bStopIn[2]))
+ ret = ret + 2;
+ if (ret==0)
+ return ret;
+
+ //fixme, do we need to do something about start or stop being outside the field domain?
+ //maybe caclulate the intersection point and snap to that?
+ //it seems to work like this as well...
+
+ return ret;
+}
+
+
+Grid_Path Operator::FindPath(double start[], double stop[])
+{
+ Grid_Path path;
+ unsigned int uiStart[3],uiStop[3],currPos[3];
+
+ int ret = SnapLine2Mesh(start, stop, uiStart, uiStop, false, true);
+ if (ret<0)
+ return path;
+
+ currPos[0]=uiStart[0];
+ currPos[1]=uiStart[1];
+ currPos[2]=uiStart[2];
+ double meshStart[3] = {discLines[0][uiStart[0]], discLines[1][uiStart[1]], discLines[2][uiStart[2]]};
+ double meshStop[3] = {discLines[0][uiStop[0]], discLines[1][uiStop[1]], discLines[2][uiStop[2]]};
+ bool UpDir = false;
+ double foot=0,dist=0,minFoot=0,minDist=0;
+ int minDir=0;
+ unsigned int minPos[3];
+ double startFoot,stopFoot,currFoot;
+ Point_Line_Distance(meshStart,start,stop,startFoot,dist, m_MeshType);
+ Point_Line_Distance(meshStop,start,stop,stopFoot,dist, m_MeshType);
+ currFoot=startFoot;
+ minFoot=startFoot;
+ double P[3];
+
+ while (minFoot<stopFoot)
+ {
+ minDist=1e300;
+ for (int n=0; n<3; ++n) //check all 6 surrounding points
+ {
+ P[0] = discLines[0][currPos[0]];
+ P[1] = discLines[1][currPos[1]];
+ P[2] = discLines[2][currPos[2]];
+ if (((int)currPos[n]-1)>=0)
+ {
+ P[n] = discLines[n][currPos[n]-1];
+ Point_Line_Distance(P,start,stop,foot,dist, m_MeshType);
+ if ((foot>currFoot) && (dist<minDist))
+ {
+ minFoot=foot;
+ minDist=dist;
+ minDir = n;
+ UpDir = false;
+ }
+ }
+ if ((currPos[n]+1)<numLines[n])
+ {
+ P[n] = discLines[n][currPos[n]+1];
+ Point_Line_Distance(P,start,stop,foot,dist, m_MeshType);
+ if ((foot>currFoot) && (dist<minDist))
+ {
+ minFoot=foot;
+ minDist=dist;
+ minDir = n;
+ UpDir = true;
+ }
+ }
+ }
+ minPos[0]=currPos[0];
+ minPos[1]=currPos[1];
+ minPos[2]=currPos[2];
+ if (UpDir)
+ {
+ currPos[minDir]+=1;
+ }
+ else
+ {
+ currPos[minDir]+=-1;
+ minPos[minDir]-=1;
+ }
+ //check validity of current postion
+ for (int n=0;n<3;++n)
+ if (currPos[n]>=numLines[n])
+ {
+ cerr << __func__ << ": Error, path went out of simulation domain, skipping path!" << endl;
+ Grid_Path empty;
+ return empty;
+ }
+ path.posPath[0].push_back(minPos[0]);
+ path.posPath[1].push_back(minPos[1]);
+ path.posPath[2].push_back(minPos[2]);
+ currFoot=minFoot;
+ path.dir.push_back(minDir);
+ }
+
+ //close missing edges, if currPos is not equal to uiStopPos
+ for (int n=0; n<3; ++n)
+ {
+ if (currPos[n]>uiStop[n])
+ {
+ --currPos[n];
+ path.posPath[0].push_back(currPos[0]);
+ path.posPath[1].push_back(currPos[1]);
+ path.posPath[2].push_back(currPos[2]);
+ path.dir.push_back(n);
+ }
+ else if (currPos[n]<uiStop[n])
+ {
+ path.posPath[0].push_back(currPos[0]);
+ path.posPath[1].push_back(currPos[1]);
+ path.posPath[2].push_back(currPos[2]);
+ path.dir.push_back(n);
+ }
+ }
+
+ return path;
+}
+
+void Operator::SetMaterialAvgMethod(MatAverageMethods method)
+{
+ switch (method)
+ {
+ default:
+ case QuarterCell:
+ return SetQuarterCellMaterialAvg();
+ case CentralCell:
+ return SetCellConstantMaterial();
+ }
+}
+
+double Operator::GetNumberCells() const
+{
+ if (numLines)
+ return (numLines[0])*(numLines[1])*(numLines[2]); //it's more like number of nodes???
+ return 0;
+}
+
+void Operator::ShowStat() const
+{
+ unsigned int OpSize = 12*numLines[0]*numLines[1]*numLines[2]*sizeof(FDTD_FLOAT);
+ unsigned int FieldSize = 6*numLines[0]*numLines[1]*numLines[2]*sizeof(FDTD_FLOAT);
+ double MBdiff = 1024*1024;
+
+ cout << "------- Stat: FDTD Operator -------" << endl;
+ cout << "Dimensions\t\t: " << numLines[0] << "x" << numLines[1] << "x" << numLines[2] << " = " << numLines[0]*numLines[1]*numLines[2] << " Cells (" << numLines[0]*numLines[1]*numLines[2]/1e6 << " MCells)" << endl;
+ cout << "Size of Operator\t: " << OpSize << " Byte (" << (double)OpSize/MBdiff << " MiB) " << endl;
+ cout << "Size of Field-Data\t: " << FieldSize << " Byte (" << (double)FieldSize/MBdiff << " MiB) " << endl;
+ cout << "-----------------------------------" << endl;
+ cout << "Background materials (epsR/mueR/kappa/sigma): " << GetBackgroundEpsR() << "/" << GetBackgroundMueR() << "/" << GetBackgroundKappa() << "/" << GetBackgroundSigma() << endl;
+ cout << "-----------------------------------" << endl;
+ cout << "Number of PEC edges\t: " << m_Nr_PEC[0]+m_Nr_PEC[1]+m_Nr_PEC[2] << endl;
+ cout << "in " << GetDirName(0) << " direction\t\t: " << m_Nr_PEC[0] << endl;
+ cout << "in " << GetDirName(1) << " direction\t\t: " << m_Nr_PEC[1] << endl;
+ cout << "in " << GetDirName(2) << " direction\t\t: " << m_Nr_PEC[2] << endl;
+ cout << "-----------------------------------" << endl;
+ cout << "Timestep (s)\t\t: " << dT ;
+ if (opt_dT)
+ cout <<"\t(" << opt_dT << ")";
+ cout << endl;
+ cout << "Timestep method name\t: " << m_Used_TS_Name << endl;
+ cout << "Nyquist criteria (TS)\t: " << m_Exc->GetNyquistNum() << endl;
+ cout << "Nyquist criteria (s)\t: " << m_Exc->GetNyquistNum()*dT << endl;
+ cout << "-----------------------------------" << endl;
+}
+
+void Operator::ShowExtStat() const
+{
+ if (m_Op_exts.size()==0) return;
+ cout << "-----------------------------------" << endl;
+ for (size_t n=0; n<m_Op_exts.size(); ++n)
+ m_Op_exts.at(n)->ShowStat(cout);
+ cout << "-----------------------------------" << endl;
+}
+
+void Operator::DumpOperator2File(string filename)
+{
+#ifdef OUTPUT_IN_DRAWINGUNITS
+ double discLines_scaling = 1;
+#else
+ double discLines_scaling = GetGridDelta();
+#endif
+
+ cout << "Operator: Dumping FDTD operator information to vtk file: " << filename << " ..." << flush;
+
+ VTK_File_Writer* vtk_Writer = new VTK_File_Writer(filename.c_str(), m_MeshType);
+ vtk_Writer->SetMeshLines(discLines,numLines,discLines_scaling);
+ vtk_Writer->SetHeader("openEMS - Operator dump");
+
+ vtk_Writer->SetNativeDump(true);
+
+ //find excitation extension
+ Operator_Ext_Excitation* Op_Ext_Exc=GetExcitationExtension();
+
+ if (Op_Ext_Exc)
+ {
+ FDTD_FLOAT**** exc = NULL;
+ if (Op_Ext_Exc->Volt_Count>0)
+ {
+ exc = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ for (unsigned int n=0; n< Op_Ext_Exc->Volt_Count; ++n)
+ exc[ Op_Ext_Exc->Volt_dir[n]][ Op_Ext_Exc->Volt_index[0][n]][ Op_Ext_Exc->Volt_index[1][n]][ Op_Ext_Exc->Volt_index[2][n]] = Op_Ext_Exc->Volt_amp[n];
+ vtk_Writer->AddVectorField("exc_volt",exc);
+ Delete_N_3DArray(exc,numLines);
+ }
+
+ if ( Op_Ext_Exc->Curr_Count>0)
+ {
+ exc = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ for (unsigned int n=0; n< Op_Ext_Exc->Curr_Count; ++n)
+ exc[ Op_Ext_Exc->Curr_dir[n]][ Op_Ext_Exc->Curr_index[0][n]][ Op_Ext_Exc->Curr_index[1][n]][ Op_Ext_Exc->Curr_index[2][n]] = Op_Ext_Exc->Curr_amp[n];
+ vtk_Writer->AddVectorField("exc_curr",exc);
+ Delete_N_3DArray(exc,numLines);
+ }
+ }
+
+ FDTD_FLOAT**** vv_temp = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ FDTD_FLOAT**** vi_temp = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ FDTD_FLOAT**** iv_temp = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ FDTD_FLOAT**** ii_temp = Create_N_3DArray<FDTD_FLOAT>(numLines);
+
+ unsigned int pos[3], n;
+ for (n=0; n<3; n++)
+ for (pos[0]=0; pos[0]<numLines[0]; pos[0]++)
+ for (pos[1]=0; pos[1]<numLines[1]; pos[1]++)
+ for (pos[2]=0; pos[2]<numLines[2]; pos[2]++)
+ {
+ vv_temp[n][pos[0]][pos[1]][pos[2]] = GetVV(n,pos);
+ vi_temp[n][pos[0]][pos[1]][pos[2]] = GetVI(n,pos);
+ iv_temp[n][pos[0]][pos[1]][pos[2]] = GetIV(n,pos);
+ ii_temp[n][pos[0]][pos[1]][pos[2]] = GetII(n,pos);
+ }
+
+
+ vtk_Writer->AddVectorField("vv",vv_temp);
+ Delete_N_3DArray(vv_temp,numLines);
+ vtk_Writer->AddVectorField("vi",vi_temp);
+ Delete_N_3DArray(vi_temp,numLines);
+ vtk_Writer->AddVectorField("iv",iv_temp);
+ Delete_N_3DArray(iv_temp,numLines);
+ vtk_Writer->AddVectorField("ii",ii_temp);
+ Delete_N_3DArray(ii_temp,numLines);
+
+ if (vtk_Writer->Write()==false)
+ cerr << "Operator::DumpOperator2File: Error: Can't write file... skipping!" << endl;
+
+ delete vtk_Writer;
+}
+
+//! \brief dump PEC (perfect electric conductor) information (into VTK-file)
+//! visualization via paraview
+//! visualize only one component (x, y or z)
+void Operator::DumpPEC2File(string filename , unsigned int *range)
+{
+ cout << "Operator: Dumping PEC information to vtk file: " << filename << " ..." << flush;
+
+#ifdef OUTPUT_IN_DRAWINGUNITS
+ double scaling = 1.0;
+#else
+ double scaling = GetGridDelta();;
+#endif
+
+ unsigned int start[3] = {0, 0, 0};
+ unsigned int stop[3] = {numLines[0]-1,numLines[1]-1,numLines[2]-1};
+
+ if (range!=NULL)
+ for (int n=0;n<3;++n)
+ {
+ start[n] = range[2*n];
+ stop[n] = range[2*n+1];
+ }
+
+ vtkPolyData* polydata = vtkPolyData::New();
+ vtkCellArray *poly = vtkCellArray::New();
+ vtkPoints *points = vtkPoints::New();
+
+ int* pointIdx[2];
+ pointIdx[0] = new int[numLines[0]*numLines[1]];
+ pointIdx[1] = new int[numLines[0]*numLines[1]];
+ // init point idx
+ for (unsigned int n=0;n<numLines[0]*numLines[1];++n)
+ {
+ pointIdx[0][n]=-1;
+ pointIdx[1][n]=-1;
+ }
+
+ int nP,nPP;
+ double coord[3];
+ unsigned int pos[3],rpos[3];
+ unsigned int mesh_idx=0;
+ for (pos[2]=start[2];pos[2]<stop[2];++pos[2])
+ { // each xy-plane
+ for (unsigned int n=0;n<numLines[0]*numLines[1];++n)
+ {
+ pointIdx[0][n]=pointIdx[1][n];
+ pointIdx[1][n]=-1;
+ }
+ for (pos[0]=start[0];pos[0]<stop[0];++pos[0])
+ for (pos[1]=start[1];pos[1]<stop[1];++pos[1])
+ {
+ for (int n=0;n<3;++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ if ((GetVV(n,pos) == 0) && (GetVI(n,pos) == 0) && (pos[nP]>0) && (pos[nPP]>0))
+ {
+ rpos[0]=pos[0];
+ rpos[1]=pos[1];
+ rpos[2]=pos[2];
+
+ poly->InsertNextCell(2);
+
+ mesh_idx = rpos[0] + rpos[1]*numLines[0];
+ if (pointIdx[0][mesh_idx]<0)
+ {
+ for (int m=0;m<3;++m)
+ coord[m] = discLines[m][rpos[m]];
+ TransformCoordSystem(coord, coord, m_MeshType, CARTESIAN);
+ for (int m=0;m<3;++m)
+ coord[m] *= scaling;
+ pointIdx[0][mesh_idx] = (int)points->InsertNextPoint(coord);
+ }
+ poly->InsertCellPoint(pointIdx[0][mesh_idx]);
+
+ ++rpos[n];
+ mesh_idx = rpos[0] + rpos[1]*numLines[0];
+ if (pointIdx[n==2][mesh_idx]<0)
+ {
+ for (int m=0;m<3;++m)
+ coord[m] = discLines[m][rpos[m]];
+ TransformCoordSystem(coord, coord, m_MeshType, CARTESIAN);
+ for (int m=0;m<3;++m)
+ coord[m] *= scaling;
+ pointIdx[n==2][mesh_idx] = (int)points->InsertNextPoint(coord);
+ }
+ poly->InsertCellPoint(pointIdx[n==2][mesh_idx]);
+ }
+ }
+ }
+ }
+ delete[] pointIdx[0];
+ delete[] pointIdx[1];
+
+ polydata->SetPoints(points);
+ points->Delete();
+ polydata->SetLines(poly);
+ poly->Delete();
+
+ vtkXMLPolyDataWriter* writer = vtkXMLPolyDataWriter::New();
+ filename += ".vtp";
+ writer->SetFileName(filename.c_str());
+
+#if VTK_MAJOR_VERSION>=6
+ writer->SetInputData(polydata);
+#else
+ writer->SetInput(polydata);
+#endif
+ writer->Write();
+
+ writer->Delete();
+ polydata->Delete();
+ cout << " done." << endl;
+}
+
+void Operator::DumpMaterial2File(string filename)
+{
+#ifdef OUTPUT_IN_DRAWINGUNITS
+ double discLines_scaling = 1;
+#else
+ double discLines_scaling = GetGridDelta();
+#endif
+
+ cout << "Operator: Dumping material information to vtk file: " << filename << " ..." << flush;
+
+ FDTD_FLOAT**** epsilon = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ FDTD_FLOAT**** mue = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ FDTD_FLOAT**** kappa = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ FDTD_FLOAT**** sigma = Create_N_3DArray<FDTD_FLOAT>(numLines);
+
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ vector<CSPrimitives*> vPrims = this->GetPrimitivesBoundBox(pos[0], pos[1], -1, CSProperties::MATERIAL);
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ for (int n=0; n<3; ++n)
+ {
+ double inMat[4];
+ Calc_EffMatPos(n, pos, inMat, vPrims);
+ epsilon[n][pos[0]][pos[1]][pos[2]] = inMat[0]/__EPS0__;
+ mue[n][pos[0]][pos[1]][pos[2]] = inMat[2]/__MUE0__;
+ kappa[n][pos[0]][pos[1]][pos[2]] = inMat[1];
+ sigma[n][pos[0]][pos[1]][pos[2]] = inMat[3];
+ }
+ }
+ }
+ }
+
+ VTK_File_Writer* vtk_Writer = new VTK_File_Writer(filename.c_str(), m_MeshType);
+ vtk_Writer->SetMeshLines(discLines,numLines,discLines_scaling);
+ vtk_Writer->SetHeader("openEMS - material dump");
+
+ vtk_Writer->SetNativeDump(true);
+
+ vtk_Writer->AddVectorField("epsilon",epsilon);
+ Delete_N_3DArray(epsilon,numLines);
+ vtk_Writer->AddVectorField("mue",mue);
+ Delete_N_3DArray(mue,numLines);
+ vtk_Writer->AddVectorField("kappa",kappa);
+ Delete_N_3DArray(kappa,numLines);
+ vtk_Writer->AddVectorField("sigma",sigma);
+ Delete_N_3DArray(sigma,numLines);
+
+ if (vtk_Writer->Write()==false)
+ cerr << "Operator::DumpMaterial2File: Error: Can't write file... skipping!" << endl;
+
+ delete vtk_Writer;
+}
+
+ bool Operator::SetupCSXGrid(CSRectGrid* grid)
+ {
+ for (int n=0; n<3; ++n)
+ {
+ discLines[n] = grid->GetLines(n,discLines[n],numLines[n],true);
+ if (numLines[n]<3)
+ {
+ cerr << "CartOperator::SetupCSXGrid: you need at least 3 disc-lines in every direction (3D!)!!!" << endl;
+ Reset();
+ return false;
+ }
+ }
+ MainOp = new AdrOp(numLines[0],numLines[1],numLines[2]);
+ MainOp->SetGrid(discLines[0],discLines[1],discLines[2]);
+ if (grid->GetDeltaUnit()<=0)
+ {
+ cerr << "CartOperator::SetupCSXGrid: grid delta unit must not be <=0 !!!" << endl;
+ Reset();
+ return false;
+ }
+ else gridDelta=grid->GetDeltaUnit();
+ MainOp->SetGridDelta(1);
+ MainOp->AddCellAdrOp();
+
+ //delete the grid clone...
+ delete grid;
+ return true;
+ }
+
+bool Operator::SetGeometryCSX(ContinuousStructure* geo)
+{
+ if (geo==NULL) return false;
+
+ CSX = geo;
+
+ CSBackgroundMaterial* bg_mat=CSX->GetBackgroundMaterial();
+ SetBackgroundEpsR(bg_mat->GetEpsilon());
+ SetBackgroundMueR(bg_mat->GetMue());
+ SetBackgroundKappa(bg_mat->GetKappa());
+ SetBackgroundSigma(bg_mat->GetSigma());
+ SetBackgroundDensity(0);
+
+ CSRectGrid* grid=CSX->GetGrid();
+ return SetupCSXGrid(CSRectGrid::Clone(grid));
+}
+
+void Operator::InitOperator()
+{
+ Delete_N_3DArray(vv,numLines);
+ Delete_N_3DArray(vi,numLines);
+ Delete_N_3DArray(iv,numLines);
+ Delete_N_3DArray(ii,numLines);
+ vv = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ vi = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ iv = Create_N_3DArray<FDTD_FLOAT>(numLines);
+ ii = Create_N_3DArray<FDTD_FLOAT>(numLines);
+}
+
+void Operator::InitDataStorage()
+{
+ if (m_StoreMaterial[0])
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::InitDataStorage(): Storing epsR material data..." << endl;
+ Delete_N_3DArray(m_epsR,numLines);
+ m_epsR = Create_N_3DArray<float>(numLines);
+ }
+ if (m_StoreMaterial[1])
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::InitDataStorage(): Storing kappa material data..." << endl;
+ Delete_N_3DArray(m_kappa,numLines);
+ m_kappa = Create_N_3DArray<float>(numLines);
+ }
+ if (m_StoreMaterial[2])
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::InitDataStorage(): Storing muR material data..." << endl;
+ Delete_N_3DArray(m_mueR,numLines);
+ m_mueR = Create_N_3DArray<float>(numLines);
+ }
+ if (m_StoreMaterial[3])
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::InitDataStorage(): Storing sigma material data..." << endl;
+ Delete_N_3DArray(m_sigma,numLines);
+ m_sigma = Create_N_3DArray<float>(numLines);
+ }
+}
+
+void Operator::CleanupMaterialStorage()
+{
+ if (!m_StoreMaterial[0] && m_epsR)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::CleanupMaterialStorage(): Delete epsR material data..." << endl;
+ Delete_N_3DArray(m_epsR,numLines);
+ m_epsR = NULL;
+ }
+ if (!m_StoreMaterial[1] && m_kappa)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::CleanupMaterialStorage(): Delete kappa material data..." << endl;
+ Delete_N_3DArray(m_kappa,numLines);
+ m_kappa = NULL;
+ }
+ if (!m_StoreMaterial[2] && m_mueR)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::CleanupMaterialStorage(): Delete mueR material data..." << endl;
+ Delete_N_3DArray(m_mueR,numLines);
+ m_mueR = NULL;
+ }
+ if (!m_StoreMaterial[3] && m_sigma)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cerr << "Operator::CleanupMaterialStorage(): Delete sigma material data..." << endl;
+ Delete_N_3DArray(m_sigma,numLines);
+ m_sigma = NULL;
+ }
+}
+
+double Operator::GetDiscMaterial(int type, int n, const unsigned int pos[3]) const
+{
+ switch (type)
+ {
+ case 0:
+ if (m_epsR==0)
+ return 0;
+ return m_epsR[n][pos[0]][pos[1]][pos[2]];
+ case 1:
+ if (m_kappa==0)
+ return 0;
+ return m_kappa[n][pos[0]][pos[1]][pos[2]];
+ case 2:
+ if (m_mueR==0)
+ return 0;
+ return m_mueR[n][pos[0]][pos[1]][pos[2]];
+ case 3:
+ if (m_sigma==0)
+ return 0;
+ return m_sigma[n][pos[0]][pos[1]][pos[2]];
+ }
+ return 0;
+}
+
+void Operator::SetExcitationSignal(Excitation* exc)
+{
+ m_Exc=exc;
+}
+
+void Operator::Calc_ECOperatorPos(int n, unsigned int* pos)
+{
+ unsigned int i = MainOp->SetPos(pos[0],pos[1],pos[2]);
+ double C = EC_C[n][i];
+ double G = EC_G[n][i];
+ if (C>0)
+ {
+ SetVV(n,pos[0],pos[1],pos[2], (1.0-dT*G/2.0/C)/(1.0+dT*G/2.0/C) );
+ SetVI(n,pos[0],pos[1],pos[2], (dT/C)/(1.0+dT*G/2.0/C) );
+ }
+ else
+ {
+ SetVV(n,pos[0],pos[1],pos[2], 0 );
+ SetVI(n,pos[0],pos[1],pos[2], 0 );
+ }
+
+ double L = EC_L[n][i];
+ double R = EC_R[n][i];
+ if (L>0)
+ {
+ SetII(n,pos[0],pos[1],pos[2], (1.0-dT*R/2.0/L)/(1.0+dT*R/2.0/L) );
+ SetIV(n,pos[0],pos[1],pos[2], (dT/L)/(1.0+dT*R/2.0/L) );
+ }
+ else
+ {
+ SetII(n,pos[0],pos[1],pos[2], 0 );
+ SetIV(n,pos[0],pos[1],pos[2], 0 );
+ }
+}
+
+int Operator::CalcECOperator( DebugFlags debugFlags )
+{
+ Init_EC();
+ InitDataStorage();
+
+ if (Calc_EC()==0)
+ return -1;
+
+ m_InvaildTimestep = false;
+ opt_dT = 0;
+ if (dT>0)
+ {
+ double save_dT = dT;
+ CalcTimestep();
+ opt_dT = dT;
+ if (dT<save_dT)
+ {
+ cerr << "Operator::CalcECOperator: Warning, forced timestep: " << save_dT << "s is larger than calculated timestep: " << dT << "s! It is not recommended using this timestep!! " << endl;
+ m_InvaildTimestep = true;
+ }
+
+ dT = save_dT;
+ }
+ else
+ CalcTimestep();
+
+ dT*=m_TimeStepFactor;
+
+ if (m_Exc->GetSignalPeriod()>0)
+ {
+ unsigned int TS = ceil(m_Exc->GetSignalPeriod()/dT);
+ double new_dT = m_Exc->GetSignalPeriod()/TS;
+ cout << "Operartor::CalcECOperator: Decreasing timestep by " << round((dT-new_dT)/dT*1000)/10.0 << "% to " << new_dT << " (" << dT << ") to match periodic signal" << endl;
+ dT = new_dT;
+ }
+
+ m_Exc->Reset(dT);
+
+ InitOperator();
+
+ unsigned int pos[3];
+
+ for (int n=0; n<3; ++n)
+ {
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ Calc_ECOperatorPos(n,pos);
+ }
+ }
+ }
+ }
+
+ //Apply PEC to all boundary's
+ bool PEC[6]={1,1,1,1,1,1};
+ //make an exception for BC == -1
+ for (int n=0; n<6; ++n)
+ if ((m_BC[n]==-1))
+ PEC[n] = false;
+ ApplyElectricBC(PEC);
+
+ CalcPEC();
+
+ Calc_LumpedElements();
+
+ bool PMC[6];
+ for (int n=0; n<6; ++n)
+ PMC[n] = m_BC[n]==1;
+ ApplyMagneticBC(PMC);
+
+ //all information available for extension... create now...
+ for (size_t n=0; n<m_Op_exts.size(); ++n)
+ m_Op_exts.at(n)->BuildExtension();
+
+ //remove inactive extensions
+ vector<Operator_Extension*>::iterator it = m_Op_exts.begin();
+ while (it!=m_Op_exts.end())
+ {
+ if ( (*it)->IsActive() == false)
+ {
+ DeleteExtension((*it));
+ it = m_Op_exts.begin(); //restart search for inactive extension
+ }
+ else
+ ++it;
+ }
+
+ if (debugFlags & debugMaterial)
+ DumpMaterial2File( "material_dump" );
+ if (debugFlags & debugOperator)
+ DumpOperator2File( "operator_dump" );
+ if (debugFlags & debugPEC)
+ DumpPEC2File( "PEC_dump" );
+
+ //cleanup
+ for (int n=0; n<3; ++n)
+ {
+ delete[] EC_C[n];
+ EC_C[n]=NULL;
+ delete[] EC_G[n];
+ EC_G[n]=NULL;
+ delete[] EC_L[n];
+ EC_L[n]=NULL;
+ delete[] EC_R[n];
+ EC_R[n]=NULL;
+ }
+
+ return 0;
+}
+
+void Operator::ApplyElectricBC(bool* dirs)
+{
+ if (!dirs)
+ return;
+
+ unsigned int pos[3];
+ for (int n=0; n<3; ++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ for (pos[nP]=0; pos[nP]<numLines[nP]; ++pos[nP])
+ {
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ if (dirs[2*n])
+ {
+ // set to PEC
+ pos[n] = 0;
+ SetVV(nP, pos[0],pos[1],pos[2], 0 );
+ SetVI(nP, pos[0],pos[1],pos[2], 0 );
+ SetVV(nPP,pos[0],pos[1],pos[2], 0 );
+ SetVI(nPP,pos[0],pos[1],pos[2], 0 );
+ }
+
+ if (dirs[2*n+1])
+ {
+ // set to PEC
+ pos[n] = numLines[n]-1;
+ SetVV(n, pos[0],pos[1],pos[2], 0 ); // these are outside the FDTD-domain as defined by the main disc
+ SetVI(n, pos[0],pos[1],pos[2], 0 ); // these are outside the FDTD-domain as defined by the main disc
+
+ SetVV(nP, pos[0],pos[1],pos[2], 0 );
+ SetVI(nP, pos[0],pos[1],pos[2], 0 );
+ SetVV(nPP,pos[0],pos[1],pos[2], 0 );
+ SetVI(nPP,pos[0],pos[1],pos[2], 0 );
+ }
+ }
+ }
+ }
+}
+
+void Operator::ApplyMagneticBC(bool* dirs)
+{
+ if (!dirs)
+ return;
+
+ unsigned int pos[3];
+ for (int n=0; n<3; ++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ for (pos[nP]=0; pos[nP]<numLines[nP]; ++pos[nP])
+ {
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ if (dirs[2*n])
+ {
+ // set to PMC
+ pos[n] = 0;
+ SetII(n, pos[0],pos[1],pos[2], 0 );
+ SetIV(n, pos[0],pos[1],pos[2], 0 );
+ SetII(nP, pos[0],pos[1],pos[2], 0 );
+ SetIV(nP, pos[0],pos[1],pos[2], 0 );
+ SetII(nPP,pos[0],pos[1],pos[2], 0 );
+ SetIV(nPP,pos[0],pos[1],pos[2], 0 );
+ }
+
+ if (dirs[2*n+1])
+ {
+ // set to PMC
+ pos[n] = numLines[n]-2;
+ SetII(nP, pos[0],pos[1],pos[2], 0 );
+ SetIV(nP, pos[0],pos[1],pos[2], 0 );
+ SetII(nPP,pos[0],pos[1],pos[2], 0 );
+ SetIV(nPP,pos[0],pos[1],pos[2], 0 );
+ }
+
+ // the last current lines are outside the FDTD domain and cannot be iterated by the FDTD engine
+ pos[n] = numLines[n]-1;
+ SetII(n, pos[0],pos[1],pos[2], 0 );
+ SetIV(n, pos[0],pos[1],pos[2], 0 );
+ SetII(nP, pos[0],pos[1],pos[2], 0 );
+ SetIV(nP, pos[0],pos[1],pos[2], 0 );
+ SetII(nPP,pos[0],pos[1],pos[2], 0 );
+ SetIV(nPP,pos[0],pos[1],pos[2], 0 );
+ }
+ }
+ }
+}
+
+bool Operator::Calc_ECPos(int ny, const unsigned int* pos, double* EC, vector<CSPrimitives*> vPrims) const
+{
+ double EffMat[4];
+ Calc_EffMatPos(ny,pos,EffMat, vPrims);
+
+ if (m_epsR)
+ m_epsR[ny][pos[0]][pos[1]][pos[2]] = EffMat[0];
+ if (m_kappa)
+ m_kappa[ny][pos[0]][pos[1]][pos[2]] = EffMat[1];
+ if (m_mueR)
+ m_mueR[ny][pos[0]][pos[1]][pos[2]] = EffMat[2];
+ if (m_sigma)
+ m_sigma[ny][pos[0]][pos[1]][pos[2]] = EffMat[3];
+
+ double delta = GetEdgeLength(ny,pos);
+ double area = GetEdgeArea(ny,pos);
+
+// if (isnan(EffMat[0]))
+// {
+// cerr << ny << " " << pos[0] << " " << pos[1] << " " << pos[2] << " : " << EffMat[0] << endl;
+// }
+
+ if (delta)
+ {
+ EC[0] = EffMat[0] * area/delta;
+ EC[1] = EffMat[1] * area/delta;
+ }
+ else
+ {
+ EC[0] = 0;
+ EC[1] = 0;
+ }
+
+ delta = GetEdgeLength(ny,pos,true);
+ area = GetEdgeArea(ny,pos,true);
+
+ if (delta)
+ {
+ EC[2] = EffMat[2] * area/delta;
+ EC[3] = EffMat[3] * area/delta;
+ }
+ else
+ {
+ EC[2] = 0;
+ EC[3] = 0;
+ }
+
+ return true;
+}
+
+double Operator::GetRawDiscDelta(int ny, const int pos) const
+{
+ //numLines[ny] is expected to be larger then 1 !
+
+ if (pos<0)
+ return (discLines[ny][0] - discLines[ny][1]);
+ if (pos>=(int)numLines[ny]-1)
+ return (discLines[ny][numLines[ny]-2] - discLines[ny][numLines[ny]-1]);
+
+ return (discLines[ny][pos+1] - discLines[ny][pos]);
+}
+
+bool Operator::GetCellCenterMaterialAvgCoord(const int pos[], double coord[3]) const
+{
+ unsigned int ui_pos[3];
+ for (int n=0;n<3;++n)
+ {
+ if ((pos[n]<0) || (pos[n]>=(int)numLines[n]))
+ return false;
+ ui_pos[n] = pos[n];
+ }
+ GetNodeCoords(ui_pos, coord, true);
+ return true;
+}
+
+double Operator::GetMaterial(int ny, const double* coords, int MatType, vector<CSPrimitives*> vPrims, bool markAsUsed) const
+{
+ CSProperties* prop = CSX->GetPropertyByCoordPriority(coords,vPrims,markAsUsed);
+// CSProperties* old_prop = CSX->GetPropertyByCoordPriority(coords,CSProperties::MATERIAL,markAsUsed);
+// if (old_prop!=prop)
+// {
+// cerr << "ERROR: Unequal properties!" << endl;
+// exit(-1);
+// }
+
+ CSPropMaterial* mat = dynamic_cast<CSPropMaterial*>(prop);
+ if (mat)
+ {
+ switch (MatType)
+ {
+ case 0:
+ return mat->GetEpsilonWeighted(ny,coords);
+ case 1:
+ return mat->GetKappaWeighted(ny,coords);
+ case 2:
+ return mat->GetMueWeighted(ny,coords);
+ case 3:
+ return mat->GetSigmaWeighted(ny,coords);
+ case 4:
+ return mat->GetDensityWeighted(coords);
+ default:
+ cerr << "Operator::GetMaterial: Error: unknown material type" << endl;
+ return 0;
+ }
+ }
+
+ switch (MatType)
+ {
+ case 0:
+ return GetBackgroundEpsR();
+ case 1:
+ return GetBackgroundKappa();
+ case 2:
+ return GetBackgroundMueR();
+ case 3:
+ return GetBackgroundSigma();
+ case 4:
+ return GetBackgroundDensity();
+ default:
+ cerr << "Operator::GetMaterial: Error: unknown material type" << endl;
+ return 0;
+ }
+}
+
+bool Operator::AverageMatCellCenter(int ny, const unsigned int* pos, double* EffMat, vector<CSPrimitives *> vPrims) const
+{
+ int n=ny;
+ double coord[3];
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+
+ int loc_pos[3] = {(int)pos[0],(int)pos[1],(int)pos[2]};
+ double A_n;
+ double area = 0;
+ EffMat[0] = 0;
+ EffMat[1] = 0;
+ EffMat[2] = 0;
+ EffMat[3] = 0;
+
+ //******************************* epsilon,kappa averaging *****************************//
+ //shift up-right
+ if (GetCellCenterMaterialAvgCoord(loc_pos,coord))
+ {
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, coord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, coord, 1, vPrims)*A_n;
+ area+=A_n;
+ }
+
+ //shift up-left
+ --loc_pos[nP];
+ if (GetCellCenterMaterialAvgCoord(loc_pos,coord))
+ {
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, coord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, coord, 1, vPrims)*A_n;
+ area+=A_n;
+ }
+
+ //shift down-right
+ ++loc_pos[nP];
+ --loc_pos[nPP];
+ if (GetCellCenterMaterialAvgCoord(loc_pos,coord))
+ {
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, coord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, coord, 1, vPrims)*A_n;
+ area+=A_n;
+ }
+
+ //shift down-left
+ --loc_pos[nP];
+ if (GetCellCenterMaterialAvgCoord(loc_pos,coord))
+ {
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, coord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, coord, 1, vPrims)*A_n;
+ area+=A_n;
+ }
+
+ EffMat[0]*=__EPS0__/area;
+ EffMat[1]/=area;
+
+ //******************************* mu,sigma averaging *****************************//
+ loc_pos[0]=pos[0];
+ loc_pos[1]=pos[1];
+ loc_pos[2]=pos[2];
+ double length=0;
+ double delta_ny,sigma;
+ //shift down
+ --loc_pos[n];
+ if (GetCellCenterMaterialAvgCoord(loc_pos,coord))
+ {
+ delta_ny = GetNodeWidth(n,loc_pos,true);
+ EffMat[2] += delta_ny / GetMaterial(n, coord, 2, vPrims);
+ sigma = GetMaterial(n, coord, 3, vPrims);
+ if (sigma)
+ EffMat[3] += delta_ny / sigma;
+ else
+ EffMat[3] = 0;
+ length+=delta_ny;
+ }
+
+ //shift up
+ ++loc_pos[n];
+ if (GetCellCenterMaterialAvgCoord(loc_pos,coord))
+ {
+ delta_ny = GetNodeWidth(n,loc_pos,true);
+ EffMat[2] += delta_ny / GetMaterial(n, coord, 2, vPrims);
+ sigma = GetMaterial(n, coord, 3, vPrims);
+ if (sigma)
+ EffMat[3] += delta_ny / sigma;
+ else
+ EffMat[3] = 0;
+ length+=delta_ny;
+ }
+
+ EffMat[2] = length * __MUE0__ / EffMat[2];
+ if (EffMat[3]) EffMat[3]=length / EffMat[3];
+
+ for (int n=0; n<4; ++n)
+ if (isnan(EffMat[n]) || isinf(EffMat[n]))
+ {
+ cerr << "Operator::" << __func__ << ": Error, an effective material parameter is not a valid result, this should NOT have happend... exit..." << endl;
+ cerr << ny << "@" << n << " : " << pos[0] << "," << pos[1] << "," << pos[2] << endl;
+ exit(0);
+ }
+ return true;
+}
+
+bool Operator::AverageMatQuarterCell(int ny, const unsigned int* pos, double* EffMat, vector<CSPrimitives*> vPrims) const
+{
+ int n=ny;
+ double coord[3];
+ double shiftCoord[3];
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ coord[0] = discLines[0][pos[0]];
+ coord[1] = discLines[1][pos[1]];
+ coord[2] = discLines[2][pos[2]];
+ double delta=GetRawDiscDelta(n,pos[n]);
+ double deltaP=GetRawDiscDelta(nP,pos[nP]);
+ double deltaPP=GetRawDiscDelta(nPP,pos[nPP]);
+ double delta_M=GetRawDiscDelta(n,pos[n]-1);
+ double deltaP_M=GetRawDiscDelta(nP,pos[nP]-1);
+ double deltaPP_M=GetRawDiscDelta(nPP,pos[nPP]-1);
+
+ int loc_pos[3] = {(int)pos[0],(int)pos[1],(int)pos[2]};
+ double A_n;
+ double area = 0;
+
+ //******************************* epsilon,kappa averaging *****************************//
+ //shift up-right
+ shiftCoord[n] = coord[n]+delta*0.5;
+ shiftCoord[nP] = coord[nP]+deltaP*0.25;
+ shiftCoord[nPP] = coord[nPP]+deltaPP*0.25;
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] = GetMaterial(n, shiftCoord, 0, vPrims)*A_n;
+ EffMat[1] = GetMaterial(n, shiftCoord, 1, vPrims)*A_n;
+ area+=A_n;
+
+ //shift up-left
+ shiftCoord[n] = coord[n]+delta*0.5;
+ shiftCoord[nP] = coord[nP]-deltaP_M*0.25;
+ shiftCoord[nPP] = coord[nPP]+deltaPP*0.25;
+
+ --loc_pos[nP];
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, shiftCoord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, shiftCoord, 1, vPrims)*A_n;
+ area+=A_n;
+
+ //shift down-right
+ shiftCoord[n] = coord[n]+delta*0.5;
+ shiftCoord[nP] = coord[nP]+deltaP*0.25;
+ shiftCoord[nPP] = coord[nPP]-deltaPP_M*0.25;
+ ++loc_pos[nP];
+ --loc_pos[nPP];
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, shiftCoord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, shiftCoord, 1, vPrims)*A_n;
+ area+=A_n;
+
+ //shift down-left
+ shiftCoord[n] = coord[n]+delta*0.5;
+ shiftCoord[nP] = coord[nP]-deltaP_M*0.25;
+ shiftCoord[nPP] = coord[nPP]-deltaPP_M*0.25;
+ --loc_pos[nP];
+ A_n = GetNodeArea(ny,loc_pos,true);
+ EffMat[0] += GetMaterial(n, shiftCoord, 0, vPrims)*A_n;
+ EffMat[1] += GetMaterial(n, shiftCoord, 1, vPrims)*A_n;
+ area+=A_n;
+
+ EffMat[0]*=__EPS0__/area;
+ EffMat[1]/=area;
+
+ //******************************* mu,sigma averaging *****************************//
+ loc_pos[0]=pos[0];
+ loc_pos[1]=pos[1];
+ loc_pos[2]=pos[2];
+ double length=0;
+
+ //shift down
+ shiftCoord[n] = coord[n]-delta_M*0.25;
+ shiftCoord[nP] = coord[nP]+deltaP*0.5;
+ shiftCoord[nPP] = coord[nPP]+deltaPP*0.5;
+ --loc_pos[n];
+ double delta_ny = GetNodeWidth(n,loc_pos,true);
+ EffMat[2] = delta_ny / GetMaterial(n, shiftCoord, 2, vPrims);
+ double sigma = GetMaterial(n, shiftCoord, 3, vPrims);
+ if (sigma)
+ EffMat[3] = delta_ny / sigma;
+ else
+ EffMat[3] = 0;
+ length=delta_ny;
+
+ //shift up
+ shiftCoord[n] = coord[n]+delta*0.25;
+ shiftCoord[nP] = coord[nP]+deltaP*0.5;
+ shiftCoord[nPP] = coord[nPP]+deltaPP*0.5;
+ ++loc_pos[n];
+ delta_ny = GetNodeWidth(n,loc_pos,true);
+ EffMat[2] += delta_ny / GetMaterial(n, shiftCoord, 2, vPrims);
+ sigma = GetMaterial(n, shiftCoord, 3, vPrims);
+ if (sigma)
+ EffMat[3] += delta_ny / sigma;
+ else
+ EffMat[3] = 0;
+ length+=delta_ny;
+
+ EffMat[2] = length * __MUE0__ / EffMat[2];
+ if (EffMat[3]) EffMat[3]=length / EffMat[3];
+
+ for (int n=0; n<4; ++n)
+ if (isnan(EffMat[n]) || isinf(EffMat[n]))
+ {
+ cerr << "Operator::" << __func__ << ": Error, An effective material parameter is not a valid result, this should NOT have happend... exit..." << endl;
+ cerr << ny << "@" << n << " : " << pos[0] << "," << pos[1] << "," << pos[2] << endl;
+ exit(0);
+ }
+
+ return true;
+}
+
+bool Operator::Calc_EffMatPos(int ny, const unsigned int* pos, double* EffMat, vector<CSPrimitives *> vPrims) const
+{
+ switch (m_MatAverageMethod)
+ {
+ case QuarterCell:
+ return AverageMatQuarterCell(ny, pos, EffMat, vPrims);
+ case CentralCell:
+ return AverageMatCellCenter(ny, pos, EffMat, vPrims);
+ default:
+ cerr << "Operator:: " << __func__ << ": Error, unknown material averaging method... exit" << endl;
+ exit(1);
+ }
+ return false;
+}
+
+bool Operator::Calc_LumpedElements()
+{
+ vector<CSProperties*> props = CSX->GetPropertyByType(CSProperties::LUMPED_ELEMENT);
+ for (size_t i=0;i<props.size();++i)
+ {
+ CSPropLumpedElement* PLE = dynamic_cast<CSPropLumpedElement*>(props.at(i));
+ if (PLE==NULL)
+ return false; //sanity check: this should never happen!
+ vector<CSPrimitives*> prims = PLE->GetAllPrimitives();
+ for (size_t bn=0;bn<prims.size();++bn)
+ {
+ CSPrimBox* box = dynamic_cast<CSPrimBox*>(prims.at(bn));
+ if (box)
+ { //calculate lumped element parameter
+
+ double C = PLE->GetCapacity();
+ if (C<=0)
+ C = NAN;
+ double R = PLE->GetResistance();
+ if (R<0)
+ R = NAN;
+
+ if ((isnan(R)) && (isnan(C)))
+ {
+ cerr << "Operator::Calc_LumpedElements(): Warning: Lumped Element R or C not specified! skipping. "
+ << " ID: " << prims.at(bn)->GetID() << " @ Property: " << PLE->GetName() << endl;
+ continue;
+ }
+
+ int ny = PLE->GetDirection();
+ if ((ny<0) || (ny>2))
+ {
+ cerr << "Operator::Calc_LumpedElements(): Warning: Lumped Element direction is invalid! skipping. "
+ << " ID: " << prims.at(bn)->GetID() << " @ Property: " << PLE->GetName() << endl;
+ continue;
+ }
+ int nyP = (ny+1)%3;
+ int nyPP = (ny+2)%3;
+
+ unsigned int uiStart[3];
+ unsigned int uiStop[3];
+ // snap to the native coordinate system
+ int Snap_Dimension = Operator::SnapBox2Mesh(box->GetStartCoord()->GetCoords(m_MeshType), box->GetStopCoord()->GetCoords(m_MeshType), uiStart, uiStop, false, true);
+ if (Snap_Dimension<=0)
+ {
+ if (Snap_Dimension>=-1)
+ cerr << "Operator::Calc_LumpedElements(): Warning: Lumped Element snapping failed! Dimension is: " << Snap_Dimension << " skipping. "
+ << " ID: " << prims.at(bn)->GetID() << " @ Property: " << PLE->GetName() << endl;
+ // Snap_Dimension == -2 means outside the simulation domain --> no special warning, but box probably marked as unused!
+ continue;
+ }
+
+ if (uiStart[ny]==uiStop[ny])
+ {
+ cerr << "Operator::Calc_LumpedElements(): Warning: Lumped Element with zero (snapped) length is invalid! skipping. "
+ << " ID: " << prims.at(bn)->GetID() << " @ Property: " << PLE->GetName() << endl;
+ continue;
+ }
+
+ //calculate geometric property for this lumped element
+ unsigned int pos[3];
+ double unitGC=0;
+ int ipos=0;
+ for (pos[ny]=uiStart[ny];pos[ny]<uiStop[ny];++pos[ny])
+ {
+ double unitGC_Plane=0;
+ for (pos[nyP]=uiStart[nyP];pos[nyP]<=uiStop[nyP];++pos[nyP])
+ {
+ for (pos[nyPP]=uiStart[nyPP];pos[nyPP]<=uiStop[nyPP];++pos[nyPP])
+ {
+ // capacity/conductivity in parallel: add values
+ unitGC_Plane += GetEdgeArea(ny,pos)/GetEdgeLength(ny,pos);
+ }
+ }
+
+ //capacity/conductivity in series: add reciprocal values
+ unitGC += 1/unitGC_Plane;
+ }
+ unitGC = 1/unitGC;
+
+ bool caps = PLE->GetCaps();
+ double kappa = 0;
+ double epsilon = 0;
+ if (R>0)
+ kappa = 1 / R / unitGC;
+ if (C>0)
+ {
+ epsilon = C / unitGC;
+
+ if (epsilon< __EPS0__)
+ {
+ cerr << "Operator::Calc_LumpedElements(): Warning: Lumped Element capacity is too small for its size! skipping. "
+ << " ID: " << prims.at(bn)->GetID() << " @ Property: " << PLE->GetName() << endl;
+ C = 0;
+ }
+ }
+
+ for (pos[ny]=uiStart[ny];pos[ny]<uiStop[ny];++pos[ny])
+ {
+ for (pos[nyP]=uiStart[nyP];pos[nyP]<=uiStop[nyP];++pos[nyP])
+ {
+ for (pos[nyPP]=uiStart[nyPP];pos[nyPP]<=uiStop[nyPP];++pos[nyPP])
+ {
+ ipos = MainOp->SetPos(pos[0],pos[1],pos[2]);
+ if (C>0)
+ EC_C[ny][ipos] = epsilon * GetEdgeArea(ny,pos)/GetEdgeLength(ny,pos);
+ if (R>0)
+ EC_G[ny][ipos] = kappa * GetEdgeArea(ny,pos)/GetEdgeLength(ny,pos);
+
+ if (R==0) //make lumped element a PEC if resistance is zero
+ {
+ SetVV(ny,pos[0],pos[1],pos[2], 0 );
+ SetVI(ny,pos[0],pos[1],pos[2], 0 );
+ }
+ else //recalculate operator inside the lumped element
+ Calc_ECOperatorPos(ny,pos);
+ }
+ }
+ }
+
+ // setup metal caps
+ if (caps)
+ {
+ for (pos[nyP]=uiStart[nyP];pos[nyP]<=uiStop[nyP];++pos[nyP])
+ {
+ for (pos[nyPP]=uiStart[nyPP];pos[nyPP]<=uiStop[nyPP];++pos[nyPP])
+ {
+ pos[ny]=uiStart[ny];
+ if (pos[nyP]<uiStop[nyP])
+ {
+ SetVV(nyP,pos[0],pos[1],pos[2], 0 );
+ SetVI(nyP,pos[0],pos[1],pos[2], 0 );
+ ++m_Nr_PEC[nyP];
+ }
+
+ if (pos[nyPP]<uiStop[nyPP])
+ {
+ SetVV(nyPP,pos[0],pos[1],pos[2], 0 );
+ SetVI(nyPP,pos[0],pos[1],pos[2], 0 );
+ ++m_Nr_PEC[nyPP];
+ }
+
+ pos[ny]=uiStop[ny];
+ if (pos[nyP]<uiStop[nyP])
+ {
+ SetVV(nyP,pos[0],pos[1],pos[2], 0 );
+ SetVI(nyP,pos[0],pos[1],pos[2], 0 );
+ ++m_Nr_PEC[nyP];
+ }
+
+ if (pos[nyPP]<uiStop[nyPP])
+ {
+ SetVV(nyPP,pos[0],pos[1],pos[2], 0 );
+ SetVI(nyPP,pos[0],pos[1],pos[2], 0 );
+ ++m_Nr_PEC[nyPP];
+ }
+ }
+ }
+ }
+ box->SetPrimitiveUsed(true);
+
+ }
+ else
+ cerr << "Operator::Calc_LumpedElements(): Warning: Primitves other than boxes are not supported for lumped elements! skipping "
+ << prims.at(bn)->GetTypeName() << " ID: " << prims.at(bn)->GetID() << " @ Property: " << PLE->GetName() << endl;
+ }
+ }
+ return true;
+}
+
+void Operator::Init_EC()
+{
+ for (int n=0; n<3; ++n)
+ {
+ //init x-cell-array
+ delete[] EC_C[n];
+ delete[] EC_G[n];
+ delete[] EC_L[n];
+ delete[] EC_R[n];
+ EC_C[n] = new FDTD_FLOAT[MainOp->GetSize()];
+ EC_G[n] = new FDTD_FLOAT[MainOp->GetSize()];
+ EC_L[n] = new FDTD_FLOAT[MainOp->GetSize()];
+ EC_R[n] = new FDTD_FLOAT[MainOp->GetSize()];
+ for (unsigned int i=0; i<MainOp->GetSize(); i++) //init all
+ {
+ EC_C[n][i]=0;
+ EC_G[n][i]=0;
+ EC_L[n][i]=0;
+ EC_R[n][i]=0;
+ }
+ }
+}
+
+bool Operator::Calc_EC()
+{
+ if (CSX==NULL)
+ {
+ cerr << "CartOperator::Calc_EC: CSX not given or invalid!!!" << endl;
+ return false;
+ }
+
+ MainOp->SetPos(0,0,0);
+ Calc_EC_Range(0,numLines[0]-1);
+ return true;
+}
+
+vector<CSPrimitives*> Operator::GetPrimitivesBoundBox(int posX, int posY, int posZ, CSProperties::PropertyType type) const
+{
+ double boundBox[6];
+ int BBpos[3] = {posX, posY, posZ};
+ for (int n=0;n<3;++n)
+ {
+ if (BBpos[n]<0)
+ {
+ boundBox[2*n] = this->GetDiscLine(n,0);
+ boundBox[2*n+1] = this->GetDiscLine(n,numLines[n]-1);
+ }
+ else
+ {
+ boundBox[2*n] = this->GetDiscLine(n, max(0, BBpos[n]-1));
+ boundBox[2*n+1] = this->GetDiscLine(n, min(int(numLines[n])-1, BBpos[n]+1));
+ }
+ }
+
+ vector<CSPrimitives*> vPrim = this->CSX->GetPrimitivesByBoundBox(boundBox, true, type);
+ return vPrim;
+}
+
+void Operator::Calc_EC_Range(unsigned int xStart, unsigned int xStop)
+{
+// vector<CSPrimitives*> vPrims = this->CSX->GetAllPrimitives(true, CSProperties::MATERIAL);
+ unsigned int ipos;
+ unsigned int pos[3];
+ double inEC[4];
+ for (pos[0]=xStart; pos[0]<=xStop; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ vector<CSPrimitives*> vPrims = this->GetPrimitivesBoundBox(pos[0], pos[1], -1, CSProperties::MATERIAL);
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ ipos = MainOp->GetPos(pos[0],pos[1],pos[2]);
+ for (int n=0; n<3; ++n)
+ {
+ Calc_ECPos(n,pos,inEC,vPrims);
+ EC_C[n][ipos]=inEC[0];
+ EC_G[n][ipos]=inEC[1];
+ EC_L[n][ipos]=inEC[2];
+ EC_R[n][ipos]=inEC[3];
+ }
+ }
+ }
+ }
+}
+
+void Operator::SetTimestepFactor(double factor)
+{
+ if ((factor<=0) || (factor>1))
+ {
+ cerr << "Operator::SetTimestepFactor: Warning, invalid timestep factor, skipping!" << endl;
+ return;
+ }
+
+ cout << "Operator::SetTimestepFactor: Setting timestep factor to " << factor << endl;
+ m_TimeStepFactor=factor;
+}
+
+double Operator::CalcTimestep()
+{
+ if (m_TimeStepVar==3)
+ return CalcTimestep_Var3(); //the biggest one for cartesian meshes
+
+ //variant 1 is default
+ return CalcTimestep_Var1();
+}
+
+////Berechnung nach Andreas Rennings Dissertation 2008, Seite 66, Formel 4.52
+double Operator::CalcTimestep_Var1()
+{
+ m_Used_TS_Name = string("Rennings_1");
+// cout << "Operator::CalcTimestep(): Using timestep algorithm by Andreas Rennings, Dissertation @ University Duisburg-Essen, 2008, pp. 66, eq. 4.52" << endl;
+ dT=1e200;
+ double newT;
+ unsigned int pos[3];
+ unsigned int smallest_pos[3] = {0, 0, 0};
+ unsigned int smallest_n = 0;
+ unsigned int ipos;
+ unsigned int ipos_PM;
+ unsigned int ipos_PPM;
+ MainOp->SetReflection2Cell();
+ for (int n=0; n<3; ++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ ipos = MainOp->SetPos(pos[0],pos[1],pos[2]);
+ ipos_PM = MainOp->Shift(nP,-1);
+ MainOp->ResetShift();
+ ipos_PPM= MainOp->Shift(nPP,-1);
+ MainOp->ResetShift();
+ newT = 2/sqrt( ( 4/EC_L[nP][ipos] + 4/EC_L[nP][ipos_PPM] + 4/EC_L[nPP][ipos] + 4/EC_L[nPP][ipos_PM]) / EC_C[n][ipos] );
+ if ((newT<dT) && (newT>0.0))
+ {
+ dT=newT;
+ smallest_pos[0]=pos[0];smallest_pos[1]=pos[1];smallest_pos[2]=pos[2];
+ smallest_n = n;
+ }
+ }
+ }
+ }
+ }
+ if (dT==0)
+ {
+ cerr << "Operator::CalcTimestep: Timestep is zero... this is not supposed to happen!!! exit!" << endl;
+ exit(3);
+ }
+ if (g_settings.GetVerboseLevel()>1)
+ {
+ cout << "Operator::CalcTimestep_Var1: Smallest timestep (" << dT << "s) found at position: " << smallest_n << " : " << smallest_pos[0] << ";" << smallest_pos[1] << ";" << smallest_pos[2] << endl;
+ }
+ return 0;
+}
+
+double min(double* val, unsigned int count)
+{
+ if (count==0)
+ return 0.0;
+ double min = val[0];
+ for (unsigned int n=1; n<count; ++n)
+ if (val[n]<min)
+ min = val[n];
+ return min;
+}
+
+//Berechnung nach Andreas Rennings Dissertation 2008, Seite 76 ff, Formel 4.77 ff
+double Operator::CalcTimestep_Var3()
+{
+ dT=1e200;
+ m_Used_TS_Name = string("Rennings_2");
+// cout << "Operator::CalcTimestep(): Using timestep algorithm by Andreas Rennings, Dissertation @ University Duisburg-Essen, 2008, pp. 76, eq. 4.77 ff." << endl;
+ double newT;
+ unsigned int pos[3];
+ unsigned int smallest_pos[3] = {0, 0, 0};
+ unsigned int smallest_n = 0;
+ unsigned int ipos;
+ double w_total=0;
+ double wqp=0,wt1=0,wt2=0;
+ double wt_4[4]={0,0,0,0};
+ MainOp->SetReflection2Cell();
+ for (int n=0; n<3; ++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ MainOp->ResetShift();
+ ipos = MainOp->SetPos(pos[0],pos[1],pos[2]);
+ wqp = 1/(EC_L[nPP][ipos]*EC_C[n][MainOp->GetShiftedPos(nP ,1)]) + 1/(EC_L[nPP][ipos]*EC_C[n][ipos]);
+ wqp += 1/(EC_L[nP ][ipos]*EC_C[n][MainOp->GetShiftedPos(nPP,1)]) + 1/(EC_L[nP ][ipos]*EC_C[n][ipos]);
+ ipos = MainOp->Shift(nP,-1);
+ wqp += 1/(EC_L[nPP][ipos]*EC_C[n][MainOp->GetShiftedPos(nP ,1)]) + 1/(EC_L[nPP][ipos]*EC_C[n][ipos]);
+ ipos = MainOp->Shift(nPP,-1);
+ wqp += 1/(EC_L[nP ][ipos]*EC_C[n][MainOp->GetShiftedPos(nPP,1)]) + 1/(EC_L[nP ][ipos]*EC_C[n][ipos]);
+
+ MainOp->ResetShift();
+ ipos = MainOp->SetPos(pos[0],pos[1],pos[2]);
+ wt_4[0] = 1/(EC_L[nPP][ipos] *EC_C[nP ][ipos]);
+ wt_4[1] = 1/(EC_L[nPP][MainOp->GetShiftedPos(nP ,-1)] *EC_C[nP ][ipos]);
+ wt_4[2] = 1/(EC_L[nP ][ipos] *EC_C[nPP][ipos]);
+ wt_4[3] = 1/(EC_L[nP ][MainOp->GetShiftedPos(nPP,-1)] *EC_C[nPP][ipos]);
+
+ wt1 = wt_4[0]+wt_4[1]+wt_4[2]+wt_4[3] - 2*min(wt_4,4);
+
+ MainOp->ResetShift();
+ ipos = MainOp->SetPos(pos[0],pos[1],pos[2]);
+ wt_4[0] = 1/(EC_L[nPP][ipos] *EC_C[nP ][MainOp->GetShiftedPos(n,1)]);
+ wt_4[1] = 1/(EC_L[nPP][MainOp->GetShiftedPos(nP ,-1)] *EC_C[nP ][MainOp->GetShiftedPos(n,1)]);
+ wt_4[2] = 1/(EC_L[nP ][ipos] *EC_C[nPP][MainOp->GetShiftedPos(n,1)]);
+ wt_4[3] = 1/(EC_L[nP ][MainOp->GetShiftedPos(nPP,-1)] *EC_C[nPP][MainOp->GetShiftedPos(n,1)]);
+
+ wt2 = wt_4[0]+wt_4[1]+wt_4[2]+wt_4[3] - 2*min(wt_4,4);
+
+ w_total = wqp + wt1 + wt2;
+ newT = 2/sqrt( w_total );
+ if ((newT<dT) && (newT>0.0))
+ {
+ dT=newT;
+ smallest_pos[0]=pos[0];smallest_pos[1]=pos[1];smallest_pos[2]=pos[2];
+ smallest_n = n;
+ }
+ }
+ }
+ }
+ }
+ if (dT==0)
+ {
+ cerr << "Operator::CalcTimestep: Timestep is zero... this is not supposed to happen!!! exit!" << endl;
+ exit(3);
+ }
+ if (g_settings.GetVerboseLevel()>1)
+ {
+ cout << "Operator::CalcTimestep_Var3: Smallest timestep (" << dT << "s) found at position: " << smallest_n << " : " << smallest_pos[0] << ";" << smallest_pos[1] << ";" << smallest_pos[2] << endl;
+ }
+ return 0;
+}
+
+bool Operator::CalcPEC()
+{
+ m_Nr_PEC[0]=0;
+ m_Nr_PEC[1]=0;
+ m_Nr_PEC[2]=0;
+
+ CalcPEC_Range(0,numLines[0]-1,m_Nr_PEC);
+
+ CalcPEC_Curves();
+
+ return true;
+}
+
+void Operator::CalcPEC_Range(unsigned int startX, unsigned int stopX, unsigned int* counter)
+{
+ double coord[3];
+ unsigned int pos[3];
+ for (pos[0]=startX; pos[0]<=stopX; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ vector<CSPrimitives*> vPrims = this->GetPrimitivesBoundBox(pos[0], pos[1], -1, (CSProperties::PropertyType)(CSProperties::MATERIAL | CSProperties::METAL));
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ for (int n=0; n<3; ++n)
+ {
+ GetYeeCoords(n,pos,coord,false);
+ CSProperties* prop = CSX->GetPropertyByCoordPriority(coord, vPrims, true);
+// CSProperties* old_prop = CSX->GetPropertyByCoordPriority(coord, (CSProperties::PropertyType)(CSProperties::MATERIAL | CSProperties::METAL), true);
+// if (old_prop!=prop)
+// {
+// cerr << "CalcPEC_Range: " << old_prop << " vs " << prop << endl;
+// exit(-1);
+// }
+ if (prop)
+ {
+ if (prop->GetType()==CSProperties::METAL) //set to PEC
+ {
+ SetVV(n,pos[0],pos[1],pos[2], 0 );
+ SetVI(n,pos[0],pos[1],pos[2], 0 );
+ ++counter[n];
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+void Operator::CalcPEC_Curves()
+{
+ //special treatment for primitives of type curve (treated as wires)
+ double p1[3];
+ double p2[3];
+ Grid_Path path;
+ vector<CSProperties*> vec_prop = CSX->GetPropertyByType(CSProperties::METAL);
+ for (size_t p=0; p<vec_prop.size(); ++p)
+ {
+ CSProperties* prop = vec_prop.at(p);
+ for (size_t n=0; n<prop->GetQtyPrimitives(); ++n)
+ {
+ CSPrimitives* prim = prop->GetPrimitive(n);
+ CSPrimCurve* curv = prim->ToCurve();
+ if (curv)
+ {
+ for (size_t i=1; i<curv->GetNumberOfPoints(); ++i)
+ {
+ curv->GetPoint(i-1,p1,m_MeshType);
+ curv->GetPoint(i,p2,m_MeshType);
+ path = FindPath(p1,p2);
+ if (path.dir.size()>0)
+ prim->SetPrimitiveUsed(true);
+ for (size_t t=0; t<path.dir.size(); ++t)
+ {
+ SetVV(path.dir.at(t),path.posPath[0].at(t),path.posPath[1].at(t),path.posPath[2].at(t), 0 );
+ SetVI(path.dir.at(t),path.posPath[0].at(t),path.posPath[1].at(t),path.posPath[2].at(t), 0 );
+ ++m_Nr_PEC[path.dir.at(t)];
+ }
+ }
+ }
+ }
+ }
+}
+
+Operator_Ext_Excitation* Operator::GetExcitationExtension() const
+{
+ //search for excitation extension
+ Operator_Ext_Excitation* Op_Ext_Exc=0;
+ for (size_t n=0; n<m_Op_exts.size(); ++n)
+ {
+ Op_Ext_Exc = dynamic_cast<Operator_Ext_Excitation*>(m_Op_exts.at(n));
+ if (Op_Ext_Exc)
+ break;
+ }
+ return Op_Ext_Exc;
+}
+
+void Operator::AddExtension(Operator_Extension* op_ext)
+{
+ m_Op_exts.push_back(op_ext);
+}
+
+void Operator::DeleteExtension(Operator_Extension* op_ext)
+{
+ for (size_t n=0;n<m_Op_exts.size();++n)
+ {
+ if (m_Op_exts.at(n)==op_ext)
+ {
+ m_Op_exts.erase(m_Op_exts.begin()+n);
+ return;
+ }
+ }
+}
+
+double Operator::CalcNumericPhaseVelocity(unsigned int start[3], unsigned int stop[3], double propDir[3], float freq) const
+{
+ double average_mesh_disc[3];
+ double c0 = __C0__/sqrt(GetBackgroundEpsR()*GetBackgroundMueR());
+
+ //calculate average mesh deltas
+ for (int n=0;n<3;++n)
+ {
+ average_mesh_disc[n] = fabs(GetDiscLine(n,start[n])-GetDiscLine(n,stop[n]))*GetGridDelta() / (fabs(stop[n]-start[n]));
+ }
+
+ // if propagation is in a Cartesian direction, return analytic solution
+ for (int n=0;n<3;++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ if ((fabs(propDir[n])==1) && (propDir[nP]==0) && (propDir[nPP]==0))
+ {
+ double kx = asin(average_mesh_disc[0]/c0/dT*sin(2*PI*freq*dT/2))*2/average_mesh_disc[0];
+ return 2*PI*freq/kx;
+ }
+ }
+
+ // else, do an newton iterative estimation
+ double k0=2*PI*freq/c0;
+ double k=k0;
+ double RHS = pow(sin(2*PI*freq*dT/2)/c0/dT,2);
+ double fk=1,fdk=0;
+ double old_phv=0;
+ double phv=c0;
+ double err_est = 1e-6;
+ int it_count=0;
+ while (fabs(old_phv-phv)>err_est)
+ {
+ ++it_count;
+ old_phv=phv;
+ fk=0;
+ fdk=0;
+ for (int n=0;n<3;++n)
+ {
+ fk+= pow(sin(propDir[n]*k*average_mesh_disc[n]/2)/average_mesh_disc[n],2);
+ fdk+= propDir[n]*sin(propDir[n]*k*average_mesh_disc[n]/2)*cos(propDir[n]*k*average_mesh_disc[n]/2)/average_mesh_disc[n];
+ }
+ fk -= RHS;
+ k-=fk/fdk;
+
+ // do not allow a speed greater than c0 due to a numerical inaccuracy
+ if (k<k0)
+ k=k0;
+
+ phv=2*PI*freq/k;
+
+ //abort if iteration count is getting to high!
+ if (it_count>99)
+ {
+ cerr << "Operator::CalcNumericPhaseVelocity: Error, newton iteration estimation can't find a solution!!" << endl;
+ break;
+ }
+ }
+
+ if (g_settings.GetVerboseLevel()>1)
+ cerr << "Operator::CalcNumericPhaseVelocity: Newton iteration estimated solution: " << phv/__C0__ << "*c0 in " << it_count << " iterations." << endl;
+
+ return phv;
+}
diff --git a/openEMS/FDTD/operator.h b/openEMS/FDTD/operator.h
new file mode 100644
index 0000000..8fc0409
--- /dev/null
+++ b/openEMS/FDTD/operator.h
@@ -0,0 +1,287 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_H
+#define OPERATOR_H
+
+#include "tools/AdrOp.h"
+#include "tools/constants.h"
+#include "excitation.h"
+#include "Common/operator_base.h"
+
+class Operator_Extension;
+class Operator_Ext_Excitation;
+class Engine;
+class TiXmlElement;
+
+//! Basic FDTD-operator
+class Operator : public Operator_Base
+{
+ friend class Engine;
+ friend class Engine_Interface_FDTD;
+ friend class Operator_Ext_LorentzMaterial; //we need to find a way around this... friend class Operator_Extension only would be nice
+ friend class Operator_Ext_ConductingSheet; //we need to find a way around this... friend class Operator_Extension only would be nice
+ friend class Operator_Ext_PML_SF_Plane;
+ friend class Operator_Ext_Excitation;
+ friend class Operator_Ext_UPML;
+ friend class Operator_Ext_Cylinder;
+public:
+ enum DebugFlags {None=0,debugMaterial=1,debugOperator=2,debugPEC=4};
+
+ enum MatAverageMethods {QuarterCell=0, CentralCell=1};
+
+ //! Create a new operator
+ static Operator* New();
+ virtual ~Operator();
+
+ virtual Engine* CreateEngine();
+ virtual Engine* GetEngine() const {return m_Engine;}
+
+ virtual bool SetGeometryCSX(ContinuousStructure* geo);
+
+ virtual int CalcECOperator( DebugFlags debugFlags = None );
+
+ // the next four functions need to be reimplemented in a derived class
+ inline virtual FDTD_FLOAT GetVV( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return vv[n][x][y][z]; }
+ inline virtual FDTD_FLOAT GetVI( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return vi[n][x][y][z]; }
+ inline virtual FDTD_FLOAT GetII( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return ii[n][x][y][z]; }
+ inline virtual FDTD_FLOAT GetIV( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return iv[n][x][y][z]; }
+
+ // convenient access functions
+ inline virtual FDTD_FLOAT GetVV( unsigned int n, unsigned int pos[3] ) const { return GetVV(n,pos[0],pos[1],pos[2]); }
+ inline virtual FDTD_FLOAT GetVI( unsigned int n, unsigned int pos[3] ) const { return GetVI(n,pos[0],pos[1],pos[2]); }
+ inline virtual FDTD_FLOAT GetII( unsigned int n, unsigned int pos[3] ) const { return GetII(n,pos[0],pos[1],pos[2]); }
+ inline virtual FDTD_FLOAT GetIV( unsigned int n, unsigned int pos[3] ) const { return GetIV(n,pos[0],pos[1],pos[2]); }
+
+ // the next four functions need to be reimplemented in a derived class
+ inline virtual void SetVV( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { vv[n][x][y][z] = value; }
+ inline virtual void SetVI( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { vi[n][x][y][z] = value; }
+ inline virtual void SetII( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { ii[n][x][y][z] = value; }
+ inline virtual void SetIV( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { iv[n][x][y][z] = value; }
+
+ virtual void ApplyElectricBC(bool* dirs); //applied by default to all boundaries
+ virtual void ApplyMagneticBC(bool* dirs);
+
+ virtual void SetBCSize(int dir, int size) {m_BC_Size[dir]=size;}
+ virtual int GetBCSize(int dir) {return m_BC_Size[dir];}
+
+ //! Set a forced timestep to use by the operator
+ virtual void SetTimestep(double ts) {dT = ts;}
+ virtual void SetTimestepFactor(double factor);
+ bool GetTimestepValid() const {return !m_InvaildTimestep;}
+
+ //! Choose a time step method (0=auto, 1=CFL, 3=Rennings)
+ void SetTimeStepMethod(int var) {m_TimeStepVar=var;}
+
+ //! Set the material averaging method /sa MatAverageMethods
+ void SetMaterialAvgMethod(MatAverageMethods method);
+
+ //! Set material averaging method to the advanced quarter cell material interpolation (default)
+ void SetQuarterCellMaterialAvg() {m_MatAverageMethod=QuarterCell;}
+
+ //! Set operator to assume a constant material inside a cell (material probing in the cell center)
+ void SetCellConstantMaterial() {m_MatAverageMethod=CentralCell;}
+
+ virtual double GetNumberCells() const;
+
+ virtual unsigned int GetNumberOfNyquistTimesteps() const {return m_Exc->GetNyquistNum();}
+
+ virtual unsigned int GetNumberOfLines(int ny, bool full=false) const {UNUSED(full);return numLines[ny];}
+
+ virtual void ShowStat() const;
+ virtual void ShowExtStat() const;
+
+ virtual double GetGridDelta() const {return gridDelta;}
+
+ //! Get the disc line in \a n direction (in drawing units)
+ virtual double GetDiscLine(int n, unsigned int pos, bool dualMesh=false) const;
+
+ //! Get the disc line delta in \a n direction (in drawing units)
+ virtual double GetDiscDelta(int n, unsigned int pos, bool dualMesh=false) const;
+
+ //! Get the coordinates for a given node index and component, according to the yee-algorithm. Returns true if inside the FDTD domain.
+ virtual bool GetYeeCoords(int ny, unsigned int pos[3], double* coords, bool dualMesh) const;
+
+ virtual bool GetNodeCoords(const unsigned int pos[3], double* coords, bool dualMesh=false, CoordinateSystem c_system=UNDEFINED_CS) const;
+
+ //! Get the node width for a given direction \a n and a given mesh position \a pos
+ virtual double GetNodeWidth(int ny, const unsigned int pos[3], bool dualMesh = false) const {return GetEdgeLength(ny,pos,!dualMesh);}
+ //! Get the node width for a given direction \a n and a given mesh position \a pos
+ virtual double GetNodeWidth(int ny, const int pos[3], bool dualMesh = false) const;
+
+ //! Get the node area for a given direction \a n and a given mesh position \a pos
+ virtual double GetNodeArea(int ny, const unsigned int pos[3], bool dualMesh = false) const;
+ //! Get the node area for a given direction \a n and a given mesh position \a pos
+ virtual double GetNodeArea(int ny, const int pos[3], bool dualMesh = false) const;
+
+ //! Get the length of an FDTD edge (unit is meter).
+ virtual double GetEdgeLength(int ny, const unsigned int pos[3], bool dualMesh = false) const;
+
+ //! Get the volume of an FDTD cell
+ virtual double GetCellVolume(const unsigned int pos[3], bool dualMesh = false) const;
+
+ //! Get the area around an edge for a given direction \a n and a given mesh posisition \a pos
+ /*!
+ This will return the area around an edge with a given direction, measured at the middle of the edge.
+ In a cartesian mesh this is equal to the NodeArea, may be different in other coordinate systems.
+ */
+ virtual double GetEdgeArea(int ny, const unsigned int pos[3], bool dualMesh = false) const {return GetNodeArea(ny,pos,dualMesh);}
+
+ virtual unsigned int SnapToMeshLine(int ny, double coord, bool &inside, bool dualMesh=false, bool fullMesh=false) const;
+
+ //! Snap the given coodinates to mesh indices
+ virtual bool SnapToMesh(const double* coord, unsigned int* uicoord, bool dualMesh=false, bool fullMesh=false, bool* inside=NULL) const;
+
+ //! Snap a given box to the FDTD mesh
+ virtual int SnapBox2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh=false, bool fullMesh=false, int SnapMethod=0, bool* bStartIn=NULL, bool* bStopIn=NULL) const;
+
+ //! Snap a given line to the operator mesh
+ /*!
+ \param[in] start coorindate of the line
+ \param[in] stop coorindate of the line
+ \param[out] uiStart the snapped line-start coorindate index
+ \param[out] uiStop the snapped line-stop coorindate index
+ \param[in] dualMesh snap to main or dual mesh (default is main mesh)
+ \return returns a status, 0 = success, 1 = start outside, 2 = stop outside, 3 = both outside
+ */
+ virtual int SnapLine2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh=false, bool fullMesh=false) const;
+
+ virtual void AddExtension(Operator_Extension* op_ext);
+ virtual void DeleteExtension(Operator_Extension* op_ext);
+ virtual size_t GetNumberOfExtentions() const {return m_Op_exts.size();}
+ virtual Operator_Extension* GetExtension(size_t index) const {return m_Op_exts.at(index);}
+
+ virtual void CleanupMaterialStorage();
+
+ virtual double GetDiscMaterial(int type, int ny, const unsigned int pos[3]) const;
+
+ //! Get the cell center coordinate usable for material averaging (Warning, may not be the yee cell center)
+ virtual bool GetCellCenterMaterialAvgCoord(const int pos[3], double coord[3]) const;
+
+ virtual void SetExcitationSignal(Excitation* exc);
+ virtual Excitation* GetExcitationSignal() const {return m_Exc;}
+
+ Operator_Ext_Excitation* GetExcitationExtension() const;
+
+ virtual double CalcNumericPhaseVelocity(unsigned int start[3], unsigned int stop[3], double propDir[3], float freq) const;
+
+ virtual vector<CSPrimitives*> GetPrimitivesBoundBox(int posX, int posY, int posZ, CSProperties::PropertyType type=CSProperties::ANY) const;
+
+protected:
+ //! use New() for creating a new Operator
+ Operator();
+
+ virtual void Init();
+ void Delete();
+ virtual void Reset();
+ virtual void InitOperator();
+ virtual void InitDataStorage();
+
+ virtual bool SetupCSXGrid(CSRectGrid* grid);
+
+ virtual Grid_Path FindPath(double start[], double stop[]);
+
+ // debug
+ virtual void DumpOperator2File(string filename);
+ virtual void DumpMaterial2File(string filename);
+ virtual void DumpPEC2File( string filename, unsigned int *range = NULL );
+
+ unsigned int m_Nr_PEC[3]; //count PEC edges
+ virtual bool CalcPEC();
+ virtual void CalcPEC_Range(unsigned int startX, unsigned int stopX, unsigned int* counter); //internal to CalcPEC
+ virtual void CalcPEC_Curves(); //internal to CalcPEC
+
+ //Calc timestep only internal use
+ int m_TimeStepVar;
+ double m_TimeStepFactor;
+ virtual double CalcTimestep();
+ double opt_dT;
+ bool m_InvaildTimestep;
+ string m_Used_TS_Name;
+
+ double CalcTimestep_Var1();
+ double CalcTimestep_Var3();
+
+ //! Calculate the FDTD equivalent circuit parameter for the given position and direction ny. \sa Calc_EffMat_Pos
+ virtual bool Calc_ECPos(int ny, const unsigned int* pos, double* EC, vector<CSPrimitives *> vPrims) const;
+
+ //! Get the FDTD raw disc delta, needed by Calc_EffMatPos() \sa Calc_EffMatPos
+ /*!
+ Get the raw disc delta for a given position and direction.
+ The result will be positive if a disc delta inside the simulation domain is requested.
+ The result will be the negative value of the first or last disc delta respectivly if the position is outside the field domain.
+ */
+ virtual double GetRawDiscDelta(int ny, const int pos) const;
+
+ //! Get the material at a given coordinate, direction and type from CSX (internal use only)
+ virtual double GetMaterial(int ny, const double coords[3], int MatType, vector<CSPrimitives*> vPrims, bool markAsUsed=true) const;
+
+ MatAverageMethods m_MatAverageMethod;
+
+ //! Calculate the effective/averaged material properties at the given position and direction ny.
+ virtual bool Calc_EffMatPos(int ny, const unsigned int* pos, double* EffMat, vector<CSPrimitives*> vPrims) const;
+
+ virtual bool AverageMatCellCenter(int ny, const unsigned int* pos, double* EffMat, vector<CSPrimitives*> vPrims) const;
+ virtual bool AverageMatQuarterCell(int ny, const unsigned int* pos, double* EffMat, vector<CSPrimitives*> vPrims) const;
+
+ //! Calc operator at certain \a pos
+ virtual void Calc_ECOperatorPos(int n, unsigned int* pos);
+
+ //! Calculate and setup lumped elements
+ virtual bool Calc_LumpedElements();
+
+ //! Store the size of the applied boundary conditions
+ int m_BC_Size[6];
+
+ //store material properties for post-processing
+ float**** m_epsR;
+ float**** m_kappa;
+ float**** m_mueR;
+ float**** m_sigma;
+
+ //EC elements, internal only!
+ virtual void Init_EC();
+ virtual bool Calc_EC();
+ virtual void Calc_EC_Range(unsigned int xStart, unsigned int xStop);
+ FDTD_FLOAT* EC_C[3];
+ FDTD_FLOAT* EC_G[3];
+ FDTD_FLOAT* EC_L[3];
+ FDTD_FLOAT* EC_R[3];
+
+ AdrOp* MainOp;
+
+ vector<Operator_Extension*> m_Op_exts;
+
+ Engine* m_Engine;
+
+ // excitation classes
+ Excitation* m_Exc; // excitation time signal class
+// Operator_Ext_Excitation* m_Op_Ext_Exc; // excitation extension
+
+ // engine/post-proc needs access
+public:
+ //EC operator
+ FDTD_FLOAT**** vv; //calc new voltage from old voltage
+ FDTD_FLOAT**** vi; //calc new voltage from old current
+ FDTD_FLOAT**** ii; //calc new current from old current
+ FDTD_FLOAT**** iv; //calc new current from old voltage
+};
+
+inline Operator::DebugFlags operator|( Operator::DebugFlags a, Operator::DebugFlags b ) { return static_cast<Operator::DebugFlags>(static_cast<int>(a) | static_cast<int>(b)); }
+inline Operator::DebugFlags& operator|=( Operator::DebugFlags& a, const Operator::DebugFlags& b ) { return a = a | b; }
+
+#endif // OPERATOR_H
diff --git a/openEMS/FDTD/operator_cylinder.cpp b/openEMS/FDTD/operator_cylinder.cpp
new file mode 100644
index 0000000..342415f
--- /dev/null
+++ b/openEMS/FDTD/operator_cylinder.cpp
@@ -0,0 +1,576 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine.h"
+#include "engine_cylinder.h"
+#include "Common/processfields.h"
+#include "operator_cylinder.h"
+#include "extensions/operator_extension.h"
+#include "extensions/operator_ext_cylinder.h"
+#include "tools/useful.h"
+
+Operator_Cylinder* Operator_Cylinder::New(unsigned int numThreads)
+{
+ cout << "Create cylindrical FDTD operator" << endl;
+ Operator_Cylinder* op = new Operator_Cylinder();
+ op->setNumThreads(numThreads);
+ op->Init();
+ return op;
+}
+
+Operator_Cylinder::Operator_Cylinder() : Operator_Multithread()
+{
+ m_MeshType = CYLINDRICAL;
+ m_Cyl_Ext = NULL;
+}
+
+Operator_Cylinder::~Operator_Cylinder()
+{
+}
+
+
+Engine* Operator_Cylinder::CreateEngine()
+{
+ //! create a special cylindrical-engine
+ m_Engine = Engine_Cylinder::New(this, m_numThreads);
+ return m_Engine;
+}
+
+void Operator_Cylinder::Init()
+{
+ CC_closedAlpha = false;
+ CC_R0_included = false;
+ Operator_Multithread::Init();
+}
+
+double Operator_Cylinder::GetRawDiscDelta(int ny, const int pos) const
+{
+ if (CC_closedAlpha && ny==1 && pos==-1)
+ return (discLines[1][numLines[1]-2] - discLines[1][numLines[1]-3]);
+ if (CC_closedAlpha && ny==1 && (pos==(int)numLines[ny]-1))
+ return (discLines[1][2] - discLines[1][1]);
+
+ return Operator_Multithread::GetRawDiscDelta(ny,pos);
+}
+
+double Operator_Cylinder::GetMaterial(int ny, const double* coords, int MatType, vector<CSPrimitives*> vPrims, bool markAsUsed) const
+{
+ double l_coords[] = {coords[0],coords[1],coords[2]};
+ if (CC_closedAlpha && (coords[1]>GetDiscLine(1,0,false)+2*PI))
+ l_coords[1]-=2*PI;
+ if (CC_closedAlpha && (coords[1]<GetDiscLine(1,0,false)))
+ l_coords[1] += 2*PI;
+ return Operator_Multithread::GetMaterial(ny,l_coords,MatType,vPrims,markAsUsed);
+}
+
+int Operator_Cylinder::CalcECOperator( DebugFlags debugFlags )
+{
+ // debugs only work with the native vector dumps
+ bool natDump = g_settings.NativeFieldDumps();
+ g_settings.SetNativeFieldDumps(true);
+ int rc = Operator_Multithread::CalcECOperator(debugFlags);
+ // reset original settings
+ g_settings.SetNativeFieldDumps(natDump);
+ return rc;
+}
+
+double Operator_Cylinder::CalcTimestep()
+{
+ if (discLines[0][0]==0.0)
+ // use conservative timestep for a mesh including the r==0 singularity
+ m_TimeStepVar = 1;
+
+ return Operator::CalcTimestep();
+}
+
+inline unsigned int Operator_Cylinder::GetNumberOfLines(int ny, bool full) const
+{
+ if (full)
+ return Operator_Multithread::GetNumberOfLines(ny, full);
+
+ //this is necessary for a correct field processing... cylindrical engine has to reset this by adding +1
+ if (CC_closedAlpha && ny==1)
+ return Operator_Multithread::GetNumberOfLines(ny, true)-2;
+
+ return Operator_Multithread::GetNumberOfLines(ny, full);
+}
+
+string Operator_Cylinder::GetDirName(int ny) const
+{
+ if (ny==0) return "rho";
+ if (ny==1) return "alpha";
+ if (ny==2) return "z";
+ return "";
+}
+
+bool Operator_Cylinder::GetYeeCoords(int ny, unsigned int pos[3], double* coords, bool dualMesh) const
+{
+ bool ret = Operator_Multithread::GetYeeCoords(ny,pos,coords,dualMesh);
+
+ if (CC_closedAlpha && (coords[1]>=GetDiscLine(1,0,false)+2*PI))
+ coords[1]-=2*PI;
+ if (CC_closedAlpha && (coords[1]<GetDiscLine(1,0,false)))
+ coords[1]+=2*PI;
+
+ return ret;
+}
+
+double Operator_Cylinder::GetNodeWidth(int ny, const unsigned int pos[3], bool dualMesh) const
+{
+ if ((ny<0) || (ny>2)) return 0.0;
+ if (pos[ny]>=numLines[ny]) return 0.0;
+ double width = Operator_Multithread::GetEdgeLength(ny,pos,!dualMesh);
+ if (ny==1)
+ width *= GetDiscLine(0,pos[0],dualMesh);
+ return width;
+}
+
+double Operator_Cylinder::GetNodeWidth(int ny, const int pos[3], bool dualMesh) const
+{
+ if ( (pos[0]<0) || (pos[1]<0 && CC_closedAlpha==false) || (pos[2]<0) )
+ return 0.0;
+
+ unsigned int uiPos[]={(unsigned int)pos[0],(unsigned int)pos[1],(unsigned int)pos[2]};
+ if (pos[1]<0 && CC_closedAlpha==true)
+ uiPos[1]+=numLines[1]-2;
+
+ return GetNodeWidth(ny, uiPos, dualMesh);
+}
+
+double Operator_Cylinder::GetNodeArea(int ny, const unsigned int pos[3], bool dualMesh) const
+{
+ if (pos[ny]>=numLines[ny]) return 0.0;
+ if (pos[0]>=numLines[0]) return 0.0;
+ if (ny==2)
+ {
+ double da = Operator_Multithread::GetEdgeLength(1,pos,dualMesh)/gridDelta;
+ double r1,r2;
+
+ if (dualMesh)
+ {
+ r1 = GetDiscLine(0,pos[0],false)*gridDelta;
+ r2 = r1 + GetEdgeLength(0,pos,false);
+ }
+ else
+ {
+ r2 = GetDiscLine(0,pos[0],!dualMesh)*gridDelta;
+ r1 = r2 - GetEdgeLength(0,pos,true);
+ }
+
+ if (r1<=0)
+ return da/2 * pow(r2,2);
+ else
+ return da/2* (pow(r2,2) - pow(r1,2));
+ }
+
+ return Operator_Multithread::GetNodeArea(ny,pos,dualMesh);
+}
+
+double Operator_Cylinder::GetNodeArea(int ny, const int pos[3], bool dualMesh) const
+{
+ if ( (pos[0]<0) || (pos[1]<0 && CC_closedAlpha==false) || (pos[2]<0) )
+ return 0.0;
+
+ unsigned int uiPos[]={(unsigned int)pos[0],(unsigned int)pos[1],(unsigned int)pos[2]};
+ if (pos[1]<0 && CC_closedAlpha==true)
+ uiPos[1]+=numLines[1]-2;
+
+ return GetNodeArea(ny, uiPos, dualMesh);
+}
+
+double Operator_Cylinder::GetEdgeLength(int ny, const unsigned int pos[3], bool dualMesh) const
+{
+ double length = Operator_Multithread::GetEdgeLength(ny,pos,dualMesh);
+ if (ny!=1)
+ return length;
+ return length * GetDiscLine(0,pos[0],dualMesh);
+}
+
+double Operator_Cylinder::GetCellVolume(const unsigned int pos[3], bool dualMesh) const
+{
+ return GetEdgeArea(2,pos,dualMesh)*GetEdgeLength(2,pos,dualMesh);
+}
+
+double Operator_Cylinder::GetEdgeArea(int ny, const unsigned int pos[3], bool dualMesh) const
+{
+ if (ny!=0)
+ return GetNodeArea(ny,pos,dualMesh);
+
+ return GetEdgeLength(1,pos,!dualMesh) * GetEdgeLength(2,pos,!dualMesh);
+}
+
+double Operator_Cylinder::FitToAlphaRange(double a_coord, bool fullMesh) const
+{
+ double min = GetDiscLine(1,0);
+ double max = GetDiscLine(1,GetNumberOfLines(1, fullMesh)-1);
+ if ((a_coord>=min) && (a_coord<=max))
+ return a_coord;
+ while (a_coord<min)
+ {
+ a_coord+=2*PI;
+ if (a_coord>max)
+ return a_coord-2*PI;
+ if (a_coord>min)
+ return a_coord;
+ }
+ while (a_coord>max)
+ {
+ a_coord-=2*PI;
+ if (a_coord<min)
+ return a_coord+2*PI;
+ if (a_coord<max)
+ return a_coord;
+ }
+ // this cannot happen
+ return a_coord;
+}
+
+int Operator_Cylinder::MapAlphaIndex2Range(int pos) const
+{
+ if (!CC_closedAlpha)
+ return pos;
+ if (pos<0)
+ return (int)numLines[1]+pos-2;
+ else if (pos>=(int)numLines[1]-2)
+ return pos-(int)numLines[1]+2;
+ else
+ return pos;
+}
+
+bool Operator_Cylinder::GetCellCenterMaterialAvgCoord(const int pos[3], double coord[3]) const
+{
+ if (!CC_closedAlpha || ((pos[1]>=0) && (pos[1]<(int)numLines[1]-2)))
+ {
+ return Operator_Multithread::GetCellCenterMaterialAvgCoord(pos, coord);
+ }
+ if ((pos[0]<0) || (pos[2]<0))
+ return false;
+ int l_pos[3] = {pos[0], 0, pos[2]};
+ l_pos[1] = MapAlphaIndex2Range(pos[1]);
+ return Operator_Multithread::GetCellCenterMaterialAvgCoord(l_pos, coord);
+}
+
+unsigned int Operator_Cylinder::SnapToMeshLine(int ny, double coord, bool &inside, bool dualMesh, bool fullMesh) const
+{
+ if (ny==1)
+ coord=FitToAlphaRange(coord);
+ return Operator_Multithread::SnapToMeshLine(ny, coord, inside, dualMesh, fullMesh);
+}
+
+int Operator_Cylinder::SnapBox2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh, bool fullMesh, int SnapMethod, bool* bStartIn, bool* bStopIn) const
+{
+ double a_min = GetDiscLine(1,0);
+ double a_max = GetDiscLine(1,GetNumberOfLines(1,fullMesh)-1);
+
+ double a_size = stop[1] - start[1];
+ double a_center = FitToAlphaRange(0.5*(stop[1]+start[1]));
+ double a_start = a_center-a_size/2;
+ double a_stop = a_start + a_size;
+ if (a_stop>a_max)
+ a_stop=a_max;
+ if (a_stop<a_min)
+ a_stop=a_min;
+ if (a_start>a_max)
+ a_start=a_max;
+ if (a_start<a_min)
+ a_start=a_min;
+
+ double l_start[3] = {start[0], a_start, start[2]};
+ double l_stop[3] = {stop[0] , a_stop , stop[2] };
+ return Operator_Multithread::SnapBox2Mesh(l_start, l_stop, uiStart, uiStop, dualMesh, fullMesh, SnapMethod, bStartIn, bStopIn);
+}
+
+int Operator_Cylinder::SnapLine2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh, bool fullMesh) const
+{
+ int ret = Operator_Multithread::SnapLine2Mesh(start, stop, uiStart, uiStop, dualMesh, fullMesh);
+
+ if ((stop[1]>start[1]) && (uiStop[1]<uiStart[1]) && (uiStop[1]==0))
+ uiStop[1] = GetNumberOfLines(1, fullMesh)-1-(int)CC_closedAlpha;
+ if ((stop[1]<start[1]) && (uiStop[1]>uiStart[1]) && (uiStop[1]==GetNumberOfLines(1, fullMesh)-1-(int)CC_closedAlpha))
+ uiStop[1] = 0;
+
+ return ret;
+}
+
+
+Grid_Path Operator_Cylinder::FindPath(double start[], double stop[])
+{
+ double l_start[3];
+ double l_stop[3];
+
+ for (int n=0;n<3;++n)
+ {
+ l_start[n] = start[n];
+ l_stop[n] = stop[n];
+ }
+
+ while (fabs(l_stop[1]-l_start[1])>PI)
+ {
+ if (l_stop[1]>l_start[1])
+ l_stop[1]-=2*PI;
+ else
+ l_stop[1]+=2*PI;
+ }
+
+ double help=0;
+ if (l_start[1]>l_stop[1])
+ {
+ for (int n=0;n<3;++n)
+ {
+ help = l_start[n];
+ l_start[n] = l_stop[n];
+ l_stop[n] = help;
+ }
+ }
+
+ double a_start = FitToAlphaRange(l_start[1]);
+ double a_stop = FitToAlphaRange(l_stop[1]);
+
+ if (a_stop >= a_start)
+ {
+ l_start[1] = a_start;
+ l_stop[1] = a_stop;
+ return Operator_Multithread::FindPath(l_start, l_stop);
+ }
+
+ // if a-stop fitted to disc range is now smaller than a-start, it must step over the a-bounds...
+
+ Grid_Path path;
+ for (int n=0;n<3;++n)
+ {
+ if ((l_start[n]<GetDiscLine(n,0)) && (l_stop[n]<GetDiscLine(n,0)))
+ return path; //lower bound violation
+ if ((l_start[n]>GetDiscLine(n,GetNumberOfLines(n,true)-1)) && (l_stop[n]>GetDiscLine(n,GetNumberOfLines(n,true)-1)))
+ return path; //upper bound violation
+ }
+
+ if (g_settings.GetVerboseLevel()>2)
+ cerr << __func__ << ": A path was leaving the alpha-direction mesh..." << endl;
+
+ // this section comes into play, if the line moves over the angulare mesh-end/start
+ // we try to have one part of the path on both "ends" of the mesh and stitch them together
+
+ Grid_Path path1;
+ Grid_Path path2;
+
+ // calculate the intersection of the line with the a-max boundary
+ double p0[3],p1[3],p2[3];
+ for (int n=0;n<3;++n)
+ {
+ p0[n] = GetDiscLine(n,0);
+ p1[n] = p0[n];
+ p2[n] = p0[n];
+ }
+ p0[1] = GetDiscLine(1,GetNumberOfLines(1,true)-1-(int)CC_closedAlpha);
+ p1[1] = p0[1];
+ p2[1] = p0[1];
+ p1[0] = discLines[0][numLines[0]-1];
+ p2[2] = discLines[2][numLines[2]-1];
+
+ TransformCoordSystem(p0,p0,m_MeshType,CARTESIAN);
+ TransformCoordSystem(p1,p1,m_MeshType,CARTESIAN);
+ TransformCoordSystem(p2,p2,m_MeshType,CARTESIAN);
+
+ double c_start[3],c_stop[3];
+ TransformCoordSystem(l_start,c_start,m_MeshType,CARTESIAN);
+ TransformCoordSystem(l_stop,c_stop,m_MeshType,CARTESIAN);
+ double intersect[3];
+ double dist;
+ int ret = LinePlaneIntersection(p0,p1,p2,c_start,c_stop,intersect,dist);
+ if (ret<0)
+ {
+ cerr << __func__ << ": Error, unable to calculate intersection, this should not happen!" << endl;
+ return path; // return empty path;
+ }
+
+ if (ret==0)
+ {
+ TransformCoordSystem(intersect,intersect,CARTESIAN,m_MeshType);
+ intersect[1] = GetDiscLine(1,GetNumberOfLines(1,true)-1-(int)CC_closedAlpha);
+ l_start[1] = FitToAlphaRange(l_start[1]);
+ path1 = Operator::FindPath(l_start, intersect);
+ if (g_settings.GetVerboseLevel()>2)
+ cerr << __func__ << ": Intersection top: " << intersect[0] << "," << intersect[1] << "," << intersect[2] << endl;
+ } //otherwise the path was not intersecting the upper a-bound...
+
+ if (CC_closedAlpha==false)
+ {
+ for (int n=0;n<3;++n)
+ {
+ p0[n] = GetDiscLine(n,0);
+ p1[n] = p0[n];
+ p2[n] = p0[n];
+ }
+ p1[0] = discLines[0][numLines[0]-1];
+ p2[2] = discLines[2][numLines[2]-1];
+
+ TransformCoordSystem(p0,p0,m_MeshType,CARTESIAN);
+ TransformCoordSystem(p1,p1,m_MeshType,CARTESIAN);
+ TransformCoordSystem(p2,p2,m_MeshType,CARTESIAN);
+
+ TransformCoordSystem(l_start,c_start,m_MeshType,CARTESIAN);
+ TransformCoordSystem(l_stop,c_stop,m_MeshType,CARTESIAN);
+
+ ret = LinePlaneIntersection(p0,p1,p2,c_start,c_stop,intersect,dist);
+ TransformCoordSystem(intersect,intersect,CARTESIAN,m_MeshType);
+ }
+
+ if (ret==0)
+ {
+ intersect[1] = GetDiscLine(1,0);
+ l_stop[1] = FitToAlphaRange(l_stop[1]);
+ path2 = Operator::FindPath(intersect, l_stop);
+ if (g_settings.GetVerboseLevel()>2)
+ cerr << __func__ << ": Intersection bottom: " << intersect[0] << "," << intersect[1] << "," << intersect[2] << endl;
+ }
+
+ //combine path
+ for (size_t t=0; t<path1.dir.size(); ++t)
+ {
+ path.posPath[0].push_back(path1.posPath[0].at(t));
+ path.posPath[1].push_back(path1.posPath[1].at(t));
+ path.posPath[2].push_back(path1.posPath[2].at(t));
+ path.dir.push_back(path1.dir.at(t));
+ }
+ for (size_t t=0; t<path2.dir.size(); ++t)
+ {
+ path.posPath[0].push_back(path2.posPath[0].at(t));
+ path.posPath[1].push_back(path2.posPath[1].at(t));
+ path.posPath[2].push_back(path2.posPath[2].at(t));
+ path.dir.push_back(path2.dir.at(t));
+ }
+
+ if (CC_closedAlpha==true)
+ for (size_t t=0; t<path.dir.size(); ++t)
+ {
+ if ( ((path.dir.at(t)==0) || (path.dir.at(t)==2)) && (path.posPath[1].at(t)==0))
+ path.posPath[1].at(t) = numLines[1]-2;
+ }
+
+ return path;
+}
+
+bool Operator_Cylinder::SetupCSXGrid(CSRectGrid* grid)
+{
+ unsigned int alphaNum;
+ double* alphaLines = NULL;
+ alphaLines = grid->GetLines(1,alphaLines,alphaNum,true);
+
+ double minmaxA = fabs(alphaLines[alphaNum-1]-alphaLines[0]);
+ if (fabs(minmaxA-2*PI) < OPERATOR_CYLINDER_CLOSED_ALPHA_THRESHOLD)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Operator_Cylinder::SetupCSXGrid: Alpha is a full 2*PI => closed Cylinder..." << endl;
+ CC_closedAlpha = true;
+ grid->SetLine(1,alphaNum-1,2*PI+alphaLines[0]);
+ grid->AddDiscLine(1,2*PI+alphaLines[1]);
+ }
+ else if (minmaxA>2*PI)
+ {
+ cerr << "Operator_Cylinder::SetupCSXGrid: Alpha Max-Min must not be larger than 2*PI!!!" << endl;
+ Reset();
+ return false;
+ }
+ else
+ {
+ CC_closedAlpha=false;
+ }
+
+ CC_R0_included = false;
+ if (grid->GetLine(0,0)<0)
+ {
+ cerr << "Operator_Cylinder::SetupCSXGrid: r<0 not allowed in Cylinder Coordinates!!!" << endl;
+ Reset();
+ return false;
+ }
+ else if (grid->GetLine(0,0)==0.0)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Operator_Cylinder::SetupCSXGrid: r=0 included..." << endl;
+ CC_R0_included = CC_closedAlpha; //needed for correct ec-calculation, deactivate if closed cylinder is false... --> E_r = 0 anyways
+ }
+
+#ifdef MPI_SUPPORT
+ // Setup an MPI split in alpha direction for a closed cylinder
+ CC_MPI_Alpha = false;
+ if ((m_NeighborUp[1]>=0) || (m_NeighborDown[1]>=0)) //check for MPI split in alpha direction
+ {
+ double minmaxA = 2*PI;// fabs(m_OrigDiscLines[1][m_OrigNumLines[1]-1]-m_OrigDiscLines[1][0]);
+ if (fabs(minmaxA-2*PI) < OPERATOR_CYLINDER_CLOSED_ALPHA_THRESHOLD) //check for closed alpha MPI split
+ {
+ CC_MPI_Alpha = true;
+ if (m_OrigDiscLines[0][0]==0)
+ {
+ cerr << "Operator_Cylinder::SetupCSXGrid: Error: MPI split in alpha direction for closed cylinder including r==0 is currently not supported! Exit!" << endl;
+ exit(-2);
+ }
+
+ if (m_NeighborUp[1]<0) //check if this process is at the alpha-end
+ {
+ grid->SetLine(1,alphaNum-1,2*PI+m_OrigDiscLines[1][0]);
+ grid->AddDiscLine(1,2*PI+m_OrigDiscLines[1][1]);
+
+ SetNeighborUp(1,m_ProcTable[m_ProcTablePos[0]][0][m_ProcTablePos[2]]);
+ }
+
+ if (m_NeighborDown[1]<0) //check if this process is at the alpha-start
+ {
+ SetNeighborDown(1,m_ProcTable[m_ProcTablePos[0]][m_SplitNumber[1]-1][m_ProcTablePos[2]]);
+ }
+
+ //Note: the process table will not reflect this up/down neighbors necessary for a closed cylinder
+ }
+ }
+#endif
+
+ if (Operator_Multithread::SetupCSXGrid(grid)==false)
+ return false;
+
+ if (CC_closedAlpha || CC_R0_included)
+ {
+ m_Cyl_Ext = new Operator_Ext_Cylinder(this);
+ this->AddExtension(m_Cyl_Ext);
+ }
+
+ return true;
+}
+
+void Operator_Cylinder::ApplyMagneticBC(bool* dirs)
+{
+ if (dirs==NULL) return;
+ if (CC_closedAlpha)
+ {
+ dirs[2]=0;
+ dirs[3]=0; //no PMC in alpha directions...
+ }
+ if (CC_R0_included)
+ {
+ dirs[0]=0; //no PMC in r_min directions...
+ }
+ Operator_Multithread::ApplyMagneticBC(dirs);
+}
+
+void Operator_Cylinder::AddExtension(Operator_Extension* op_ext)
+{
+ if (op_ext->IsCylinderCoordsSave(CC_closedAlpha, CC_R0_included))
+ Operator_Multithread::AddExtension(op_ext);
+ else
+ {
+ cerr << "Operator_Cylinder::AddExtension: Warning: Operator extension \"" << op_ext->GetExtensionName() << "\" is not compatible with cylinder-coords!! skipping...!" << endl;
+ delete op_ext;
+ }
+}
diff --git a/openEMS/FDTD/operator_cylinder.h b/openEMS/FDTD/operator_cylinder.h
new file mode 100644
index 0000000..152f618
--- /dev/null
+++ b/openEMS/FDTD/operator_cylinder.h
@@ -0,0 +1,118 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_CYLINDER_H
+#define OPERATOR_CYLINDER_H
+
+#define OPERATOR_CYLINDER_CLOSED_ALPHA_THRESHOLD 1e-6
+
+#include "operator_multithread.h"
+
+class Operator_Ext_Cylinder;
+
+//! This class creates an operator for a cylindrical FDTD.
+/*!
+This class creates an operator for a cylindrical FDTD. No special engine is necessary,
+all special cases e.g. a closed alpha mesh or an included r=0 case is treated by an operator/engine extension \sa operator_ext_cylinder.
+*/
+class Operator_Cylinder : public Operator_Multithread
+{
+ friend class Operator_CylinderMultiGrid;
+ friend class Operator_Ext_Cylinder;
+ friend class Operator_Ext_LorentzMaterial;
+public:
+ static Operator_Cylinder* New(unsigned int numThreads = 0);
+ virtual ~Operator_Cylinder();
+
+ virtual void ApplyMagneticBC(bool* dirs);
+
+ virtual unsigned int GetNumberOfLines(int ny, bool full=false) const;
+
+ //! Get the name for the given direction: 0 -> rho, 1 -> alpha, 2 -> z
+ virtual string GetDirName(int ny) const;
+
+ //! Get the coordinates for a given node index and component, according to the cylindrical yee-algorithm. Returns true if inside the FDTD domain.
+ virtual bool GetYeeCoords(int ny, unsigned int pos[3], double* coords, bool dualMesh) const;
+
+ //! Get the node width for a given direction \a n and a given mesh posisition \a pos
+ virtual double GetNodeWidth(int ny, const unsigned int pos[3], bool dualMesh = false) const;
+ //! Get the node width for a given direction \a n and a given mesh posisition \a pos
+ virtual double GetNodeWidth(int ny, const int pos[3], bool dualMesh = false) const;
+
+ //! Get the node area for a given direction \a n and a given mesh posisition \a pos
+ virtual double GetNodeArea(int n, const unsigned int* pos, bool dualMesh=false) const;
+ //! Get the node area for a given direction \a n and a given mesh posisition \a pos
+ virtual double GetNodeArea(int ny, const int pos[3], bool dualMesh = false) const;
+
+ //! Get the length of an FDTD edge, including radius corrected alpha-mesh width.
+ virtual double GetEdgeLength(int ny, const unsigned int pos[3], bool dualMesh = false) const;
+
+ //! Get the volume of an FDTD cell
+ virtual double GetCellVolume(const unsigned int pos[3], bool dualMesh = false) const;
+
+ //! Get the area around an edge for a given direction \a n and a given mesh posisition \a pos
+ /*!
+ This will return the area around an edge with a given direction, measured at the middle of the edge.
+ In a cartesian mesh this is equal to the NodeArea, may be different in other coordinate systems.
+ */
+ virtual double GetEdgeArea(int ny, const unsigned int pos[3], bool dualMesh = false) const;
+
+ virtual double FitToAlphaRange(double a_coord, bool fullMesh=false) const;
+
+ //! Map a negative or out of range index in alpha direction back into the closed alpha mesh
+ virtual int MapAlphaIndex2Range(int pos) const;
+
+ virtual bool GetCellCenterMaterialAvgCoord(const int pos[3], double coord[3]) const;
+
+ virtual unsigned int SnapToMeshLine(int ny, double coord, bool &inside, bool dualMesh=false, bool fullMesh=false) const;
+
+ //! Snap a given box to the FDTD mesh
+ virtual int SnapBox2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh=false, bool fullMesh=false, int SnapMethod=0, bool* bStartIn=NULL, bool* bStopIn=NULL) const;
+
+ virtual int SnapLine2Mesh(const double* start, const double* stop, unsigned int* uiStart, unsigned int* uiStop, bool dualMesh=false, bool fullMesh=false) const;
+
+ bool GetClosedAlpha() const {return CC_closedAlpha;}
+ bool GetR0Included() const {return CC_R0_included;}
+
+ virtual void AddExtension(Operator_Extension* op_ext);
+
+ virtual Engine* CreateEngine();
+
+protected:
+ Operator_Cylinder();
+ virtual void Init();
+
+ virtual bool SetupCSXGrid(CSRectGrid* grid);
+
+ virtual Grid_Path FindPath(double start[], double stop[]);
+
+ virtual double GetRawDiscDelta(int ny, const int pos) const;
+
+ virtual double GetMaterial(int ny, const double coords[3], int MatType, vector<CSPrimitives*> vPrims, bool markAsUsed=true) const;
+
+ virtual int CalcECOperator( DebugFlags debugFlags = None );
+ virtual double CalcTimestep();
+ bool CC_closedAlpha;
+ bool CC_R0_included;
+ Operator_Ext_Cylinder* m_Cyl_Ext;
+
+#ifdef MPI_SUPPORT
+ bool CC_MPI_Alpha;
+#endif
+};
+
+#endif // OPERATOR_CYLINDER_H
diff --git a/openEMS/FDTD/operator_cylindermultigrid.cpp b/openEMS/FDTD/operator_cylindermultigrid.cpp
new file mode 100644
index 0000000..88f9f82
--- /dev/null
+++ b/openEMS/FDTD/operator_cylindermultigrid.cpp
@@ -0,0 +1,569 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_cylindermultigrid.h"
+#include "engine_cylindermultigrid.h"
+#include "extensions/operator_ext_cylinder.h"
+#include "tools/useful.h"
+#include "CSUseful.h"
+
+Operator_CylinderMultiGrid::Operator_CylinderMultiGrid(vector<double> Split_Radii, unsigned int level) : Operator_Cylinder()
+{
+ m_Split_Radii = Split_Radii;
+ m_Split_Rad = m_Split_Radii.back();
+ m_Split_Radii.pop_back();
+ m_MultiGridLevel = level;
+}
+
+Operator_CylinderMultiGrid::~Operator_CylinderMultiGrid()
+{
+ Delete();
+}
+
+Operator_CylinderMultiGrid* Operator_CylinderMultiGrid::New(vector<double> Split_Radii, unsigned int numThreads, unsigned int level)
+{
+ if ((Split_Radii.size()==0) || (Split_Radii.size()>CYLIDINDERMULTIGRID_LIMIT))
+ {
+ cerr << "Operator_CylinderMultiGrid::New: Warning: Number of multigrids invalid! Split-Number: " << Split_Radii.size() << endl;
+ return NULL;
+ }
+ cout << "Create cylindrical multi grid FDTD operator " << endl;
+ Operator_CylinderMultiGrid* op = new Operator_CylinderMultiGrid(Split_Radii, level);
+ op->setNumThreads(numThreads);
+ op->Init();
+
+ return op;
+}
+
+Engine* Operator_CylinderMultiGrid::CreateEngine()
+{
+ m_Engine = Engine_CylinderMultiGrid::New(this,m_numThreads);
+ return m_Engine;
+}
+
+double Operator_CylinderMultiGrid::GetNumberCells() const
+{
+ if (numLines)
+ return (numLines[0]-m_Split_Pos)*(numLines[1])*(numLines[2]) + m_InnerOp->GetNumberCells();
+ return 0;
+}
+
+bool Operator_CylinderMultiGrid::SetupCSXGrid(CSRectGrid* grid)
+{
+ if (Operator_Cylinder::SetupCSXGrid(grid)==false)
+ return false;
+
+ // make this multigrid use the larger timestep by method 3, since no r==0 singularity can be part of this engine
+ m_TimeStepVar = 3;
+
+ if ((numLines[1]-CC_closedAlpha)%2 != 1)
+ {
+ cerr << "Operator_CylinderMultiGrid::SetupCSXGrid: Error, number of line in alpha direction must be odd... found: " << numLines[1] << endl;
+ exit(0);
+ }
+
+ m_Split_Pos = 0;
+ for (unsigned int n=0; n<numLines[0]; ++n)
+ {
+ if (m_Split_Rad < discLines[0][n])
+ {
+ m_Split_Pos = n;
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Operator_CylinderMultiGrid::SetupCSXGrid: Found mesh split position @" << m_Split_Pos << endl;
+ m_Split_Rad = discLines[0][n];
+ break;
+ }
+ }
+ if ((m_Split_Pos<4) || (m_Split_Pos>numLines[0]-4))
+ {
+ cerr << "Operator_CylinderMultiGrid::SetupCSXGrid: Error, split invalid..." << endl;
+ return false;
+ }
+ return true;
+}
+
+bool Operator_CylinderMultiGrid::SetGeometryCSX(ContinuousStructure* geo)
+{
+ if (Operator_Cylinder::SetGeometryCSX(geo)==false)
+ return false;
+
+ CSRectGrid* grid = geo->GetGrid();
+
+ grid->ClearLines(0);
+ grid->ClearLines(1);
+ for (unsigned int n=0; n<m_Split_Pos ; ++n)
+ grid->AddDiscLine(0,discLines[0][n]);
+ for (unsigned int n=0; n<numLines[1]; n+=2)
+ grid->AddDiscLine(1,discLines[1][n]);
+
+ if (m_InnerOp->SetGeometryCSX(CSX)==false)
+ return false;
+
+ //restore grid to original mesh
+ grid->ClearLines(0);
+ grid->ClearLines(1);
+ for (unsigned int n=0; n<numLines[0]; ++n)
+ grid->AddDiscLine(0,discLines[0][n]);
+ for (unsigned int n=0; n<numLines[1]; ++n)
+ grid->AddDiscLine(1,discLines[1][n]);
+
+ return true;
+}
+
+void Operator_CylinderMultiGrid::Init()
+{
+ Operator_Cylinder::Init();
+
+ if (m_Split_Radii.empty())
+ m_InnerOp = Operator_Cylinder::New(m_numThreads);
+ else
+ m_InnerOp = Operator_CylinderMultiGrid::New(m_Split_Radii,m_numThreads, m_MultiGridLevel+1);
+
+ for (int n=0;n<2;++n)
+ {
+ m_interpol_pos_v_2p[n] = NULL;
+ f4_interpol_v_2p[n]=NULL;
+ m_interpol_pos_v_2pp[n] = NULL;
+ f4_interpol_v_2pp[n]=NULL;
+
+ m_interpol_pos_i_2p[n] = NULL;
+ f4_interpol_i_2p[n]=NULL;
+ m_interpol_pos_i_2pp[n] = NULL;
+ f4_interpol_i_2pp[n]=NULL;
+ }
+}
+
+bool Operator_CylinderMultiGrid::GetYeeCoords(int ny, unsigned int pos[3], double* coords, bool dualMesh) const
+{
+ bool ret = Operator_Cylinder::GetYeeCoords(ny,pos,coords,dualMesh);
+
+ if (pos[0]<(m_Split_Pos-1))
+ ret = false;
+
+ return ret;
+}
+
+#ifdef MPI_SUPPORT
+void Operator_CylinderMultiGrid::SetTag(int tag)
+{
+ m_MyTag = tag;
+ m_InnerOp->SetTag(tag+1);
+}
+
+void Operator_CylinderMultiGrid::SetNeighborUp(int ny, int id)
+{
+ if (ny==0)
+ {
+ cerr << "Operator_CylinderMultiGrid::SetNeighborUp: Error: MPI segregation in radial direction not supported for a cylindircal multigrid. Exit!";
+ MPI_Barrier(MPI_COMM_WORLD);
+ exit(-1);
+ }
+ Operator_Cylinder::SetNeighborUp(ny,id);
+ m_InnerOp->SetNeighborUp(ny,id);
+}
+
+void Operator_CylinderMultiGrid::SetNeighborDown(int ny, int id)
+{
+ if (ny==0)
+ {
+ cerr << "Operator_CylinderMultiGrid::SetNeighborDown: Error: MPI segregation in radial direction not supported for a cylindircal multigrid. Exit!";
+ MPI_Barrier(MPI_COMM_WORLD);
+ exit(-1);
+ }
+ Operator_Cylinder::SetNeighborDown(ny,id);
+ m_InnerOp->SetNeighborDown(ny,id);
+}
+#endif
+
+void Operator_CylinderMultiGrid::CalcStartStopLines(unsigned int &numThreads, vector<unsigned int> &start, vector<unsigned int> &stop) const
+{
+ vector<unsigned int> jpt = AssignJobs2Threads(numLines[0]- m_Split_Pos + 1, numThreads, true);
+
+ numThreads = jpt.size();
+
+ start.resize(numThreads);
+ stop.resize(numThreads);
+
+ start.at(0)= m_Split_Pos-1;
+ stop.at(0)= jpt.at(0)-1 + m_Split_Pos-1;
+
+ for (unsigned int n=1; n<numThreads; n++)
+ {
+ start.at(n) = stop.at(n-1)+1;
+ stop.at(n) = start.at(n) + jpt.at(n) - 1;
+ }
+}
+
+
+void Operator_CylinderMultiGrid::FillMissingDataStorage()
+{
+ unsigned int pos[3];
+ double EffMat[4];
+ for (int ny=0; ny<3; ++ny)
+ {
+ for (pos[0]=0; pos[0]<m_Split_Pos-1; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ vector<CSPrimitives*> vPrims = this->GetPrimitivesBoundBox(pos[0], pos[1], -1, CSProperties::MATERIAL);
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ Calc_EffMatPos(ny,pos,EffMat,vPrims);
+
+ if (m_epsR)
+ m_epsR[ny][pos[0]][pos[1]][pos[2]] = EffMat[0];
+ if (m_kappa)
+ m_kappa[ny][pos[0]][pos[1]][pos[2]] = EffMat[1];
+ if (m_mueR)
+ m_mueR[ny][pos[0]][pos[1]][pos[2]] = EffMat[2];
+ if (m_sigma)
+ m_sigma[ny][pos[0]][pos[1]][pos[2]] = EffMat[3];
+ }
+ }
+ }
+ }
+}
+
+bool Operator_CylinderMultiGrid::GetCellCenterMaterialAvgCoord(const int pos[3], double coord[3]) const
+{
+ if (Operator_Cylinder::GetCellCenterMaterialAvgCoord(pos, coord)==false)
+ return false;
+
+ if (pos[0]>=((int)m_Split_Pos))
+ return true;
+
+ int pos_a = MapAlphaIndex2Range(pos[1])/2;
+ if ((pos_a<0) || (pos_a>=(int)m_InnerOp->numLines[1]))
+ return false;
+ coord[1] = m_InnerOp->GetDiscLine(1,pos_a,true);
+ return true;
+}
+
+int Operator_CylinderMultiGrid::CalcECOperator( DebugFlags debugFlags )
+{
+ int retCode=0;
+ if (dT)
+ m_InnerOp->SetTimestep(dT);
+
+ //calc inner child first
+ m_InnerOp->CalcECOperator();
+
+ dT = m_InnerOp->GetTimestep();
+
+ retCode = Operator_Cylinder::CalcECOperator( debugFlags );
+ if (GetTimestepValid()==false)
+ {
+ cerr << "Operator_CylinderMultiGrid::CalcECOperator(): Warning, timestep invalid... resetting..." << endl;
+ dT = opt_dT;
+ m_InnerOp->SetTimestep(dT);
+ m_InnerOp->CalcECOperator();
+ retCode = Operator_Cylinder::CalcECOperator( debugFlags );
+ }
+
+ SetupInterpolation();
+
+ //the data storage will only be filled up to m_Split_Pos-1, fill the remaining area here...
+ FillMissingDataStorage();
+ return retCode;
+}
+
+void Operator_CylinderMultiGrid::DumpPEC2File( string filename, unsigned int *range)
+{
+ if (range!=NULL)
+ return Operator_Cylinder::DumpPEC2File(filename, range);
+
+ range = new unsigned int[6];
+ for (int n=0;n<3;++n)
+ {
+ range[2*n] = 0;
+ range[2*n+1] = numLines[n]-1;
+ }
+ range[0] = m_Split_Pos-1;
+ Operator_Cylinder::DumpPEC2File(filename + "_S" + ConvertInt(m_MultiGridLevel), range);
+ delete[] range;
+ range=NULL;
+
+ if (dynamic_cast<Operator_CylinderMultiGrid*>(m_InnerOp))
+ m_InnerOp->DumpPEC2File(filename);
+ else // base cylindrical grid
+ m_InnerOp->DumpPEC2File(filename + "_S" + ConvertInt(m_MultiGridLevel+1));
+}
+
+void Operator_CylinderMultiGrid::SetupInterpolation()
+{
+ // n==0 --> interpolation in r&z-direction
+ // n==1 --> interpolation in a-direction
+ for (int n=0;n<2;++n)
+ {
+ delete[] m_interpol_pos_v_2p[n];
+ m_interpol_pos_v_2p[n] = new unsigned int[numLines[1]];
+ Delete1DArray_v4sf(f4_interpol_v_2p[n]);
+ f4_interpol_v_2p[n]=Create1DArray_v4sf(numLines[1]);
+
+ delete[] m_interpol_pos_v_2pp[n];
+ m_interpol_pos_v_2pp[n] = new unsigned int[numLines[1]];
+ Delete1DArray_v4sf(f4_interpol_v_2pp[n]);
+ f4_interpol_v_2pp[n]=Create1DArray_v4sf(numLines[1]);
+
+ delete[] m_interpol_pos_i_2p[n];
+ m_interpol_pos_i_2p[n] = new unsigned int[numLines[1]];
+ Delete1DArray_v4sf(f4_interpol_i_2p[n]);
+ f4_interpol_i_2p[n]=Create1DArray_v4sf(numLines[1]);
+
+ delete[] m_interpol_pos_i_2pp[n];
+ m_interpol_pos_i_2pp[n] = new unsigned int[numLines[1]];
+ Delete1DArray_v4sf(f4_interpol_i_2pp[n]);
+ f4_interpol_i_2pp[n]=Create1DArray_v4sf(numLines[1]);
+ }
+
+ bool isOdd, isEven;
+ for (unsigned int a_n=0; a_n<numLines[1]; ++a_n)
+ {
+ isOdd = (a_n%2);
+ isEven = !isOdd;
+
+ /* current interpolation position for r,z direction
+ this sub_grid 2p sub_grid 2pp
+ 0 <-- 0 (-1) 0
+ 1 <-- 0 1
+ 2 <-- 1 0
+ 3 <-- 1 2
+ 4 <-- 2 1
+ 5 <-- 2 3
+ ...
+ */
+ m_interpol_pos_i_2p[0][a_n] = a_n/2;
+ m_interpol_pos_i_2pp[0][a_n] = a_n/2 + isOdd - isEven;
+ if ((a_n==0) && CC_closedAlpha)
+ m_interpol_pos_i_2pp[0][a_n] = m_InnerOp->numLines[1]-3;
+ else if ((a_n==0) && !CC_closedAlpha)
+ m_interpol_pos_i_2pp[0][a_n] = 0;
+
+ //setup some special treatments for not closed alpha mesh
+ if ((a_n==numLines[1]-2) && !CC_closedAlpha)
+ m_interpol_pos_i_2pp[0][a_n] = a_n/2 - 1;
+ if ((a_n==numLines[1]-1) && !CC_closedAlpha)
+ m_interpol_pos_i_2p[0][a_n] = m_interpol_pos_i_2pp[0][a_n] = a_n/2;
+
+ double dl_p=m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2p[0][a_n],true);
+ double dl_pp=m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2pp[0][a_n],true);
+ if ((a_n==0) && CC_closedAlpha)
+ dl_pp -= 2*PI;
+
+ for (int v=0;v<4;++v)
+ {
+ if (m_interpol_pos_i_2p[0][a_n]==m_interpol_pos_i_2pp[0][a_n])
+ f4_interpol_i_2p[0][a_n].f[v] = 1.0;
+ else
+ {
+ f4_interpol_i_2p[0][a_n].f[v] = (dl_pp-GetDiscLine(1,a_n,true)) / (dl_pp-dl_p);
+ f4_interpol_i_2pp[0][a_n].f[v] = (GetDiscLine(1,a_n,true)-dl_p) / (dl_pp-dl_p);
+ }
+ }
+
+ /* voltage interpolation position for r,z direction
+ this sub_grid 2p sub_grid 2pp
+ 0 <-- 0 0
+ 1 <-- 0 1
+ 2 <-- 1 1
+ 3 <-- 1 2
+ 4 <-- 2 2
+ 5 <-- 2 3
+ ...
+ */
+ m_interpol_pos_v_2p[0][a_n] = a_n/2;
+ m_interpol_pos_v_2pp[0][a_n] = a_n/2 + isOdd;
+
+ dl_p=m_InnerOp->GetDiscLine(1,m_interpol_pos_v_2p[0][a_n],false);
+ dl_pp=m_InnerOp->GetDiscLine(1,m_interpol_pos_v_2pp[0][a_n],false);
+
+ for (int v=0;v<4;++v)
+ {
+ if (m_interpol_pos_v_2p[0][a_n]==m_interpol_pos_v_2pp[0][a_n])
+ f4_interpol_v_2p[0][a_n].f[v] = 1.0;
+ else
+ {
+ f4_interpol_v_2p[0][a_n].f[v] = (dl_pp-GetDiscLine(1,a_n,false)) / (dl_pp-dl_p);
+ f4_interpol_v_2pp[0][a_n].f[v] = (GetDiscLine(1,a_n,false)-dl_p) / (dl_pp-dl_p);
+ }
+ }
+
+ /* current interpolation position for the alpha direction
+ this sub_grid 2p sub_grid 2pp
+ 0 <-- 0 0
+ 1 <-- 0 1
+ 2 <-- 1 1
+ 3 <-- 1 2
+ 4 <-- 2 2
+ 5 <-- 2 3
+ ...
+ */
+ m_interpol_pos_i_2p[1][a_n] = a_n/2;
+ m_interpol_pos_i_2pp[1][a_n] = a_n/2 + isOdd;
+
+ //setup some special treatments for not closed alpha mesh
+ if ((a_n==1) && !CC_closedAlpha)
+ m_interpol_pos_i_2p[1][a_n] = 2;
+ if ((a_n==numLines[1]-2) && !CC_closedAlpha)
+ m_interpol_pos_i_2pp[1][a_n] = a_n/2 - 1;
+
+ for (int v=0;v<4;++v)
+ {
+ if (m_interpol_pos_i_2p[1][a_n]==m_interpol_pos_i_2pp[1][a_n])
+ f4_interpol_i_2p[1][a_n].f[v] = GetDiscDelta(1,a_n,true)/m_InnerOp->GetDiscDelta(1,m_interpol_pos_i_2p[1][a_n],true);
+ else
+ {
+ f4_interpol_i_2p[1][a_n].f[v] = (m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2pp[1][a_n],false)-GetDiscLine(1,a_n,false)) /
+ (m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2pp[1][a_n],false)-m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2p[1][a_n],false));
+ f4_interpol_i_2p[1][a_n].f[v] *= GetDiscDelta(1,a_n,true)/m_InnerOp->GetDiscDelta(1,m_interpol_pos_i_2p[1][a_n],true);
+
+ f4_interpol_i_2pp[1][a_n].f[v] = (GetDiscLine(1,a_n,false)-m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2p[1][a_n],false)) /
+ (m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2pp[1][a_n],false)-m_InnerOp->GetDiscLine(1,m_interpol_pos_i_2p[1][a_n],false));
+ f4_interpol_i_2pp[1][a_n].f[v] *= GetDiscDelta(1,a_n,true)/m_InnerOp->GetDiscDelta(1,m_interpol_pos_i_2pp[1][a_n],true);
+ }
+ }
+
+ /* voltage interpolation position for the alpha direction
+ this sub_grid 2p sub_grid 2pp
+ 0 <-- 0 (-1) 0
+ 1 <-- 0 1
+ 2 <-- 1 0
+ 3 <-- 1 2
+ 4 <-- 2 1
+ 5 <-- 2 3
+ ...
+ */
+ m_interpol_pos_v_2p[1][a_n] = a_n/2;
+ m_interpol_pos_v_2pp[1][a_n] = a_n/2 + isOdd - isEven;
+
+ if ((a_n==0) && CC_closedAlpha)
+ m_interpol_pos_v_2pp[1][a_n] = m_InnerOp->numLines[1]-3;
+ else if ((a_n==0) && !CC_closedAlpha)
+ m_interpol_pos_v_2pp[1][a_n] = 1;
+
+ //setup some special treatments for not closed alpha mesh
+ if ((a_n==numLines[1]-2) && !CC_closedAlpha)
+ m_interpol_pos_v_2pp[1][a_n] = a_n/2 - 1;
+ if ((a_n==numLines[1]-1) && !CC_closedAlpha)
+ {
+ m_interpol_pos_v_2p[1][a_n] = 0;
+ m_interpol_pos_v_2pp[1][a_n] = 0;
+ }
+
+ dl_p=m_InnerOp->GetDiscLine(1,m_interpol_pos_v_2p[1][a_n],true);
+ dl_pp=m_InnerOp->GetDiscLine(1,m_interpol_pos_v_2pp[1][a_n],true);
+
+ for (int v=0;v<4;++v)
+ {
+ if (m_interpol_pos_v_2p[1][a_n]==m_interpol_pos_v_2pp[1][a_n])
+ f4_interpol_v_2p[1][a_n].f[v] = f4_interpol_v_2pp[1][a_n].f[v] = 0;
+ else
+ {
+ f4_interpol_v_2p[1][a_n].f[v] = (dl_pp-GetDiscLine(1,a_n,true)) / (dl_pp-dl_p);
+ f4_interpol_v_2p[1][a_n].f[v] *= GetDiscDelta(1,a_n,false)/m_InnerOp->GetDiscDelta(1,m_interpol_pos_v_2p[1][a_n],false);
+
+ f4_interpol_v_2pp[1][a_n].f[v] = (GetDiscLine(1,a_n,true)-dl_p) / (dl_pp-dl_p);
+ f4_interpol_v_2pp[1][a_n].f[v] *= GetDiscDelta(1,a_n,false)/m_InnerOp->GetDiscDelta(1,m_interpol_pos_v_2pp[1][a_n],false);
+ }
+ }
+ }
+}
+
+void Operator_CylinderMultiGrid::SetExcitationSignal(Excitation* exc)
+{
+ m_InnerOp->SetExcitationSignal(exc);
+ Operator_Cylinder::SetExcitationSignal(exc);
+}
+
+void Operator_CylinderMultiGrid::Delete()
+{
+ delete m_InnerOp;
+ m_InnerOp=0;
+
+ for (int n=0;n<2;++n)
+ {
+ delete[] m_interpol_pos_v_2p[n];
+ m_interpol_pos_v_2p[n]=NULL;
+ Delete1DArray_v4sf(f4_interpol_v_2p[n]);
+ f4_interpol_v_2p[n]=NULL;
+ delete[] m_interpol_pos_v_2pp[n];
+ m_interpol_pos_v_2pp[n]=NULL;
+ Delete1DArray_v4sf(f4_interpol_v_2pp[n]);
+ f4_interpol_v_2pp[n]=NULL;
+
+ delete[] m_interpol_pos_i_2p[n];
+ m_interpol_pos_i_2p[n]=NULL;
+ Delete1DArray_v4sf(f4_interpol_i_2p[n]);
+ f4_interpol_i_2p[n]=NULL;
+ delete[] m_interpol_pos_i_2pp[n];
+ m_interpol_pos_i_2pp[n]=NULL;
+ Delete1DArray_v4sf(f4_interpol_i_2pp[n]);
+ f4_interpol_i_2pp[n]=NULL;
+ }
+}
+
+void Operator_CylinderMultiGrid::Reset()
+{
+ Delete();
+ Operator_Cylinder::Reset();
+}
+
+void Operator_CylinderMultiGrid::SetBoundaryCondition(int* BCs)
+{
+ Operator_Cylinder::SetBoundaryCondition(BCs);
+ int oldBC = BCs[1];
+ BCs[1] = 0; //always PEC in +r-direction
+ m_InnerOp->SetBoundaryCondition(BCs);
+ BCs[1] = oldBC;
+}
+
+void Operator_CylinderMultiGrid::AddExtension(Operator_Extension* op_ext)
+{
+ //check whether extension is save to use in multi-grid
+ if (op_ext->IsCylindricalMultiGridSave(false)==false)
+ {
+ cerr << "Operator_CylinderMultiGrid::AddExtension: Warning: Operator extension \"" << op_ext->GetExtensionName() << "\" is not compatible with cylindrical multi-grids!! skipping...!" << endl;
+ delete op_ext;
+ return;
+ }
+
+ Operator_Cylinder::AddExtension(op_ext);
+
+ // cylinder extension does not need to be cloned, it will be created by each operator of its own...
+ if (dynamic_cast<Operator_Ext_Cylinder*>(op_ext))
+ return;
+
+ //check whether extension is save to use in child multi-grid
+ if (op_ext->IsCylindricalMultiGridSave(true))
+ {
+ Operator_Extension* child_Ext = op_ext->Clone(m_InnerOp);
+ if (child_Ext==NULL)
+ {
+ cerr << "Operator_CylinderMultiGrid::AddExtension: Warning, extension: " << op_ext->GetExtensionName() << " can not be cloned for the child operator. Skipping Extension... " << endl;
+ return;
+ }
+ //give the copy to child
+ m_InnerOp->AddExtension(child_Ext);
+ }
+}
+
+void Operator_CylinderMultiGrid::ShowStat() const
+{
+ m_InnerOp->ShowStat();
+ m_InnerOp->ShowExtStat();
+ Operator_Cylinder::ShowStat();
+}
diff --git a/openEMS/FDTD/operator_cylindermultigrid.h b/openEMS/FDTD/operator_cylindermultigrid.h
new file mode 100644
index 0000000..57481f1
--- /dev/null
+++ b/openEMS/FDTD/operator_cylindermultigrid.h
@@ -0,0 +1,109 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_CYLINDERMULTIGRID_H
+#define OPERATOR_CYLINDERMULTIGRID_H
+
+#define CYLIDINDERMULTIGRID_LIMIT 20
+
+#include "operator_cylinder.h"
+
+//! This is a cylindrical FDTD operator using a simple multi-grid approach.
+/*!
+ This cylindrical multi-grid operator itself is not calculating any real operator, instead it is hosting two separate "child" operators of type "Operator_Cylinder".
+ This operator class (or the corresponding engine) will perform the interpolation and connection between these two child-operator/engines.
+ One of the child operators itself may be another multi-grid operator to allow for a cascaded multi-grid approach.
+ */
+class Operator_CylinderMultiGrid : public Operator_Cylinder
+{
+ friend class Engine_CylinderMultiGrid;
+public:
+ static Operator_CylinderMultiGrid* New(vector<double> Split_Radii, unsigned int numThreads = 0, unsigned int level = 0);
+ virtual ~Operator_CylinderMultiGrid();
+
+ virtual double GetNumberCells() const;
+
+ virtual Engine* CreateEngine();
+
+ virtual bool SetGeometryCSX(ContinuousStructure* geo);
+
+ //! Get the coordinates for a given node index and component, according to the cylindrical yee-algorithm. Returns true if inside the FDTD domain.
+ virtual bool GetYeeCoords(int ny, unsigned int pos[3], double* coords, bool dualMesh) const;
+
+ virtual unsigned int GetSplitPos() const {return m_Split_Pos;}
+
+ virtual void SetBoundaryCondition(int* BCs);
+
+ virtual void AddExtension(Operator_Extension* op_ext);
+
+ //! Get the multi grid level of this operator, e.g. 0 is main grid --> no parent grid
+ int GetMultiGridLevel() const {return m_MultiGridLevel;}
+
+ Operator_Cylinder* GetInnerOperator() const {return m_InnerOp;}
+
+ virtual void SetExcitationSignal(Excitation* exc);
+
+ virtual void ShowStat() const;
+
+ //! Get the cell center coordinate usable for material averaging (Warning, may not be the yee cell center)
+ virtual bool GetCellCenterMaterialAvgCoord(const int pos[3], double coord[3]) const;
+
+#ifdef MPI_SUPPORT
+ virtual void SetTag(int tag);
+ virtual void SetNeighborUp(int ny, int id);
+ virtual void SetNeighborDown(int ny, int id);
+#endif
+
+protected:
+ Operator_CylinderMultiGrid(vector<double> Split_Radii, unsigned int level);
+ virtual void Init();
+ void Delete();
+ virtual void Reset();
+
+ virtual bool SetupCSXGrid(CSRectGrid* grid);
+
+ virtual int CalcECOperator( DebugFlags debugFlags = None );
+
+ virtual void DumpPEC2File( string filename, unsigned int *range = NULL );
+
+ //! The material data storage in the sub-grid area's will not be filled by the base-operator. Check and do this here!
+ void FillMissingDataStorage();
+
+ unsigned int m_MultiGridLevel;
+ double m_Split_Rad;
+ vector<double> m_Split_Radii;
+ unsigned int m_Split_Pos;
+
+ Operator_Cylinder* m_InnerOp;
+
+ // sub-grid to base interpolation coefficients
+ unsigned int* m_interpol_pos_v_2p[2];
+ f4vector* f4_interpol_v_2p[2];
+ unsigned int* m_interpol_pos_v_2pp[2];
+ f4vector* f4_interpol_v_2pp[2];
+
+ unsigned int* m_interpol_pos_i_2p[2];
+ f4vector* f4_interpol_i_2p[2];
+ unsigned int* m_interpol_pos_i_2pp[2];
+ f4vector* f4_interpol_i_2pp[2];
+
+ void SetupInterpolation();
+
+ virtual void CalcStartStopLines(unsigned int &numThreads, vector<unsigned int> &start, vector<unsigned int> &stop) const;
+};
+
+#endif // OPERATOR_CYLINDERMULTIGRID_H
diff --git a/openEMS/FDTD/operator_mpi.cpp b/openEMS/FDTD/operator_mpi.cpp
new file mode 100644
index 0000000..432f5d7
--- /dev/null
+++ b/openEMS/FDTD/operator_mpi.cpp
@@ -0,0 +1,209 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_mpi.h"
+#include "operator_sse_compressed.h"
+#include "engine_sse_compressed.h"
+#include "engine_mpi.h"
+#include "extensions/operator_extension.h"
+#include "tools/array_ops.h"
+#include "tools/useful.h"
+#include "mpi.h"
+
+Operator_MPI* Operator_MPI::New()
+{
+ cout << "Create FDTD operator (compressed SSE + MPI)" << endl;
+ Operator_MPI* op = new Operator_MPI();
+ op->Init();
+ return op;
+}
+
+Operator_MPI::Operator_MPI() : Operator_SSE_Compressed()
+{
+ m_NumProc = MPI::COMM_WORLD.Get_size();
+
+ //enabled only if more than one process is active
+ m_MPI_Enabled = m_NumProc>1;
+}
+
+Operator_MPI::~Operator_MPI()
+{
+ Delete();
+}
+
+double Operator_MPI::CalcTimestep()
+{
+ double ret = Operator::CalcTimestep();
+
+ if (!m_MPI_Enabled)
+ return ret;
+
+ double local_dT = dT;
+ //find the smallest time-step requestes by all processings
+ MPI_Reduce(&local_dT, &dT, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);
+ //send the smallest time-step to all
+ MPI_Bcast(&dT, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
+
+ return ret;
+}
+
+void Operator_MPI::SetBoundaryCondition(int* BCs)
+{
+ if (!m_MPI_Enabled)
+ return Operator_SSE_Compressed::SetBoundaryCondition(BCs);
+
+ //set boundary conditions on MPI interfaces to PEC, ApplyElectricBC will handle proper interface handling...
+ for (int n=0;n<3;++n)
+ {
+ if (m_NeighborUp[n]>=0)
+ BCs[2*n+1] = 0;
+ if (m_NeighborDown[n]>=0)
+ BCs[2*n] = 0;
+ }
+ Operator_SSE_Compressed::SetBoundaryCondition(BCs);
+}
+
+Engine* Operator_MPI::CreateEngine()
+{
+ if (m_MPI_Enabled)
+ m_Engine = Engine_MPI::New(this);
+ else
+ m_Engine = Engine_SSE_Compressed::New(this);
+ return m_Engine;
+}
+
+void Operator_MPI::SetNeighborUp(int ny, int id)
+{
+ if ((ny<0) || (ny>2))
+ return;
+ m_NeighborUp[ny]=id;
+}
+
+void Operator_MPI::SetNeighborDown(int ny, int id)
+{
+ if ((ny<0) || (ny>2))
+ return;
+ m_NeighborDown[ny]=id;
+}
+
+void Operator_MPI::Init()
+{
+ Operator_SSE_Compressed::Init();
+
+ m_MyTag = 0;
+
+ for (int i=0;i<3;++i)
+ {
+ m_NeighborUp[i]=-1;
+ m_NeighborDown[i]=-1;
+ m_OrigDiscLines[i]=NULL;
+ }
+
+ m_ProcTable = NULL;
+ m_SplitNumber[0]=0;
+ m_SplitNumber[1]=0;
+ m_SplitNumber[2]=0;
+
+ int namelen;
+ m_NumProc = MPI::COMM_WORLD.Get_size();
+ m_MyID = MPI::COMM_WORLD.Get_rank();
+
+ m_Processor_Name = new char[MPI_MAX_PROCESSOR_NAME];
+ MPI::Get_processor_name(m_Processor_Name,namelen);
+
+ if ((m_MPI_Enabled) && (g_settings.GetVerboseLevel()>0))
+ cerr << "Operator_MPI::Init(): Running on " << m_Processor_Name << endl;
+}
+
+void Operator_MPI::Delete()
+{
+ delete[] m_Processor_Name;
+ m_Processor_Name = NULL;
+ for (int i=0;i<3;++i)
+ {
+ delete[] m_OrigDiscLines[i];
+ m_OrigDiscLines[i] = NULL;
+ }
+ Delete3DArray(m_ProcTable,m_SplitNumber);
+ m_ProcTable=NULL;
+}
+
+void Operator_MPI::Reset()
+{
+ Delete();
+ Operator_SSE_Compressed::Reset();
+}
+
+void Operator_MPI::SetOriginalMesh(CSRectGrid* orig_Mesh)
+{
+ for (int n=0;n<3;++n)
+ {
+ delete[] m_OrigDiscLines[n];
+ m_OrigDiscLines[n] = orig_Mesh->GetLines(n,NULL,m_OrigNumLines[n]);
+ }
+}
+
+unsigned int Operator_MPI::GetNumberOfLines(int ny, bool fullMesh) const
+{
+ if (fullMesh)
+ return Operator_SSE_Compressed::GetNumberOfLines(ny,fullMesh);
+
+ if ((!m_MPI_Enabled) || (m_NeighborUp[ny]<0))
+ return Operator_SSE_Compressed::GetNumberOfLines(ny,fullMesh);
+
+ return Operator_SSE_Compressed::GetNumberOfLines(ny)-1;
+}
+
+void Operator_MPI::AddExtension(Operator_Extension* op_ext)
+{
+ if (m_MPI_Enabled==false)
+ return Operator_SSE_Compressed::AddExtension(op_ext);
+
+ if (op_ext->IsMPISave())
+ Operator_SSE_Compressed::AddExtension(op_ext);
+ else
+ {
+ cerr << "Operator_MPI::AddExtension: Warning: Operator extension \"" << op_ext->GetExtensionName() << "\" is not compatible with MPI!! skipping...!" << endl;
+ delete op_ext;
+ }
+}
+
+
+string Operator_MPI::PrependRank(string name)
+{
+ stringstream out_name;
+ if (m_MPI_Enabled)
+ out_name << "ID" << m_MyID << "_" << name;
+ else
+ out_name << name;
+ return out_name.str();
+}
+
+void Operator_MPI::DumpOperator2File(string filename)
+{
+ Operator_SSE_Compressed::DumpOperator2File(PrependRank(filename));
+}
+
+void Operator_MPI::DumpMaterial2File(string filename)
+{
+ Operator_SSE_Compressed::DumpMaterial2File(PrependRank(filename));
+}
+
+void Operator_MPI::DumpPEC2File(string filename , unsigned int *range)
+{
+ Operator_SSE_Compressed::DumpPEC2File(PrependRank(filename), range);
+}
diff --git a/openEMS/FDTD/operator_mpi.h b/openEMS/FDTD/operator_mpi.h
new file mode 100644
index 0000000..c09616e
--- /dev/null
+++ b/openEMS/FDTD/operator_mpi.h
@@ -0,0 +1,90 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY{} without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_MPI_H
+#define OPERATOR_MPI_H
+
+#include "operator_sse_compressed.h"
+
+class Operator_MPI : public Operator_SSE_Compressed
+{
+ friend class Engine_MPI;
+public:
+ //! Create a new operator
+ static Operator_MPI* New();
+ virtual ~Operator_MPI();
+
+ bool GetMPIEnabled() const {return m_MPI_Enabled;}
+
+ virtual void SetBoundaryCondition(int* BCs);
+
+ virtual Engine* CreateEngine();
+
+ virtual void SetTag(int tag) {m_MyTag=tag;}
+
+ //! Set the number of splits for a given direction. This also defines the size of the process table. \sa SetProcessTable
+ virtual void SetSplitNumbers(int ny, unsigned int splits) {m_SplitNumber[ny]=splits;}
+ //! Set the table containing a list of all MPI rank ID's and there mesh affiliation. \sa SetProcessTablePosition
+ virtual void SetProcessTable(unsigned int*** procTable) {m_ProcTable=procTable;}
+ //! Save the position for this rank in the process table. \sa SetProcessTable
+ virtual void SetProcessTablePosition(int ny, unsigned int pos) {m_ProcTablePos[ny]=pos;}
+
+ virtual void SetNeighborUp(int ny, int id);
+ virtual void SetNeighborDown(int ny, int id);
+
+ //! Set the lower original mesh position
+ virtual void SetSplitPos(int ny, unsigned int pos) {m_SplitPos[ny]=pos;}
+ virtual void SetOriginalMesh(CSRectGrid* orig_Mesh);
+
+ virtual unsigned int GetNumberOfLines(int ny, bool fullMesh=false) const;
+
+ virtual void AddExtension(Operator_Extension* op_ext);
+
+protected:
+ Operator_MPI();
+ bool m_MPI_Enabled;
+ virtual void Init();
+ void Delete();
+ virtual void Reset();
+
+ virtual double CalcTimestep();
+
+ unsigned int m_MyID;
+ unsigned int m_NumProc;
+ int m_MyTag;
+ char* m_Processor_Name;
+
+ //the up and down neighbors, -1 if non for the given direction
+ int m_NeighborUp[3];
+ int m_NeighborDown[3];
+
+ unsigned int m_SplitNumber[3];
+ unsigned int m_ProcTablePos[3];
+ unsigned int*** m_ProcTable;
+
+ double* m_OrigDiscLines[3];
+ unsigned int m_OrigNumLines[3];
+ unsigned int m_SplitPos[3];
+
+ string PrependRank(string name);
+
+ virtual void DumpOperator2File(string filename);
+ virtual void DumpMaterial2File(string filename);
+ virtual void DumpPEC2File( string filename, unsigned int *range = NULL );
+};
+
+#endif // OPERATOR_MPI_H
diff --git a/openEMS/FDTD/operator_multithread.cpp b/openEMS/FDTD/operator_multithread.cpp
new file mode 100644
index 0000000..9a602a6
--- /dev/null
+++ b/openEMS/FDTD/operator_multithread.cpp
@@ -0,0 +1,203 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_multithread.h"
+#include "engine_multithread.h"
+#include "tools/useful.h"
+
+Operator_Multithread* Operator_Multithread::New(unsigned int numThreads)
+{
+ cout << "Create FDTD operator (compressed SSE + multi-threading)" << endl;
+ Operator_Multithread* op = new Operator_Multithread();
+ op->setNumThreads(numThreads);
+ op->Init();
+ return op;
+}
+
+Operator_Multithread::~Operator_Multithread()
+{
+ Delete();
+}
+
+void Operator_Multithread::setNumThreads( unsigned int numThreads )
+{
+ m_numThreads = numThreads;
+}
+
+Engine* Operator_Multithread::CreateEngine()
+{
+ m_Engine = Engine_Multithread::New(this,m_numThreads);
+ return m_Engine;
+}
+
+Operator_Multithread::Operator_Multithread() : OPERATOR_MULTITHREAD_BASE()
+{
+ m_CalcEC_Start=NULL;
+ m_CalcEC_Stop=NULL;
+
+ m_CalcPEC_Start=NULL;
+ m_CalcPEC_Stop=NULL;
+}
+
+void Operator_Multithread::Init()
+{
+ OPERATOR_MULTITHREAD_BASE::Init();
+
+ m_CalcEC_Start=NULL;
+ m_CalcEC_Stop=NULL;
+
+ m_CalcPEC_Start=NULL;
+ m_CalcPEC_Stop=NULL;
+}
+
+void Operator_Multithread::Delete()
+{
+ m_thread_group.join_all();
+
+ delete m_CalcEC_Start;
+ m_CalcEC_Start=NULL;
+ delete m_CalcEC_Stop;
+ m_CalcEC_Stop=NULL;
+
+ delete m_CalcPEC_Start;
+ m_CalcPEC_Start=NULL;
+ delete m_CalcPEC_Stop;
+ m_CalcPEC_Stop=NULL;
+}
+
+void Operator_Multithread::Reset()
+{
+ Delete();
+ OPERATOR_MULTITHREAD_BASE::Reset();
+}
+
+void Operator_Multithread::CalcStartStopLines(unsigned int &numThreads, vector<unsigned int> &start, vector<unsigned int> &stop) const
+{
+ vector<unsigned int> jpt = AssignJobs2Threads(numLines[0], numThreads, true);
+
+ numThreads = jpt.size();
+
+ start.resize(numThreads);
+ stop.resize(numThreads);
+
+ start.at(0)=0;
+ stop.at(0)=jpt.at(0)-1;
+
+ for (unsigned int n=1; n<numThreads; n++)
+ {
+ start.at(n) = stop.at(n-1)+1;
+ stop.at(n) = start.at(n) + jpt.at(n) - 1;
+ }
+}
+
+int Operator_Multithread::CalcECOperator( DebugFlags debugFlags )
+{
+ if (m_numThreads == 0)
+ m_numThreads = boost::thread::hardware_concurrency();
+
+ vector<unsigned int> m_Start_Lines;
+ vector<unsigned int> m_Stop_Lines;
+ CalcStartStopLines( m_numThreads, m_Start_Lines, m_Stop_Lines );
+
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Multithreaded operator using " << m_numThreads << " threads." << std::endl;
+
+ m_thread_group.join_all();
+ delete m_CalcEC_Start;
+ m_CalcEC_Start = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+ delete m_CalcEC_Stop;
+ m_CalcEC_Stop = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+
+ delete m_CalcPEC_Start;
+ m_CalcPEC_Start = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+ delete m_CalcPEC_Stop;
+ m_CalcPEC_Stop = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+
+ for (unsigned int n=0; n<m_numThreads; n++)
+ {
+ boost::thread *t = new boost::thread( Operator_Thread(this,m_Start_Lines.at(n),m_Stop_Lines.at(n),n) );
+ m_thread_group.add_thread( t );
+ }
+
+ return OPERATOR_MULTITHREAD_BASE::CalcECOperator( debugFlags );
+}
+
+bool Operator_Multithread::Calc_EC()
+{
+ if (CSX==NULL)
+ {
+ cerr << "CartOperator::Calc_EC: CSX not given or invalid!!!" << endl;
+ return false;
+ }
+
+ MainOp->SetPos(0,0,0);
+
+ m_CalcEC_Start->wait();
+
+ m_CalcEC_Stop->wait();
+
+ return true;
+}
+
+bool Operator_Multithread::CalcPEC()
+{
+ m_Nr_PEC[0]=0;
+ m_Nr_PEC[1]=0;
+ m_Nr_PEC[2]=0;
+
+ m_Nr_PEC_thread = new unsigned int[m_numThreads][3];
+
+ m_CalcPEC_Start->wait();
+
+ m_CalcPEC_Stop->wait();
+
+ for (unsigned int t=0; t<m_numThreads; ++t)
+ for (int n=0; n<3; ++n)
+ m_Nr_PEC[n]+=m_Nr_PEC_thread[t][n];
+
+ CalcPEC_Curves();
+
+ delete[] m_Nr_PEC_thread;
+
+ return true;
+}
+
+
+Operator_Thread::Operator_Thread( Operator_Multithread* ptr, unsigned int start, unsigned int stop, unsigned int threadID )
+{
+ m_start=start;
+ m_stop=stop;
+ m_threadID=threadID;
+ m_OpPtr = ptr;
+}
+
+void Operator_Thread::operator()()
+{
+ //************** calculate EC (Calc_EC) ***********************//
+ m_OpPtr->m_CalcEC_Start->wait();
+ m_OpPtr->Calc_EC_Range(m_start,m_stop);
+ m_OpPtr->m_CalcEC_Stop->wait();
+
+ //************** calculate EC (Calc_EC) ***********************//
+ m_OpPtr->m_CalcPEC_Start->wait();
+ for (int n=0; n<3; ++n)
+ m_OpPtr->m_Nr_PEC_thread[m_threadID][n] = 0;
+
+ m_OpPtr->CalcPEC_Range(m_start,m_stop,m_OpPtr->m_Nr_PEC_thread[m_threadID]);
+ m_OpPtr->m_CalcPEC_Stop->wait();
+}
+
diff --git a/openEMS/FDTD/operator_multithread.h b/openEMS/FDTD/operator_multithread.h
new file mode 100644
index 0000000..65f4748
--- /dev/null
+++ b/openEMS/FDTD/operator_multithread.h
@@ -0,0 +1,89 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_MULTITHREAD_H
+#define OPERATOR_MULTITHREAD_H
+
+#include "operator_sse_compressed.h"
+
+#include <boost/thread.hpp>
+
+#ifdef MPI_SUPPORT
+ #define OPERATOR_MULTITHREAD_BASE Operator_MPI
+ #include "operator_mpi.h"
+#else
+ #define OPERATOR_MULTITHREAD_BASE Operator_SSE_Compressed
+#endif
+
+class Operator_Multithread : public OPERATOR_MULTITHREAD_BASE
+{
+ friend class Engine_Multithread;
+ friend class Operator_Thread;
+public:
+ //! Create a new operator
+ static Operator_Multithread* New(unsigned int numThreads = 0);
+ virtual ~Operator_Multithread();
+
+ virtual void setNumThreads( unsigned int numThreads );
+
+ virtual Engine* CreateEngine();
+
+protected:
+ Operator_Multithread();
+ virtual void Init();
+ void Delete();
+ virtual void Reset();
+
+ virtual bool Calc_EC(); //this method is using multi-threading
+
+ unsigned int (*m_Nr_PEC_thread)[3]; //count PEC edges per thread
+ virtual bool CalcPEC(); //this method is using multi-threading
+
+ virtual int CalcECOperator( DebugFlags debugFlags = None );
+
+ //Calc_EC barrier
+ boost::barrier* m_CalcEC_Start;
+ boost::barrier* m_CalcEC_Stop;
+ //CalcPEC barrier
+ boost::barrier* m_CalcPEC_Start;
+ boost::barrier* m_CalcPEC_Stop;
+
+ boost::thread_group m_thread_group;
+ unsigned int m_numThreads; // number of worker threads
+
+ //! Calculate the start/stop lines for the multithreading operator and engine.
+ /*!
+ It depends on the number of threads and number of lines to simulate.
+ This method is also used by the multithreading engine!
+ This method may also reduce the usable number of thread in case of too few lines or otherwise bad utilization.
+ */
+ virtual void CalcStartStopLines(unsigned int &numThreads, vector<unsigned int> &start, vector<unsigned int> &stop) const;
+};
+
+class Operator_Thread
+{
+public:
+ Operator_Thread( Operator_Multithread* ptr, unsigned int start, unsigned int stop, unsigned int threadID );
+ void operator()();
+
+protected:
+ unsigned int m_start, m_stop, m_threadID;
+ Operator_Multithread *m_OpPtr;
+};
+
+
+#endif // OPERATOR_MULTITHREAD_H
diff --git a/openEMS/FDTD/operator_sse.cpp b/openEMS/FDTD/operator_sse.cpp
new file mode 100644
index 0000000..8a1b21b
--- /dev/null
+++ b/openEMS/FDTD/operator_sse.cpp
@@ -0,0 +1,91 @@
+/*
+* Copyright (C) 2010 Sebastian Held (Sebastian.Held@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "engine_sse.h"
+#include "operator_sse.h"
+#include "tools/array_ops.h"
+//#include "processfields.h"
+
+Operator_sse* Operator_sse::New()
+{
+ cout << "Create FDTD operator (SSE)" << endl;
+ Operator_sse* op = new Operator_sse();
+ op->Init();
+ return op;
+}
+
+Operator_sse::Operator_sse() : Operator()
+{
+ f4_vv = 0;
+ f4_vi = 0;
+ f4_iv = 0;
+ f4_ii = 0;
+}
+
+Operator_sse::~Operator_sse()
+{
+ Delete();
+}
+
+Engine* Operator_sse::CreateEngine() const
+{
+ //! create a special sse-engine
+ Engine_sse* eng = Engine_sse::New(this);
+ return eng;
+}
+
+void Operator_sse::Init()
+{
+ Operator::Init();
+ f4_vv = 0;
+ f4_vi = 0;
+ f4_iv = 0;
+ f4_ii = 0;
+}
+
+void Operator_sse::Delete()
+{
+ Delete_N_3DArray_v4sf(f4_vv,numLines);
+ Delete_N_3DArray_v4sf(f4_vi,numLines);
+ Delete_N_3DArray_v4sf(f4_iv,numLines);
+ Delete_N_3DArray_v4sf(f4_ii,numLines);
+ f4_vv = 0;
+ f4_vi = 0;
+ f4_iv = 0;
+ f4_ii = 0;
+}
+
+void Operator_sse::Reset()
+{
+ Delete();
+ Operator::Reset();
+}
+
+
+void Operator_sse::InitOperator()
+{
+ Delete_N_3DArray_v4sf(f4_vv,numLines);
+ Delete_N_3DArray_v4sf(f4_vi,numLines);
+ Delete_N_3DArray_v4sf(f4_iv,numLines);
+ Delete_N_3DArray_v4sf(f4_ii,numLines);
+ f4_vv = Create_N_3DArray_v4sf(numLines);
+ f4_vi = Create_N_3DArray_v4sf(numLines);
+ f4_iv = Create_N_3DArray_v4sf(numLines);
+ f4_ii = Create_N_3DArray_v4sf(numLines);
+
+ numVectors = ceil((double)numLines[2]/4.0);
+}
diff --git a/openEMS/FDTD/operator_sse.h b/openEMS/FDTD/operator_sse.h
new file mode 100644
index 0000000..317ea72
--- /dev/null
+++ b/openEMS/FDTD/operator_sse.h
@@ -0,0 +1,63 @@
+/*
+* Copyright (C) 2010 Sebastian Held (Sebastian.Held@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_SSE_H
+#define OPERATOR_SSE_H
+
+#include "operator.h"
+#include "tools/array_ops.h"
+
+class Operator_sse : public Operator
+{
+ friend class Engine_Interface_SSE_FDTD;
+public:
+ //! Create a new operator
+ static Operator_sse* New();
+ virtual ~Operator_sse();
+
+ virtual Engine* CreateEngine() const;
+
+ inline virtual FDTD_FLOAT GetVV( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return f4_vv[n][x][y][z%numVectors].f[z/numVectors]; }
+ inline virtual FDTD_FLOAT GetVI( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return f4_vi[n][x][y][z%numVectors].f[z/numVectors]; }
+ inline virtual FDTD_FLOAT GetII( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return f4_ii[n][x][y][z%numVectors].f[z/numVectors]; }
+ inline virtual FDTD_FLOAT GetIV( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { return f4_iv[n][x][y][z%numVectors].f[z/numVectors]; }
+
+ inline virtual void SetVV( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { f4_vv[n][x][y][z%numVectors].f[z/numVectors] = value; }
+ inline virtual void SetVI( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { f4_vi[n][x][y][z%numVectors].f[z/numVectors] = value; }
+ inline virtual void SetII( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { f4_ii[n][x][y][z%numVectors].f[z/numVectors] = value; }
+ inline virtual void SetIV( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { f4_iv[n][x][y][z%numVectors].f[z/numVectors] = value; }
+
+protected:
+ //! use New() for creating a new Operator
+ Operator_sse();
+
+ virtual void Init();
+ void Delete();
+ virtual void Reset();
+ virtual void InitOperator();
+
+ unsigned int numVectors;
+
+ // engine/post-proc needs access
+public:
+ f4vector**** f4_vv; //calc new voltage from old voltage
+ f4vector**** f4_vi; //calc new voltage from old current
+ f4vector**** f4_iv; //calc new current from old current
+ f4vector**** f4_ii; //calc new current from old voltage
+};
+
+#endif // OPERATOR_SSE_H
diff --git a/openEMS/FDTD/operator_sse_compressed.cpp b/openEMS/FDTD/operator_sse_compressed.cpp
new file mode 100644
index 0000000..5214892
--- /dev/null
+++ b/openEMS/FDTD/operator_sse_compressed.cpp
@@ -0,0 +1,251 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "operator_sse_compressed.h"
+#include "engine_sse_compressed.h"
+#include "engine_sse.h"
+#include "tools/array_ops.h"
+
+#include <map>
+#include <cstring>
+
+Operator_SSE_Compressed* Operator_SSE_Compressed::New()
+{
+ cout << "Create FDTD operator (compressed SSE)" << endl;
+ Operator_SSE_Compressed* op = new Operator_SSE_Compressed();
+ op->Init();
+ return op;
+}
+
+Operator_SSE_Compressed::Operator_SSE_Compressed() : Operator_sse()
+{
+ m_Op_index = NULL;
+ m_Use_Compression = false;
+}
+
+Operator_SSE_Compressed::~Operator_SSE_Compressed()
+{
+ Delete();
+}
+
+Engine* Operator_SSE_Compressed::CreateEngine() const
+{
+ if (!m_Use_Compression)
+ {
+ //! create a default sse-engine
+ Engine_sse* eng = Engine_sse::New(this);
+ return eng;
+ }
+ Engine_SSE_Compressed* eng = Engine_SSE_Compressed::New(this);
+ return eng;
+}
+
+int Operator_SSE_Compressed::CalcECOperator( DebugFlags debugFlags )
+{
+ int ErrCode = Operator_sse::CalcECOperator( debugFlags );
+ m_Use_Compression = false;
+ m_Use_Compression = CompressOperator();
+
+ return ErrCode;
+}
+
+void Operator_SSE_Compressed::Init()
+{
+ Operator_sse::Init();
+ m_Use_Compression = false;
+ m_Op_index = NULL;
+}
+
+void Operator_SSE_Compressed::Delete()
+{
+ if (m_Op_index)
+ {
+ Delete3DArray<unsigned int>( m_Op_index, numLines );
+ m_Op_index = 0;
+ }
+
+ m_Use_Compression = false;
+ for (int n=0; n<3; n++)
+ {
+ f4_vv_Compressed[n].clear();
+ f4_vi_Compressed[n].clear();
+ f4_iv_Compressed[n].clear();
+ f4_ii_Compressed[n].clear();
+ }
+}
+
+void Operator_SSE_Compressed::Reset()
+{
+ Delete();
+ Operator_sse::Reset();
+}
+
+void Operator_SSE_Compressed::InitOperator()
+{
+ //cleanup compression
+ m_Use_Compression = false;
+ for (int n=0; n<3; n++)
+ {
+ f4_vv_Compressed[n].clear();
+ f4_vi_Compressed[n].clear();
+ f4_iv_Compressed[n].clear();
+ f4_ii_Compressed[n].clear();
+ }
+
+ Operator_sse::InitOperator();
+ m_Op_index = Create3DArray<unsigned int>( numLines );
+}
+
+void Operator_SSE_Compressed::ShowStat() const
+{
+ Operator_sse::ShowStat();
+
+ cout << "SSE compression enabled\t: " << (m_Use_Compression?"yes":"no") << endl;
+ cout << "Unique SSE operators\t: " << f4_vv_Compressed->size() << endl;
+ cout << "-----------------------------------" << endl;
+}
+
+bool Operator_SSE_Compressed::CompressOperator()
+{
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Compressing the FDTD operator... this may take a while..." << endl;
+
+ map<SSE_coeff,unsigned int> lookUpMap;
+
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numVectors; ++pos[2])
+ {
+ f4vector vv[3] = { f4_vv[0][pos[0]][pos[1]][pos[2]], f4_vv[1][pos[0]][pos[1]][pos[2]], f4_vv[2][pos[0]][pos[1]][pos[2]] };
+ f4vector vi[3] = { f4_vi[0][pos[0]][pos[1]][pos[2]], f4_vi[1][pos[0]][pos[1]][pos[2]], f4_vi[2][pos[0]][pos[1]][pos[2]] };
+ f4vector iv[3] = { f4_iv[0][pos[0]][pos[1]][pos[2]], f4_iv[1][pos[0]][pos[1]][pos[2]], f4_iv[2][pos[0]][pos[1]][pos[2]] };
+ f4vector ii[3] = { f4_ii[0][pos[0]][pos[1]][pos[2]], f4_ii[1][pos[0]][pos[1]][pos[2]], f4_ii[2][pos[0]][pos[1]][pos[2]] };
+ SSE_coeff c( vv, vi, iv, ii );
+
+ map<SSE_coeff,unsigned int>::iterator it;
+ it = lookUpMap.find(c);
+ if (it == lookUpMap.end())
+ {
+ // not found -> insert
+ unsigned int index = f4_vv_Compressed[0].size();
+ for (int n=0; n<3; n++)
+ {
+ f4_vv_Compressed[n].push_back( vv[n] );
+ f4_vi_Compressed[n].push_back( vi[n] );
+ f4_iv_Compressed[n].push_back( iv[n] );
+ f4_ii_Compressed[n].push_back( ii[n] );
+ }
+ lookUpMap[c] = index;
+ m_Op_index[pos[0]][pos[1]][pos[2]] = index;
+ }
+ else
+ {
+ // this operator is already in the list
+ unsigned int index = (*it).second;
+ m_Op_index[pos[0]][pos[1]][pos[2]] = index;
+ }
+ }
+ }
+ }
+
+ Delete_N_3DArray_v4sf(f4_vv,numLines);
+ Delete_N_3DArray_v4sf(f4_vi,numLines);
+ Delete_N_3DArray_v4sf(f4_iv,numLines);
+ Delete_N_3DArray_v4sf(f4_ii,numLines);
+ f4_vv = 0;
+ f4_vi = 0;
+ f4_iv = 0;
+ f4_ii = 0;
+
+ return true;
+}
+
+
+
+
+// ----------------------------------------------------------------------------
+
+SSE_coeff::SSE_coeff( f4vector vv[3], f4vector vi[3], f4vector iv[3], f4vector ii[3] )
+{
+ for (int n=0; n<3; n++)
+ {
+ m_vv[n] = vv[n];
+ m_vi[n] = vi[n];
+ m_iv[n] = iv[n];
+ m_ii[n] = ii[n];
+ }
+}
+
+bool SSE_coeff::operator==( const SSE_coeff& other ) const
+{
+ for (int n=0; n<3; n++)
+ {
+ if (memcmp( &(m_vv[n]), &(other.m_vv[n]), sizeof(f4vector) ) != 0) return false;
+ if (memcmp( &(m_vi[n]), &(other.m_vi[n]), sizeof(f4vector) ) != 0) return false;
+ if (memcmp( &(m_iv[n]), &(other.m_iv[n]), sizeof(f4vector) ) != 0) return false;
+ if (memcmp( &(m_ii[n]), &(other.m_ii[n]), sizeof(f4vector) ) != 0) return false;
+ }
+ return true;
+}
+bool SSE_coeff::operator!=( const SSE_coeff& other ) const
+{
+ return !(*this == other);
+}
+bool SSE_coeff::operator<( const SSE_coeff& other ) const
+{
+ for (int n=0; n<3; n++)
+ {
+ for (int c=0; c<4; c++)
+ {
+ if (m_vv[n].f[c] > other.m_vv[n].f[c]) return false;
+ if (m_vv[n].f[c] < other.m_vv[n].f[c]) return true;
+ if (m_vi[n].f[c] > other.m_vi[n].f[c]) return false;
+ if (m_vi[n].f[c] < other.m_vi[n].f[c]) return true;
+ if (m_iv[n].f[c] > other.m_iv[n].f[c]) return false;
+ if (m_iv[n].f[c] < other.m_iv[n].f[c]) return true;
+ if (m_ii[n].f[c] > other.m_ii[n].f[c]) return false;
+ if (m_ii[n].f[c] < other.m_ii[n].f[c]) return true;
+ }
+ }
+ return false;
+}
+
+void SSE_coeff::print( ostream& stream ) const
+{
+ stream << "SSE_coeff: (" << endl;
+ for (int n=0; n<3; n++)
+ {
+ stream << "n=" << n << ":" << endl;
+ stream << "vv=";
+ for (int c=0; c<4; c++)
+ stream << m_vv[n].f[c] << " ";
+ stream << endl << "vi=";
+ for (int c=0; c<4; c++)
+ stream << m_vi[n].f[c] << " ";
+ stream << endl << "iv=";
+ for (int c=0; c<4; c++)
+ stream << m_iv[n].f[c] << " ";
+ stream << endl << "ii=";
+ for (int c=0; c<4; c++)
+ stream << m_ii[n].f[c] << " ";
+ stream << endl;
+ }
+ stream << ")" << endl;
+}
diff --git a/openEMS/FDTD/operator_sse_compressed.h b/openEMS/FDTD/operator_sse_compressed.h
new file mode 100644
index 0000000..5d3454f
--- /dev/null
+++ b/openEMS/FDTD/operator_sse_compressed.h
@@ -0,0 +1,84 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPERATOR_SSE_COMPRESSED_H
+#define OPERATOR_SSE_COMPRESSED_H
+
+#include "operator_sse.h"
+#include "tools/aligned_allocator.h"
+
+class SSE_coeff
+{
+public:
+ SSE_coeff( f4vector vv[3], f4vector vi[3], f4vector iv[3], f4vector ii[3] );
+ bool operator==( const SSE_coeff& ) const;
+ bool operator!=( const SSE_coeff& ) const;
+ bool operator<( const SSE_coeff& ) const;
+ void print( ostream& stream ) const;
+protected:
+ f4vector m_vv[3];
+ f4vector m_vi[3];
+ f4vector m_iv[3];
+ f4vector m_ii[3];
+};
+
+class Operator_SSE_Compressed : public Operator_sse
+{
+public:
+ //! Create a new operator
+ static Operator_SSE_Compressed* New();
+ virtual ~Operator_SSE_Compressed();
+
+ virtual Engine* CreateEngine() const;
+
+ inline virtual FDTD_FLOAT GetVV( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { if (m_Use_Compression) return f4_vv_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors]; else return Operator_sse::GetVV(n,x,y,z);}
+ inline virtual FDTD_FLOAT GetVI( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { if (m_Use_Compression) return f4_vi_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors]; else return Operator_sse::GetVI(n,x,y,z);}
+ inline virtual FDTD_FLOAT GetII( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { if (m_Use_Compression) return f4_ii_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors]; else return Operator_sse::GetII(n,x,y,z);}
+ inline virtual FDTD_FLOAT GetIV( unsigned int n, unsigned int x, unsigned int y, unsigned int z ) const { if (m_Use_Compression) return f4_iv_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors]; else return Operator_sse::GetIV(n,x,y,z);}
+
+ inline virtual void SetVV( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { if (m_Use_Compression) f4_vv_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors] = value; else Operator_sse::SetVV(n,x,y,z,value);}
+ inline virtual void SetVI( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { if (m_Use_Compression) f4_vi_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors] = value; else Operator_sse::SetVI(n,x,y,z,value);}
+ inline virtual void SetII( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { if (m_Use_Compression) f4_ii_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors] = value; else Operator_sse::SetII(n,x,y,z,value);}
+ inline virtual void SetIV( unsigned int n, unsigned int x, unsigned int y, unsigned int z, FDTD_FLOAT value ) { if (m_Use_Compression) f4_iv_Compressed[n][m_Op_index[x][y][z%numVectors]].f[z/numVectors] = value; else Operator_sse::SetIV(n,x,y,z,value);}
+
+ virtual void ShowStat() const;
+
+ bool CompressOperator();
+
+protected:
+ Operator_SSE_Compressed();
+
+ bool m_Use_Compression;
+
+ virtual void Init();
+ void Delete();
+ virtual void Reset();
+ virtual void InitOperator();
+
+ virtual int CalcECOperator( DebugFlags debugFlags = None );
+
+ // engine needs access
+public:
+ unsigned int*** m_Op_index;
+ vector<f4vector,aligned_allocator<f4vector> > f4_vv_Compressed[3]; //!< coefficient: calc new voltage from old voltage
+ vector<f4vector,aligned_allocator<f4vector> > f4_vi_Compressed[3]; //!< coefficient: calc new voltage from old current
+ vector<f4vector,aligned_allocator<f4vector> > f4_iv_Compressed[3]; //!< coefficient: calc new current from old voltage
+ vector<f4vector,aligned_allocator<f4vector> > f4_ii_Compressed[3]; //!< coefficient: calc new current from old current
+
+};
+
+#endif // OPERATOR_SSE_Compressed_H
diff --git a/openEMS/INSTALL b/openEMS/INSTALL
new file mode 100644
index 0000000..6678190
--- /dev/null
+++ b/openEMS/INSTALL
@@ -0,0 +1,27 @@
+Install instructions for openEMS:
+---------------------------------------------
+
+1) Prerequirements:
+ openEMS relies on a number of libraries:
+ - CSXCAD (http://openEMS.de)
+ - fparser (http://warp.povusers.org/FunctionParser/)
+ - tinyxml (http://www.grinninglizard.com/tinyxml/)
+ - hdf5 (http://www.hdfgroup.org/HDF5/)
+ - vtk (http://www.vtk.org/)
+ - boost (http://www.boost.org/)
+ - cgal (http://www.cgal.org/)
+ - zlib (http://www.zlib.net/)
+
+2) Build:
+ - change directory to openEMS
+ - build:
+ mkdir build
+ cd build
+ cmake .. -DCMAKE_INSTALL_PREFIX=<path/to/install/> -DFPARSER_ROOT_DIR=<path/to/fparser> -DCSXCAD_ROOT_DIR=<path/to/CSXCAD>
+ make
+ make install (may require root)
+
+ Note:
+ - all path informations may be stored in a localConfig.cmake
+ - the default "prefix" is /usr/local
+
diff --git a/openEMS/NEWS b/openEMS/NEWS
new file mode 100644
index 0000000..769a73b
--- /dev/null
+++ b/openEMS/NEWS
@@ -0,0 +1,40 @@
+Summary of most noticeable changes for version 0.0.31:
+-----------------------------------------------------
+ - nf2ff: calculate circular polarization
+ - improvements to calcPort
+ - allow 1D and 2D lumped ports
+ - improvements to SAR calculations
+ - curve primitives and port fixes & improvements
+ - FDTD operator now supports different material averaging methods
+ - support for full multi-polar Lorentz/Drude/Debye dispersive material types
+ - new ports for waveguides (rectangular and circular waveguides)
+ - improved PEC debugging
+ - improvements/simplifications in plotting far-fields (thanks to Stefan)
+ - new tutorials and examples
+ - many fixes and updates
+
+Summary of most noticeable changes for version 0.0.30:
+-----------------------------------------------------
+ - meshing improved with new detect edges and new smoothing capabilities
+ - new calcPort function for simplified port analysis
+ - cylindrical mesh improvement by considering 360° rotation symmetry
+ - support for harminv on all platforms
+ - update to auto-regressive model for voltage/current probes
+ - new SAR calculation options, incl. 1g/10g averaging
+ - support for a new primitive: polyhedron
+ - CAD import: STL/PLY surface solids supported (matlab: ImportSTL / ImportPLY)
+ - CAD export: STL/PLY export (using AppCSXCAD)
+ - lot of minor fixes and updates
+
+Summary of most noticeable changes for version 0.0.29:
+-----------------------------------------------------
+ - Cylindrical sub-grids now fully support alpha-graded meshes
+ - Property Electrode has been renamed to Excitation
+ This doesn't have any effect on the Matlab/Octave interface,
+ but old *.xml files cannot be run with a current openEMS/CSXCAD version.
+ - Overall memory usage reduced during pre-processing
+ - New excitation: Total-field/scattered field (TFSF)
+ - New tutorial on radar cross section on a metallic sphere using the TFSF excitation
+ - official support for 64-bit windows version
+ - check for engine extensions MPI compatibility
+ - CSXCAD: support for new CSXGeomPlot export options (see help for more infos)
diff --git a/openEMS/README b/openEMS/README
new file mode 100644
index 0000000..fdfd137
--- /dev/null
+++ b/openEMS/README
@@ -0,0 +1,19 @@
+*
+* openEMS - a free and open electromagnetic field solver
+*
+* Copyright (C) 2010-2015 Thorsten Liebig
+*
+
+openEMS is licensed under the terms of the GPLv3, see <http://www.gnu.org/licenses/>.
+
+
+Website: http://openems.de
+Forum: http://openems.de/forum/
+Tutorials: http://openems.de/index.php/Tutorials
+
+
+To use openEMS from Matlab or Octave, you need to include the <openEMS-install-folder>/matlab folder in the respective environment:
+> addpath( '<openEMS-install-folder>/matlab' );
+
+To verify the correct installation follow the instructions at:
+http://openems.de/index.php/Tutorial:_First_Steps
diff --git a/openEMS/TESTSUITE/combinedtests/Coax.m b/openEMS/TESTSUITE/combinedtests/Coax.m
new file mode 100644
index 0000000..18ed5ab
--- /dev/null
+++ b/openEMS/TESTSUITE/combinedtests/Coax.m
@@ -0,0 +1,158 @@
+function pass = Coax( openEMS_options, options )
+
+physical_constants;
+
+
+ENABLE_PLOTS = 1;
+CLEANUP = 1; % if enabled and result is PASS, remove simulation folder
+STOP_IF_FAILED = 1; % if enabled and result is FAILED, stop with error
+SILENT = 0; % 0=show openEMS output
+
+if nargin < 1
+ openEMS_options = '';
+end
+if nargin < 2
+ options = '';
+end
+if any(strcmp( options, 'run_testsuite' ))
+ ENABLE_PLOTS = 0;
+ STOP_IF_FAILED = 0;
+ SILENT = 1;
+end
+
+% LIMITS
+upper_error = 0.03; % max +3%
+lower_error = 0.01; % max -1%
+
+% structure
+length = 1000;
+coax_rad_i = 100;
+coax_rad_ai = 230;
+coax_rad_aa = 240;
+mesh_res = [5 5 5];
+f_start = 0;
+f_stop = 1e9;
+
+Sim_Path = 'tmp_Coax';
+Sim_CSX = 'coax.xml';
+
+[status,message,messageid]=rmdir(Sim_Path,'s');
+[status,message,messageid]=mkdir(Sim_Path);
+
+%setup FDTD parameter
+FDTD = InitFDTD(5000,1e-6);
+FDTD = SetGaussExcite(FDTD,0,f_stop);
+FDTD = SetBoundaryCond(FDTD,{'PEC','PEC','PEC','PEC','PEC','PML_8'});
+
+%setup CSXCAD geometry
+CSX = InitCSX();
+mesh.x = -2.5*mesh_res(1)-coax_rad_aa : mesh_res(1) : coax_rad_aa+2.5*mesh_res(1);
+mesh.y = mesh.x;
+mesh.z = 0 : mesh_res(3) : length;
+mesh.z = linspace(0,length,numel(mesh.z));
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+% create a perfect electric conductor
+CSX = AddMetal(CSX,'PEC');
+
+%%% coax
+start = [0, 0 , 0];stop = [0, 0 , length];
+CSX = AddCylinder(CSX,'PEC',1 ,start,stop,coax_rad_i); % inner conductor
+CSX = AddCylindricalShell(CSX,'PEC',0 ,start,stop,0.5*(coax_rad_aa+coax_rad_ai),(coax_rad_aa-coax_rad_ai)); % outer conductor
+
+%%% add excitation
+start(3) = 0; stop(3)=mesh_res(1)/2;
+CSX = AddExcitation(CSX,'excite',0,[1 1 0]);
+weight{1} = '(x)/(x*x+y*y)';
+weight{2} = 'y/pow(rho,2)';
+weight{3} = '0';
+CSX = SetExcitationWeight(CSX, 'excite', weight );
+CSX = AddCylindricalShell(CSX,'excite',0 ,start,stop,0.5*(coax_rad_i+coax_rad_ai),(coax_rad_ai-coax_rad_i));
+
+% %dump
+% CSX = AddDump(CSX,'Et_',0,2);
+% start = [mesh.x(1) , 0 , mesh.z(1)];
+% stop = [mesh.x(end) , 0 , mesh.z(end)];
+% CSX = AddBox(CSX,'Et_',0 , start,stop);
+%
+% CSX = AddDump(CSX,'Ht_',1,2);
+% CSX = AddBox(CSX,'Ht_',0,start,stop);
+
+%voltage calc
+CSX = AddProbe(CSX,'ut1',0);
+start = [ coax_rad_i 0 length/2 ];stop = [ coax_rad_ai 0 length/2 ];
+CSX = AddBox(CSX,'ut1', 0 ,start,stop);
+
+%current calc
+CSX = AddProbe(CSX,'it1',1);
+% mid = 0.5*(coax_rad_i+coax_rad_ai);
+mid = coax_rad_i+3*mesh_res(1);
+start = [ -mid -mid length/2 ];stop = [ mid mid length/2 ];
+CSX = AddBox(CSX,'it1', 0 ,start,stop);
+
+%Write openEMS compatible xml-file
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+% show structure
+% CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+% run openEMS
+folder = fileparts( mfilename('fullpath') );
+Settings.LogFile = [folder '/' Sim_Path '/openEMS.log'];
+Settings.Silent = SILENT;
+RunOpenEMS( Sim_Path, Sim_CSX, openEMS_options, Settings );
+UI = ReadUI( {[Sim_Path '/ut1'], [Sim_Path '/it1']} );
+
+
+%
+% analysis
+%
+
+f = UI.FD{2}.f;
+u = UI.FD{1}.val;
+i = UI.FD{2}.val;
+
+f_idx_start = interp1( f, 1:numel(f), f_start, 'nearest' );
+f_idx_stop = interp1( f, 1:numel(f), f_stop, 'nearest' );
+f = f(f_idx_start:f_idx_stop);
+u = u(f_idx_start:f_idx_stop);
+i = i(f_idx_start:f_idx_stop);
+
+Z = abs(u./i);
+
+% analytic formular for characteristic impedance
+Z0 = sqrt(MUE0/EPS0) * log(coax_rad_ai/coax_rad_i) / (2*pi);
+upper_limit = Z0 * (1+upper_error);
+lower_limit = Z0 * (1-lower_error);
+
+if ENABLE_PLOTS
+ upper = upper_limit * ones(1,size(Z,2));
+ lower = lower_limit * ones(1,size(Z,2));
+ Z0_plot = Z0 * ones(1,size(Z,2));
+ figure
+ plot(f/1e9,[Z;upper;lower])
+ hold on
+ plot(f/1e9,Z0_plot,'m-.','LineWidth',2)
+ hold off
+ xlabel('Frequency (GHz)')
+ ylabel('Impedance (Ohm)')
+ legend( {'sim', 'upper limit', 'lower limit', 'theoretical'} );
+end
+
+pass = check_limits( Z, upper_limit, lower_limit );
+if pass
+ disp( 'combinedtests/Coax.m (characteristic impedance): pass' );
+else
+ disp( 'combinedtests/Coax.m (characteristic impedance): * FAILED *' );
+end
+
+
+
+
+if pass && CLEANUP
+ rmdir( Sim_Path, 's' );
+end
+if ~pass && STOP_IF_FAILED
+ error 'test failed';
+end
+
diff --git a/openEMS/TESTSUITE/combinedtests/README b/openEMS/TESTSUITE/combinedtests/README
new file mode 100644
index 0000000..cc29c5b
--- /dev/null
+++ b/openEMS/TESTSUITE/combinedtests/README
@@ -0,0 +1,3 @@
+#
+# These scripts test the full simulator (not single features)
+# \ No newline at end of file
diff --git a/openEMS/TESTSUITE/combinedtests/cavity.m b/openEMS/TESTSUITE/combinedtests/cavity.m
new file mode 100644
index 0000000..4123a81
--- /dev/null
+++ b/openEMS/TESTSUITE/combinedtests/cavity.m
@@ -0,0 +1,229 @@
+function pass = cavity( openEMS_options, options )
+
+physical_constants;
+
+
+ENABLE_PLOTS = 1;
+CLEANUP = 1; % if enabled and result is PASS, remove simulation folder
+STOP_IF_FAILED = 1; % if enabled and result is FAILED, stop with error
+SILENT = 0; % 0=show openEMS output
+
+if nargin < 1
+ openEMS_options = '';
+end
+if nargin < 2
+ options = '';
+end
+if any(strcmp( options, 'run_testsuite' ))
+ ENABLE_PLOTS = 0;
+ STOP_IF_FAILED = 0;
+ SILENT = 1;
+end
+
+% LIMITS - inside
+lower_rel_limit = 1.3e-3; % -0.13%
+upper_rel_limit = 1.3e-3; % +0.13%
+lower_rel_limit_TM = 2.5e-3; % -0.25%
+upper_rel_limit_TM = 0; % +0%
+min_rel_amplitude = 0.6; % 60%
+min_rel_amplitude_TM = 0.27; % 27%
+
+% LIMITS - outside
+outer_rel_limit = 0.02;
+max_rel_amplitude = 0.17;
+
+
+% structure
+a = 5e-2;
+b = 2e-2;
+d = 6e-2;
+if ~((b<a) && (a<d))
+ error 'correct the dimensions of the cavity'
+end
+
+f_start = 1e9;
+f_stop = 10e9;
+
+Sim_Path = 'tmp_cavity';
+Sim_CSX = 'cavity.xml';
+
+[status,message,messageid]=rmdir(Sim_Path,'s');
+[status,message,messageid]=mkdir(Sim_Path);
+
+%setup FDTD parameter
+FDTD = InitFDTD( 20000,1e-6 );
+FDTD = SetGaussExcite(FDTD,(f_stop-f_start)/2,(f_stop-f_start)/2);
+BC = [0 0 0 0 0 0]; % PEC boundaries
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%setup CSXCAD geometry
+CSX = InitCSX();
+% grid_res = 2e-3;
+% mesh.x = 0:grid_res:a; %linspace(0,a,25);
+% mesh.y = 0:grid_res:b; %linspace(0,b,25);
+% mesh.z = 0:grid_res:d; %linspace(0,d,25);
+mesh.x = linspace(0,a,26);
+mesh.y = linspace(0,b,11);
+mesh.z = linspace(0,d,32);
+CSX = DefineRectGrid(CSX, 1,mesh);
+
+% excitation
+CSX = AddExcitation(CSX,'excite1',0,[1 1 1]);
+p(1,1) = mesh.x(floor(end*2/3));
+p(2,1) = mesh.y(floor(end*2/3));
+p(3,1) = mesh.z(floor(end*2/3));
+p(1,2) = mesh.x(floor(end*2/3)+1);
+p(2,2) = mesh.y(floor(end*2/3)+1);
+p(3,2) = mesh.z(floor(end*2/3)+1);
+CSX = AddCurve( CSX, 'excite1', 0, p );
+
+%dump
+% CSX = AddDump(CSX,'Et_',0,2);
+% pos1 = [mesh.x(1) mesh.y(1) mesh.z(1)];
+% pos2 = [mesh.x(end) mesh.y(end) mesh.z(end)];
+% CSX = AddBox(CSX,'Et_',0 , pos1,pos2);
+
+% %dump
+% CSX = AddDump(CSX,'Et2_',0,2);
+% pos1 = [mesh.x(1) mesh.y(1) mesh.z(1)];
+% pos2 = [mesh.x(end) mesh.y(1) mesh.z(end)];
+% CSX = AddBox(CSX,'Et2_',0 , pos1,pos2);
+%
+% %dump
+% CSX = AddDump(CSX,'Et3_',0,2);
+% pos1 = [mesh.x(1) mesh.y(end-1) mesh.z(1)];
+% pos2 = [mesh.x(end) mesh.y(end-1) mesh.z(end)];
+% CSX = AddBox(CSX,'Et3_',0 , pos1,pos2);
+
+%voltage calc
+CSX = AddProbe(CSX,'ut1x',0);
+pos1 = [mesh.x(floor(end/4)) mesh.y(floor(end/2)) mesh.z(floor(end/5))];
+pos2 = [mesh.x(floor(end/4)+1) mesh.y(floor(end/2)) mesh.z(floor(end/5))];
+CSX = AddBox(CSX,'ut1x', 0 ,pos1,pos2);
+
+CSX = AddProbe(CSX,'ut1y',0);
+pos1 = [mesh.x(floor(end/4)) mesh.y(floor(end/2)) mesh.z(floor(end/5))];
+pos2 = [mesh.x(floor(end/4)) mesh.y(floor(end/2)+1) mesh.z(floor(end/5))];
+CSX = AddBox(CSX,'ut1y', 0 ,pos1,pos2);
+
+CSX = AddProbe(CSX,'ut1z',0);
+pos1 = [mesh.x(floor(end/2)) mesh.y(floor(end/2)) mesh.z(floor(end/5))];
+pos2 = [mesh.x(floor(end/2)) mesh.y(floor(end/2)) mesh.z(floor(end/5)+1)];
+CSX = AddBox(CSX,'ut1z', 0 ,pos1,pos2);
+
+%Write openEMS compatible xml-file
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+% run openEMS
+folder = fileparts( mfilename('fullpath') );
+Settings.LogFile = [folder '/' Sim_Path '/openEMS.log'];
+Settings.Silent = SILENT;
+RunOpenEMS( Sim_Path, Sim_CSX, openEMS_options, Settings );
+UI = ReadUI( {[Sim_Path '/ut1x'], [Sim_Path '/ut1y'], [Sim_Path '/ut1z']} );
+
+
+
+%
+% analysis
+%
+
+% remove excitation from time series
+t_start = 7e-10; % FIXME to be calculated
+t_idx_start = interp1( UI.TD{1}.t, 1:numel(UI.TD{1}.t), t_start, 'nearest' );
+for n=1:numel(UI.TD)
+ UI.TD{n}.t = UI.TD{n}.t(t_idx_start:end);
+ UI.TD{n}.val = UI.TD{n}.val(t_idx_start:end);
+ [UI.FD{n}.f,UI.FD{n}.val] = FFT_time2freq( UI.TD{n}.t, UI.TD{n}.val );
+end
+
+
+f = UI.FD{1}.f;
+ux = UI.FD{1}.val;
+uy = UI.FD{2}.val;
+uz = UI.FD{3}.val;
+
+f_idx_start = interp1( f, 1:numel(f), f_start, 'nearest' );
+f_idx_stop = interp1( f, 1:numel(f), f_stop, 'nearest' );
+f = f(f_idx_start:f_idx_stop);
+ux = ux(f_idx_start:f_idx_stop);
+uy = uy(f_idx_start:f_idx_stop);
+uz = uz(f_idx_start:f_idx_stop);
+
+% analytic formula for resonant wavenumber
+k = @(m,n,l) sqrt( (m*pi/a)^2 + (n*pi/b)^2 + (l*pi/d)^2 );
+f_TE101 = c0/(2*pi) * k(1,0,1);
+f_TE102 = c0/(2*pi) * k(1,0,2);
+f_TE201 = c0/(2*pi) * k(2,0,1);
+f_TE202 = c0/(2*pi) * k(2,0,2);
+f_TM110 = c0/(2*pi) * k(1,1,0);
+f_TM111 = c0/(2*pi) * k(1,1,1);
+
+f_TE = [f_TE101 f_TE102 f_TE201 f_TE202];
+f_TM = [f_TM110 f_TM111];
+
+% calculate frequency limits
+temp = [f_start f_TE f_stop];
+f_outer1 = [];
+f_outer2 = [];
+for n=1:numel(temp)-1
+ f_outer1 = [f_outer1 temp(n) .* (1+outer_rel_limit)];
+ f_outer2 = [f_outer2 temp(n+1) .* (1-outer_rel_limit)];
+end
+
+temp = [f_start f_TM f_stop];
+f_outer1_TM = [];
+f_outer2_TM = [];
+for n=1:numel(temp)-1
+ f_outer1_TM = [f_outer1_TM temp(n) .* (1+outer_rel_limit)];
+ f_outer2_TM = [f_outer2_TM temp(n+1) .* (1-outer_rel_limit)];
+end
+
+
+if ENABLE_PLOTS
+ figure
+ plot(f/1e9,abs(uy))
+ max1 = max(abs(uy));
+ hold on
+ plot( repmat(f_TE,2,1)/1e9, repmat([0; max1],1,numel(f_TE)), 'm-.', 'LineWidth', 2 )
+ plot( (repmat(f_TE,2,1) .* repmat(1-lower_rel_limit,2,numel(f_TE)))/1e9, repmat([0; max1],1,numel(f_TE)), 'r-', 'LineWidth', 1 )
+ plot( (repmat(f_TE,2,1) .* repmat(1+upper_rel_limit,2,numel(f_TE)))/1e9, repmat([0; max1],1,numel(f_TE)), 'r-', 'LineWidth', 1 )
+ plot( (repmat(f_TE,2,1) .* repmat([1-outer_rel_limit;1+outer_rel_limit],1,numel(f_TE)))/1e9, repmat(max1*min_rel_amplitude,2,numel(f_TE)), 'r-', 'LineWidth', 1 ) % freq limits
+ plot( [f_outer1;f_outer2]/1e9, repmat(max1*max_rel_amplitude,2,numel(f_outer1)), 'g-', 'LineWidth', 1 ) % amplitude limits
+ xlabel('Frequency (GHz)')
+ legend( {'u_y','theoretical'} )
+ title( 'TE-modes' )
+
+ figure
+ plot(f/1e9,abs(uz))
+ max1 = max(abs(uz));
+ hold on
+ plot( repmat(f_TM,2,1)/1e9, repmat([0; max1],1,numel(f_TM)), 'm-.', 'LineWidth', 2 )
+ plot( (repmat(f_TM,2,1) .* repmat(1-lower_rel_limit_TM,2,numel(f_TM)))/1e9, repmat([0; max1],1,numel(f_TM)), 'r-', 'LineWidth', 1 )
+ plot( (repmat(f_TM,2,1) .* repmat(1+upper_rel_limit_TM,2,numel(f_TM)))/1e9, repmat([0; max1],1,numel(f_TM)), 'r-', 'LineWidth', 1 )
+ plot( (repmat(f_TM,2,1) .* repmat([1-lower_rel_limit_TM;1+upper_rel_limit_TM],1,numel(f_TM)))/1e9, repmat(max1*min_rel_amplitude_TM,2,numel(f_TM)), 'r-', 'LineWidth', 1 ) % freq limits
+ plot( [f_outer1_TM;f_outer2_TM]/1e9, repmat(max1*max_rel_amplitude,2,numel(f_outer1_TM)), 'g-', 'LineWidth', 1 ) % amplitude limits
+ xlabel('Frequency (GHz)')
+ legend( {'u_z','theoretical'} )
+ title( 'TM-modes' )
+end
+
+pass1 = check_frequency( f, abs(uy), f_TE*(1+upper_rel_limit), f_TE*(1-lower_rel_limit), min_rel_amplitude, 'inside' );
+pass2 = check_frequency( f, abs(uz), f_TM*(1+upper_rel_limit_TM), f_TM*(1-lower_rel_limit_TM), min_rel_amplitude_TM, 'inside' );
+pass3 = check_frequency( f, abs(uy), f_outer2, f_outer1, max_rel_amplitude, 'outside' );
+pass4 = check_frequency( f, abs(uz), f_outer2_TM, f_outer1_TM, max_rel_amplitude, 'outside' );
+pass = pass1 && pass2 && pass3 && pass4;
+if pass
+ disp( 'combinedtests/cavity.m (resonance frequency): pass' );
+else
+ disp( 'combinedtests/cavity.m (resonance frequency): * FAILED *' );
+end
+
+
+
+
+if pass && CLEANUP
+ rmdir( Sim_Path, 's' );
+end
+if ~pass && STOP_IF_FAILED
+ error 'test failed';
+end
diff --git a/openEMS/TESTSUITE/enginetests/cavity.m b/openEMS/TESTSUITE/enginetests/cavity.m
new file mode 100644
index 0000000..03976fa
--- /dev/null
+++ b/openEMS/TESTSUITE/enginetests/cavity.m
@@ -0,0 +1,190 @@
+function pass = cavity( openEMS_options, options )
+%pass = cavity( openEMS_options, options )
+%
+% Checks, if different engines produces identical results
+
+CLEANUP = 1; % if enabled and result is PASS, remove simulation folder
+STOP_IF_FAILED = 1; % if enabled and result is FAILED, stop with error
+global ENABLE_PLOTS;
+ENABLE_PLOTS = 1;
+SILENT = 0; % 0=show openEMS output
+
+if nargin < 1
+ openEMS_options = '';
+end
+if nargin < 2
+ options = '';
+end
+if any(strcmp( options, 'run_testsuite' ))
+ ENABLE_PLOTS = 0;
+ STOP_IF_FAILED = 0;
+ SILENT = 1;
+end
+% clean openEMS_options
+openEMS_options = regexprep( openEMS_options, '--engine=\w+', '' );
+
+engines = {'--engine=basic' '--engine=sse' '--engine=sse-compressed' '--engine=multithreaded'};
+% engines = [engines {'--engine=sse-compressed-linear' '--engine=multithreaded-linear'}];
+
+global Sim_Path Sim_CSX
+Sim_Path = 'tmp_cavity';
+Sim_CSX = 'cavity.xml';
+
+for n=1:numel(engines)
+ result{n} = sim( [engines{n} ' ' openEMS_options], SILENT );
+end
+
+pass = compare( result, SILENT );
+
+if pass
+ disp( 'enginetests/cavity.m (engine comparison): pass' );
+else
+ disp( 'enginetests/cavity.m (engine comparison): * FAILED *' );
+end
+
+if pass && CLEANUP
+ rmdir( Sim_Path, 's' );
+end
+if ~pass && STOP_IF_FAILED
+ error 'test failed'
+end
+
+return
+
+
+function result = sim( openEMS_options, SILENT )
+global Sim_Path Sim_CSX
+physical_constants;
+
+% structure
+a = 5e-2;
+b = 2e-2;
+d = 6e-2;
+if ~((b<a) && (a<d))
+ error 'correct the dimensions of the cavity'
+end
+
+f_start = 1e9;
+f_stop = 10e9;
+
+% prepare simulation dir
+[status,message,messageid] = rmdir(Sim_Path,'s');
+[status,message,messageid] = mkdir(Sim_Path);
+
+% setup FDTD parameter
+FDTD = InitFDTD( 1000, 0 );
+FDTD = SetGaussExcite(FDTD,(f_stop-f_start)/2,(f_stop-f_start)/2);
+BC = {'MUR' 'PML_8' 'PMC' 'PEC' 'PEC' 'PEC'}; % boundaries
+FDTD = SetBoundaryCond(FDTD,BC);
+
+% setup CSXCAD geometry
+CSX = InitCSX();
+mesh.x = linspace(0,a,27);
+mesh.y = linspace(0,b,11);
+mesh.z = linspace(0,d,33);
+CSX = DefineRectGrid(CSX, 1,mesh);
+
+% excitation
+CSX = AddExcitation(CSX,'excite1',0,[1 1 1]);
+p(1,1) = mesh.x(floor(end*2/3));
+p(2,1) = mesh.y(floor(end*2/3));
+p(3,1) = mesh.z(floor(end*2/3));
+p(1,2) = mesh.x(floor(end*2/3)+1);
+p(2,2) = mesh.y(floor(end*2/3)+1);
+p(3,2) = mesh.z(floor(end*2/3)+1);
+CSX = AddCurve( CSX, 'excite1', 0, p );
+
+% probes
+CSX = AddProbe( CSX, 'E_probe', 2 );
+p(1,1) = mesh.x(floor(end*1/3));
+p(2,1) = mesh.y(floor(end*1/3));
+p(3,1) = mesh.z(floor(end*1/3));
+CSX = AddPoint( CSX, 'E_probe', 0, p );
+CSX = AddProbe( CSX, 'H_probe', 3 );
+CSX = AddPoint( CSX, 'H_probe', 0, p );
+
+% material
+CSX = AddMaterial( CSX, 'RO4350B', 'Epsilon', 3.66 );
+start = [mesh.x(3) mesh.y(3) mesh.z(3)];
+stop = [mesh.x(5) mesh.y(4) mesh.z(6)];
+CSX = AddBox( CSX, 'RO4350B', 100, start, stop );
+
+% dump
+CSX = AddDump( CSX, 'Et', 'DumpType', 0, 'DumpMode', 0, 'FileType', 1 ); % hdf5 E-field dump without interpolation
+pos1 = [mesh.x(1) mesh.y(1) mesh.z(1)];
+pos2 = [mesh.x(end) mesh.y(end) mesh.z(end)];
+CSX = AddBox( CSX, 'Et', 0, pos1, pos2 );
+
+% dump
+CSX = AddDump( CSX, 'Ht', 'DumpType', 1, 'DumpMode', 0, 'FileType', 1 ); % hdf5 H-field dump without interpolation
+pos1 = [mesh.x(1) mesh.y(1) mesh.z(1)]; % should be half a cell more than now
+pos2 = [mesh.x(end) mesh.y(end) mesh.z(end)]; % should be half a cell less than now
+CSX = AddBox( CSX, 'Ht', 0, pos1, pos2 );
+
+% Write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+% cd to working dir and run openEMS
+folder = fileparts( mfilename('fullpath') );
+Settings.LogFile = [folder '/' Sim_Path '/openEMS.log'];
+Settings.Silent = SILENT;
+RunOpenEMS( Sim_Path, Sim_CSX, openEMS_options, Settings );
+
+% collect result
+E.mesh = ReadHDF5Mesh( [Sim_Path '/Et.h5'] );
+E.data = ReadHDF5FieldData( [Sim_Path '/Et.h5'] );
+H.mesh = ReadHDF5Mesh( [Sim_Path '/Ht.h5'] );
+H.data = ReadHDF5FieldData( [Sim_Path '/Ht.h5'] );
+result.E = E;
+result.H = H;
+result.probes = ReadUI( {'E_probe','H_probe'}, Sim_Path );
+
+
+
+function pass = compare( results, SILENT )
+pass = 0;
+% n=1: reference simulation
+for n=2:numel(results)
+ % iterate over all simulations
+ EHfields = {'E','H'};
+ for m=1:numel(EHfields)
+ % iterate over all fields (E, H)
+ EHfield = EHfields{m};
+ for o=1:numel(results{1}.(EHfield).data.TD.values)
+ % iterate over all timesteps
+ cmp_result = results{1}.(EHfield).data.TD.values{o} ~= results{n}.(EHfield).data.TD.values{o};
+ if any(cmp_result(:))
+ disp( ['compare error: n=' num2str(n) ' field=' EHfield ' timestep:' num2str(o) '=' results{1}.(EHfield).data.names{o}] );
+ disp( ' coords:' );
+ find( results{1}.(EHfield).data.TD.values{o} ~= results{n}.(EHfield).data.TD.values{o} )
+ return
+ end
+ end
+ end
+ if ~SILENT
+ disp( ['simulation ' num2str(n) ' is identical to simulation 1'] );
+ end
+end
+
+global ENABLE_PLOTS;
+if ENABLE_PLOTS
+ figure
+ l = {};
+ for n=1:numel(results)
+ plot( results{n}.probes.TD{1}.t, results{n}.probes.TD{1}.val );
+ hold all
+ l = [l ['sim ' num2str(n)]];
+ end
+ legend( l );
+
+ figure
+ l = {};
+ for n=1:numel(results)
+ plot( results{n}.probes.TD{2}.t, results{n}.probes.TD{2}.val );
+ hold all
+ l = [l ['sim ' num2str(n)]];
+ end
+ legend( l );
+end
+
+pass = 1;
diff --git a/openEMS/TESTSUITE/helperscripts/check_frequency.m b/openEMS/TESTSUITE/helperscripts/check_frequency.m
new file mode 100644
index 0000000..33a7cca
--- /dev/null
+++ b/openEMS/TESTSUITE/helperscripts/check_frequency.m
@@ -0,0 +1,31 @@
+function pass = check_frequency( f, val, f_upper, f_lower, rel_amplitude, type )
+
+pass = true;
+max1 = max(val);
+
+if numel(f_upper) ~= numel(f_lower)
+ error 'inconsistant vectors'
+end
+
+for n=1:numel(f_upper)
+ f1 = f_lower(n);
+ f2 = f_upper(n);
+ f1_idx = interp1( f, 1:numel(f), f1, 'nearest' );
+% if f(f1_idx) < f1, f1_idx = f1_idx + 1; end
+ f2_idx = interp1( f, 1:numel(f), f2, 'nearest' );
+% if f(f2_idx) > f2, f2_idx = f2_idx - 1; end
+
+ if strcmp( type, 'inside' )
+ if max( val(f1_idx:f2_idx) ) < max1 * rel_amplitude
+ pass = false;
+ return
+ end
+ elseif strcmp( type, 'outside' )
+ if max( val(f1_idx:f2_idx) ) > max1 * rel_amplitude
+ pass = false;
+ return
+ end
+ else
+ error 'unsupported operation'
+ end
+end
diff --git a/openEMS/TESTSUITE/helperscripts/check_limits.m b/openEMS/TESTSUITE/helperscripts/check_limits.m
new file mode 100644
index 0000000..c1cba3d
--- /dev/null
+++ b/openEMS/TESTSUITE/helperscripts/check_limits.m
@@ -0,0 +1,22 @@
+function pass = check_limits( Z, upper_limit, lower_limit )
+
+% make row vector
+if size(Z,1) ~= 1
+ Z = Z.';
+end
+
+if numel(upper_limit) == 1
+ upper_limit = upper_limit * ones(1,size(Z,2));
+end
+if numel(lower_limit) == 1
+ lower_limit = lower_limit * ones(1,size(Z,2));
+end
+
+
+pass = 1;
+if any( Z > upper_limit )
+ pass = 0;
+end
+if any( Z < lower_limit )
+ pass = 0;
+end
diff --git a/openEMS/TESTSUITE/probes/fieldprobes.m b/openEMS/TESTSUITE/probes/fieldprobes.m
new file mode 100644
index 0000000..edf7ed2
--- /dev/null
+++ b/openEMS/TESTSUITE/probes/fieldprobes.m
@@ -0,0 +1,324 @@
+function pass = fieldprobes( openEMS_options, options )
+%
+% infinitesimal dipole in free-space
+%
+% E/H-field probes are compared to hdf5 field dumps
+%
+
+pass = 1;
+
+physical_constants;
+
+
+ENABLE_PLOTS = 1;
+CLEANUP = 1; % if enabled and result is PASS, remove simulation folder
+STOP_IF_FAILED = 1; % if enabled and result is FAILED, stop with error
+VERBOSE = 1;
+SILENT = 0; % 0=show openEMS output
+
+if nargin < 1
+ openEMS_options = '';
+end
+if nargin < 2
+ options = '';
+end
+if any(strcmp( options, 'run_testsuite' ))
+ ENABLE_PLOTS = 0;
+ STOP_IF_FAILED = 0;
+ SILENT = 1;
+ VERBOSE = 0;
+end
+
+% LIMITS
+limit_max_time_diff = 1e-13;
+limit_max_amp_diff = 1e-7; %relative amplitude difference
+limit_min_e_amp = 5e-3;
+limit_min_h_amp = 1e-7;
+
+
+% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+drawingunit = 1e-6; % specify everything in um
+Sim_Path = 'tmp_fieldprobes';
+Sim_CSX = 'tmp.xml';
+
+f_max = 1e9;
+lambda = c0/f_max /drawingunit;
+
+% setup geometry values
+dipole_length = lambda/50;
+
+
+% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = -dipole_length*20:dipole_length/2:dipole_length*20;
+mesh.y = -dipole_length*20:dipole_length/2:dipole_length*20;
+mesh.z = -dipole_length*20:dipole_length/2:dipole_length*20;
+CSX = DefineRectGrid( CSX, drawingunit, mesh );
+
+% excitation
+CSX = AddExcitation( CSX, 'infDipole', 1, [0 0 1] );
+start = [0, 0, -dipole_length/2];
+stop = [0, 0, +dipole_length/2];
+CSX = AddBox( CSX, 'infDipole', 1, start, stop );
+
+% NFFF contour
+s1 = [-4.5, -4.5, -4.5] * dipole_length/2;
+s2 = [ 4.5, 4.5, 4.5] * dipole_length/2;
+CSX = AddBox( AddDump(CSX,'Et_xn','DumpType',0,'DumpMode',0,'FileType',1), 'Et_xn', 0, s1, [s1(1) s2(2) s2(3)] );
+CSX = AddBox( AddDump(CSX,'Et_xp','DumpType',0,'DumpMode',0,'FileType',1), 'Et_xp', 0, [s2(1) s1(2) s1(3)], s2 );
+CSX = AddBox( AddDump(CSX,'Et_yn','DumpType',0,'DumpMode',0,'FileType',1), 'Et_yn', 0, s1, [s2(1) s1(2) s2(3)] );
+CSX = AddBox( AddDump(CSX,'Et_yp','DumpType',0,'DumpMode',0,'FileType',1), 'Et_yp', 0, [s1(1) s2(2) s1(3)], s2 );
+CSX = AddBox( AddDump(CSX,'Et_zn','DumpType',0,'DumpMode',0,'FileType',1), 'Et_zn', 0, s1, [s2(1) s2(2) s1(3)] );
+CSX = AddBox( AddDump(CSX,'Et_zp','DumpType',0,'DumpMode',0,'FileType',1), 'Et_zp', 0, [s1(1) s1(2) s2(3)], s2 );
+CSX = AddBox( AddDump(CSX,'Ht_xn','DumpType',1,'DumpMode',0,'FileType',1), 'Ht_xn', 0, s1, [s1(1) s2(2) s2(3)] );
+CSX = AddBox( AddDump(CSX,'Ht_xp','DumpType',1,'DumpMode',0,'FileType',1), 'Ht_xp', 0, [s2(1) s1(2) s1(3)], s2 );
+CSX = AddBox( AddDump(CSX,'Ht_yn','DumpType',1,'DumpMode',0,'FileType',1), 'Ht_yn', 0, s1, [s2(1) s1(2) s2(3)] );
+CSX = AddBox( AddDump(CSX,'Ht_yp','DumpType',1,'DumpMode',0,'FileType',1), 'Ht_yp', 0, [s1(1) s2(2) s1(3)], s2 );
+CSX = AddBox( AddDump(CSX,'Ht_zn','DumpType',1,'DumpMode',0,'FileType',1), 'Ht_zn', 0, s1, [s2(1) s2(2) s1(3)] );
+CSX = AddBox( AddDump(CSX,'Ht_zp','DumpType',1,'DumpMode',0,'FileType',1), 'Ht_zp', 0, [s1(1) s1(2) s2(3)], s2 );
+
+% E-field probes
+coords{1} = [s1(1) 0 0];
+CSX = AddPoint( AddProbe(CSX,'et1',2), 'et1', 0, coords{1} );
+coords{2} = [s2(1) 0 0];
+CSX = AddPoint( AddProbe(CSX,'et2',2), 'et2', 0, coords{2} );
+coords{3} = [0 s1(2) 0];
+CSX = AddPoint( AddProbe(CSX,'et3',2), 'et3', 0, coords{3} );
+coords{4} = [0 s2(2) 0];
+CSX = AddPoint( AddProbe(CSX,'et4',2), 'et4', 0, coords{4} );
+coords{5} = [0 0 s1(3)];
+CSX = AddPoint( AddProbe(CSX,'et5',2), 'et5', 0, coords{5} );
+coords{6} = [0 0 s2(3)];
+CSX = AddPoint( AddProbe(CSX,'et6',2), 'et6', 0, coords{6} );
+
+% H-field probes
+CSX = AddPoint( AddProbe(CSX,'ht1',3), 'ht1', 0, [s1(1) 0 0] );
+CSX = AddPoint( AddProbe(CSX,'ht2',3), 'ht2', 0, [s2(1) 0 0] );
+CSX = AddPoint( AddProbe(CSX,'ht3',3), 'ht3', 0, [0 s1(2) 0] );
+CSX = AddPoint( AddProbe(CSX,'ht4',3), 'ht4', 0, [0 s2(2) 0] );
+CSX = AddPoint( AddProbe(CSX,'ht5',3), 'ht5', 0, [0 0 s1(3)] );
+CSX = AddPoint( AddProbe(CSX,'ht6',3), 'ht6', 0, [0 0 s2(3)] );
+
+
+
+% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+max_timesteps = 10000;
+min_decrement = 1e-6;
+FDTD = InitFDTD( max_timesteps, min_decrement,'OverSampling',10 );
+FDTD = SetGaussExcite( FDTD, 0, f_max );
+BC = [2 2 2 2 2 2];
+FDTD = SetBoundaryCond( FDTD, BC );
+
+% Write openEMS compatible xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[~,~,~] = rmdir(Sim_Path,'s');
+[~,~,~] = mkdir(Sim_Path);
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+% run openEMS
+folder = fileparts( mfilename('fullpath') );
+Settings.LogFile = [folder '/' Sim_Path '/openEMS.log'];
+Settings.Silent = SILENT;
+RunOpenEMS( Sim_Path, Sim_CSX, openEMS_options, Settings );
+
+
+%% POSTPROCESS
+filenames_E = {'Et_xn.h5','Et_xp.h5','Et_yn.h5','Et_yp.h5','Et_zn.h5','Et_zp.h5'};
+filenames_H = {'Ht_xn.h5','Ht_xp.h5','Ht_yn.h5','Ht_yp.h5','Ht_zn.h5','Ht_zp.h5'};
+
+for n=1:numel(filenames_E)
+ Et{n} = ReadHDF5FieldData( [Sim_Path '/' filenames_E{n}] );
+ E_mesh{n} = ReadHDF5Mesh( [Sim_Path '/' filenames_E{n}] );
+ Ht{n} = ReadHDF5FieldData( [Sim_Path '/' filenames_H{n}] );
+ H_mesh{n} = ReadHDF5Mesh( [Sim_Path '/' filenames_H{n}] );
+ Et_probe{n} = load( [Sim_Path '/et' num2str(n)] );
+ Ht_probe{n} = load( [Sim_Path '/ht' num2str(n)] );
+end
+
+if ENABLE_PLOTS
+ close all
+end
+
+%
+% E-fields
+%
+if VERBOSE, disp( 'extracting field components from field dumps...' ); end
+for n=1:6
+ if numel(E_mesh{n}.lines{1}) > 1
+ x_idx = interp1( E_mesh{n}.lines{1}, 1:numel(E_mesh{n}.lines{1}), coords{n}(1), 'nearest' );
+ else
+ x_idx = 1;
+ end
+ if numel(E_mesh{n}.lines{2}) > 1
+ y_idx = interp1( E_mesh{n}.lines{2}, 1:numel(E_mesh{n}.lines{2}), coords{n}(2), 'nearest' );
+ else
+ y_idx = 1;
+ end
+ if numel(E_mesh{n}.lines{3}) > 1
+ z_idx = interp1( E_mesh{n}.lines{3}, 1:numel(E_mesh{n}.lines{3}), coords{n}(3), 'nearest' );
+ else
+ z_idx = 1;
+ end
+
+ if VERBOSE
+ disp( ['n=' num2str(n) ' coords: (' num2str(E_mesh{n}.lines{1}(x_idx)) ','...
+ num2str(E_mesh{n}.lines{2}(y_idx)) ','...
+ num2str(E_mesh{n}.lines{3}(z_idx)) ') m indices: ('...
+ num2str(x_idx) ',' num2str(y_idx) ',' num2str(z_idx) ')'] );
+ end
+
+ field_x = zeros(numel(Et{n}.TD.values),1);
+ field_y = zeros(numel(Et{n}.TD.values),1);
+ field_z = zeros(numel(Et{n}.TD.values),1);
+ for t=1:numel(Et{n}.TD.values)
+ field_x(t) = squeeze(Et{n}.TD.values{t}(x_idx,y_idx,z_idx,1));
+ field_y(t) = squeeze(Et{n}.TD.values{t}(x_idx,y_idx,z_idx,2));
+ field_z(t) = squeeze(Et{n}.TD.values{t}(x_idx,y_idx,z_idx,3));
+ end
+ field_t = reshape( Et{n}.TD.time, [], 1 );
+
+ % check vector length
+ if numel(field_x) ~= size(Et_probe{n},1)
+ pass = 0;
+ disp( 'probes/fieldprobes.m (vector length): * FAILED *' );
+ break
+ end
+
+ % check absolute simulation time
+ if any(abs(field_t - Et_probe{n}(:,1)) > limit_max_time_diff)
+ pass = 0;
+ disp( 'probes/fieldprobes.m (time inconsistant): * FAILED *' );
+ break
+ end
+
+ if ENABLE_PLOTS
+ figure
+ subplot(2,3,1);
+ plot( field_t, [field_x Et_probe{n}(:,2)] );
+ subplot(2,3,2);
+ plot( field_t, [field_y Et_probe{n}(:,3)] );
+ subplot(2,3,3);
+ plot( field_t, [field_z Et_probe{n}(:,4)] );
+ subplot(2,3,4);
+ plot( field_t, (field_x - Et_probe{n}(:,2))./field_x );
+ subplot(2,3,5);
+ plot( field_t, (field_y - Et_probe{n}(:,3))./field_y );
+ subplot(2,3,6);
+ plot( field_t, (field_z - Et_probe{n}(:,4))./field_z );
+ end
+
+ % difference
+ if any( abs( (field_x - Et_probe{n}(:,2))./field_x) > limit_max_amp_diff ) || ...
+ any( abs( (field_y - Et_probe{n}(:,3))./field_y) > limit_max_amp_diff ) || ...
+ any( abs( (field_z - Et_probe{n}(:,4))./field_z) > limit_max_amp_diff )
+ pass = 0;
+ disp( 'probes/fieldprobes.m (amplitudes differ too much): * FAILED *' );
+ break
+ end
+
+ % check absolute field strength of z component
+ if max(abs(field_z)) < limit_min_e_amp
+ pass = 0;
+ disp( 'probes/fieldprobes.m (amplitude of z-component too small): * FAILED *' );
+ break
+ end
+end
+
+%
+% H-fields
+%
+if VERBOSE, disp( 'extracting field components from field dumps...' ); end
+for n=1:6
+ if numel(H_mesh{n}.lines{1}) > 1
+ x_idx = interp1( H_mesh{n}.lines{1}, 1:numel(H_mesh{n}.lines{1}), coords{n}(1), 'nearest' );
+ else
+ x_idx = 1;
+ end
+ if numel(E_mesh{n}.lines{2}) > 1
+ y_idx = interp1( H_mesh{n}.lines{2}, 1:numel(H_mesh{n}.lines{2}), coords{n}(2), 'nearest' );
+ else
+ y_idx = 1;
+ end
+ if numel(E_mesh{n}.lines{3}) > 1
+ z_idx = interp1( H_mesh{n}.lines{3}, 1:numel(H_mesh{n}.lines{3}), coords{n}(3), 'nearest' );
+ else
+ z_idx = 1;
+ end
+
+ if VERBOSE
+ disp( ['n=' num2str(n) ' coords: (' num2str(E_mesh{n}.lines{1}(x_idx)) ','...
+ num2str(E_mesh{n}.lines{2}(y_idx)) ','...
+ num2str(E_mesh{n}.lines{3}(z_idx)) ') m indices: ('...
+ num2str(x_idx) ',' num2str(y_idx) ',' num2str(z_idx) ')'] );
+ end
+
+ field_x = zeros(numel(Ht{n}.TD.values),1);
+ field_y = zeros(numel(Ht{n}.TD.values),1);
+ field_z = zeros(numel(Ht{n}.TD.values),1);
+ for t=1:numel(Ht{n}.TD.values)
+ field_x(t) = squeeze(Ht{n}.TD.values{t}(x_idx,y_idx,z_idx,1));
+ field_y(t) = squeeze(Ht{n}.TD.values{t}(x_idx,y_idx,z_idx,2));
+ field_z(t) = squeeze(Ht{n}.TD.values{t}(x_idx,y_idx,z_idx,3));
+ end
+ field_t = reshape( Ht{n}.TD.time, [], 1 );
+
+ % check vector length
+ if numel(field_x) ~= size(Ht_probe{n},1)
+ pass = 0;
+ disp( 'probes/fieldprobes.m (vector length): * FAILED *' );
+ break
+ end
+
+ % check absolute simulation time
+ if any(abs(field_t - Ht_probe{n}(:,1)) > limit_max_time_diff)
+ pass = 0;
+ disp( 'probes/fieldprobes.m (time inconsistant): * FAILED *' );
+ break
+ end
+
+ if ENABLE_PLOTS
+ figure
+ subplot(2,3,1);
+ plot( field_t, [field_x Ht_probe{n}(:,2)] );
+ subplot(2,3,2);
+ plot( field_t, [field_y Ht_probe{n}(:,3)] );
+ subplot(2,3,3);
+ plot( field_t, [field_z Ht_probe{n}(:,4)] );
+ subplot(2,3,4);
+ plot( field_t, (field_x - Ht_probe{n}(:,2))./field_x );
+ subplot(2,3,5);
+ plot( field_t, (field_y - Ht_probe{n}(:,3))./field_y );
+ subplot(2,3,6);
+ plot( field_t, (field_z - Ht_probe{n}(:,4))./field_z );
+ end
+
+ % difference
+ if any( abs( (field_x - Ht_probe{n}(:,2))./field_x) > limit_max_amp_diff ) || ...
+ any( abs( (field_y - Ht_probe{n}(:,3))./field_y) > limit_max_amp_diff ) || ...
+ any( abs( (field_z - Ht_probe{n}(:,4))./field_z) > limit_max_amp_diff )
+ pass = 0;
+ disp( 'probes/fieldprobes.m (amplitudes differ too much): * FAILED *' );
+ break
+ end
+
+ % check absolute field strength of z component
+ if (max(abs(field_x)) < limit_min_h_amp) || (max(abs(field_y)) < limit_min_h_amp)
+ pass = 0;
+ disp( 'probes/fieldprobes.m (amplitude of x- or y-component too small): * FAILED *' );
+ break
+ end
+end
+
+
+
+
+if pass
+ disp( 'probes/fieldprobes.m: pass' );
+end
+
+
+if pass && CLEANUP
+ rmdir( Sim_Path, 's' );
+end
+if ~pass && STOP_IF_FAILED
+ error 'test failed';
+end
diff --git a/openEMS/TESTSUITE/run_testsuite.m b/openEMS/TESTSUITE/run_testsuite.m
new file mode 100644
index 0000000..9f1707b
--- /dev/null
+++ b/openEMS/TESTSUITE/run_testsuite.m
@@ -0,0 +1,58 @@
+%
+% run the testsuite
+%
+
+clc
+clear
+close all
+drawnow
+
+if isOctave
+ confirm_recursive_rmdir(0);
+ page_screen_output(0); % do not buffer output
+ page_output_immediately(1); % do not buffer output
+end
+
+folder = fileparts( mfilename( 'fullpath' ) );
+cd( folder );
+addpath( [folder filesep 'helperscripts'] );
+
+% openEMS options
+options = {'--engine=multithreaded', '--engine=sse-compressed', '--engine=sse', '--engine=basic'};
+
+for o=1:numel(options)
+
+ disp( [datestr(now) ' *** TESTSUITE started (options: ' options{o} ')'] );
+
+ % now list the tests
+ folders = dir();
+ for f=1:numel(folders)
+ if folders(f).isdir
+ if strcmp(folders(f).name,'.') || strcmp(folders(f).name,'..')
+ continue
+ end
+ if strcmp(folders(f).name,'helperscripts')
+ continue
+ end
+ oldpwd = pwd;
+ cd( folders(f).name );
+ scripts = dir('*.m');
+ for s=1:numel(scripts)
+ if ~scripts(s).isdir
+ % execute function
+ disp( [datestr(now) ' executing: ' folders(f).name '/' scripts(s).name] );
+ [~,fname] = fileparts( scripts(s).name );
+ if isOctave
+ fflush(1); % flush stdout
+ end
+ pass = feval( fname, options{o}, 'run_testsuite' );
+ end
+ end
+ cd(oldpwd);
+ end
+ end
+end
+
+disp( '***' );
+disp( ['*** ' datestr(now) ' ALL TESTS DONE'] );
+disp( '***' );
diff --git a/openEMS/TODO b/openEMS/TODO
new file mode 100644
index 0000000..a6e6d2c
--- /dev/null
+++ b/openEMS/TODO
@@ -0,0 +1,14 @@
+#this is a todo/wish/feature-request/outlook list for the openEMS project
+#priorities: todo (highest) --> outlook (lowest)
+
+todo / mandatory for v0.1.0:
+- more examples and lots of testing...
+- improvments and testing for MPI engine
+
+wishes:
+- location dependend excitation given by a file (e.g. mode-profile simulated with comsol)
+- more import filter (e.g. gerber import)
+
+outlook:
+- incorporate a static FD-solver into openEMS
+- include other EM-solver (e.g. FEM, FDFD, TLM)
diff --git a/openEMS/astyle.sh b/openEMS/astyle.sh
new file mode 100755
index 0000000..2c8bd41
--- /dev/null
+++ b/openEMS/astyle.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+find . -type f -name \*.cpp -exec astyle --style=allman --indent=tab --indent-cases {} \;
+find . -type f -name \*.h -exec astyle --style=allman --indent=tab --keep-one-line-blocks --indent-cases {} \;
diff --git a/openEMS/cmake/Modules/FindTinyXML.cmake b/openEMS/cmake/Modules/FindTinyXML.cmake
new file mode 100644
index 0000000..aabb323
--- /dev/null
+++ b/openEMS/cmake/Modules/FindTinyXML.cmake
@@ -0,0 +1,74 @@
+##################################################################################################
+#
+# CMake script for finding TinyXML.
+#
+# Input variables:
+#
+# - TinyXML_ROOT_DIR (optional): When specified, header files and libraries will be searched for in
+# ${TinyXML_ROOT_DIR}/include
+# ${TinyXML_ROOT_DIR}/libs
+# respectively, and the default CMake search order will be ignored. When unspecified, the default
+# CMake search order is used.
+# This variable can be specified either as a CMake or environment variable. If both are set,
+# preference is given to the CMake variable.
+# Use this variable for finding packages installed in a nonstandard location, or for enforcing
+# that one of multiple package installations is picked up.
+#
+#
+# Cache variables (not intended to be used in CMakeLists.txt files)
+#
+# - TinyXML_INCLUDE_DIR: Absolute path to package headers.
+# - TinyXML_LIBRARY: Absolute path to library.
+#
+#
+# Output variables:
+#
+# - TinyXML_FOUND: Boolean that indicates if the package was found
+# - TinyXML_INCLUDE_DIRS: Paths to the necessary header files
+# - TinyXML_LIBRARIES: Package libraries
+#
+#
+# Example usage:
+#
+# find_package(TinyXML)
+# if(NOT TinyXML_FOUND)
+# # Error handling
+# endif()
+# ...
+# include_directories(${TinyXML_INCLUDE_DIRS} ...)
+# ...
+# target_link_libraries(my_target ${TinyXML_LIBRARIES})
+#
+##################################################################################################
+
+# Get package location hint from environment variable (if any)
+if(NOT TinyXML_ROOT_DIR AND DEFINED ENV{TinyXML_ROOT_DIR})
+ set(TinyXML_ROOT_DIR "$ENV{TinyXML_ROOT_DIR}" CACHE PATH
+ "TinyXML base directory location (optional, used for nonstandard installation paths)")
+endif()
+
+# Search path for nonstandard package locations
+if(TinyXML_ROOT_DIR)
+ set(TinyXML_INCLUDE_PATH PATHS "${TinyXML_ROOT_DIR}/include" NO_DEFAULT_PATH)
+ set(TinyXML_LIBRARY_PATH PATHS "${TinyXML_ROOT_DIR}/lib" NO_DEFAULT_PATH)
+endif()
+
+# Find headers and libraries
+find_path(TinyXML_INCLUDE_DIR NAMES tinyxml.h PATH_SUFFIXES "tinyxml" ${TinyXML_INCLUDE_PATH})
+find_library(TinyXML_LIBRARY NAMES tinyxml PATH_SUFFIXES "tinyxml" ${TinyXML_LIBRARY_PATH})
+
+mark_as_advanced(TinyXML_INCLUDE_DIR
+ TinyXML_LIBRARY)
+
+# Output variables generation
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(TinyXML DEFAULT_MSG TinyXML_LIBRARY
+ TinyXML_INCLUDE_DIR)
+
+set(TinyXML_FOUND ${TINYXML_FOUND}) # Enforce case-correctness: Set appropriately cased variable...
+unset(TINYXML_FOUND) # ...and unset uppercase variable generated by find_package_handle_standard_args
+
+if(TinyXML_FOUND)
+ set(TinyXML_INCLUDE_DIRS ${TinyXML_INCLUDE_DIR})
+ set(TinyXML_LIBRARIES ${TinyXML_LIBRARY})
+endif()
diff --git a/openEMS/known_bugs b/openEMS/known_bugs
new file mode 100644
index 0000000..944b1a2
--- /dev/null
+++ b/openEMS/known_bugs
@@ -0,0 +1 @@
+#known bugs list
diff --git a/openEMS/known_problems b/openEMS/known_problems
new file mode 100644
index 0000000..0257b1b
--- /dev/null
+++ b/openEMS/known_problems
@@ -0,0 +1,4 @@
+#known problems that also might be bugs
+
+11-03-2010
+example Coaxial_Cartesian: field distribution with PEC != kappa very large, staircasing problem??
diff --git a/openEMS/linux/CalcNF2FF.m.patch b/openEMS/linux/CalcNF2FF.m.patch
new file mode 100644
index 0000000..ae091af
--- /dev/null
+++ b/openEMS/linux/CalcNF2FF.m.patch
@@ -0,0 +1,14 @@
+diff --git a/matlab/CalcNF2FF.m b/matlab/CalcNF2FF.m
+index 35c11c7..1638110 100644
+--- a/matlab/CalcNF2FF.m
++++ b/matlab/CalcNF2FF.m
+@@ -83,7 +83,8 @@ cd(Sim_Path);
+ try
+ if isunix
+ % remove LD_LIBRARY_PATH set by matlab
+- system(['export LD_LIBRARY_PATH=; ' openEMS_Path 'nf2ff/nf2ff ' filename '.xml']);
++ % this is a packaged openEMS; nf2ff is found within PATH
++ system(['LD_LIBRARY_PATH=; nf2ff ' filename '.xml']);
+ else
+ system([openEMS_Path 'nf2ff.exe ' filename '.xml']);
+ end
diff --git a/openEMS/linux/README.patch b/openEMS/linux/README.patch
new file mode 100644
index 0000000..e005adb
--- /dev/null
+++ b/openEMS/linux/README.patch
@@ -0,0 +1,15 @@
+diff --git a/README b/README
+index 1962055..ae6df82 100644
+--- a/README
++++ b/README
+@@ -10,8 +10,8 @@ Forum: http://openems.de/forum/
+ Tutorials: http://openems.de/index.php/Tutorials
+
+
+-To use openEMS from Matlab or Octave, you need to include the <openEMS-install-folder>/matlab folder in the respective environment:
+-> addpath( '<openEMS-install-folder>/matlab' );
++To use openEMS from Matlab or Octave, you need to include the /usr/share/openEMS/matlab folder in the respective environment:
++> addpath( '/usr/share/openEMS/matlab' );
+
+ To verify the correct installation follow the instructions at:
+ http://openems.de/index.php/Tutorial:_First_Steps
diff --git a/openEMS/linux/debian.changelog b/openEMS/linux/debian.changelog
new file mode 100644
index 0000000..755d0f4
--- /dev/null
+++ b/openEMS/linux/debian.changelog
@@ -0,0 +1,27 @@
+openems (0.0.28-2) stable; urgency=low
+ * display correct version
+ -- Sebastian Held <sebastian.held@gmx.de> Sun, 24 Jun 2012 14:17:00 +0200
+openems (0.0.28-1) stable; urgency=low
+ * New upstream release
+ -- Sebastian Held <sebastian.held@gmx.de> Sun, 17 Jun 2012 23:28:29 +0200
+openems (0.0.27-1) stable; urgency=low
+ * New upstream release
+ -- Sebastian Held <sebastian.held@gmx.de> Thu, 1 Mar 2012 22:37:38 +0100
+openems (0.0.26-1) stable; urgency=low
+ * New upstream release
+ -- Sebastian Held <sebastian.held@gmx.de> Sat, 21 Jan 2012 12:32:38 +0100
+openems (0.0.25-5) stable; urgency=low
+ * added README
+ -- Sebastian Held <sebastian.held@gmx.de> Thu, 29 Dec 2011 20:35:38 +0100
+openems (0.0.25-4) stable; urgency=low
+ * Upstream fixes
+ -- Sebastian Held <sebastian.held@gmx.de> Sun, 25 Dec 2011 21:23:38 +0100
+openems (0.0.25-3) stable; urgency=low
+ * Changed dependancy on boost to enable build on oneiric
+ -- Sebastian Held <sebastian.held@gmx.de> Sun, 18 Dec 2011 21:39:38 +0100
+openems (0.0.25-2) stable; urgency=low
+ * New upstream release
+ -- Sebastian Held <sebastian.held@gmx.de> Sun, 4 Dec 2011 17:19:38 +0100
+openems (0.0.24-1) stable; urgency=low
+ * Initial Release
+ -- Sebastian Held <sebastian.held@gmx.de> Thu, 8 Oct 2011 8:30:38 +0200
diff --git a/openEMS/linux/debian.control b/openEMS/linux/debian.control
new file mode 100644
index 0000000..43f9441
--- /dev/null
+++ b/openEMS/linux/debian.control
@@ -0,0 +1,12 @@
+Source: openems
+Section: contrib/science
+Priority: optional
+Maintainer: Sebastian Held <sebastian.held@gmx.de>
+Build-Depends: debhelper (>=7.0.50~), qt4-qmake, libfparser4, libhdf5-serial-dev, libtinyxml-dev, csxcad-dev (>= 0.2.4), libopenmpi-dev, libvtk5-qt4-dev, libboost-all-dev
+
+Package: openems
+Architecture: any
+Depends: ${shlibs:Depends}
+Recommends: octave3.2, paraview
+Description: Free and Open Electromagnetic Field Solver
+ OpenEMS is a free and open-source electromagnetic field solver using the (EC-)FDTD method.
diff --git a/openEMS/linux/debian.docs b/openEMS/linux/debian.docs
new file mode 100644
index 0000000..2e3abae
--- /dev/null
+++ b/openEMS/linux/debian.docs
@@ -0,0 +1,2 @@
+COPYING
+README
diff --git a/openEMS/linux/debian.rules b/openEMS/linux/debian.rules
new file mode 100644
index 0000000..a3edec1
--- /dev/null
+++ b/openEMS/linux/debian.rules
@@ -0,0 +1,90 @@
+#!/usr/bin/make -f
+# Sample debian/rules that uses debhelper.
+# GNU copyright 1997 to 1999 by Joey Hess.
+
+# Uncomment this to turn on verbose mode.
+#export DH_VERBOSE=1
+
+# This is the debhelper compatibility version to use.
+export DH_COMPAT=4
+
+CFLAGS = -g -msse
+ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
+CFLAGS += -O0
+else
+CFLAGS += -O2
+endif
+
+build: build-stamp
+build-stamp:
+ dh_testdir
+
+ # Add here commands to compile the package.
+ qmake-qt4 QMAKE_CFLAGS="$$CFLAGS" QMAKE_CXXFLAGS="$$CFLAGS" CONFIG+=packaging openEMS.pro
+ make
+ cd nf2ff && qmake-qt4 QMAKE_CFLAGS="$$CFLAGS" QMAKE_CXXFLAGS="$$CFLAGS" CONFIG+=packaging nf2ff.pro
+ make -C nf2ff
+ # --- end custom part for compiling
+
+ touch build-stamp
+
+clean:
+ dh_testdir
+ dh_testroot
+ rm -f build-stamp
+
+ # Add here commands to clean up after the build process.
+ make clean || true
+ make -C nf2ff clean || true
+ # --- end custom part for cleaning up
+
+ dh_clean
+
+install: build
+ dh_testdir
+ dh_testroot
+ dh_clean -k
+ dh_installdirs
+
+ # Add here commands to install the package
+ # The DESTDIR Has To Be Exactly /usr/src/packages/BUILD/debian/<nameOfPackage>
+ make install INSTALL_ROOT=/usr/src/packages/BUILD/debian/openems
+ make -C nf2ff install INSTALL_ROOT=/usr/src/packages/BUILD/debian/openems
+ # --- end custom part for installing
+
+# Build architecture-independent files here.
+binary-indep: build install
+ # We have nothing to do by default.
+
+# Build architecture-dependent files here.
+binary-arch: build install
+ dh_testdir
+ dh_testroot
+# dh_installdebconf
+ dh_installdocs
+ dh_installexamples
+ dh_installmenu
+# dh_installlogrotate
+# dh_installemacsen
+# dh_installpam
+# dh_installmime
+# dh_installinit
+ dh_installcron
+ dh_installman
+ dh_installinfo
+# dh_undocumented
+ dh_installchangelogs
+ dh_link
+ dh_strip
+ dh_compress
+ dh_fixperms
+# dh_makeshlibs
+ dh_installdeb
+# dh_perl
+ dh_shlibdeps
+ dh_gencontrol
+ dh_md5sums
+ dh_builddeb
+
+binary: binary-indep binary-arch
+.PHONY: build clean binary-indep binary-arch binary install
diff --git a/openEMS/linux/debian.series b/openEMS/linux/debian.series
new file mode 100644
index 0000000..61ef578
--- /dev/null
+++ b/openEMS/linux/debian.series
@@ -0,0 +1,3 @@
+invoke_openEMS.m.patch -p1
+README.patch -p1
+CalcNF2FF.m.patch -p1
diff --git a/openEMS/linux/fedora17.diff b/openEMS/linux/fedora17.diff
new file mode 100644
index 0000000..12b1b41
--- /dev/null
+++ b/openEMS/linux/fedora17.diff
@@ -0,0 +1,13 @@
+diff --git a/openEMS.pro b/openEMS.pro
+index 97b0632..b9c3cf7 100644
+--- a/openEMS.pro
++++ b/openEMS.pro
+@@ -68,7 +68,7 @@ win32 {
+ /usr/include/vtk-5.10 \
+ /usr/include/vtk
+ INCLUDEPATH += /usr/include/CSXCAD
+- LIBS += -lvtkCommon \
++ LIBS += -L/usr/lib/vtk -L/usr/lib64/vtk -lvtkCommon \
+ -lvtkIO \
+ -lvtksys \
+ -lvtkFiltering
diff --git a/openEMS/linux/invoke_openEMS.m.patch b/openEMS/linux/invoke_openEMS.m.patch
new file mode 100644
index 0000000..cbd3073
--- /dev/null
+++ b/openEMS/linux/invoke_openEMS.m.patch
@@ -0,0 +1,15 @@
+diff --git a/matlab/private/invoke_openEMS.m b/matlab/private/invoke_openEMS.m
+index ce3ac53..d64771d 100644
+--- a/matlab/private/invoke_openEMS.m
++++ b/matlab/private/invoke_openEMS.m
+@@ -32,7 +32,9 @@ end
+ filename = mfilename('fullpath');
+ dir = fileparts( filename );
+ openEMS_Path = [dir filesep '../..' filesep];
+-
++
++openEMS_Path = ''; % this is a packaged openEMS installation; openEMS.sh is found in $PATH
++
+ if isunix
+ openEMS_Path = [openEMS_Path 'openEMS.sh'];
+ else
diff --git a/openEMS/linux/openEMS.dsc b/openEMS/linux/openEMS.dsc
new file mode 100644
index 0000000..b50da0e
--- /dev/null
+++ b/openEMS/linux/openEMS.dsc
@@ -0,0 +1,9 @@
+Format: 1.0
+Source: openems
+Version: 0.0.28-2
+Binary: openems
+Maintainer: Thorsten Liebig <thorsten.liebig@uni-due.de>, Sebastian Held <sebastian.held@gmx.de>
+Homepage: http://www.openems.de
+Architecture: any
+Build-Depends: debhelper (>= 5.0.0), qt4-qmake, libfparser4, libhdf5-serial-dev, libtinyxml-dev, csxcad-dev (>= 0.3.0-2), libopenmpi-dev, libvtk5-qt4-dev, libboost-all-dev
+DEBTRANSFORM-TAR: openEMS-0.0.28.tar.bz2
diff --git a/openEMS/linux/openEMS.spec b/openEMS/linux/openEMS.spec
new file mode 100644
index 0000000..f7b0b18
--- /dev/null
+++ b/openEMS/linux/openEMS.spec
@@ -0,0 +1,113 @@
+#
+# spec file for package [spectemplate]
+#
+# Copyright (c) 2010 SUSE LINUX Products GmbH, Nuernberg, Germany.
+#
+# All modifications and additions to the file contributed by third parties
+# remain the property of their copyright owners, unless otherwise agreed
+# upon. The license for this file, and modifications and additions to the
+# file, is the same license as for the pristine package itself (unless the
+# license for the pristine package is not an Open Source License, in which
+# case the license is the MIT License). An "Open Source License" is a
+# license that conforms to the Open Source Definition (Version 1.9)
+# published by the Open Source Initiative.
+
+# Please submit bugfixes or comments via http://bugs.opensuse.org/
+#
+
+# norootforbuild
+
+Name: openEMS
+Version: 0.0.28
+Release: 3
+Summary: Free and Open Electromagnetic Field Solver
+Group: Productivity/Scientific/Physics
+License: GPLv3
+URL: http://www.openems.de
+Source0: %{name}-%{version}.tar.bz2
+Patch0: invoke_openEMS.m.patch
+Patch1: README.patch
+Patch2: CalcNF2FF.m.patch
+Patch3: fedora17.diff
+BuildRoot: %_tmppath/%name-%version-build
+
+# libqt4-devel is needed only to provide qmake (the Qt-libraries are not used)
+# libfparser4-devel contains a static library => no runtime requirement
+BuildRequires: libqt4-devel gcc-c++ libfparser4-devel hdf5-devel tinyxml-devel CSXCAD-devel openmpi-devel vtk-devel boost-devel
+Requires: CSXCAD
+
+# determine qt4 qmake executable
+%if 0%{?fedora}
+ %global qmake qmake-qt4
+%else
+ %global qmake qmake
+%endif
+
+
+
+%description
+OpenEMS is a free and open-source electromagnetic field solver using the (EC-)FDTD method.
+
+
+%prep
+%setup -q
+%patch0 -p1
+#%if 0%{?fedora}
+#%patch1 -p1
+#%endif
+%patch1 -p1
+%patch2 -p1
+%if 0%{?fedora} >= 17
+%patch3 -p1
+%endif
+
+%build
+ADDFLAGS="-msse" # enable at least the SSE command set (no SSE makes no sense -- way too slow)
+%qmake QMAKE_CFLAGS="%optflags $ADDFLAGS" QMAKE_CXXFLAGS="%optflags $ADDFLAGS" LIB_SUFFIX="$(echo %_lib | cut -b4-)" CONFIG+=packaging openEMS.pro
+make %{?_smp_mflags}
+cd nf2ff
+%qmake QMAKE_CFLAGS="%optflags $ADDFLAGS" QMAKE_CXXFLAGS="%optflags $ADDFLAGS" LIB_SUFFIX="$(echo %_lib | cut -b4-)" CONFIG+=packaging nf2ff.pro
+make %{?_smp_mflags}
+cd ..
+
+%install
+make INSTALL_ROOT=%{buildroot} install
+cd nf2ff
+make INSTALL_ROOT=%{buildroot} install
+cd ..
+find %{buildroot} -name '*.la' -exec rm -f {} ';'
+
+
+%clean
+rm -rf %{buildroot}
+
+
+%files
+%defattr(-,root,root)
+%doc README COPYING TODO known_bugs known_problems
+/usr/share/%{name}
+/usr/bin/openEMS*
+/usr/bin/nf2ff
+
+
+%changelog
+* Sat Jun 23 2012 Sebastian Held <sebastian.held@gmx.de> - 0.0.28-3
+- display correct version
+* Mon Jun 18 2012 Sebastian Held <sebastian.held@gmx.de> - 0.0.28-2
+- Fedora 17 build fixes
+* Sun Jun 17 2012 Sebastian Held <sebastian.held@gmx.de> - 0.0.28-1
+- new upstream version
+* Thu Mar 1 2012 Sebastian Held <sebastian.held@gmx.de> - 0.0.27-1
+- new upstream version
+* Sat Jan 21 2012 Sebastian Held <sebastian.held@gmx.de> - 0.0.26-1
+- new upstream version
+* Mon Jan 9 2012 Sebastian Held <sebastian.held@gmx.de> - 0.0.25-4
+- added runtime dep on CSXCAD
+* Thu Dec 29 2011 Sebastian Held <sebastian.held@gmx.de> - 0.0.25-3
+- added README
+* Sun Dec 25 2011 Sebastian Held <sebastian.held@gmx.de> - 0.0.25-2
+- Fedora 16 build fix and upstream fixes
+* Sun Dec 4 2011 Sebastian Held <sebastian.held@gmx.de> - 0.0.25-1
+- new upstream version
+* Mon Oct 3 2011 Sebastian Held <sebastian.held@gmx.de> - 0.0.24-1
+- initial version
diff --git a/openEMS/main.cpp b/openEMS/main.cpp
new file mode 100644
index 0000000..1d03481
--- /dev/null
+++ b/openEMS/main.cpp
@@ -0,0 +1,81 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+
+#ifdef MPI_SUPPORT
+#include "mpi.h"
+#include "FDTD/openems_fdtd_mpi.h"
+#else
+#include "openems.h"
+#endif
+
+#include "tools/global.h"
+
+#ifndef GIT_VERSION
+#define GIT_VERSION "unknown:compiled@" __DATE__
+#endif
+
+using namespace std;
+
+int main(int argc, char *argv[])
+{
+#ifdef MPI_SUPPORT
+ //init MPI
+ MPI::Init(argc,argv);
+ openEMS_FDTD_MPI FDTD(false);
+#else
+ openEMS FDTD;
+#endif
+
+#ifdef MPI_SUPPORT
+ openEMS_FDTD_MPI::WelcomeScreen();
+#else
+ openEMS::WelcomeScreen();
+#endif
+
+ if (argc<=1)
+ {
+ openEMS::showUsage();
+ exit(-1);
+ }
+
+ if (argc>=3)
+ {
+ for (int n=2; n<argc; ++n)
+ {
+ if ( (!FDTD.parseCommandLineArgument(argv[n])) && (!g_settings.parseCommandLineArgument(argv[n])))
+ cout << "openEMS - unknown argument: " << argv[n] << endl;
+ }
+ }
+
+ int EC = FDTD.ParseFDTDSetup(argv[1]);
+ EC = FDTD.SetupFDTD();
+ if (EC) return EC;
+ FDTD.RunFDTD();
+
+#ifdef MPI_SUPPORT
+ FDTD.Reset(); //make sure everything is cleaned-up before calling MPI::Finalize()
+ MPI::Finalize();
+#endif
+
+ return 0;
+}
diff --git a/openEMS/matlab/AR_estimate.m b/openEMS/matlab/AR_estimate.m
new file mode 100644
index 0000000..ab6e293
--- /dev/null
+++ b/openEMS/matlab/AR_estimate.m
@@ -0,0 +1,115 @@
+function [val_ar t_ar f_val_ar EC] = AR_estimate( t, val, freq, nu, mu, expand_factor)
+% [val_ar t_ar f_val_ar EC] = AR_estimate( t, val, freq, < nu, mu, expand_factor >)
+%
+% apply autoregressive signal model to improve dft results
+%
+% t : time vector
+% val : time domain values
+% freq : frequency vector for dft
+%
+% optional
+% nu : AR order (default 40)
+% mu : number of timesteps to train the model (default 3*nu)
+% expand_factor : increase signal length by this factor (default 5)
+%
+% return values:
+% val_ar: AR estimated time signal
+% t_ar: time vector
+% f_val_ar: FD transformed AR estimated signal
+% EC: error code
+% 0 --> no error
+% 1 --> input error: t and val mismatch
+% 2 --> input error: mu has to be larger than 2*nu
+% 3 --> inout error: expand_factor has to be larger than 1
+% 10 --> AR error: signal is to short for AR estimate --> decrease AR order
+% 11 --> AR error: estimated signal appears to be unstable --> use a different mu
+%
+% openEMS matlab interface
+% -----------------------
+% Author: Thorsten Liebig, 2011
+%
+% See also ReadUI, DFT_time2freq
+
+EC = 0;
+val_ar = [];
+t_ar = [];
+f_val_ar = [];
+
+
+if numel(t) ~= numel(val)
+ if (nargout<4)
+ error 'numel(t) ~= numel(val)'
+ else
+ EC = 1;
+ return
+ end
+end
+
+if (nargin<4)
+ nu = 40;
+end
+if (nargin<5)
+ mu = 3*nu;
+end
+if (nargin<6)
+ expand_factor=5;
+end
+
+if (mu<=2*nu)
+ if (nargout<4)
+ error 'mu has to be larger than 2*nu'
+ else
+ EC = 2;
+ return
+ end
+end
+
+if (expand_factor<=1)
+ if (nargout<4)
+ error 'expand_factor has to be larger than 1'
+ else
+ EC = 3;
+ return
+ end
+end
+
+dt = t(2)-t(1);
+
+M = numel(t);
+
+if (M<0.6*mu)
+ if (nargout<4)
+ error 'signal is to short for AR estimate --> decrease AR order'
+ else
+ EC = 10;
+ return
+ end
+end
+
+for n=1:mu-nu
+ b(n) = val(end-n+1);
+ for m=1:nu
+ A(n,m)=val(end-n+1-m);
+ end
+end
+
+a = ((A'*A)\A')*b';
+
+val_ar = val;
+t_ar = t;
+for k=M:expand_factor*M
+ val_ar(k) = 0;
+ t_ar(k) = t_ar(k-1)+dt;
+ val_ar(k) = sum(a.*val_ar(k-(1:nu))');
+end
+
+if (max(val_ar(M:end)) > max(val))
+ if (nargout<4)
+ error 'estimated signal appears to be unstable --> use a different mu'
+ else
+ EC = 11;
+ return
+ end
+end
+
+f_val_ar = DFT_time2freq(t_ar, val_ar, freq);
diff --git a/openEMS/matlab/Add2Queue.m b/openEMS/matlab/Add2Queue.m
new file mode 100644
index 0000000..a80bdc9
--- /dev/null
+++ b/openEMS/matlab/Add2Queue.m
@@ -0,0 +1,48 @@
+function [queue] = Add2Queue(queue,func_name, func_args, varargin)
+% function [queue] = Add2Queue(queue,func_name, func_args, varargin)
+%
+% Use this function to add a funtion to the queue.
+%
+% For more details see: InitQueue
+%
+% See also: InitQueue, FinishQueue, ResultsQueue, RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if isfield(queue,'jobs')
+ jobnum = numel(queue.jobs)+1;
+else
+ jobnum = 1;
+end
+
+running = numel(queue.jobs_finished) - sum(queue.jobs_finished);
+
+while (running>=queue.maxThreads)
+ [queue running] = CheckQueue(queue);
+end
+
+
+if (queue.verbose>=1)
+ disp(['Add2Queue: Job #' num2str(jobnum) ' starting...']);
+end
+
+queue.jobs_finished(jobnum) = 0;
+
+queue.jobs{jobnum}.argsfile = [tempname '.mat'];
+save(queue.jobs{jobnum}.argsfile,'func_args');
+
+queue.jobs{jobnum}.nargout = nargout(func_name);
+queue.jobs{jobnum}.outargsfile = [tempname '.mat'];
+
+queue.jobs{jobnum}.command = [queue.bin queue.bin_options ' "load(''' queue.jobs{jobnum}.argsfile ''');' ...
+ queue.DependPath ...
+ 'err=[];' ...
+ 'try;' ...
+ '[outargs{1:' num2str(queue.jobs{jobnum}.nargout) '}]=' func_name '(func_args{:});' ...
+ 'catch err;outargs=0;end;' ...
+ 'save(''-V7'',''' queue.jobs{jobnum}.outargsfile ''',''outargs'',''err'');' ...
+ 'exit;"'];
+
+[queue.jobs{jobnum}.pid, queue.jobs{jobnum}.filenames] = queue_addProcess( queue.jobs{jobnum}.command );
diff --git a/openEMS/matlab/AddCPWPort.m b/openEMS/matlab/AddCPWPort.m
new file mode 100644
index 0000000..ba4fc4a
--- /dev/null
+++ b/openEMS/matlab/AddCPWPort.m
@@ -0,0 +1,285 @@
+function [CSX,port] = AddCPWPort( CSX, prio, portnr, materialname, start, stop, gap_width, dir, evec, varargin )
+% [CSX,port] = AddCPWPort( CSX, prio, portnr, materialname, start, stop, gap_width, dir, evec, varargin )
+%
+% CSX: CSX-object created by InitCSX()
+% prio: priority for excitation and probe boxes
+% portnr: (integer) number of the port
+% materialname: property for the CPW (created by AddMetal())
+% start: 3D start rowvector for port definition
+% stop: 3D end rowvector for port definition
+% gap_width: width of the CPW gap (left and right)
+% dir: direction of wave propagation (choices: 0, 1, 2 or 'x','y','z')
+% evec: excitation vector, which defines the direction of the e-field (must be the same as used in AddExcitation())
+%
+% variable input:
+% varargin: optional additional excitations options, see also AddExcitation
+% 'ExcitePort' true/false to make the port an active feeding port (default
+% is false)
+% 'FeedShift' shift to port from start by a given distance in drawing
+% units. Default is 0. Only active if 'ExcitePort' is set!
+% 'Feed_R' Specifiy a lumped port resistance. Default is no lumped
+% port resistance --> port has to end in an ABC.
+% 'MeasPlaneShift' Shift the measurement plane from start t a given distance
+% in drawing units. Default is the middle of start/stop.
+% 'PortNamePrefix' a prefix to the port name
+%
+% Important: The mesh has to be already set and defined by DefineRectGrid!
+%
+% example:
+% CSX = AddMetal( CSX, 'metal' ); %create a PEC called 'metal'
+% start = [0 -width/2 0];
+% stop = [length +width/2 0];
+% [CSX,port] = AddCPWPort( CSX, 0, 1, 'metal', start, stop, gap_width, 'x', ...
+% [0 0 -1], 'ExcitePort', true, 'Feed_R', 50 )
+% Explanation:
+% - this defines a stripline in x-direction (dir='x')
+% --> the wave travels along the x-direction
+% - with an e-field excitation in -z-direction (evec=[0 0 -1])
+% - the excitation is active and placed at x=start(1) ('ExcitePort', true)
+% - a 50 Ohm lumped port resistance is placed at x=start(1) ('Feed_R', 50)
+% - the width-direction is determined by the cross product of the
+% direction of propagtion (dir='x') and the excitation vector
+% (evec=[0 0 -1]), in this case it is the y-direction
+% - the stripline-metal is created in a xy-plane at a height at z=start(3)
+% --> The upper and lower reference plane (ground) must be defined by
+% the user
+%
+% Thorsten Liebig <thorsten.liebig@gmx.de> (c) 2014
+%
+% See also InitCSX DefineRectGrid AddMetal AddMaterial AddExcitation calcPort
+
+%% validate arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%check mesh
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+if (~isfield(CSX.RectilinearGrid,'XLines') || ~isfield(CSX.RectilinearGrid,'YLines') || ~isfield(CSX.RectilinearGrid,'ZLines'))
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+
+% check dir
+dir = DirChar2Int(dir);
+
+% check evec
+if ~(evec(1) == evec(2) == 0) && ~(evec(1) == evec(3) == 0) && ~(evec(2) == evec(3) == 0) || (sum(evec) == 0)
+ error 'evec must have exactly one component ~= 0'
+end
+evec0 = evec ./ sum(evec); % evec0 is a unit vector
+
+%set defaults
+feed_shift = 0;
+feed_R = inf; %(default is open, no resitance)
+excite = false;
+measplanepos = nan;
+PortNamePrefix = '';
+
+excite_args = {};
+
+%% read optional arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'FeedShift')==1);
+ feed_shift = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'FeedShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'Feed_R')==1);
+ feed_R = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'Feed_R must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'MeasPlaneShift')==1);
+ measplanepos = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'MeasPlaneShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'ExcitePort')==1);
+ if ischar(varargin{n+1})
+ warning('CSXCAD:AddCPWPort','depreceated: a string as excite option is no longer supported and will be removed in the future, please use true or false');
+ if ~isempty(excite)
+ excite = true;
+ else
+ excite = false;
+ end
+ else
+ excite = varargin{n+1};
+ end
+ elseif (strcmpi(varargin{n},'PortNamePrefix'))
+ PortNamePrefix = varargin{n+1};
+ else
+ excite_args{end+1} = varargin{n};
+ excite_args{end+1} = varargin{n+1};
+ end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% normalize start and stop
+nstart = min( [start;stop] );
+nstop = max( [start;stop] );
+
+% determine index (1, 2 or 3) of propagation (length of CPW)
+idx_prop = dir + 1;
+
+% determine index (1, 2 or 3) of width of CPW
+dir = [0 0 0];
+dir(idx_prop) = 1;
+idx_height = abs(cross(dir,evec0)) * [1;2;3];
+
+% determine index (1, 2 or 3) of height
+idx_width = abs(evec0) * [1;2;3];
+
+
+if (start(idx_height)~=stop(idx_height))
+ error('openEMS:AddCPWPort','start/stop in height direction must be equal');
+end
+
+% direction of propagation
+if stop(idx_prop)-start(idx_prop) > 0
+ direction = +1;
+else
+ direction = -1;
+end
+
+% create the metal/material for the CPW
+SL_start = start;
+SL_stop = stop;
+CSX = AddBox( CSX, materialname, prio, SL_start, SL_stop );
+
+if isnan(measplanepos)
+ measplanepos = (nstart(idx_prop)+nstop(idx_prop))/2;
+else
+ measplanepos = start(idx_prop)+direction*measplanepos;
+end
+
+% calculate position of the voltage probes
+mesh{1} = sort(CSX.RectilinearGrid.XLines);
+mesh{2} = sort(CSX.RectilinearGrid.YLines);
+mesh{3} = sort(CSX.RectilinearGrid.ZLines);
+meshlines = interp1( mesh{idx_prop}, 1:numel(mesh{idx_prop}), measplanepos, 'nearest' );
+meshlines = mesh{idx_prop}(meshlines-1:meshlines+1); % get three lines (approx. at center)
+if direction == -1
+ meshlines = fliplr(meshlines);
+end
+SL_w2 = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), (nstart(idx_width)+nstop(idx_width))/2, 'nearest' );
+SL_w2 = mesh{idx_width}(SL_w2); % get e-line at center of CPW (SL_width/2)
+v1_start(idx_prop) = meshlines(1);
+v1_start(idx_width) = (nstart(idx_width)+nstop(idx_width))/2;
+v1_start(idx_height) = start(idx_height);
+v1_stop = v1_start;
+v2_start = v1_start;
+v2_stop = v1_stop;
+v2_start(idx_prop) = meshlines(2);
+v2_stop(idx_prop) = meshlines(2);
+v3_start = v2_start;
+v3_stop = v2_stop;
+v3_start(idx_prop) = meshlines(3);
+v3_stop(idx_prop) = meshlines(3);
+
+width_add_start = [0 0 0];
+width_add_stop = [0 0 0];
+width_add_start(idx_width) = (nstop(idx_width)-nstart(idx_width))/2;
+width_add_stop(idx_width) = (nstop(idx_width)-nstart(idx_width))/2+gap_width;
+
+weight = 0.5;
+% create the voltage-probes
+port.U_filename{1,1} = [PortNamePrefix 'port_ut' num2str(portnr) 'A1'];
+CSX = AddProbe( CSX, port.U_filename{1,1}, 0, 'weight', -1*weight );
+CSX = AddBox( CSX, port.U_filename{1,1}, prio, v1_start-width_add_start, v1_stop-width_add_stop);
+
+port.U_filename{1,2} = [PortNamePrefix 'port_ut' num2str(portnr) 'A2'];
+CSX = AddProbe( CSX, port.U_filename{1,2}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{1,2}, prio, v1_start+width_add_start, v1_stop+width_add_stop);
+
+
+port.U_filename{2,1} = [PortNamePrefix 'port_ut' num2str(portnr) 'B1'];
+CSX = AddProbe( CSX, port.U_filename{2,1}, 0, 'weight', -1*weight );
+CSX = AddBox( CSX, port.U_filename{2,1}, prio, v2_start-width_add_start, v2_stop-width_add_stop );
+
+port.U_filename{2,2} = [PortNamePrefix 'port_ut' num2str(portnr) 'B2'];
+CSX = AddProbe( CSX, port.U_filename{2,2}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{2,2}, prio, v2_start+width_add_start, v2_stop+width_add_stop );
+
+
+port.U_filename{3,1} = [PortNamePrefix 'port_ut' num2str(portnr) 'C1'];
+CSX = AddProbe( CSX, port.U_filename{3,1}, 0, 'weight', -1*weight );
+CSX = AddBox( CSX, port.U_filename{3,1}, prio, v3_start-width_add_start, v3_stop-width_add_stop );
+
+port.U_filename{3,2} = [PortNamePrefix 'port_ut' num2str(portnr) 'C2'];
+CSX = AddProbe( CSX, port.U_filename{3,2}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{3,2}, prio, v3_start+width_add_start, v3_stop+width_add_stop );
+
+% calculate position of the current probes
+idx = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), nstart(idx_width), 'nearest' );
+i1_start(idx_width) = mesh{idx_width}(idx) - diff(mesh{idx_width}(idx-1:idx))/2;
+idx = interp1( mesh{idx_height}, 1:numel(mesh{idx_height}), start(idx_height), 'nearest' );
+i1_start(idx_height) = mesh{idx_height}(idx-1) - diff(mesh{idx_height}(idx-2:idx-1))/2;
+i1_stop(idx_height) = mesh{idx_height}(idx+1) + diff(mesh{idx_height}(idx+1:idx+2))/2;
+i1_start(idx_prop) = sum(meshlines(1:2))/2;
+i1_stop(idx_prop) = i1_start(idx_prop);
+idx = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), nstop(idx_width), 'nearest' );
+i1_stop(idx_width) = mesh{idx_width}(idx) + diff(mesh{idx_width}(idx:idx+1))/2;
+i2_start = i1_start;
+i2_stop = i1_stop;
+i2_start(idx_prop) = sum(meshlines(2:3))/2;
+i2_stop(idx_prop) = i2_start(idx_prop);
+
+% create the curr-probes
+weight = direction;
+port.I_filename{1} = [PortNamePrefix 'port_it' num2str(portnr) 'A'];
+CSX = AddProbe( CSX, port.I_filename{1}, 1, 'weight', weight );
+CSX = AddBox( CSX, port.I_filename{1}, prio, i1_start, i1_stop );
+port.I_filename{2} = [PortNamePrefix 'port_it' num2str(portnr) 'B'];
+CSX = AddProbe( CSX, port.I_filename{2}, 1,'weight', weight );
+CSX = AddBox( CSX, port.I_filename{2}, prio, i2_start, i2_stop );
+
+% create port structure
+port.LengthScale = 1;
+if ((CSX.ATTRIBUTE.CoordSystem==1) && (idx_prop==2))
+ port.LengthScale = SL_stop(idx_height);
+end
+port.nr = portnr;
+port.type = 'CPW';
+port.drawingunit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+port.v_delta = diff(meshlines)*port.LengthScale;
+port.i_delta = diff( meshlines(1:end-1) + diff(meshlines)/2 )*port.LengthScale;
+port.direction = direction;
+port.excite = 0;
+port.measplanepos = abs(v2_start(idx_prop) - start(idx_prop))*port.LengthScale;
+% port
+
+% create excitation (if enabled) and port resistance
+meshline = interp1( mesh{idx_prop}, 1:numel(mesh{idx_prop}), start(idx_prop) + feed_shift*direction, 'nearest' );
+ex_start(idx_prop) = mesh{idx_prop}(meshline) ;
+ex_start(idx_width) = (nstart(idx_width)+nstop(idx_width))/2;
+ex_start(idx_height) = nstart(idx_height);
+ex_stop(idx_prop) = ex_start(idx_prop);
+ex_stop(idx_width) = (nstart(idx_width)+nstop(idx_width))/2;
+ex_stop(idx_height) = nstop(idx_height);
+
+port.excite = 0;
+if excite
+ port.excite = 1;
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_1_' num2str(portnr)], 0, evec, excite_args{:} );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_1_' num2str(portnr)], prio, ex_start-width_add_start, ex_stop-width_add_stop );
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_2_' num2str(portnr)], 0, -evec, excite_args{:} );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_2_' num2str(portnr)], prio, ex_start+width_add_start, ex_stop+width_add_stop );
+end
+
+%% CPW resitance at start of CPW line
+ex_start(idx_prop) = start(idx_prop);
+ex_stop(idx_prop) = ex_start(idx_prop);
+
+if (feed_R > 0) && ~isinf(feed_R)
+ CSX = AddLumpedElement( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], idx_width-1, 'R', 2*feed_R );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], prio, ex_start-width_add_start, ex_stop-width_add_stop );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], prio, ex_start+width_add_start, ex_stop+width_add_stop );
+elseif isinf(feed_R)
+ % do nothing --> open port
+elseif feed_R == 0
+ %port "resistance" as metal
+ CSX = AddBox( CSX, materialname, prio, ex_start-width_add_start, ex_stop-width_add_stop );
+ CSX = AddBox( CSX, materialname, prio, ex_start+width_add_start, ex_stop+width_add_stop );
+else
+ error('openEMS:AddCPWPort','CPW port with resitance <= 0 it not possible');
+end
+end
diff --git a/openEMS/matlab/AddCircWaveGuidePort.m b/openEMS/matlab/AddCircWaveGuidePort.m
new file mode 100644
index 0000000..2d2e7ff
--- /dev/null
+++ b/openEMS/matlab/AddCircWaveGuidePort.m
@@ -0,0 +1,109 @@
+function [CSX,port] = AddCircWaveGuidePort( CSX, prio, portnr, start, stop, radius, mode_name, pol_ang, exc_amp, varargin )
+% function [CSX,port] = AddCircWaveGuidePort( CSX, prio, portnr, start, stop, radius, mode_name, pol_ang, exc_amp, varargin )
+%
+% Create a circular waveguide port, including an optional excitation and probes
+%
+% Note: - The excitation will be located at the start position in the given direction
+% - The voltage and current probes at the stop position in the given direction
+%
+% input:
+% CSX: complete CSX structure (must contain a mesh)
+% prio: priority of primitives
+% start: start coordinates of waveguide port box
+% stop: stop coordinates of waveguide port box
+% radius: circular waveguide radius (in meter)
+% mode_name: mode name, e.g. 'TE11' or 'TM21'
+% pol_ang: polarization angle (e.g. 0 = horizontal, pi/2 = vertical)
+% exc_amp: excitation amplitude (set 0 to be passive)
+%
+% optional (key/values):
+% varargin: optional additional excitations options, see also AddExcitation
+% 'PortNamePrefix': a prefix to the port name
+%
+% output:
+% CSX: modified CSX structure
+% port: port structure to use with calcPort
+%
+% example:
+% % create a TE11 circular waveguide mode, using cylindircal coordinates
+% start=[mesh.r(1) mesh.a(1) 0 ];
+% stop =[mesh.r(end) mesh.a(end) 100];
+% [CSX,port] = AddCircWaveGuidePort( CSX, 99, 1, start, stop, 320e-3, 'TE11', 0, 1);
+%
+% openEMS matlab interface
+% -----------------------
+% (c) 2013 Thorsten Liebig (thorsten.liebig@gmx.de)
+%
+% See also InitCSX, AddExcitation, calcWGPort, calcPort
+
+if (~strcmpi(mode_name(1:2),'TE'))
+ error 'currently only TE type modes are supported'
+end
+
+if (nargin<9)
+ exc_amp = 0;
+end
+if (nargin<8)
+ pol_ang = 0;
+end
+
+pnm = 0;
+n = str2double(mode_name(3));
+m = str2double(mode_name(4));
+
+% values by David M. Pozar, Microwave Engineering, third edition
+if ((n==0) && (m==1))
+ pnm = 3.832;
+elseif ((n==1) && (m==1))
+ pnm = 1.841;
+elseif ((n==2) && (m==1))
+ pnm = 3.054;
+elseif ((n==0) && (m==2))
+ pnm = 7.016;
+elseif ((n==1) && (m==2))
+ pnm = 5.331;
+elseif ((n==2) && (m==2))
+ pnm = 6.706;
+elseif ((n==0) && (m==3))
+ pnm = 10.174;
+elseif ((n==1) && (m==3))
+ pnm = 8.536;
+elseif ((n==2) && (m==3))
+ pnm = 9.970;
+else
+ error 'invalid TE_nm mode'
+end
+
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+
+unit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+kc = pnm/radius;
+kc_draw = kc*unit;
+
+angle = ['a-' num2str(pol_ang)];
+% functions by David M. Pozar, Microwave Engineering, third edition
+% electric field mode profile
+func_Er = [ num2str(-1/kc_draw^2,15) '/rho*cos(' angle ')*j1(' num2str(kc_draw,15) '*rho)'];
+func_Ea = [ num2str(1/kc_draw,15) '*sin(' angle ')*0.5*(j0(' num2str(kc_draw,15) '*rho)-jn(2,' num2str(kc_draw,15) '*rho))'];
+
+% magnetic field mode profile
+func_Hr = [ num2str(-1/kc_draw,15) '*sin(' angle ')*0.5*(j0(' num2str(kc_draw,15) '*rho)-jn(2,' num2str(kc_draw,15) '*rho))'];
+func_Ha = [ num2str(-1/kc_draw^2,15) '/rho*cos(' angle ')*j1(' num2str(kc_draw,15) '*rho)'];
+
+if (CSX.ATTRIBUTE.CoordSystem==1)
+ func_E = {func_Er, func_Ea, 0};
+ func_H = {func_Hr, func_Ha, 0};
+else
+ func_Ex = ['(' func_Er '*cos(a) - ' func_Ea '*sin(a) ) * (rho<' num2str(radius/unit) ')'];
+ func_Ey = ['(' func_Er '*sin(a) + ' func_Ea '*cos(a) ) * (rho<' num2str(radius/unit) ')'];
+ func_E = {func_Ex, func_Ey, 0};
+
+ func_Hx = ['(' func_Hr '*cos(a) - ' func_Ha '*sin(a) ) * (rho<' num2str(radius/unit) ')'];
+ func_Hy = ['(' func_Hr '*sin(a) + ' func_Ha '*cos(a) ) * (rho<' num2str(radius/unit) ')'];
+ func_H = {func_Hx, func_Hy, 0};
+end
+
+[CSX,port] = AddWaveGuidePort( CSX, prio, portnr, start, stop, 2, func_E, func_H, kc, exc_amp, varargin{:} );
+
diff --git a/openEMS/matlab/AddCoaxialPort.m b/openEMS/matlab/AddCoaxialPort.m
new file mode 100644
index 0000000..45c0d2b
--- /dev/null
+++ b/openEMS/matlab/AddCoaxialPort.m
@@ -0,0 +1,232 @@
+function [CSX,port] = AddCoaxialPort( CSX, prio, portnr, pec_name, materialname, start, stop, dir, r_i, r_o, r_os, varargin )
+% function [CSX,port] = AddCoaxialPort( CSX, prio, portnr, pec_name, materialname, start, stop, dir, r_i, r_o, r_os, varargin )
+%
+% CSX: CSX-object created by InitCSX()
+% prio: priority for excitation and probe boxes
+% portnr: (integer) number of the port
+% pec_name: metal property for coaxial inner/outer conductor (created by AddMetal())
+% materialname: substrate property for coaxial line (created by AddMaterial())
+% Note: this may be empty for an "air filled" coaxial line
+% start: 3D start rowvector for coaxial cable axis
+% stop: 3D end rowvector for coaxial cable axis
+% dir: direction of wave propagation (choices: 0, 1, 2 or 'x','y','z')
+% r_i: inner coaxial radius (in drawing unit)
+% r_o: outer coaxial radius (in drawing unit)
+% r_os: outer shell coaxial radius (in drawing unit)
+%
+% variable input:
+% varargin: optional additional excitations options, see also AddExcitation
+% 'ExciteAmp' excitation amplitude of transversal electric field profile,
+% set to 0 (default) for a passive port
+% 'FeedShift' shift to port from start by a given distance in drawing
+% units. Default is 0. Only active if 'ExciteAmp' is set!
+% 'Feed_R' Specifiy a lumped port resistance. Default is no lumped
+% port resistance --> port has to end in an ABC.
+% 'MeasPlaneShift' Shift the measurement plane from start t a given distance
+% in drawing units. Default is the middle of start/stop.
+% 'PortNamePrefix' a prefix to the port name
+%
+% the mesh must be already initialized
+%
+% example:
+%
+% openEMS matlab interface
+% -----------------------
+% Thorsten Liebig <thorsten.liebig@gmx.de> (c) 2013
+%
+% See also InitCSX AddMetal AddMaterial AddExcitation calcPort
+
+%% validate arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%check mesh
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+if (~isfield(CSX.RectilinearGrid,'XLines') || ~isfield(CSX.RectilinearGrid,'YLines') || ~isfield(CSX.RectilinearGrid,'ZLines'))
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+
+% check dir
+dir = DirChar2Int(dir);
+
+%set defaults
+feed_shift = 0;
+feed_R = inf; %(default is open, no resitance)
+excite_amp = 0;
+measplanepos = nan;
+PortNamePrefix = '';
+
+excite_args = {};
+
+%% read optional arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'FeedShift')==1);
+ feed_shift = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'FeedShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'Feed_R')==1);
+ feed_R = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'Feed_R must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'MeasPlaneShift')==1);
+ measplanepos = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'MeasPlaneShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'ExciteAmp')==1);
+ excite_amp = varargin{n+1};
+ elseif (strcmpi(varargin{n},'PortNamePrefix'))
+ PortNamePrefix = varargin{n+1};
+ else
+ excite_args{end+1} = varargin{n};
+ excite_args{end+1} = varargin{n+1};
+ end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% determine index (1, 2 or 3) of propagation (length of MSL)
+idx_prop_n = dir + 1;
+idx_prop_nP = mod((dir+1),3)+1;
+idx_prop_nPP = mod((dir+2),3)+1;
+
+% direction of propagation
+if stop(idx_prop_n)-start(idx_prop_n) > 0
+ direction = +1;
+else
+ direction = -1;
+end
+
+% create the metal for the coaxial line
+CSX = AddCylinder( CSX, pec_name, prio, start, stop, r_i );
+CSX = AddCylindricalShell( CSX, pec_name, prio, start, stop, 0.5*(r_o+r_os), r_os-r_o );
+
+% create the material filling for the coaxial line
+if (~isempty(materialname))
+ CSX = AddCylindricalShell( CSX, materialname, prio-1, start, stop, 0.5*(r_o+r_i), r_o-r_i );
+end
+
+if isnan(measplanepos)
+ measplanepos = (start(idx_prop_n)+stop(idx_prop_n))/2;
+else
+ measplanepos = start(idx_prop_n)+direction*measplanepos;
+end
+
+% calculate position of the voltage probes
+mesh{1} = sort(unique(CSX.RectilinearGrid.XLines));
+mesh{2} = sort(unique(CSX.RectilinearGrid.YLines));
+mesh{3} = sort(unique(CSX.RectilinearGrid.ZLines));
+meshlines = interp1( mesh{idx_prop_n}, 1:numel(mesh{idx_prop_n}), measplanepos, 'nearest' );
+meshlines = mesh{idx_prop_n}(meshlines-1:meshlines+1); % get three lines (approx. at center)
+if direction == -1
+ meshlines = fliplr(meshlines);
+end
+v1_start(idx_prop_n) = meshlines(1);
+v1_start(idx_prop_nP) = start(idx_prop_nP)+r_i;
+v1_start(idx_prop_nPP) = start(idx_prop_nPP);
+v1_stop = v1_start;
+v1_stop(idx_prop_nP) = start(idx_prop_nP)+r_o;
+v2_start = v1_start;
+v2_stop = v1_stop;
+v2_start(idx_prop_n) = meshlines(2);
+v2_stop(idx_prop_n) = meshlines(2);
+v3_start = v2_start;
+v3_stop = v2_stop;
+v3_start(idx_prop_n) = meshlines(3);
+v3_stop(idx_prop_n) = meshlines(3);
+
+% calculate position of the current probes
+i1_start(idx_prop_n) = 0.5*(meshlines(1)+meshlines(2));
+i1_start(idx_prop_nP) = start(idx_prop_nP)-r_i-0.1*(r_o-r_i);
+i1_start(idx_prop_nPP) = start(idx_prop_nPP)-r_i-0.1*(r_o-r_i);
+i1_stop = i1_start;
+i1_stop(idx_prop_nP) = start(idx_prop_nP)+r_i+0.1*(r_o-r_i);
+i1_stop(idx_prop_nPP) = start(idx_prop_nPP)+r_i+0.1*(r_o-r_i);
+
+i2_start = i1_start;
+i2_stop = i1_stop;
+i2_start(idx_prop_n) = 0.5*(meshlines(2)+meshlines(3));
+i2_stop(idx_prop_n) = 0.5*(meshlines(2)+meshlines(3));
+
+% create the probes
+port.U_filename{1} = [PortNamePrefix 'port_ut' num2str(portnr) 'A'];
+weight = 1;
+CSX = AddProbe( CSX, port.U_filename{1}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{1}, prio, v1_start, v1_stop );
+port.U_filename{2} = [PortNamePrefix 'port_ut' num2str(portnr) 'B'];
+CSX = AddProbe( CSX, port.U_filename{2}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{2}, prio, v2_start, v2_stop );
+port.U_filename{3} = [PortNamePrefix 'port_ut' num2str(portnr) 'C'];
+CSX = AddProbe( CSX, port.U_filename{3}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{3}, prio, v3_start, v3_stop );
+
+weight = direction;
+port.I_filename{1} = [PortNamePrefix 'port_it' num2str(portnr) 'A'];
+CSX = AddProbe( CSX, port.I_filename{1}, 1, 'weight', weight );
+CSX = AddBox( CSX, port.I_filename{1}, prio, i1_start, i1_stop );
+port.I_filename{2} = [PortNamePrefix 'port_it' num2str(portnr) 'B'];
+CSX = AddProbe( CSX, port.I_filename{2}, 1,'weight', weight );
+CSX = AddBox( CSX, port.I_filename{2}, prio, i2_start, i2_stop );
+
+% create port structure
+port.LengthScale = 1;
+port.nr = portnr;
+port.type = 'Coaxial';
+port.drawingunit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+port.v_delta = diff(meshlines)*port.LengthScale;
+port.i_delta = diff( meshlines(1:end-1) + diff(meshlines)/2 )*port.LengthScale;
+port.direction = direction;
+port.excite = 0;
+port.measplanepos = abs(v2_start(idx_prop_n) - start(idx_prop_n))*port.LengthScale;
+
+port.r_i = r_i;
+port.r_o = r_o;
+
+% create excitation (if enabled) and port resistance
+meshline = interp1( mesh{idx_prop_n}, 1:numel(mesh{idx_prop_n}), start(idx_prop_n) + feed_shift*direction, 'nearest' );
+min_cell_prop = min(diff(mesh{idx_prop_n}));
+ex_start = start;
+ex_start(idx_prop_n) = mesh{idx_prop_n}(meshline) - 0.01*min_cell_prop;
+ex_stop = ex_start;
+ex_stop(idx_prop_n) = mesh{idx_prop_n}(meshline) + 0.01*min_cell_prop;
+
+port.excite = 0;
+if (excite_amp~=0)
+ dir_names={'x','y','z'};
+ nameX = ['(' dir_names{idx_prop_nP} '-' num2str(start(idx_prop_nP)) ')'];
+ nameY = ['(' dir_names{idx_prop_nPP} '-' num2str(start(idx_prop_nPP)) ')'];
+
+ func_Ex = [ nameX '/(' nameX '*' nameX '+' nameY '*' nameY ') * (sqrt(' nameX '*' nameX '+' nameY '*' nameY ')<' num2str(r_o) ') * (sqrt(' nameX '*' nameX '+' nameY '*' nameY ')>' num2str(r_i) ')'];
+ func_Ey = [ nameY '/(' nameX '*' nameX '+' nameY '*' nameY ') * (sqrt(' nameX '*' nameX '+' nameY '*' nameY ')<' num2str(r_o) ') * (sqrt(' nameX '*' nameX '+' nameY '*' nameY ')>' num2str(r_i) ')'];
+
+ func_E{idx_prop_n} = 0;
+ func_E{idx_prop_nP} = func_Ex;
+ func_E{idx_prop_nPP} = func_Ey;
+
+ port.excite = 1;
+ evec = [1 1 1];
+ evec(idx_prop_n) = 0;
+
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], 0, evec, excite_args{:} );
+ CSX = SetExcitationWeight(CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], func_E );
+ CSX = AddCylindricalShell(CSX,[PortNamePrefix 'port_excite_' num2str(portnr)],0 ,ex_start,ex_stop,0.5*(r_i+r_o),(r_o-r_i));
+end
+
+%% resitance at start of coaxial line
+ex_start = start;
+ex_stop = stop;
+ex_stop(idx_prop_n) = ex_start(idx_prop_n);
+
+if (feed_R > 0) && ~isinf(feed_R)
+ error 'feed_R not yet implemented'
+elseif isinf(feed_R)
+ % do nothing --> open port
+elseif feed_R == 0
+ %port "resistance" as metal
+ CSX = AddBox( CSX, pec_name, prio, ex_start, ex_stop );
+ CSX = AddCylindricalShell(CSX, pec_name, prio ,ex_start, ex_stop, 0.5*(r_i+r_o),(r_o-r_i));
+else
+ error('openEMS:AddMSLPort','MSL port with resitance <= 0 it not possible');
+end
+end
diff --git a/openEMS/matlab/AddCurvePort.m b/openEMS/matlab/AddCurvePort.m
new file mode 100644
index 0000000..6ea99aa
--- /dev/null
+++ b/openEMS/matlab/AddCurvePort.m
@@ -0,0 +1,182 @@
+function [CSX,port] = AddCurvePort( CSX, prio, portnr, R, start, stop, excite, varargin )
+%[CSX,port] = AddCurvePort( CSX, prio, portnr, R, start, stop [, excite, varargin] )
+%
+% Creates a curve port (1-dimensional).
+% The mesh must already be initialized.
+%
+% input:
+% CSX: CSX-object created by InitCSX()
+% prio: priority for excitation, metal, sheet and probe boxes
+% portnr: (integer) number of the port
+% R: internal resistance of the port
+% start: 3D start rowvector for port definition
+% stop: 3D end rowvector for port definition
+% excite (optional): if true, the port will be switched on (see AddExcitation())
+% Note: for legacy support a string will be accepted
+% optional (key/values):
+% varargin: optional additional excitations options, see also AddExcitation
+% 'PortNamePrefix': a prefix to the port name
+%
+% output:
+% CSX:
+% port:
+%
+% example:
+% start = [0 0 0]; stop = [0 0 12];
+% this defines a lumped port in z-direction
+% the excitation/probe is placed between start(1) and stop(1)
+%
+% (C) 2010 Sebastian Held <sebastian.held@uni-due.de>
+% See also InitCSX AddExcitation
+
+port.type='Lumped';
+port.nr=portnr;
+
+PortNamePrefix = '';
+
+varargin_tmp = varargin;
+for n=1:2:numel(varargin_tmp)
+ if strcmpi('PortNamePrefix',varargin_tmp{n})
+ PortNamePrefix = varargin_tmp{n+1};
+ varargin([n n+1]) = [];
+ end
+end
+
+% make row vector
+start = reshape( start, 1, [] );
+stop = reshape( stop , 1, [] );
+
+% get grid
+mesh{1} = sort(unique(CSX.RectilinearGrid.XLines));
+mesh{2} = sort(unique(CSX.RectilinearGrid.YLines));
+mesh{3} = sort(unique(CSX.RectilinearGrid.ZLines));
+unit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+
+% find port direction
+dir = abs(stop - start);
+[dummy,dir] = max(dir);
+
+% other directions
+dir1 = mod(dir,3)+1;
+dir2 = mod(dir+1,3)+1;
+
+% normalize start and stop
+if start(dir) < stop(dir)
+ nstart = start;
+ nstop = stop;
+else
+ nstart = stop;
+ nstop = start;
+end
+
+% snap to grid
+start_idx = zeros(1,3);
+stop_idx = zeros(1,3);
+for n=1:3
+ start_idx(n) = interp1( mesh{n}, 1:numel(mesh{n}), nstart(n), 'nearest' );
+ stop_idx(n) = interp1( mesh{n}, 1:numel(mesh{n}), nstop(n), 'nearest' );
+end
+
+% calculate position
+port_start_idx = start_idx;
+port_stop_idx = stop_idx;
+if abs(start_idx(dir) - stop_idx(dir)) ~= 1
+ % calc port position
+ idx = interp1( mesh{dir}, 1:numel(mesh{dir}), (nstart(dir)+nstop(dir))/2, 'nearest' );
+ idx1 = interp1( mesh{dir1}, 1:numel(mesh{dir1}), (nstart(dir1)+nstop(dir1))/2, 'nearest' );
+ idx2 = interp1( mesh{dir2}, 1:numel(mesh{dir2}), (nstart(dir2)+nstop(dir2))/2, 'nearest' );
+ port_start_idx(dir) = idx;
+ port_start_idx(dir1) = idx1;
+ port_start_idx(dir2) = idx2;
+ port_stop_idx(dir) = idx+1;
+ port_stop_idx(dir1) = idx1;
+ port_stop_idx(dir2) = idx2;
+ metalname = [PortNamePrefix 'port' num2str(portnr) '_PEC'];
+ CSX = AddMetal( CSX, metalname );
+ CSX = AddCurve( CSX, metalname, prio, [nstart.' [mesh{1}(port_start_idx(1));mesh{2}(port_start_idx(2));mesh{3}(port_start_idx(3))]] );
+ CSX = AddCurve( CSX, metalname, prio, [nstop.' [mesh{1}(port_stop_idx(1));mesh{2}(port_stop_idx(2));mesh{3}(port_stop_idx(3))]] );
+end
+
+% calculate position of resistive material
+delta1_n = mesh{dir1}(port_start_idx(dir1)) - mesh{dir1}(port_start_idx(dir1)-1);
+delta1_p = mesh{dir1}(port_start_idx(dir1)+1) - mesh{dir1}(port_start_idx(dir1));
+delta2_n = mesh{dir2}(port_start_idx(dir2)) - mesh{dir2}(port_start_idx(dir2)-1);
+delta2_p = mesh{dir2}(port_start_idx(dir2)+1) - mesh{dir2}(port_start_idx(dir2));
+m_start = zeros(1,3);
+m_stop = zeros(1,3);
+for n=1:3
+ m_start(n) = mesh{n}(port_start_idx(n));
+ m_stop(n) = mesh{n}(port_stop_idx(n));
+end
+m_start(dir1) = m_start(dir1) - delta1_n/2;
+m_stop(dir1) = m_stop(dir1) + delta1_p/2;
+m_start(dir2) = m_start(dir2) - delta2_n/2;
+m_stop(dir2) = m_stop(dir2) + delta2_p/2;
+
+% calculate position of the voltage probe & excitation
+v_start = [mesh{1}(port_start_idx(1)), mesh{2}(port_start_idx(2)), mesh{3}(port_start_idx(3))];
+v_stop = [mesh{1}(port_stop_idx(1)), mesh{2}(port_stop_idx(2)), mesh{3}(port_stop_idx(3))];
+
+% calculate position of the current probe
+i_start = m_start;
+i_stop = m_stop;
+i_start(dir) = (i_start(dir)+i_stop(dir))/2;
+i_stop(dir) = i_start(dir);
+
+% create the probes
+port.U_filename = [PortNamePrefix 'port_ut' num2str(portnr)];
+weight = -1;
+CSX = AddProbe( CSX, port.U_filename, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename, prio, v_start, v_stop );
+port.I_filename = [PortNamePrefix 'port_it' num2str(portnr)];
+weight = 1;
+CSX = AddProbe( CSX, port.I_filename, 1, 'weight', weight );
+CSX = AddBox( CSX, port.I_filename, prio, i_start, i_stop );
+
+% create port structure
+port.drawingunit = unit;
+% port.start = start;
+% port.stop = stop;
+% port.v_start = v_start;
+% port.v_stop = v_stop;
+% port.i_start = i_start;
+% port.i_stop = i_stop;
+% port.dir = dir;
+% port.direction = direction;
+% port.idx_cal = idx_cal;
+% port.idx1 = idx1;
+% port.idx1 = idx1;
+
+if (nargin < 7)
+ excite = false;
+end
+
+% legacy support, will be removed at some point
+if ischar(excite)
+ warning('CSXCAD:AddCurvePort','depreceated: a string as excite option is no longer supported and will be removed in the future, please use true or false');
+ if ~isempty(excite)
+ excite = true;
+ else
+ excite = false;
+ end
+end
+
+port.excite = excite;
+
+% create excitation
+if (excite)
+ % excitation of this port is enabled
+ port.excite = 1;
+ e_start = v_start;
+ e_stop = v_stop;
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], 0, start_idx ~= stop_idx, varargin{:});
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], prio, e_start, e_stop );
+end
+
+port.Feed_R = R;
+if (R>0 && (~isinf(R)))
+ CSX = AddLumpedElement( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], dir-1, 'R', R);
+ CSX = AddBox( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], prio, v_start, v_stop );
+elseif (R==0)
+ CSX = AddBox(CSX,metalname, prio, v_start, v_stop);
+end \ No newline at end of file
diff --git a/openEMS/matlab/AddLumpedPort.m b/openEMS/matlab/AddLumpedPort.m
new file mode 100644
index 0000000..ad6d5fa
--- /dev/null
+++ b/openEMS/matlab/AddLumpedPort.m
@@ -0,0 +1,129 @@
+function [CSX, port] = AddLumpedPort( CSX, prio, portnr, R, start, stop, dir, excite, varargin )
+% [CSX, port] = AddLumpedPort( CSX, prio, portnr, R, start, stop, dir, excite, varargin )
+%
+% Add a lumped port as an excitation.
+%
+% A lumped port consists of an excitation, a lumped resistor, a voltage and
+% current probe.
+%
+% CSX: CSX-object created by InitCSX()
+% prio: priority for substrate and probe boxes
+% portnr: (integer) number of the port
+% R: internal resistance of the port (lumped element)
+% start: 3D start rowvector for port definition
+% stop: 3D end rowvector for port definition
+% dir: direction/amplitude of port (e.g.: [1 0 0], [0 1 0] or [0 0 1])
+% excite (optional): if true, the port will be switched on (see AddExcitation())
+% Note: for legacy support a string will be accepted
+% V_Probe_Weight: additional weigth for the voltage probes
+% I_Probe_Weight: additional weigth for the current probes
+% optional (key/values):
+% 'PortNamePrefix': an prefix to the port name
+% varargin (optional): additional excitations options, see also AddExcitation
+%
+% example:
+% start = [0 -width/2 0];
+% stop = [0 width/2 height];
+% [CSX] = AddLumpedPort(CSX, 5 ,1 , 50, start, stop, [0 0 1], true);
+% %this defines an active lumped port in z-direction with a 50 Ohm port impedence
+%
+% openEMS matlab interface
+% -----------------------
+% Sebastian Held <sebastian.held@gmx.de>
+% Jun 1 2010
+% Thorsten Liebig
+% Jul 13 2011
+%
+% See also InitCSX AddExcitation
+
+% check dir
+
+port.type='Lumped';
+port.nr=portnr;
+
+V_Probe_Weight = 1;
+I_Probe_Weight = 1;
+
+if (dir(1)~=0) && (dir(2) == 0) && (dir(3)==0)
+ n_dir = 1;
+elseif (dir(1)==0) && (dir(2) ~= 0) && (dir(3)==0)
+ n_dir = 2;
+elseif (dir(1)==0) && (dir(2) == 0) && (dir(3)~=0)
+ n_dir = 3;
+else
+ error 'dir must have exactly one component ~= 0'
+end
+
+PortNamePrefix = '';
+
+varargin_tmp = varargin;
+for n=1:2:numel(varargin_tmp)
+ if strcmpi('PortNamePrefix',varargin_tmp{n})
+ PortNamePrefix = varargin_tmp{n+1};
+ varargin([n n+1]) = [];
+ elseif strcmpi('V_Probe_Weight',varargin_tmp{n})
+ V_Probe_Weight = varargin_tmp{n+1};
+ elseif strcmpi('I_Probe_Weight',varargin_tmp{n})
+ I_Probe_Weight = varargin_tmp{n+1};
+ end
+end
+
+if (stop(n_dir)==start(n_dir))
+ error 'start/stop in excitation direction in must not be equal'
+end
+
+if (stop(n_dir)-start(n_dir)) > 0
+ direction = +1;
+else
+ direction = -1;
+end
+port.direction = direction;
+
+port.Feed_R = R;
+if (R>0 && (~isinf(R)))
+ CSX = AddLumpedElement(CSX,[PortNamePrefix 'port_resist_' int2str(portnr)], n_dir-1, 'Caps', 1, 'R', R);
+ CSX = AddBox(CSX,[PortNamePrefix 'port_resist_' int2str(portnr)], prio, start, stop);
+elseif (R<=0)
+ CSX = AddMetal(CSX,[PortNamePrefix 'port_resist_' int2str(portnr)]);
+ CSX = AddBox(CSX,[PortNamePrefix 'port_resist_' int2str(portnr)], prio, start, stop);
+end
+
+if (nargin < 8)
+ excite = false;
+end
+
+% legacy support, will be removed at some point
+if ischar(excite)
+ warning('CSXCAD:AddLumpedPort','depreceated: a string as excite option is no longer supported and will be removed in the future, please use true or false');
+ if ~isempty(excite)
+ excite = true;
+ else
+ excite = false;
+ end
+end
+
+port.excite = excite;
+% create excitation
+if (excite)
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], 0, -dir*direction, varargin{:});
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], prio, start, stop );
+end
+
+u_start = 0.5*(start + stop);
+u_stop = 0.5*(start + stop);
+u_start(n_dir) = start(n_dir);
+u_stop(n_dir) = stop(n_dir);
+
+port.U_filename = [PortNamePrefix 'port_ut' int2str(portnr)];
+CSX = AddProbe(CSX, port.U_filename, 0, 'weight', -direction*V_Probe_Weight);
+CSX = AddBox(CSX, port.U_filename, prio, u_start, u_stop);
+
+i_start = start;
+i_stop = stop;
+i_start(n_dir) = 0.5*(start(n_dir)+stop(n_dir));
+i_stop(n_dir) = 0.5*(start(n_dir)+stop(n_dir));
+
+port.I_filename = [PortNamePrefix 'port_it' int2str(portnr)];
+CSX = AddProbe(CSX, port.I_filename, 1, 'weight', direction*I_Probe_Weight, 'NormDir', n_dir-1);
+CSX = AddBox(CSX, port.I_filename, prio, i_start, i_stop);
+
diff --git a/openEMS/matlab/AddMRStub.m b/openEMS/matlab/AddMRStub.m
new file mode 100644
index 0000000..432fa6a
--- /dev/null
+++ b/openEMS/matlab/AddMRStub.m
@@ -0,0 +1,73 @@
+function CSX = AddMRStub( CSX, materialname, prio, MSL_width, len, alpha, resolution, orientation, normVector, position )
+% CSX = AddMRStub( CSX, materialname, prio, MSL_width, len, alpha,
+% resolution, orientation, normVector, position )
+%
+% Microstrip Radial Stub
+%
+% CSX: CSX-object created by InitCSX()
+% materialname: property for the MSL (created by AddMetal() or AddMaterial())
+% prio: priority
+% MSL_width: width of the MSL to connect the stub to
+% len: length of the radial stub
+% alpha: angle subtended by the radial stub (degrees)
+% resolution: discrete angle spacing (degrees)
+% orientation: angle of main direction of the radial stub (degrees)
+% normVector: normal vector of the stub
+% position: position of the end of the MSL
+%
+% This radial stub definition is equivalent to the one Agilent ADS uses.
+%
+% example:
+% CSX = AddMRStub( CSX, 'PEC', 10, 1000, 5900, 30, 1, -90, [0 0 1], [0 -10000 254] );
+%
+%
+% Sebastian Held <sebastian.held@gmx.de>
+% Jun 1 2010
+%
+% See also InitCSX AddMetal AddMaterial
+
+% check normVector
+if ~(normVector(1) == normVector(2) == 0) && ...
+ ~(normVector(1) == normVector(3) == 0) && ...
+ ~(normVector(2) == normVector(3) == 0) || (sum(normVector) == 0)
+ error 'normVector must have exactly one component ~= 0'
+end
+normVector = normVector ./ sum(normVector); % normVector is now a unit vector
+
+% convert angles to radians
+alpha_rad = alpha/180*pi;
+orientation_rad = orientation/180*pi;
+resolution_rad = resolution/180*pi;
+
+%
+% build stub at origin (0,0,0) and translate/rotate it later
+%
+
+D = 0.5 * MSL_width / sin(alpha_rad/2);
+R = cos(alpha_rad/2) * D;
+
+% point at the center of the MSL
+p(1,1) = 0;
+p(2,1) = -MSL_width/2;
+p(1,2) = 0;
+p(2,2) = MSL_width/2;
+
+for a = alpha_rad/2 : -resolution_rad : -alpha_rad/2
+ p(1,end+1) = cos(a) * (D+len) - R;
+ p(2,end) = sin(a) * (D+len);
+end
+
+% rotate
+rot = [cos(-orientation_rad), -sin(-orientation_rad); sin(-orientation_rad), cos(-orientation_rad)];
+p = (p.' * rot).';
+
+% translate
+idx_elevation = [1 2 3];
+idx_elevation = idx_elevation(normVector>0);
+dim1 = mod( idx_elevation, 3 ) + 1;
+dim2 = mod( idx_elevation+1, 3 ) + 1;
+p(1,:) = p(1,:) + position(dim1);
+p(2,:) = p(2,:) + position(dim2);
+
+elevation = position(idx_elevation);
+CSX = AddPolygon( CSX, materialname, prio, normVector, elevation, p );
diff --git a/openEMS/matlab/AddMSLPort.m b/openEMS/matlab/AddMSLPort.m
new file mode 100644
index 0000000..462db14
--- /dev/null
+++ b/openEMS/matlab/AddMSLPort.m
@@ -0,0 +1,265 @@
+function [CSX,port] = AddMSLPort( CSX, prio, portnr, materialname, start, stop, dir, evec, varargin )
+% [CSX,port] = AddMSLPort( CSX, prio, portnr, materialname, start, stop, dir, evec, varargin )
+%
+% CSX: CSX-object created by InitCSX()
+% prio: priority for excitation and probe boxes
+% portnr: (integer) number of the port
+% materialname: property for the MSL (created by AddMetal())
+% start: 3D start rowvector for port definition
+% stop: 3D end rowvector for port definition
+% dir: direction of wave propagation (choices: 0, 1, 2 or 'x','y','z')
+% evec: excitation vector, which defines the direction of the e-field (must be the same as used in AddExcitation())
+%
+% variable input:
+% varargin: optional additional excitations options, see also AddExcitation
+% 'ExcitePort' true/false to make the port an active feeding port (default
+% is false)
+% 'FeedShift' shift to port from start by a given distance in drawing
+% units. Default is 0. Only active if 'ExcitePort' is set!
+% 'Feed_R' Specifiy a lumped port resistance. Default is no lumped
+% port resistance --> port has to end in an ABC.
+% 'MeasPlaneShift' Shift the measurement plane from start t a given distance
+% in drawing units. Default is the middle of start/stop.
+% 'PortNamePrefix' a prefix to the port name
+%
+% Important: The mesh has to be already set and defined by DefineRectGrid!
+%
+% example:
+% CSX = AddMetal( CSX, 'metal' ); %create a PEC called 'metal'
+% start = [0 -width/2 height];
+% stop = [length +width/2 0 ];
+% [CSX,port] = AddMSLPort( CSX, 0, 1, 'metal', start, stop, 'x', [0 0 -1], ...
+% 'ExcitePort', true, 'Feed_R', 50 )
+% Explanation:
+% - this defines a MSL in x-direction (dir='x')
+% --> the wave travels along the x-direction
+% - with an e-field excitation in -z-direction (evec=[0 0 -1])
+% - the excitation is active and placed at x=start(1) ('ExcitePort', true)
+% - a 50 Ohm lumped port resistance is placed at x=start(1) ('Feed_R', 50)
+% - the width-direction is determined by the cross product of the
+% direction of propagtion (dir='x') and the excitation vector
+% (evec=[0 0 -1]), in this case it is the y-direction
+% - the MSL-metal is created in a xy-plane at a height at z=start(3)
+% --> It is important to define the MSL height in the start coordinate!
+% - the ground (xy-plane, not defined by the port) is assumed at z=stop(3)
+% --> The reference plane (ground) is defined in the stop coordinate!
+%
+% Sebastian Held <sebastian.held@gmx.de> May 13 2010
+% Thorsten Liebig <thorsten.liebig@gmx.de> (c) 2011-2013
+%
+% See also InitCSX DefineRectGrid AddMetal AddMaterial AddExcitation calcPort
+
+%% validate arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%check mesh
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+if (~isfield(CSX.RectilinearGrid,'XLines') || ~isfield(CSX.RectilinearGrid,'YLines') || ~isfield(CSX.RectilinearGrid,'ZLines'))
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+
+% check dir
+dir = DirChar2Int(dir);
+
+% check evec
+if ~(evec(1) == evec(2) == 0) && ~(evec(1) == evec(3) == 0) && ~(evec(2) == evec(3) == 0) || (sum(evec) == 0)
+ error 'evec must have exactly one component ~= 0'
+end
+evec0 = evec ./ sum(evec); % evec0 is a unit vector
+
+%set defaults
+feed_shift = 0;
+feed_R = inf; %(default is open, no resitance)
+excite = false;
+measplanepos = nan;
+PortNamePrefix = '';
+
+excite_args = {};
+
+%% read optional arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'FeedShift')==1);
+ feed_shift = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'FeedShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'Feed_R')==1);
+ feed_R = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'Feed_R must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'MeasPlaneShift')==1);
+ measplanepos = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'MeasPlaneShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'ExcitePort')==1);
+ if ischar(varargin{n+1})
+ warning('CSXCAD:AddMSLPort','depreceated: a string as excite option is no longer supported and will be removed in the future, please use true or false');
+ if ~isempty(excite)
+ excite = true;
+ else
+ excite = false;
+ end
+ else
+ excite = varargin{n+1};
+ end
+ elseif (strcmpi(varargin{n},'PortNamePrefix'))
+ PortNamePrefix = varargin{n+1};
+ else
+ excite_args{end+1} = varargin{n};
+ excite_args{end+1} = varargin{n+1};
+ end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% normalize start and stop
+nstart = min( [start;stop] );
+nstop = max( [start;stop] );
+
+% determine index (1, 2 or 3) of propagation (length of MSL)
+idx_prop = dir + 1;
+
+% determine index (1, 2 or 3) of width of MSL
+dir = [0 0 0];
+dir(idx_prop) = 1;
+idx_width = abs(cross(dir,evec0)) * [1;2;3];
+
+% determine index (1, 2 or 3) of height
+idx_height = abs(evec0) * [1;2;3];
+
+% direction of propagation
+if stop(idx_prop)-start(idx_prop) > 0
+ direction = +1;
+else
+ direction = -1;
+end
+
+% direction of propagation
+if stop(idx_height)-start(idx_height) > 0
+ upsidedown = +1;
+else
+ upsidedown = -1;
+end
+
+% create the metal/material for the MSL
+MSL_start = start;
+MSL_stop = stop;
+MSL_stop(idx_height) = MSL_start(idx_height);
+CSX = AddBox( CSX, materialname, prio, MSL_start, MSL_stop );
+
+if isnan(measplanepos)
+ measplanepos = (nstart(idx_prop)+nstop(idx_prop))/2;
+else
+ measplanepos = start(idx_prop)+direction*measplanepos;
+end
+
+% calculate position of the voltage probes
+mesh{1} = sort(CSX.RectilinearGrid.XLines);
+mesh{2} = sort(CSX.RectilinearGrid.YLines);
+mesh{3} = sort(CSX.RectilinearGrid.ZLines);
+meshlines = interp1( mesh{idx_prop}, 1:numel(mesh{idx_prop}), measplanepos, 'nearest' );
+meshlines = mesh{idx_prop}(meshlines-1:meshlines+1); % get three lines (approx. at center)
+if direction == -1
+ meshlines = fliplr(meshlines);
+end
+MSL_w2 = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), (nstart(idx_width)+nstop(idx_width))/2, 'nearest' );
+MSL_w2 = mesh{idx_width}(MSL_w2); % get e-line at center of MSL (MSL_width/2)
+v1_start(idx_prop) = meshlines(1);
+v1_start(idx_width) = MSL_w2;
+v1_start(idx_height) = start(idx_height);
+v1_stop = v1_start;
+v1_stop(idx_height) = stop(idx_height);
+v2_start = v1_start;
+v2_stop = v1_stop;
+v2_start(idx_prop) = meshlines(2);
+v2_stop(idx_prop) = meshlines(2);
+v3_start = v2_start;
+v3_stop = v2_stop;
+v3_start(idx_prop) = meshlines(3);
+v3_stop(idx_prop) = meshlines(3);
+
+% calculate position of the current probes
+idx = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), nstart(idx_width), 'nearest' );
+i1_start(idx_width) = mesh{idx_width}(idx) - diff(mesh{idx_width}(idx-1:idx))/2;
+idx = interp1( mesh{idx_height}, 1:numel(mesh{idx_height}), start(idx_height), 'nearest' );
+i1_start(idx_height) = mesh{idx_height}(idx-1) - diff(mesh{idx_height}(idx-2:idx-1))/2;
+i1_stop(idx_height) = mesh{idx_height}(idx+1) + diff(mesh{idx_height}(idx+1:idx+2))/2;
+i1_start(idx_prop) = sum(meshlines(1:2))/2;
+i1_stop(idx_prop) = i1_start(idx_prop);
+idx = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), nstop(idx_width), 'nearest' );
+i1_stop(idx_width) = mesh{idx_width}(idx) + diff(mesh{idx_width}(idx:idx+1))/2;
+i2_start = i1_start;
+i2_stop = i1_stop;
+i2_start(idx_prop) = sum(meshlines(2:3))/2;
+i2_stop(idx_prop) = i2_start(idx_prop);
+
+% create the probes
+port.U_filename{1} = [PortNamePrefix 'port_ut' num2str(portnr) 'A'];
+% weight = sign(stop(idx_height)-start(idx_height))
+weight = upsidedown;
+CSX = AddProbe( CSX, port.U_filename{1}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{1}, prio, v1_start, v1_stop );
+port.U_filename{2} = [PortNamePrefix 'port_ut' num2str(portnr) 'B'];
+CSX = AddProbe( CSX, port.U_filename{2}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{2}, prio, v2_start, v2_stop );
+port.U_filename{3} = [PortNamePrefix 'port_ut' num2str(portnr) 'C'];
+CSX = AddProbe( CSX, port.U_filename{3}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{3}, prio, v3_start, v3_stop );
+
+weight = direction;
+port.I_filename{1} = [PortNamePrefix 'port_it' num2str(portnr) 'A'];
+CSX = AddProbe( CSX, port.I_filename{1}, 1, 'weight', weight );
+CSX = AddBox( CSX, port.I_filename{1}, prio, i1_start, i1_stop );
+port.I_filename{2} = [PortNamePrefix 'port_it' num2str(portnr) 'B'];
+CSX = AddProbe( CSX, port.I_filename{2}, 1,'weight', weight );
+CSX = AddBox( CSX, port.I_filename{2}, prio, i2_start, i2_stop );
+
+% create port structure
+port.LengthScale = 1;
+if ((CSX.ATTRIBUTE.CoordSystem==1) && (idx_prop==2))
+ port.LengthScale = MSL_stop(idx_height);
+end
+port.nr = portnr;
+port.type = 'MSL';
+port.drawingunit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+port.v_delta = diff(meshlines)*port.LengthScale;
+port.i_delta = diff( meshlines(1:end-1) + diff(meshlines)/2 )*port.LengthScale;
+port.direction = direction;
+port.excite = 0;
+port.measplanepos = abs(v2_start(idx_prop) - start(idx_prop))*port.LengthScale;
+% port
+
+% create excitation (if enabled) and port resistance
+meshline = interp1( mesh{idx_prop}, 1:numel(mesh{idx_prop}), start(idx_prop) + feed_shift*direction, 'nearest' );
+ex_start(idx_prop) = mesh{idx_prop}(meshline) ;
+ex_start(idx_width) = nstart(idx_width);
+ex_start(idx_height) = nstart(idx_height);
+ex_stop(idx_prop) = ex_start(idx_prop);
+ex_stop(idx_width) = nstop(idx_width);
+ex_stop(idx_height) = nstop(idx_height);
+
+port.excite = 0;
+if excite
+ port.excite = 1;
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], 0, evec, excite_args{:} );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_' num2str(portnr)], prio, ex_start, ex_stop );
+end
+
+%% MSL resitance at start of MSL line
+ex_start(idx_prop) = start(idx_prop);
+ex_stop(idx_prop) = ex_start(idx_prop);
+
+if (feed_R > 0) && ~isinf(feed_R)
+ CSX = AddLumpedElement( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], idx_height-1, 'R', feed_R );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], prio, ex_start, ex_stop );
+elseif isinf(feed_R)
+ % do nothing --> open port
+elseif feed_R == 0
+ %port "resistance" as metal
+ CSX = AddBox( CSX, materialname, prio, ex_start, ex_stop );
+else
+ error('openEMS:AddMSLPort','MSL port with resitance <= 0 it not possible');
+end
+end
diff --git a/openEMS/matlab/AddPML.m b/openEMS/matlab/AddPML.m
new file mode 100644
index 0000000..4e7ba80
--- /dev/null
+++ b/openEMS/matlab/AddPML.m
@@ -0,0 +1,92 @@
+function mesh = AddPML( mesh, numcells, CoordSystem )
+% mesh = AddPML( mesh, numcells, <CoordSystem> )
+%
+% Adds equidistant cells to the specified directions of the simulation
+% area. This is used to put a PML (perfectly matched layer) absorber there.
+% Remember: this function only adds space for the PML, the boundary
+% conditions need to be set correctly to really add PML material.
+%
+% The mesh is sorted and duplicate lines are removed.
+%
+% input:
+% mesh: mesh structure
+% numcells: 1x6 vector (xmin,xmax,ymin,ymax,zmin,zmax) with number of
+% cells to add to this direction
+% CoordSystem (optional): set to 1 in case of cylindrical mesh using
+% mesh.r, mesh.a and mesh.z
+%
+% output:
+% mesh: new mesh with the added lines
+%
+% example:
+% % some fixed mesh lines
+% mesh.x = [-100 0 100];
+% mesh.y = [-100 0 100];
+% mesh.z = [0 500];
+% mesh = DetectEdges(CSX, mesh); %detect edges
+% mesh = SmoothMesh(mesh, c0/fmax/20/unit); % smooth the mesh
+%
+% mesh = AddPML(mesh, 8); % add 8 lines to all directions
+% % or
+% mesh = AddPML(mesh, [0 0 0 0 8 8]); % add 8 lines in both z-directions
+%
+% See also DefineRectGrid, SmoothMesh, DetectEdges
+%
+% openEMS matlab interface
+% -----------------------
+% Sebastian Held <sebastian.held@uni-due.de>
+
+% check
+error( nargchk(2,3,nargin) );
+
+if (numel(numcells)==1)
+ numcells = ones(6,1)*numcells;
+end
+
+numcells = reshape( numcells, 1, [] );
+if numel(numcells) ~= 6
+ error( 'argument numcells needs to have exactly 6 elements' );
+end
+
+if (nargin<3)
+ CoordSystem = 0;
+end
+
+dir_names = 'xyz';
+if (CoordSystem==1)
+ dir_names = 'raz';
+end
+
+mesh.(dir_names(1)) = unique(sort(mesh.(dir_names(1))));
+mesh.(dir_names(2)) = unique(sort(mesh.(dir_names(2))));
+mesh.(dir_names(3)) = unique(sort(mesh.(dir_names(3))));
+
+% xmin
+delta = mesh.(dir_names(1))(2) - mesh.(dir_names(1))(1);
+start = mesh.(dir_names(1))(1) - numcells(1)*delta;
+mesh.(dir_names(1)) = [start:delta:(mesh.(dir_names(1))(1)-delta), mesh.(dir_names(1))];
+
+% xmax
+delta = mesh.(dir_names(1))(end) - mesh.(dir_names(1))(end-1);
+stop = mesh.(dir_names(1))(end) + numcells(2)*delta;
+mesh.(dir_names(1)) = [mesh.(dir_names(1)), (mesh.(dir_names(1))(end)+delta):delta:stop];
+
+% ymin
+delta = mesh.(dir_names(2))(2) - mesh.(dir_names(2))(1);
+start = mesh.(dir_names(2))(1) - numcells(3)*delta;
+mesh.(dir_names(2)) = [start:delta:(mesh.(dir_names(2))(1)-delta), mesh.(dir_names(2))];
+
+% ymax
+delta = mesh.(dir_names(2))(end) - mesh.(dir_names(2))(end-1);
+stop = mesh.(dir_names(2))(end) + numcells(4)*delta;
+mesh.(dir_names(2)) = [mesh.(dir_names(2)), (mesh.(dir_names(2))(end)+delta):delta:stop];
+
+% zmin
+delta = mesh.(dir_names(3))(2) - mesh.(dir_names(3))(1);
+start = mesh.(dir_names(3))(1) - numcells(5)*delta;
+mesh.(dir_names(3)) = [start:delta:(mesh.(dir_names(3))(1)-delta), mesh.(dir_names(3))];
+
+% zmax
+delta = mesh.(dir_names(3))(end) - mesh.(dir_names(3))(end-1);
+stop = mesh.(dir_names(3))(end) + numcells(6)*delta;
+mesh.(dir_names(3)) = [mesh.(dir_names(3)), (mesh.(dir_names(3))(end)+delta):delta:stop];
diff --git a/openEMS/matlab/AddRectWaveGuidePort.m b/openEMS/matlab/AddRectWaveGuidePort.m
new file mode 100644
index 0000000..8233f77
--- /dev/null
+++ b/openEMS/matlab/AddRectWaveGuidePort.m
@@ -0,0 +1,92 @@
+function [CSX,port] = AddRectWaveGuidePort( CSX, prio, portnr, start, stop, dir, a, b, mode_name, exc_amp, varargin )
+% function [CSX,port] = AddRectWaveGuidePort( CSX, prio, portnr, start, stop, dir, a, b, mode_name, exc_amp, varargin )
+%
+% Create a rectangular waveguide port, including an optional excitation and probes
+%
+% Note: - The excitation will be located at the start position in the given direction
+% - The voltage and current probes at the stop position in the given direction
+%
+% input:
+% CSX: complete CSX structure (must contain a mesh)
+% prio: priority of primitives
+% start: start coordinates of waveguide port box
+% stop: stop coordinates of waveguide port box
+% dir: direction of port (0/1/2 or 'x'/'y'/'z'-direction)
+% a,b: rectangular waveguide width and height (in meter)
+% mode_name: mode name, e.g. 'TE11' or 'TM21'
+% exc_amp: excitation amplitude (set 0 to be passive)
+%
+% optional (key/values):
+% varargin: optional additional excitations options, see also AddExcitation
+% 'PortNamePrefix': a prefix to the port name
+%
+% output:
+% CSX: modified CSX structure
+% port: port structure to use with calcPort
+%
+% example:
+% % create a TE10 circular waveguide mode, using cylindircal coordinates
+% start=[mesh.r(1) mesh.a(1) 0 ];
+% stop =[mesh.r(end) mesh.a(end) 100];
+% [CSX,port] = AddCircWaveGuidePort( CSX, 99, 1, start, stop, 320e-3, 'TE11', 0, 1);
+%
+% openEMS matlab interface
+% -----------------------
+% (c) 2013 Thorsten Liebig (thorsten.liebig@gmx.de)
+%
+% See also InitCSX, AddExcitation, calcWGPort, calcPort
+
+if (~strcmpi(mode_name(1:2),'TE'))
+ error 'currently only TE type modes are supported'
+end
+
+if (nargin<10)
+ exc_amp = 0;
+end
+
+m = str2double(mode_name(3));
+n = str2double(mode_name(4));
+
+% values by David M. Pozar, Microwave Engineering, third edition
+kc = sqrt((m*pi/a)^2 + (n*pi/b)^2);
+
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+ if (~isfield(CSX.RectilinearGrid,'XLines') || ~isfield(CSX.RectilinearGrid,'YLines') || ~isfield(CSX.RectilinearGrid,'ZLines'))
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+ end
+end
+
+unit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+
+dir = DirChar2Int(dir);
+dir_names={'x','y','z'};
+
+dirP = mod((dir+1),3)+1;
+dirPP = mod((dir+2),3)+1;
+nameX = ['(' dir_names{dirP} '-' num2str(start(dirP)) ')'];
+nameY = ['(' dir_names{dirPP} '-' num2str(start(dirPP)) ')'];
+
+%convert a&b to drawing units
+a = a/unit;
+b = b/unit;
+% functions by David M. Pozar, Microwave Engineering, third edition
+% electric field mode profile
+func_Ex = [num2str( n/b) '*cos(' num2str(m*pi/a) '*' nameX ')*sin(' num2str(n*pi/b) '*' nameY ')'];
+func_Ey = [num2str(-m/a) '*sin(' num2str(m*pi/a) '*' nameX ')*cos(' num2str(n*pi/b) '*' nameY ')'];
+
+% magnetic field mode profile
+func_Hx = [num2str(m/a) '*sin(' num2str(m*pi/a) '*' nameX ')*cos(' num2str(n*pi/b) '*' nameY ')'];
+func_Hy = [num2str(n/b) '*cos(' num2str(m*pi/a) '*' nameX ')*sin(' num2str(n*pi/b) '*' nameY ')'];
+
+
+func_E{dir+1} = 0;
+func_E{dirP} = func_Ex;
+func_E{dirPP} = func_Ey;
+
+func_H{dir+1} = 0;
+func_H{dirP} = func_Hx;
+func_H{dirPP} = func_Hy;
+
+[CSX,port] = AddWaveGuidePort( CSX, prio, portnr, start, stop, dir, func_E, func_H, kc, exc_amp, varargin{:} );
+
diff --git a/openEMS/matlab/AddStripLinePort.m b/openEMS/matlab/AddStripLinePort.m
new file mode 100644
index 0000000..70dd065
--- /dev/null
+++ b/openEMS/matlab/AddStripLinePort.m
@@ -0,0 +1,283 @@
+function [CSX,port] = AddStripLinePort( CSX, prio, portnr, materialname, start, stop, height, dir, evec, varargin )
+% [CSX,port] = AddStripLinePort( CSX, prio, portnr, materialname, start, stop, height, dir, evec, varargin )
+%
+% CSX: CSX-object created by InitCSX()
+% prio: priority for excitation and probe boxes
+% portnr: (integer) number of the port
+% materialname: property for the MSL (created by AddMetal())
+% start: 3D start rowvector for port definition
+% stop: 3D end rowvector for port definition
+% height: height of the stripline (top and bottom)
+% dir: direction of wave propagation (choices: 0, 1, 2 or 'x','y','z')
+% evec: excitation vector, which defines the direction of the e-field (must be the same as used in AddExcitation())
+%
+% variable input:
+% varargin: optional additional excitations options, see also AddExcitation
+% 'ExcitePort' true/false to make the port an active feeding port (default
+% is false)
+% 'FeedShift' shift to port from start by a given distance in drawing
+% units. Default is 0. Only active if 'ExcitePort' is set!
+% 'Feed_R' Specifiy a lumped port resistance. Default is no lumped
+% port resistance --> port has to end in an ABC.
+% 'MeasPlaneShift' Shift the measurement plane from start t a given distance
+% in drawing units. Default is the middle of start/stop.
+% 'PortNamePrefix' a prefix to the port name
+%
+% Important: The mesh has to be already set and defined by DefineRectGrid!
+%
+% example:
+% CSX = AddMetal( CSX, 'metal' ); %create a PEC called 'metal'
+% start = [0 -width/2 0];
+% stop = [length +width/2 0];
+% [CSX,port] = AddStripLinePort( CSX, 0, 1, 'metal', start, stop, height, 'x', ...
+% [0 0 -1], 'ExcitePort', true, 'Feed_R', 50 )
+% Explanation:
+% - this defines a stripline in x-direction (dir='x')
+% --> the wave travels along the x-direction
+% - with an e-field excitation in -z-direction (evec=[0 0 -1])
+% - the excitation is active and placed at x=start(1) ('ExcitePort', true)
+% - a 50 Ohm lumped port resistance is placed at x=start(1) ('Feed_R', 50)
+% - the width-direction is determined by the cross product of the
+% direction of propagtion (dir='x') and the excitation vector
+% (evec=[0 0 -1]), in this case it is the y-direction
+% - the stripline-metal is created in a xy-plane at a height at z=start(3)
+% --> The upper and lower reference plane (ground) must be defined by
+% the user
+%
+% Thorsten Liebig <thorsten.liebig@gmx.de> (c) 2013
+%
+% See also InitCSX DefineRectGrid AddMetal AddMaterial AddExcitation calcPort
+
+%% validate arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%check mesh
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+if (~isfield(CSX.RectilinearGrid,'XLines') || ~isfield(CSX.RectilinearGrid,'YLines') || ~isfield(CSX.RectilinearGrid,'ZLines'))
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+
+% check dir
+dir = DirChar2Int(dir);
+
+% check evec
+if ~(evec(1) == evec(2) == 0) && ~(evec(1) == evec(3) == 0) && ~(evec(2) == evec(3) == 0) || (sum(evec) == 0)
+ error 'evec must have exactly one component ~= 0'
+end
+evec0 = evec ./ sum(evec); % evec0 is a unit vector
+
+%set defaults
+feed_shift = 0;
+feed_R = inf; %(default is open, no resitance)
+excite = false;
+measplanepos = nan;
+PortNamePrefix = '';
+
+excite_args = {};
+
+%% read optional arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'FeedShift')==1);
+ feed_shift = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'FeedShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'Feed_R')==1);
+ feed_R = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'Feed_R must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'MeasPlaneShift')==1);
+ measplanepos = varargin{n+1};
+ if (numel(feed_shift)>1)
+ error 'MeasPlaneShift must be a scalar value'
+ end
+ elseif (strcmp(varargin{n},'ExcitePort')==1);
+ if ischar(varargin{n+1})
+ warning('CSXCAD:AddMSLPort','depreceated: a string as excite option is no longer supported and will be removed in the future, please use true or false');
+ if ~isempty(excite)
+ excite = true;
+ else
+ excite = false;
+ end
+ else
+ excite = varargin{n+1};
+ end
+ elseif (strcmpi(varargin{n},'PortNamePrefix'))
+ PortNamePrefix = varargin{n+1};
+ else
+ excite_args{end+1} = varargin{n};
+ excite_args{end+1} = varargin{n+1};
+ end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% normalize start and stop
+nstart = min( [start;stop] );
+nstop = max( [start;stop] );
+
+% determine index (1, 2 or 3) of propagation (length of MSL)
+idx_prop = dir + 1;
+
+% determine index (1, 2 or 3) of width of MSL
+dir = [0 0 0];
+dir(idx_prop) = 1;
+idx_width = abs(cross(dir,evec0)) * [1;2;3];
+
+% determine index (1, 2 or 3) of height
+idx_height = abs(evec0) * [1;2;3];
+
+if (start(idx_height)~=stop(idx_height))
+ error('openEMS:AddStripLinePort','start/stop in height direction must be equal');
+end
+
+% direction of propagation
+if stop(idx_prop)-start(idx_prop) > 0
+ direction = +1;
+else
+ direction = -1;
+end
+
+% create the metal/material for the MSL
+SL_start = start;
+SL_stop = stop;
+CSX = AddBox( CSX, materialname, prio, SL_start, SL_stop );
+
+if isnan(measplanepos)
+ measplanepos = (nstart(idx_prop)+nstop(idx_prop))/2;
+else
+ measplanepos = start(idx_prop)+direction*measplanepos;
+end
+
+% calculate position of the voltage probes
+mesh{1} = sort(CSX.RectilinearGrid.XLines);
+mesh{2} = sort(CSX.RectilinearGrid.YLines);
+mesh{3} = sort(CSX.RectilinearGrid.ZLines);
+meshlines = interp1( mesh{idx_prop}, 1:numel(mesh{idx_prop}), measplanepos, 'nearest' );
+meshlines = mesh{idx_prop}(meshlines-1:meshlines+1); % get three lines (approx. at center)
+if direction == -1
+ meshlines = fliplr(meshlines);
+end
+SL_w2 = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), (nstart(idx_width)+nstop(idx_width))/2, 'nearest' );
+SL_w2 = mesh{idx_width}(SL_w2); % get e-line at center of MSL (SL_width/2)
+v1_start(idx_prop) = meshlines(1);
+v1_start(idx_width) = SL_w2;
+v1_start(idx_height) = start(idx_height);
+v1_stop = v1_start;
+v1_stop(idx_height) = v1_start(idx_height);
+v2_start = v1_start;
+v2_stop = v1_stop;
+v2_start(idx_prop) = meshlines(2);
+v2_stop(idx_prop) = meshlines(2);
+v3_start = v2_start;
+v3_stop = v2_stop;
+v3_start(idx_prop) = meshlines(3);
+v3_stop(idx_prop) = meshlines(3);
+
+height_vector = [0 0 0];
+height_vector(idx_height) = height;
+
+weight = 0.5;
+% create the voltage-probes
+port.U_filename{1,1} = [PortNamePrefix 'port_ut' num2str(portnr) 'A1'];
+CSX = AddProbe( CSX, port.U_filename{1,1}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{1,1}, prio, v1_start, v1_stop+height_vector);
+
+port.U_filename{1,2} = [PortNamePrefix 'port_ut' num2str(portnr) 'A2'];
+CSX = AddProbe( CSX, port.U_filename{1,2}, 0, 'weight', -1*weight );
+CSX = AddBox( CSX, port.U_filename{1,2}, prio, v1_start, v1_stop-height_vector);
+
+
+port.U_filename{2,1} = [PortNamePrefix 'port_ut' num2str(portnr) 'B1'];
+CSX = AddProbe( CSX, port.U_filename{2,1}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{2,1}, prio, v2_start, v2_stop+height_vector );
+
+port.U_filename{2,2} = [PortNamePrefix 'port_ut' num2str(portnr) 'B2'];
+CSX = AddProbe( CSX, port.U_filename{2,2}, 0, 'weight', -1*weight );
+CSX = AddBox( CSX, port.U_filename{2,2}, prio, v2_start, v2_stop-height_vector );
+
+
+port.U_filename{3,1} = [PortNamePrefix 'port_ut' num2str(portnr) 'C1'];
+CSX = AddProbe( CSX, port.U_filename{3,1}, 0, 'weight', weight );
+CSX = AddBox( CSX, port.U_filename{3,1}, prio, v3_start, v3_stop+height_vector );
+
+port.U_filename{3,2} = [PortNamePrefix 'port_ut' num2str(portnr) 'C2'];
+CSX = AddProbe( CSX, port.U_filename{3,2}, 0, 'weight', -1*weight );
+CSX = AddBox( CSX, port.U_filename{3,2}, prio, v3_start, v3_stop-height_vector );
+
+% calculate position of the current probes
+idx = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), nstart(idx_width), 'nearest' );
+i1_start(idx_width) = mesh{idx_width}(idx) - diff(mesh{idx_width}(idx-1:idx))/2;
+idx = interp1( mesh{idx_height}, 1:numel(mesh{idx_height}), start(idx_height), 'nearest' );
+i1_start(idx_height) = mesh{idx_height}(idx-1) - diff(mesh{idx_height}(idx-2:idx-1))/2;
+i1_stop(idx_height) = mesh{idx_height}(idx+1) + diff(mesh{idx_height}(idx+1:idx+2))/2;
+i1_start(idx_prop) = sum(meshlines(1:2))/2;
+i1_stop(idx_prop) = i1_start(idx_prop);
+idx = interp1( mesh{idx_width}, 1:numel(mesh{idx_width}), nstop(idx_width), 'nearest' );
+i1_stop(idx_width) = mesh{idx_width}(idx) + diff(mesh{idx_width}(idx:idx+1))/2;
+i2_start = i1_start;
+i2_stop = i1_stop;
+i2_start(idx_prop) = sum(meshlines(2:3))/2;
+i2_stop(idx_prop) = i2_start(idx_prop);
+
+% create the curr-probes
+weight = direction;
+port.I_filename{1} = [PortNamePrefix 'port_it' num2str(portnr) 'A'];
+CSX = AddProbe( CSX, port.I_filename{1}, 1, 'weight', weight );
+CSX = AddBox( CSX, port.I_filename{1}, prio, i1_start, i1_stop );
+port.I_filename{2} = [PortNamePrefix 'port_it' num2str(portnr) 'B'];
+CSX = AddProbe( CSX, port.I_filename{2}, 1,'weight', weight );
+CSX = AddBox( CSX, port.I_filename{2}, prio, i2_start, i2_stop );
+
+% create port structure
+port.LengthScale = 1;
+if ((CSX.ATTRIBUTE.CoordSystem==1) && (idx_prop==2))
+ port.LengthScale = SL_stop(idx_height);
+end
+port.nr = portnr;
+port.type = 'StripLine';
+port.drawingunit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+port.v_delta = diff(meshlines)*port.LengthScale;
+port.i_delta = diff( meshlines(1:end-1) + diff(meshlines)/2 )*port.LengthScale;
+port.direction = direction;
+port.excite = 0;
+port.measplanepos = abs(v2_start(idx_prop) - start(idx_prop))*port.LengthScale;
+% port
+
+% create excitation (if enabled) and port resistance
+meshline = interp1( mesh{idx_prop}, 1:numel(mesh{idx_prop}), start(idx_prop) + feed_shift*direction, 'nearest' );
+ex_start(idx_prop) = mesh{idx_prop}(meshline) ;
+ex_start(idx_width) = nstart(idx_width);
+ex_start(idx_height) = nstart(idx_height);
+ex_stop(idx_prop) = ex_start(idx_prop);
+ex_stop(idx_width) = nstop(idx_width);
+ex_stop(idx_height) = nstop(idx_height);
+
+port.excite = 0;
+if excite
+ port.excite = 1;
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_1_' num2str(portnr)], 0, evec, excite_args{:} );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_1_' num2str(portnr)], prio, ex_start, ex_stop+height_vector );
+ CSX = AddExcitation( CSX, [PortNamePrefix 'port_excite_2_' num2str(portnr)], 0, -evec, excite_args{:} );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_excite_2_' num2str(portnr)], prio, ex_start, ex_stop-height_vector );
+end
+
+%% MSL resitance at start of MSL line
+ex_start(idx_prop) = start(idx_prop);
+ex_stop(idx_prop) = ex_start(idx_prop);
+
+if (feed_R > 0) && ~isinf(feed_R)
+ CSX = AddLumpedElement( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], idx_height-1, 'R', 2*feed_R );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], prio, ex_start, ex_stop+height_vector );
+ CSX = AddBox( CSX, [PortNamePrefix 'port_resist_' int2str(portnr)], prio, ex_start, ex_stop-height_vector );
+elseif isinf(feed_R)
+ % do nothing --> open port
+elseif feed_R == 0
+ %port "resistance" as metal
+ CSX = AddBox( CSX, materialname, prio, ex_start, ex_stop+height_vector );
+ CSX = AddBox( CSX, materialname, prio, ex_start, ex_stop-height_vector );
+else
+ error('openEMS:AddMSLPort','MSL port with resitance <= 0 it not possible');
+end
+end
diff --git a/openEMS/matlab/AddWaveGuidePort.m b/openEMS/matlab/AddWaveGuidePort.m
new file mode 100644
index 0000000..1a17db2
--- /dev/null
+++ b/openEMS/matlab/AddWaveGuidePort.m
@@ -0,0 +1,119 @@
+function [CSX,port] = AddWaveGuidePort( CSX, prio, portnr, start, stop, dir, E_WG_func, H_WG_func, kc, exc_amp, varargin )
+% function [CSX,port] = AddWaveGuidePort( CSX, prio, portnr, start, stop, dir, E_WG_func, H_WG_func, kc, exc_amp, varargin )
+%
+% Create a waveguide port, including an optional excitation and probes
+%
+% Note: - The excitation will be located at the start position in the given direction
+% - The voltage and current probes at the stop position in the given direction
+%
+% parameter:
+% CSX: complete CSX structure (must contain a mesh)
+% prio: priority of primitives
+% start: start coordinates of waveguide port box
+% stop: stop coordinates of waveguide port box
+% dir: direction of port (0/1/2 or 'x'/'y'/'z'-direction)
+% E_WG_func: electric field mode profile function as a string
+% H_WG_func: magnetic field mode profile function as a string
+% kc: cutoff wavenumber (defined by the waveguide dimensions)
+% exc_amp: excitation amplitude (set 0 to be passive)
+%
+% optional (key/values):
+% varargin: optional additional excitations options, see also AddExcitation
+% 'PortNamePrefix': a prefix to the port name
+%
+% output:
+% CSX: modified CSX structure
+% port: port structure to use with calcPort
+%
+% example:
+% % create a TE11 circular waveguide mode, using cylindircal coordinates
+% p11 = 1.841;
+% kc = p11 / radius; % cutoff wavenumber with radius in meter
+% kc_draw = kc*unit; % cutoff wavenumber in drawing units
+%
+% % electric field mode profile
+% func_E{1} = [ num2str(-1/kc_draw^2,15) '/rho*cos(a)*j1(' num2str(kc_draw,15) '*rho)'];
+% func_E{2} = [ num2str(1/kc_draw,15) '*sin(a)*0.5*(j0(' num2str(kc_draw,15) '*rho)-jn(2,' num2str(kc_draw,15) '*rho))'];
+% func_E{3} = 0;
+%
+% % magnetic field mode profile
+% func_H{1} = [ '-1*' num2str(1/kc_draw,15) '*sin(a)*0.5*(j0(' num2str(kc_draw,15) '*rho)-jn(2,' num2str(kc_draw,15) '*rho))'];
+% func_H{2} = [ num2str(-1/kc_draw^2,15) '/rho*cos(a)*j1(' num2str(kc_draw,15) '*rho)'];
+% func_H{3} = 0;
+%
+% start=[mesh.r(1) mesh.a(1) 0 ];
+% stop =[mesh.r(end) mesh.a(end) 100];
+% [CSX, port{1}] = AddWaveGuidePort(CSX, 0, 1, start, stop, 2, func_E, func_H, kc, 1);
+%
+% openEMS matlab interface
+% -----------------------
+% (c) 2013 Thorsten Liebig (thorsten.liebig@gmx.de)
+%
+% See also InitCSX, AddExcitation, calcWGPort, calcPort
+
+%check mesh
+if ~isfield(CSX,'RectilinearGrid')
+ error 'mesh needs to be defined! Use DefineRectGrid() first!';
+end
+
+dir = DirChar2Int(dir);
+
+port.type='WaveGuide';
+port.nr=portnr;
+port.kc = kc;
+port.dir = dir;
+port.drawingunit = CSX.RectilinearGrid.ATTRIBUTE.DeltaUnit;
+
+PortNamePrefix = '';
+
+varargin_tmp = varargin;
+for n=1:2:numel(varargin_tmp)
+ if strcmpi('PortNamePrefix',varargin_tmp{n})
+ PortNamePrefix = varargin_tmp{n+1};
+ varargin([n n+1]) = [];
+ end
+end
+
+% matlab adressing
+dir = dir + 1;
+dir_sign = sign(stop(dir) - start(dir));
+if (dir_sign==0)
+ dir_sign = 1;
+end
+
+port.direction = dir_sign;
+
+E_WG_func{dir} = 0;
+H_WG_func{dir} = 0;
+
+port.excite = 0;
+if (exc_amp~=0)
+ if (start(dir)==stop(dir))
+ error 'if waveguide port is to be excited, the length in propagation direction must not be zero'
+ end
+ e_start = start;
+ e_stop = stop;
+ e_stop(dir) = e_start(dir);
+ port.excite = 1;
+ port.excitepos = e_start(dir);
+ e_vec = [1 1 1]*exc_amp;
+ e_vec(dir) = 0;
+ exc_name = [PortNamePrefix 'port_excite_' num2str(portnr)];
+ CSX = AddExcitation( CSX, exc_name, 0, e_vec, varargin{:});
+ CSX = SetExcitationWeight(CSX, exc_name, E_WG_func );
+ CSX = AddBox( CSX, exc_name, prio, e_start, e_stop);
+end
+
+% voltage/current planes
+m_start = start;
+m_stop = stop;
+m_start(dir) = stop(dir);
+
+port.measplanepos = m_start(dir);
+port.U_filename = [PortNamePrefix 'port_ut' int2str(portnr)];
+CSX = AddProbe(CSX, port.U_filename, 10, 'ModeFunction', E_WG_func);
+CSX = AddBox(CSX, port.U_filename, 0 ,m_start, m_stop);
+
+port.I_filename = [PortNamePrefix 'port_it' int2str(portnr)];
+CSX = AddProbe(CSX, port.I_filename, 11, 'ModeFunction', H_WG_func, 'weight', dir_sign);
+CSX = AddBox(CSX, port.I_filename, 0 ,m_start, m_stop);
diff --git a/openEMS/matlab/AnalyzeNF2FF.m b/openEMS/matlab/AnalyzeNF2FF.m
new file mode 100644
index 0000000..bc88b72
--- /dev/null
+++ b/openEMS/matlab/AnalyzeNF2FF.m
@@ -0,0 +1,231 @@
+function [E_theta,E_phi,Prad,Dmax] = AnalyzeNF2FF( Sim_Path, nf2ff, f, theta, phi, r )
+% [E_theta,E_phi,Prad,Dmax] = AnalyzeNF2FF( Sim_Path, filenames_E, filenames_H, f, theta, phi, r )
+%
+% calculates the farfield via a near field to far field transformation
+%
+% input:
+% Sim_Path: simulation directory
+% nf2ff: structure on filenames etc. as created by CreateNF2FFBox
+% f: frequency (Hz) for far field calculation
+% theta: (degrees) vector of discrete theta values to calculate the far field for
+% phi: (degrees) vector of discrete phi values to calculate the far field for
+% r: (optional) Radius (m) at which the E-fields are calculated (default: 1 m)
+%
+% output:
+% E_theta: E_theta(theta,phi); theta component of the electric field strength at radius r
+% E_phi: E_phi(theta,phi); phi component of the electric field strength at radius r
+% Prad: time averaged radiated power
+% Dmax: maximum directivity
+%
+% example:
+% see examples/NF2FF/infDipol.m
+%
+% See also CreateNF2FFBox
+%
+% (C) 2010 Sebastian Held <sebastian.held@gmx.de>
+% (C) 2011 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+% check arguments
+error( nargchk(6,6,nargin) );
+if ~isscalar(f)
+ error 'Currently only one frequency is supported. Call this function multiple times.'
+end
+
+warning('openEMS:AnalyzeNF2FF','This function is deprecated, use CalcNF2FF instead');
+
+filenames_E = nf2ff.filenames_E;
+filenames_H = nf2ff.filenames_H;
+
+if (~isrow(nf2ff.directions))
+ nf2ff.directions = nf2ff.directions';
+end
+
+% read time domain field data and transform into frequency domain
+for n=find(nf2ff.directions==1)
+ [Ef{n}, E_mesh{n}] = ReadHDF5Dump( [Sim_Path '/' filenames_E{n} '.h5'], 'Frequency', f );
+
+ if (Ef{n}.FD.frequency(1) ~= f)
+ error 'frequency mismach'
+ end
+
+ %clear out time domain data
+ if isfield(Ef{n},'TD')
+ Ef{n} = rmfield(Ef{n},'TD');
+ end
+
+ [Hf{n}, H_mesh{n}] = ReadHDF5Dump( [Sim_Path '/' filenames_H{n} '.h5'], 'Frequency', f );
+ %clear out time domain data
+ if isfield(Hf{n},'TD')
+ Hf{n} = rmfield(Hf{n},'TD');
+ end
+
+ % reshape mesh into row vector
+ mesh{n}.x = reshape( E_mesh{n}.lines{1}, 1, [] );
+ mesh{n}.y = reshape( E_mesh{n}.lines{2}, 1, [] );
+ mesh{n}.z = reshape( E_mesh{n}.lines{3}, 1, [] );
+end
+
+% create a normal vector for every plane
+% FIXME!!! this is dependent upon the order of filenames_*
+n = {};
+for a=1:6
+ temp = [(a<=2), ((a>=3)&&(a<=4)), (a>=5)];
+ n{a} = temp - 2*mod(a,2)*temp;
+end
+
+
+physical_constants
+
+k = 2*pi*f/c0;
+center = [0 0 0];
+Umax = 0;
+
+phi_idx = 0;
+for phi_deg_aufpunkt = phi
+ phi_rad_aufpunkt = phi_deg_aufpunkt/180*pi; % radiant
+ phi_idx = phi_idx + 1;
+
+ theta_idx = 0;
+ for theta_deg_aufpunkt = theta
+ theta_rad_aufpunkt = theta_deg_aufpunkt/180*pi; % radiant
+ theta_idx = theta_idx + 1;
+
+ N_theta = 0;
+ N_phi = 0;
+ L_theta = 0;
+ L_phi = 0;
+ for a=find(nf2ff.directions==1)
+ [N_theta_,N_phi_,L_theta_,L_phi_] = process_plane( k, n{a}, center, mesh{a}, Ef{a}.FD.values{1}, Hf{a}.FD.values{1}, theta_rad_aufpunkt, phi_rad_aufpunkt );
+ N_theta = N_theta + N_theta_; N_phi = N_phi + N_phi_;
+ L_theta = L_theta + L_theta_; L_phi = L_phi + L_phi_;
+ end
+
+ % E-fields
+ erg_E_theta = -1i*k*exp(-1i*k*r) / (4*pi*r)*(L_phi+Z0*N_theta);
+ erg_E_phi = 1i*k*exp(-1i*k*r) / (4*pi*r)*(L_theta-Z0*N_phi);
+
+ % output
+ E_theta(theta_idx,phi_idx) = erg_E_theta;
+ E_phi(theta_idx,phi_idx) = erg_E_phi;
+
+ % directivity
+ U = r^2/(2*Z0) * sum(abs([erg_E_theta erg_E_phi]).^2);
+ Umax = max( [Umax U] );
+ end
+end
+
+% power
+Prad = 0;
+for a=find(nf2ff.directions==1)
+ [~,~,~,~,P] = process_plane( k, n{a}, center, mesh{a}, Ef{a}.FD.values{1}, Hf{a}.FD.values{1}, theta_rad_aufpunkt, phi_rad_aufpunkt );
+ Prad = Prad + P;
+end
+
+% directivity
+Dmax = 4*pi*Umax / Prad;
+
+
+% integrate over one plane
+function [N_theta,N_phi,L_theta,L_phi,Prad] = process_plane( k, n, center, mesh, E_field, H_field, theta_rad_aufpunkt, phi_rad_aufpunkt )
+% [N_theta,N_phi,L_theta,L_phi,Prad] = process_plane( k, n, center, mesh, E_field, H_field, theta_rad_aufpunkt, phi_rad_aufpunkt )
+%
+% k: wave number
+% n: normal vector of the plane
+% center: correction coordinates for the center of the antenna
+% mesh: mesh info
+% E_field: E field array ?x?x?x3
+% H_field: H field array ?x?x?x3
+
+% speed up
+sin__theta_rad_aufpunkt = sin(theta_rad_aufpunkt);
+cos__theta_rad_aufpunkt = cos(theta_rad_aufpunkt);
+sin__phi_rad_aufpunkt = sin(phi_rad_aufpunkt);
+cos__phi_rad_aufpunkt = cos(phi_rad_aufpunkt);
+
+if abs(n(1)) == 1
+ % x-plane
+ x = mesh.x(1);
+ [y z] = ndgrid( mesh.y, mesh.z );
+ coord1 = mesh.y.';
+ coord2 = mesh.z.';
+ Ex = squeeze( E_field(1,:,:,1) );
+ Ey = squeeze( E_field(1,:,:,2) );
+ Ez = squeeze( E_field(1,:,:,3) );
+ Hx = squeeze( H_field(1,:,:,1) );
+ Hy = squeeze( H_field(1,:,:,2) );
+ Hz = squeeze( H_field(1,:,:,3) );
+elseif abs(n(2)) == 1
+ % y-plane
+ y = mesh.y(1);
+ [x z] = ndgrid( mesh.x, mesh.z );
+ coord1 = mesh.x.';
+ coord2 = mesh.z.';
+ Ex = squeeze( E_field(:,1,:,1) );
+ Ey = squeeze( E_field(:,1,:,2) );
+ Ez = squeeze( E_field(:,1,:,3) );
+ Hx = squeeze( H_field(:,1,:,1) );
+ Hy = squeeze( H_field(:,1,:,2) );
+ Hz = squeeze( H_field(:,1,:,3) );
+elseif abs(n(3)) == 1
+ % z-plane
+ z = mesh.z(1);
+ [x y] = ndgrid( mesh.x, mesh.y );
+ coord1 = mesh.x.';
+ coord2 = mesh.y.';
+ Ex = squeeze( E_field(:,:,1,1) );
+ Ey = squeeze( E_field(:,:,1,2) );
+ Ez = squeeze( E_field(:,:,1,3) );
+ Hx = squeeze( H_field(:,:,1,1) );
+ Hy = squeeze( H_field(:,:,1,2) );
+ Hz = squeeze( H_field(:,:,1,3) );
+end
+
+Jx = n(2) .* Hz - n(3) .* Hy;
+Jy = n(3) .* Hx - n(1) .* Hz;
+Jz = n(1) .* Hy - n(2) .* Hx;
+Mx = -n(2) .* Ez + n(3) .* Ey;
+My = -n(3) .* Ex + n(1) .* Ez;
+Mz = -n(1) .* Ey + n(2) .* Ex;
+r_cos_psi = x*sin__theta_rad_aufpunkt*cos__phi_rad_aufpunkt + y*sin__theta_rad_aufpunkt*sin__phi_rad_aufpunkt + z*cos__theta_rad_aufpunkt;
+e_fkt = exp( +1i*k*r_cos_psi );
+N_theta = dbltrapz( ( Jx*cos__theta_rad_aufpunkt*cos__phi_rad_aufpunkt + Jy*cos__theta_rad_aufpunkt*sin__phi_rad_aufpunkt - Jz*sin__theta_rad_aufpunkt) .* e_fkt, coord1, coord2 );
+N_phi = dbltrapz( (-Jx*sin__phi_rad_aufpunkt + Jy*cos__phi_rad_aufpunkt) .* e_fkt, coord1, coord2 );
+L_theta = dbltrapz( ( Mx*cos__theta_rad_aufpunkt*cos__phi_rad_aufpunkt + My*cos__theta_rad_aufpunkt*sin__phi_rad_aufpunkt - Mz*sin__theta_rad_aufpunkt) .* e_fkt, coord1, coord2 );
+L_phi = dbltrapz( (-Mx*sin__phi_rad_aufpunkt + My*cos__phi_rad_aufpunkt) .* e_fkt, coord1, coord2 );
+
+if nargout > 4
+ % Prad requested
+
+ % this is crap! recode it!
+ EH = zeros(size(Ex));
+ for i1 = 1:numel(coord1)
+ for i2 = 1:numel(coord2)
+ E = [Ex(i1,i2) Ey(i1,i2) Ez(i1,i2)];
+ H = [Hx(i1,i2) Hy(i1,i2) Hz(i1,i2)];
+ EH(i1,i2) = real( dot(cross(E,conj(H)),n) );
+ end
+ end
+ Prad = 0.5 * dbltrapz( EH, coord1, coord2 );
+end
+
+
+
+
+function Q = dbltrapz(matrix,a,b)
+%DBLTRAPZ Trapezoidal numerical integration in two dimensions.
+% Z = DBLTRAPZ(MATRIX,A,B) computes an approximation of the double integral
+% of MATRIX via the trapezoidal method (with respect to A and B). A and B must be
+% column vectors of the same length.
+% index like this: MATRIX(A,B)
+
+if nargin < 3, error('MATLAB:dblquad:NotEnoughInputs',...
+ 'Requires at least three inputs.'); end
+if size(a,2) ~= 1, error('column vectors required'); end
+if size(b,2) ~= 1, error('column vectors required'); end
+
+temp = zeros(size(b));
+for i = 1:length(b)
+ temp(i) = trapz( a, matrix(:,i) );
+end
+
+Q = trapz( b, temp );
diff --git a/openEMS/matlab/CalcNF2FF.m b/openEMS/matlab/CalcNF2FF.m
new file mode 100644
index 0000000..c80b52e
--- /dev/null
+++ b/openEMS/matlab/CalcNF2FF.m
@@ -0,0 +1,161 @@
+function nf2ff = CalcNF2FF(nf2ff, Sim_Path, freq, theta, phi, varargin)
+% function nf2ff = CalcNF2FF(nf2ff, Sim_Path, freq, theta, phi, varargin)
+%
+% Calculate the near-field to far-field transformation created by
+% CreateNF2FFBox
+%
+% IMPORTANT:
+% Make sure to define the correct nf2ff phase center, aka. central antenna
+% position! See optional parameter below!! Default is [0 0 0]
+%
+% parameter:
+% nf2ff: data structure created by CreateNF2FFBox
+% Sim_Path: path to simulation data
+% freq: array of frequencies to analyse
+% theta,phi: spherical coordinates to evaluate the far-field on (in radians)
+%
+% optional paramater:
+% 'Center': nf2ff phase center, default is [0 0 0]
+% !! Make sure the center is never outside of your nf2ff box!!
+% Definition is the correct coordinate system necessary
+% --> either Cartesian or cylindrical coordinates
+% 'Mode': 'Mode', 0 -> read only, if data already exist (default)
+% 'Mode', 1 -> calculate anyway, overwrite existing
+% 'Mode', 2 -> read only, fail if not existing
+% 'Outfile': alternative nf2ff result hdf5 file name
+% default is: <nf2ff.name>.h5
+% 'Verbose': set verbose level for the nf2ff calculation 0-2 supported
+% 'Radius': specify the radius for the nf2ff
+% 'Eps_r': specify the relative electric permittivity for the nf2ff
+% 'Mue_r': specify the relative magnetic permeability for the nf2ff
+%
+% 'Mirror': Add mirroring in a given direction (dir), with a given
+% mirror type (PEC or PMC) and a mirror position in the given
+% direction.
+% Example: 'Mirror', {0, 'PMC', +100}
+%
+% See also: CreateNF2FFBox, ReadNF2FF
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig, 2012
+
+mode = 0;
+
+filename = nf2ff.name;
+nf2ff_xml.Planes = {};
+
+nf2ff_xml.ATTRIBUTE.Outfile = [filename '.h5'];
+
+if (isfield(nf2ff,'Eps_r'))
+ nf2ff_xml.ATTRIBUTE.Eps_r = nf2ff.Eps_r;
+end
+if (isfield(nf2ff,'Mue_r'))
+ nf2ff_xml.ATTRIBUTE.Mue_r = nf2ff.Mue_r;
+end
+
+for n=1:2:numel(varargin)-1
+ if (strcmp(varargin{n},'Mode'))
+ mode = varargin{n+1};
+ elseif (strcmp(varargin{n},'Mirror'))
+ if isfield(nf2ff_xml,'Mirror')
+ pos = length(nf2ff_xml.Mirror)+1;
+ else
+ pos = 1;
+ end
+ nf2ff_xml.Mirror{pos}.ATTRIBUTE.Dir=varargin{n+1}{1};
+ nf2ff_xml.Mirror{pos}.ATTRIBUTE.Type=varargin{n+1}{2};
+ nf2ff_xml.Mirror{pos}.ATTRIBUTE.Pos=varargin{n+1}{3};
+ else
+ nf2ff_xml.ATTRIBUTE.(varargin{n})=varargin{n+1};
+ end
+end
+
+for (n=1:numel(nf2ff.filenames_E))
+ if (nf2ff.directions(n)~=0)
+ files_E = dir([Sim_Path '/*' nf2ff.filenames_E{n} '.h5']);
+ files_H = dir([Sim_Path '/*' nf2ff.filenames_H{n} '.h5']);
+ if (numel(files_E)~=numel(files_H))
+ error 'number of E/H planes mismatch!'
+ end
+ for fn = 1:numel(files_E)
+ nf2ff_xml.Planes{end+1}.ATTRIBUTE.E_Field = files_E(fn).name;
+ nf2ff_xml.Planes{end}.ATTRIBUTE.H_Field = files_H(fn).name;
+ end
+ end
+end
+
+nf2ff_xml.ATTRIBUTE.freq = freq;
+nf2ff_xml.theta = theta;
+nf2ff_xml.phi = phi;
+
+nf2ff.xml = [Sim_Path '' filesep '' filename '.xml'];
+nf2ff.hdf5 = [Sim_Path '' filesep '' nf2ff_xml.ATTRIBUTE.Outfile];
+
+% create nf2ff structure
+struct_2_xml(nf2ff.xml,nf2ff_xml,'nf2ff');
+
+m_filename = mfilename('fullpath');
+dir_name = fileparts( m_filename );
+
+if isunix
+ nf2ff_bin = searchBinary('nf2ff', ...
+ {[dir_name filesep '..' filesep 'nf2ff' filesep], ...
+ [dir_name filesep '..' filesep '..' filesep '..' filesep 'bin' filesep]}, 0);
+else
+ nf2ff_bin = searchBinary('nf2ff.exe',[dir_name filesep '..' filesep], 0);
+end
+
+if ((exist(nf2ff.hdf5,'file') && (mode==0)) || (mode==2))
+ disp('CalcNF2FF: Reading nf2ff data only...')
+ nf2ff = ReadNF2FF(nf2ff);
+
+ % verify read data
+ if ( (vectorEqual(nf2ff.freq,freq)==0) || (vectorEqual(nf2ff.theta,theta)==0) || (vectorEqual(nf2ff.phi,phi)==0) )
+ error('openEMS:CalcNF2FF','data mismatch between read and requested data --> recalculate nf2ff --> Set Mode to 1 ');
+ end
+ return;
+end
+
+savePath = pwd;
+cd(Sim_Path);
+
+try
+ if (isempty(nf2ff_bin))
+ error('openEMS:CalcNF2FF','nf2ff binary not found!');
+ end
+ if isunix
+ % remove LD_LIBRARY_PATH set by matlab
+ system(['export LD_LIBRARY_PATH=; ' nf2ff_bin ' ' filename '.xml']);
+ else
+ system([nf2ff_bin ' ' filename '.xml']);
+ end
+ nf2ff.hdf5;
+ cd(savePath);
+catch
+ cd(savePath);
+ error 'CalcNF2FF: failed'
+end
+
+nf2ff = ReadNF2FF(nf2ff);
+
+% verify read data
+if ( (vectorEqual(nf2ff.freq,freq)==0) || (vectorEqual(nf2ff.theta,theta)==0) || (vectorEqual(nf2ff.phi,phi)==0) )
+ error('openEMS:CalcNF2FF','data mismatch between read and requested data --> THIS SHOULD NOT HAPPEN!');
+end
+
+function equal = vectorEqual(v1, v2, acc)
+if (nargin<3)
+ acc = 1e-6;
+end
+
+equal = 0;
+if numel(v1)~=numel(v2)
+ return;
+end
+
+if sum(abs((v1(:)-v2(:))/v1(:)) > acc)>0
+ return;
+end
+equal = 1;
+return
diff --git a/openEMS/matlab/CheckQueue.m b/openEMS/matlab/CheckQueue.m
new file mode 100644
index 0000000..748d706
--- /dev/null
+++ b/openEMS/matlab/CheckQueue.m
@@ -0,0 +1,60 @@
+function [queue running] = CheckQueue(queue, query_time)
+% function [queue running] = CheckQueue(queue, <query_time>)
+%
+% Check the given queue for finished tasks.
+%
+% Parameter:
+% query_time (optional): time interval to check for finished tasks
+% (in seconds, default is 5)
+%
+% For more details see: InitQueue
+%
+% See also: InitQueue, ResultsQueue, Add2Queue, RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if ~isfield(queue,'jobs')
+ running = 0;
+ return
+end
+
+if (nargin<2)
+ query_time = 5;
+end
+
+numJobs = numel(queue.jobs);
+
+pause(query_time);
+
+for n=1:numJobs
+ if (queue.jobs_finished(n)==0)
+ if (queue_checkProcess( queue.jobs{n}.pid, queue.jobs{n}.filenames)==0)
+ queue.jobs_finished(n)=1;
+ load(queue.jobs{n}.outargsfile);
+ if ~isempty(err)
+ disp(['Job with number ' num2str(n) ' failed to execute: Error message:']);
+ error(['CheckQueue:' err.message]);
+ end
+ queue.jobs{n}.outargs = outargs;
+
+ % read in output and cleanup
+ [queue.jobs{n}.stdout,queue.jobs{n}.stderr] = queue_delProcess( queue.jobs{n}.pid, queue.jobs{n}.filenames );
+
+ % cleanup
+ delete( queue.jobs{n}.argsfile );
+ clear queue.jobs{n}.argsfile;
+ delete( queue.jobs{n}.outargsfile );
+ clear queue.jobs{n}.outargsfile;
+
+ queue.jobs_finished(n) = 1;
+
+ if (queue.verbose>=1)
+ disp(['CheckQueue: Job #' num2str(n) ' is finished!']);
+ end
+ end
+ end
+end
+
+running = numel(queue.jobs_finished) - sum(queue.jobs_finished);
diff --git a/openEMS/matlab/ConvertHDF5_VTK.m b/openEMS/matlab/ConvertHDF5_VTK.m
new file mode 100644
index 0000000..545ba01
--- /dev/null
+++ b/openEMS/matlab/ConvertHDF5_VTK.m
@@ -0,0 +1,100 @@
+function ConvertHDF5_VTK(hdf_file, vtk_prefix, varargin)
+% ConvertHDF5_VTK(hdf_file, vtk_prefix, varargin)
+%
+% Convert openEMS field data stored in the given hdf5 file to a vtk file.
+%
+% arguments:
+% hdf_file: source hdf5 file
+% vtk_prefix: output vtk files prefix
+%
+% optional arguments:
+% 'TD_Dump': activate dump for time-domain data (default is off)
+% 'FD_Dump': activate dump for frequency-domain data (default is on)
+% 'NumPhase': number of phase to dump frequency domain data animation
+% (default is 36 --> 10°)
+% 'FieldName': field name written to vtk, e.g. 'E-Field'
+% 'weight': field weighting
+%
+% for more optional aguments have a look at ReadHDF5Dump
+%
+% example:
+% % read time-domian data from hdf5, perform dft and dump as vtk
+% ConvertHDF5_VTK('Et.h5','Ef','NumPhase',18,'Frequency',1e9)
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5Dump Dump2VTK
+
+do_FD_dump = 1;
+do_TD_dump = 0;
+phase_N = 36;
+weight = 1;
+
+fieldname = 'unknown';
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'TD_Dump')==1);
+ do_TD_dump = varargin{n+1};
+ elseif (strcmp(varargin{n},'FD_Dump')==1);
+ do_FD_dump = varargin{n+1};
+ elseif (strcmp(varargin{n},'NumPhase')==1);
+ phase_N = varargin{n+1};
+ elseif (strcmp(varargin{n},'FieldName')==1);
+ fieldname = varargin{n+1};
+ elseif (strcmp(varargin{n},'weight')==1);
+ weight = varargin{n+1};
+ end
+end
+
+[field mesh] = ReadHDF5Dump(hdf_file, varargin{:});
+
+if ((do_TD_dump==0) && (do_FD_dump==0))
+ warning('openEMS:ConvertHDF5_VTK','FD and TD dump disabled, nothing to be done...');
+end
+
+if (do_FD_dump)
+ if (~isfield(field,'FD'))
+ warning('openEMS:ConvertHDF5_VTK','no FD data found skipping frequency domian vtk dump...');
+ else
+ %set weighting
+ if (numel(weight)~=numel(field.FD.frequency))
+ FD_weight = ones(size(field.FD.frequency))*weight(1);
+ else
+ FD_weight = weight;
+ end
+ if (field.FD.DataType==1) % dump complex value FD data
+ ph = linspace(0,360,phase_N+1);
+ ph = ph(1:end-1);
+ for n = 1:numel(field.FD.frequency)
+ for p = ph
+ filename = [vtk_prefix '_' num2str(field.FD.frequency(n)) '_' num2str(p,'%03d') '.vtk' ];
+ Dump2VTK(filename, real(FD_weight(n)*field.FD.values{n}*exp(1j*p*pi/180)), mesh, fieldname, varargin{:});
+ end
+ filename = [vtk_prefix '_' num2str(field.FD.frequency(n)) '_abs.vtk' ];
+ Dump2VTK(filename, abs(FD_weight(n)*field.FD.values{n}), mesh, fieldname, varargin{:});
+ filename = [vtk_prefix '_' num2str(field.FD.frequency(n)) '_ang.vtk' ];
+ Dump2VTK(filename, angle(FD_weight(n)*field.FD.values{n}), mesh, fieldname, varargin{:});
+ end
+ else % dump real value FD data
+ for n = 1:numel(field.FD.frequency)
+ filename = [vtk_prefix '_' num2str(field.FD.frequency(n)) '.vtk' ];
+ Dump2VTK(filename, real(FD_weight(n)*field.FD.values{n}), mesh, fieldname, varargin{:});
+ end
+ end
+ end
+end
+
+if (do_TD_dump)
+ if (~isfield(field,'TD'))
+ warning('openEMS:ConvertHDF5_VTK','no TD data found skipping time domian vtk dump...');
+ else
+ disp('dumping time domain data...')
+ acc = ['%0' int2str(ceil(log10(numel(field.TD.time)+1))) 'd'];
+ for n = 1:numel(field.TD.time)
+ filename = [vtk_prefix '_TD_' num2str(n,acc) '.vtk' ];
+ Dump2VTK(filename, abs(weight(1))*field.TD.values{n}, mesh, fieldname, varargin{:});
+ end
+ end
+end
diff --git a/openEMS/matlab/CreateNF2FFBox.m b/openEMS/matlab/CreateNF2FFBox.m
new file mode 100644
index 0000000..a97f0d2
--- /dev/null
+++ b/openEMS/matlab/CreateNF2FFBox.m
@@ -0,0 +1,94 @@
+function [CSX nf2ff] = CreateNF2FFBox(CSX, name, start, stop, varargin)
+% function [CSX nf2ff] = CreateNF2FFBox(CSX, name, start, stop, varargin)
+%
+% create the dump boxes needed for the near field to far field transformation
+%
+% input:
+% name: name of this nf2ff box
+% start/stop: start/stop coordinates for the nf2ff box (this box has to
+% enclose all radiating structures!)
+% optional inputs:
+% 'Directions': enable/disable specific directions, e.g.
+% 'Directions',[1 1 0 0 1 1]
+% -> disable nf2ff in +/-y direction
+% 'Frequency': dump nf2ff in frequency domain, this will save disk-space
+% but is less flexible, since only this frequencies can be
+% used for the nf2ff calculations by CalcNF2FF
+% See also AddDump for more information
+% 'OptResolution': specify a dump resolution, this will save disk-space
+% See also AddDump for more information
+% e.g.: 'OptResolution', c0/max_freq/unit/15
+%
+% example:
+% see Tutorials/Simple_Patch_Antenna.m
+% see Tutorials/Helical_Antenna.m
+%
+% See also CalcNF2FF
+%
+% (C) 2010 Sebastian Held <sebastian.held@gmx.de>
+% (C) 2010-2012 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+if (nargin<5)
+ directions = ones(6,1);
+end
+
+directions = ones(6,1);
+add_args = {};
+dump_type = 0;
+dump_mode = 1;
+
+for n=1:numel(varargin)/2
+ if strcmp(varargin{2*n-1},'Frequency')
+ add_args = {add_args{:}, 'Frequency', varargin{2*n}};
+ dump_type = 10;
+ elseif strcmp(varargin{2*n-1},'Directions')
+ directions=varargin{2*n};
+ else
+ add_args = {add_args{:}, varargin{2*n-1}, varargin{2*n}};
+ end
+end
+
+nf2ff.name = name;
+nf2ff.filenames_E = {[name '_E_xn'],[name '_E_xp'],[name '_E_yn'],[name '_E_yp'],[name '_E_zn'],[name '_E_zp']};
+nf2ff.filenames_H = {[name '_H_xn'],[name '_H_xp'],[name '_H_yn'],[name '_H_yp'],[name '_H_zn'],[name '_H_zp']};
+nf2ff.directions = directions;
+
+if (isfield(CSX,'ATTRIBUTE'))
+ if (isfield(CSX.ATTRIBUTE,'CoordSystem'))
+ nf2ff.CoordSystem = CSX.ATTRIBUTE.CoordSystem;
+ end
+ if (isfield(CSX,'BackgroundMaterial'))
+ if (isfield(CSX.ATTRIBUTE,'Epsilon'))
+ nf2ff.Eps_r = CSX.ATTRIBUTE.BG_epsR;
+ end
+ if (isfield(CSX.ATTRIBUTE,'Mue'))
+ nf2ff.Mue_r = CSX.ATTRIBUTE.BG_mueR;
+ end
+ end
+end
+
+for nd = 1:3
+ pos = 2*nd-1;
+ if (directions(pos))
+ l_start = start;
+ l_stop = stop;
+ l_stop(nd) = start(nd);
+ CSX = AddBox( AddDump(CSX,nf2ff.filenames_E{pos},'DumpType',dump_type,'DumpMode',dump_mode,'FileType',1,add_args{:}), nf2ff.filenames_E{pos}, 0, l_start, l_stop );
+ CSX = AddBox( AddDump(CSX,nf2ff.filenames_H{pos},'DumpType',dump_type+1,'DumpMode',dump_mode,'FileType',1,add_args{:}), nf2ff.filenames_H{pos}, 0, l_start, l_stop );
+ else
+ nf2ff.filenames_E{pos}='';
+ nf2ff.filenames_H{pos}='';
+ end
+ pos = 2*nd;
+ if (directions(pos))
+ l_start = start;
+ l_stop = stop;
+ l_start(nd) = stop(nd);
+ CSX = AddBox( AddDump(CSX,nf2ff.filenames_E{pos},'DumpType',dump_type,'DumpMode',dump_mode,'FileType',1,add_args{:}), nf2ff.filenames_E{pos}, 0, l_start, l_stop );
+ CSX = AddBox( AddDump(CSX,nf2ff.filenames_H{pos},'DumpType',dump_type+1,'DumpMode',dump_mode,'FileType',1,add_args{:}), nf2ff.filenames_H{pos}, 0, l_start, l_stop );
+ else
+ nf2ff.filenames_E{pos}='';
+ nf2ff.filenames_H{pos}='';
+ end
+end
+
diff --git a/openEMS/matlab/DFT_time2freq.m b/openEMS/matlab/DFT_time2freq.m
new file mode 100644
index 0000000..ac84035
--- /dev/null
+++ b/openEMS/matlab/DFT_time2freq.m
@@ -0,0 +1,47 @@
+function f_val = DFT_time2freq( t, val, freq, signal_type )
+% f_val = DFT_time2freq( t, val, freq, signal_type )
+%
+% computes the DFT at the given frequencies
+%
+% parameter:
+% t : time vector
+% val: data vector
+% freq: DFT frequency vector
+% signal_type: 'pulse' (default), 'periodic'
+%
+% return values:
+% f_val: single-sided spectrum
+%
+% example:
+% t=linspace(0,1,100);
+% t_val=0.9*sin(2*pi*3*t); % sine wave; amplitude 0.9; frequency 3 Hz
+% f=linspace(1,5,101);
+% f_val=DFT_time2freq( t, t_val, f, 'periodic' );
+% interp1(f,abs(f_val),3)
+% ans = 0.8910
+% plot( t, t_val )
+% plot( f, abs(f_val) )
+
+if numel(t) ~= numel(val)
+ error 'numel(t) ~= numel(val)'
+end
+
+if nargin<4
+ signal_type = 'pulse';
+end
+
+f_val = zeros(1,numel(freq));
+for f_idx=1:numel(freq)
+ f_val(f_idx) = sum( val .* exp( -1i * 2*pi*freq(f_idx) * t ) );
+end
+
+if strcmpi(signal_type, 'pulse')
+ dt = t(2)-t(1);
+ f_val = f_val * dt;
+elseif strcmpi(signal_type, 'periodic')
+ f_val = f_val / length(t);
+else
+ error 'unknown signal type'
+end
+
+f_val = f_val * 2; % single-sided spectrum
diff --git a/openEMS/matlab/Dump2VTK.m b/openEMS/matlab/Dump2VTK.m
new file mode 100644
index 0000000..e57b153
--- /dev/null
+++ b/openEMS/matlab/Dump2VTK.m
@@ -0,0 +1,179 @@
+function Dump2VTK(filename, fields, mesh, fieldname, varargin)
+% Dump2VTK(filename, fields, mesh, fieldname, varargin)
+%
+% Dump fields extraced from an hdf5 file to a vtk file format
+%
+% possible arguments:
+% 'NativeDump': 0 (default) / 1, dump in native coordinate system
+% 'CloseAlpha': 0 (default) / 1, repeat first/last line in
+% alpha-direction for a full cylindrical mesh
+%
+% example:
+%
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5FieldData ReadHDF5Mesh GetField_TD2FD GetField_Interpolation
+
+NativeDump = 0;
+CloseAlpha = 0;
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'NativeDump')==1);
+ NativeDump = varargin{n+1};
+ elseif (strcmp(varargin{n},'CloseAlpha')==1);
+ CloseAlpha = varargin{n+1};
+ end
+end
+
+x = mesh.lines{1};
+y = mesh.lines{2};
+z = mesh.lines{3};
+
+fid = fopen(filename,'w+');
+
+% set nan values to zero
+ind = find(isnan(fields));
+if (~isempty(ind))
+ warning('openEMS:Dump2VTK','field contains nan, setting to zero');
+ fields(ind)=0;
+end
+
+% set inf values to zero
+ind = find(isinf(fields));
+if (~isempty(ind))
+ warning('openEMS:Dump2VTK','field contains inf, setting to zero');
+ fields(ind)=0;
+end
+
+if ((CloseAlpha~=0) && (mesh.type==1) && (range(y)<2*pi))
+ y(end+1) = y(1)+2*pi;
+ fields(:,end+1,:,:) = fields(:,1,:,:);
+end
+
+if (mesh.type==0) %write cartesian mesh to vtk
+ fprintf(fid,'# vtk DataFile Version 2.0\n');
+ fprintf(fid,'Rectilinear Grid by matlab-interface of openEMS\n');
+ fprintf(fid,'ASCII\n');
+ fprintf(fid,'DATASET RECTILINEAR_GRID\n');
+
+ fprintf(fid,'DIMENSIONS %d %d %d\n',numel(x),numel(y),numel(z));
+
+ fprintf(fid,'X_COORDINATES %d double\n',numel(x));
+ fprintf(fid,'%e',x(1));
+ for n=2:numel(x)
+ fprintf(fid,' %e',x(n));
+ end
+ fprintf(fid,'\n');
+
+ fprintf(fid,'Y_COORDINATES %d double\n',numel(y));
+ fprintf(fid,'%e',y(1));
+ for n=2:numel(y)
+ fprintf(fid,' %e',y(n));
+ end
+ fprintf(fid,'\n');
+
+ fprintf(fid,'Z_COORDINATES %d double\n',numel(z));
+ fprintf(fid,'%e',z(1));
+ for n=2:numel(z)
+ fprintf(fid,' %e',z(n));
+ end
+
+elseif (mesh.type==1) %write cylindrical mesh to vtk
+ fprintf(fid,'# vtk DataFile Version 3.0\n');
+ fprintf(fid,'Structured Grid by matlab-interface of openEMS\n');
+ fprintf(fid,'ASCII\n');
+ fprintf(fid,'DATASET STRUCTURED_GRID\n');
+
+ fprintf(fid,'DIMENSIONS %d %d %d\n',numel(x),numel(y),numel(z));
+
+ fprintf(fid,'POINTS %d double\n',numel(x)*numel(y)*numel(z));
+
+ for nz=1:numel(z)
+ for ny=1:numel(y)
+ for nx=1:numel(x)
+ fprintf(fid,'%e %e %e\n',x(nx)*cos(y(ny)),x(nx)*sin(y(ny)),z(nz));
+ end
+ end
+ end
+ if ((ndims(fields)==4) && (NativeDump==0))
+ [R A Z] = ndgrid(x,y,z);
+ sinA = sin(A);
+ cosA = cos(A);
+ field_CC(:,:,:,1) = fields(:,:,:,1) .* cosA - fields(:,:,:,2) .* sinA;
+ field_CC(:,:,:,2) = fields(:,:,:,1) .* sinA + fields(:,:,:,2) .* cosA;
+ field_CC(:,:,:,3) = fields(:,:,:,3);
+ fields = field_CC;
+ clear R A Z sinA cosA field_CC
+ end
+elseif (mesh.type==2) %write spherical mesh to vtk
+ fprintf(fid,'# vtk DataFile Version 3.0\n');
+ fprintf(fid,'Structured Grid by matlab-interface of openEMS\n');
+ fprintf(fid,'ASCII\n');
+ fprintf(fid,'DATASET STRUCTURED_GRID\n');
+
+ fprintf(fid,'DIMENSIONS %d %d %d\n',numel(x),numel(y),numel(z));
+
+ fprintf(fid,'POINTS %d double\n',numel(x)*numel(y)*numel(z));
+
+ for nz=1:numel(z)
+ for ny=1:numel(y)
+ for nx=1:numel(x)
+ fprintf(fid,'%e %e %e\n',...
+ x(nx)*sin(y(ny))*cos(z(nz)),...
+ x(nx)*sin(y(ny))*sin(z(nz)),...
+ x(nx)*cos(y(ny)));
+ end
+ end
+ end
+
+ if ((ndims(fields)==4) && (NativeDump==0))
+ [R T A] = ndgrid(x,y,z);
+ sinA = sin(A);
+ cosA = cos(A);
+ sinT = sin(T);
+ cosT = cos(T);
+ field_CC(:,:,:,1) = fields(:,:,:,1) .* sinT .* cosA + fields(:,:,:,2) .*cosT .* cosA - fields(:,:,:,3) .* sinA;
+ field_CC(:,:,:,2) = fields(:,:,:,1) .* sinT .* cosA + fields(:,:,:,2) .*cosT .* sinA + fields(:,:,:,3) .* cosA;
+ field_CC(:,:,:,3) = fields(:,:,:,1) .* cosT - fields(:,:,:,2) .*sinT;
+ fields = field_CC;
+ clear R A T sinA cosA sinT cosT field_CC
+ end
+end
+
+
+fprintf(fid,'\n\n');
+
+fprintf(fid,'POINT_DATA %d\n',numel(x)*numel(y)*numel(z));
+% dump vector field data
+if (size(fields,4)>1)
+ if (nargin>3)
+ fprintf(fid,['VECTORS ' fieldname ' double\n']);
+ else
+ fprintf(fid,'VECTORS field double\n');
+ end
+ fclose(fid);
+ field_x = fields(:,:,:,1);
+ field_y = fields(:,:,:,2);
+ field_z = fields(:,:,:,3);
+ clear fields
+ dumpField(:,1) = field_x(:);
+ dumpField(:,2) = field_y(:);
+ dumpField(:,3) = field_z(:);
+ save('-ascii','-append',filename,'dumpField')
+ return
+elseif (size(fields,4)==1) % scalar field
+ if (nargin>3)
+ fprintf(fid,['SCALARS ' fieldname ' double 1\nLOOKUP_TABLE default\n']);
+ else
+ fprintf(fid,'SCALARS field double 1\nLOOKUP_TABLE default\n');
+ end
+ fclose(fid);
+ dumpField = fields(:);
+ save('-ascii','-append',filename,'dumpField')
+ return
+end
+
+fclose(fid);
diff --git a/openEMS/matlab/DumpFF2VTK.m b/openEMS/matlab/DumpFF2VTK.m
new file mode 100644
index 0000000..8e6e2f8
--- /dev/null
+++ b/openEMS/matlab/DumpFF2VTK.m
@@ -0,0 +1,105 @@
+function DumpFF2VTK(filename, farfield, thetaRange, phiRange, varargin)
+% DumpFF2VTK(filename, farfield, thetaRange, phiRange, varargin)
+%
+% Dump 3D far field pattern to a vtk file
+%
+% input:
+% filename: filename of VTK file, existing file will be overwritten
+% farfield: farfield in V/m
+% thetaRange: theta range in deg
+% phiRange: phi range in deg
+%
+% variable input:
+% 'scale': - linear scale of plot, doesn't affect gain values
+% 'logscale': - if set, show farfield with logarithmic scale
+% - set the dB value for point of origin
+% - values below will be clamped
+% 'maxgain': - add max gain in dB to normalized farfield
+% - only valid if logscale is set
+% - default is 0dB
+%
+% example:
+% DumpFF2VTK(filename, farfield, thetaRange, phiRange, ...
+% 'scale', 2, 'logscale', -20, 'maxgain', 3)
+%
+% see also examples/NF2FF/infDipol.m
+%
+% See also CreateNF2FFBox, CalcNF2FF
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+
+% defaults
+scale = 1;
+maxgain = 0;
+logscale = [];
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'maxgain')==1);
+ maxgain = varargin{n+1};
+ elseif (strcmp(varargin{n},'logscale')==1);
+ logscale = varargin{n+1};
+ elseif (strcmp(varargin{n},'scale')==1);
+ scale = varargin{n+1};
+ end
+end
+
+if ~isempty(logscale)
+ farfield = 20*log10(farfield) + maxgain - logscale;
+ ind = find(farfield<0);
+ farfield(ind)=0;
+else
+ % force 0 for linear plot
+ logscale = 0;
+end
+
+t = thetaRange*pi/180;
+a = phiRange*pi/180;
+
+fid = fopen(filename,'w+');
+
+% set nan values to zero
+ind = find(isnan(farfield));
+if (~isempty(ind))
+ warning('openEMS:Dump2VTK','field contains nan, setting to zero');
+ farfield(ind)=0;
+end
+
+% set inf values to zero
+ind = find(isinf(farfield));
+if (~isempty(ind))
+ warning('openEMS:Dump2VTK','field contains inf, setting to zero');
+ farfield(ind)=0;
+end
+
+
+fprintf(fid,'# vtk DataFile Version 3.0\n');
+fprintf(fid,'Structured Grid by matlab-interface of openEMS\n');
+fprintf(fid,'ASCII\n');
+fprintf(fid,'DATASET STRUCTURED_GRID\n');
+
+fprintf(fid,'DIMENSIONS %d %d %d\n',1,numel(t),numel(a));
+
+fprintf(fid,'POINTS %d double\n',numel(t)*numel(a));
+
+for na=1:numel(phiRange)
+ for nt=1:numel(thetaRange)
+ fprintf(fid,'%e %e %e\n',...
+ scale*farfield(nt,na)*sin(t(nt))*cos(a(na)),...
+ scale*farfield(nt,na)*sin(t(nt))*sin(a(na)),...
+ scale*farfield(nt,na)*cos(t(nt)));
+ end
+end
+
+
+
+fprintf(fid,'\n\n');
+
+fprintf(fid,'POINT_DATA %d\n',numel(t)*numel(a));
+
+fprintf(fid,['SCALARS gain double 1\nLOOKUP_TABLE default\n']);
+fclose(fid);
+dumpField = farfield(:) + logscale;
+save('-ascii','-append',filename,'dumpField')
diff --git a/openEMS/matlab/FFT_time2freq.m b/openEMS/matlab/FFT_time2freq.m
new file mode 100644
index 0000000..a82c435
--- /dev/null
+++ b/openEMS/matlab/FFT_time2freq.m
@@ -0,0 +1,18 @@
+function [f,val] = FFT_time2freq( t, val )
+% [f,val] = FFT_time2freq( t, val )
+%
+% Note: This function can only be used for pulse signals
+%
+% See also DFT_time2freq
+
+dt=t(2)-t(1); % timestep
+L=numel(val); % signal length
+NFFT = 2^nextpow2(L); % next power of 2 (makes fft fast)
+%very fine freq resolution... NFFT = NFFT+100000;
+val = fft( val, NFFT)*dt;
+f = 1/(2*dt) * linspace(0,1,NFFT/2+1);
+
+val = 2*val(1:NFFT/2+1); % single-sided spectrum
+
+%correct phase for time-shifted signals
+val = val .* exp(-1j*2*pi*f * t(1));
diff --git a/openEMS/matlab/FindFreeSSH.m b/openEMS/matlab/FindFreeSSH.m
new file mode 100644
index 0000000..8fd6c22
--- /dev/null
+++ b/openEMS/matlab/FindFreeSSH.m
@@ -0,0 +1,87 @@
+function host = FindFreeSSH(host_list, Settings, wait_time, command)
+% function host = FindFreeSSH(host_list, Settings, wait_time, command)
+%
+% Find a free ssh host not running openEMS
+%
+% internal function used by RunOpenEMS
+%
+% host_list: give a list of possible host
+%
+% wait_time: wait x seconds after not finding a free host and rechecking
+% default: 600 seconds
+%
+% command: unix command to check for free host (empty result --> free)
+% default: 'ps -e | grep openEMS'
+%
+% See also RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if (nargin<4)
+ % command which should return an empty string if host is available
+ command = 'ps -e | grep openEMS';
+end
+
+% 10 seconds ssh timeout
+time_out = 10;
+
+if (nargin<3)
+ wait_time = 600;
+end
+
+if ~isunix
+ ssh_command = [Settings.SSH.Putty.Path '/plink '];
+ ssh_options = [' -i ' Settings.SSH.Putty.Key];
+ command = ['"' command '"'];
+else
+ ssh_command = 'ssh';
+ ssh_options = ['-o ConnectTimeout=' num2str(time_out)];
+ command = ['''' command ''''];
+end
+
+if ischar(host_list)
+ fid=fopen(host_list);
+ if (fid==-1)
+ error('FindFreeSSH: cant open host file');
+ end
+ clear host_list;
+ host_list = {};
+ while 1
+ line = fgetl(fid);
+ if ischar(line)
+ host_list{end+1} = line;
+ else
+ break;
+ end
+ end
+ fclose(fid);
+elseif ~iscell(host_list)
+ error('FindFreeSSH: unknown host list format');
+end
+
+while 1
+ for n = 1:numel(host_list)
+ host = host_list{n};
+ [status, result] = unix([ssh_command ' ' ssh_options ' ' host ' ' command ]);
+ if (isempty(result) && status==1)
+ disp(['FindFreeSSH:: found a free host: ' host ]);
+ return
+ elseif (~isempty(result) && status==0)
+ disp(['FindFreeSSH:: ' host ' is busy running openEMS ... ' ]);
+ else
+ disp(['FindFreeSSH:: shh connection to ' host ' failed ... ' ]);
+ end
+ end
+
+ host = '';
+
+ if (wait_time<=0)
+ warning('openEMS:FindFreeSSH',' unable to find a free host ');
+ return
+ end
+
+ disp([' no free host found waiting for ' num2str(wait_time) ' seconds ... '])
+ pause(wait_time)
+end \ No newline at end of file
diff --git a/openEMS/matlab/FinishQueue.m b/openEMS/matlab/FinishQueue.m
new file mode 100644
index 0000000..10020c5
--- /dev/null
+++ b/openEMS/matlab/FinishQueue.m
@@ -0,0 +1,40 @@
+function [queue] = FinishQueue(queue, query_time)
+% function [queue] = FinishQueue(queue, <query_time>)
+%
+% Wait for the given queue to finish.
+%
+% Parameter:
+% query_time (optional): time interval to check for finished tasks
+% (in seconds, default is 5)
+%
+% For more details see: InitQueue
+%
+% See also: InitQueue, ResultsQueue, Add2Queue, RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if ~isfield(queue,'jobs')
+ return
+end
+
+if (nargin<2)
+ query_time = 5;
+end
+
+numJobs = numel(queue.jobs);
+
+if (queue.verbose>=1)
+ disp(['FinishQueue: Waiting for ' num2str(sum(~queue.jobs_finished)) ' of ' num2str(numJobs) ' jobs to finish...']);
+end
+
+running = numel(queue.jobs_finished) - sum(queue.jobs_finished);
+
+while sum(running)>0
+ [queue running] = CheckQueue(queue, query_time);
+end
+
+if (queue.verbose>=1)
+ disp(['FinishQueue: All jobs done!'])
+end
diff --git a/openEMS/matlab/GetField_Interpolation.m b/openEMS/matlab/GetField_Interpolation.m
new file mode 100644
index 0000000..6682a83
--- /dev/null
+++ b/openEMS/matlab/GetField_Interpolation.m
@@ -0,0 +1,147 @@
+function [field_i mesh_i] = GetField_Interpolation(field, mesh, lines, varargin)
+% [field_i mesh_i] = GetField_Interpolation(field, mesh, lines, varargin)
+%
+% Get an interpolated field, e.g. read by ReadHDF5Dump
+%
+% homogen interpolation given by a 3x1 vector: e.g. [21,1,101]
+%
+% abitrary interpolation on a given mesh:
+% e.g.: mesh_interp{1} = linspace(0, 1,101) * 1e-3;
+% mesh_interp{2} = linspace(0,0.5, 51) * 1e-3;
+% mesh_interp{3} = linspace(0,0.2, 21) * 1e-3;
+%
+% example:
+% [field mesh] = ReadHDF5Dump('Et.h5');
+% %interpolate on a mesh with 21x21x101 lines
+% [field_i mesh_i] = GetField_Interpolation(field, mesh, [21 21 101]);
+% or
+% [field_i mesh_i] = GetField_Interpolation(field, mesh, mesh_interp);
+%
+% %or both steps in one with the same result:
+% [field_i mesh_i] = ReadHDF5Dump('Et.h5','Interpolation', [21 21 101]);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5Dump ReadHDF5FieldData ReadHDF5Mesh
+
+if ((~iscell(lines) && ~isnumeric(lines)) || numel(lines)~=3)
+ error('openEMS:GetField_Interpolation: numLines for interpolation must be a vector...');
+end
+
+x = mesh.lines{1};
+y = mesh.lines{2};
+z = mesh.lines{3};
+
+if (isnumeric(lines))
+ if (lines(1)==0)
+ x_i = x;
+ else
+ x_i = linspace(x(1),x(end),lines(1));
+ end
+ if (lines(2)==0)
+ y_i = y;
+ else
+ y_i = linspace(y(1),y(end),lines(2));
+ end
+ if (lines(3)==0)
+ z_i = z;
+ else
+ z_i = linspace(z(1),z(end),lines(3));
+ end
+else
+ if isempty(lines{1})
+ x_i = x;
+ else
+ x_i = lines{1};
+ end
+ if isempty(lines{2})
+ y_i = y;
+ else
+ y_i = lines{2};
+ end
+ if isempty(lines{3})
+ z_i = z;
+ else
+ z_i = lines{3};
+ end
+end
+
+field_i = field;
+mesh_i = mesh;
+mesh_i.lines{1} = x_i;
+mesh_i.lines{2} = y_i;
+mesh_i.lines{3} = z_i;
+
+% clear or create empty original indices list, since such do not make any
+% sense with interpolated field values
+mesh_i.original_indices = {};
+
+if (isfield(field,'TD'))
+ field_i.TD = interpolate_fields(field.TD,x,y,z, x_i, y_i, z_i);
+ field_i.TD.time = field.TD.time;
+ field_i.TD.names= field.TD.names;
+end
+
+if (isfield(field,'FD'))
+ field_i.FD = interpolate_fields(field.FD,x,y,z, x_i, y_i, z_i);
+ field_i.FD.frequency = field.FD.frequency;
+ field_i.FD.DataType = field.FD.DataType;
+end
+
+return
+
+function field_i = interpolate_fields(field, x,y,z, x_i, y_i, z_i)
+
+% matlab cannot handle 3D data to be 2D data, workaround for these cases
+if (numel(x)==1)
+ [Y Z] = ndgrid(y,z);
+ [Y_I Z_I] = ndgrid(y_i,z_i);
+ for n=1:numel(field.values)
+ field_i.values{n}(1,:,:,1) = interpn(Y,Z,squeeze(field.values{n}(1,:,:,1)),Y_I,Z_I);
+ if (size(field.values{n},4)>1)
+ field_i.values{n}(1,:,:,2) = interpn(Y,Z,squeeze(field.values{n}(1,:,:,2)),Y_I,Z_I);
+ field_i.values{n}(1,:,:,3) = interpn(Y,Z,squeeze(field.values{n}(1,:,:,3)),Y_I,Z_I);
+ end
+ end
+ return;
+end
+
+if (numel(y)==1)
+ [X Z] = ndgrid(x,z);
+ [X_I Z_I] = ndgrid(x_i,z_i);
+ for n=1:numel(field.values)
+ field_i.values{n}(:,1,:,1) = interpn(X,Z,squeeze(field.values{n}(:,1,:,1)),X_I,Z_I);
+ if (size(field.values{n},4)>1)
+ field_i.values{n}(:,1,:,2) = interpn(X,Z,squeeze(field.values{n}(:,1,:,2)),X_I,Z_I);
+ field_i.values{n}(:,1,:,3) = interpn(X,Z,squeeze(field.values{n}(:,1,:,3)),X_I,Z_I);
+ end
+ end
+ return;
+end
+
+if (numel(z)==1)
+ [X Y] = ndgrid(x,y);
+ [X_I Y_I] = ndgrid(x_i,y_i);
+ for n=1:numel(field.values)
+ field_i.values{n}(:,:,1,1) = interpn(X,Y,squeeze(field.values{n}(:,:,1,1)),X_I,Y_I);
+ if (size(field.values{n},4)>1)
+ field_i.values{n}(:,:,1,2) = interpn(X,Y,squeeze(field.values{n}(:,:,1,2)),X_I,Y_I);
+ field_i.values{n}(:,:,1,3) = interpn(X,Y,squeeze(field.values{n}(:,:,1,3)),X_I,Y_I);
+ end
+ end
+ return;
+end
+
+
+%real 3D case
+[X Y Z] = ndgrid(x,y,z);
+[X_I Y_I Z_I] = ndgrid(x_i,y_i,z_i);
+for n=1:numel(field.values)
+ field_i.values{n}(:,:,:,1) = interpn(X,Y,Z,field.values{n}(:,:,:,1),X_I,Y_I,Z_I);
+ if (size(field.values{n},4)>1)
+ field_i.values{n}(:,:,:,2) = interpn(X,Y,Z,field.values{n}(:,:,:,2),X_I,Y_I,Z_I);
+ field_i.values{n}(:,:,:,3) = interpn(X,Y,Z,field.values{n}(:,:,:,3),X_I,Y_I,Z_I);
+ end
+end
diff --git a/openEMS/matlab/GetField_Range.m b/openEMS/matlab/GetField_Range.m
new file mode 100644
index 0000000..8d489b9
--- /dev/null
+++ b/openEMS/matlab/GetField_Range.m
@@ -0,0 +1,71 @@
+function [field_i mesh_i] = GetField_Range(field, mesh, range)
+% [field_i mesh_i] = GetField_Range(field, mesh, range)
+%
+% Get a field dump subset within a given mesh range
+%
+% example:
+% % specify a mesh range
+% range{1} = [0 150] * 1e-3; % x in range 0..150mm
+% range{2} = [0]; % only one line close to y==0
+% range{3} = []; % no range restriction
+%
+% % read hdf data
+% [field mesh] = ReadHDF5Dump('Et.h5');
+% % extract a ranged subset
+% [field_i mesh_i] = GetField_Range(field, mesh, range);
+%
+% %or both steps in one with the same result:
+% [field_i mesh_i] = ReadHDF5Dump('Et.h5','Range', range);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5Dump ReadHDF5FieldData ReadHDF5Mesh
+
+mesh_i = mesh;
+for n=1:3
+ if (numel(range{n})==0)
+ ind_range{n} = [];
+
+ ind_range{n} = 1:numel( mesh.lines{n});
+
+ elseif (numel(range{n})==1)
+ ind_range{n} = find( mesh.lines{n}>=range{n}(1) , 1);
+
+ if (isempty(ind_range{n}))
+ ind_range{n} = find( mesh.lines{n}>=range{n}(1) , 1, 'first');
+ end
+ if (isempty(ind_range{n}))
+ ind_range{n} = find( mesh.lines{n}<=range{n}(2) , 1, 'last');
+ end
+
+ else
+ ind_range{n} = find( mesh.lines{n}>=range{n}(1) & mesh.lines{n}<=range{n}(2));
+ end
+
+ mesh_i.lines{n} = mesh.lines{n}(ind_range{n});
+end
+
+% store original indices
+if (isfield(mesh_i,'original_indices'))
+ for n=1:3
+ mesh_i.original_indices{n} = mesh_i.original_indices{n}(ind_range{n});
+ end
+else
+ mesh_i.original_indices = ind_range;
+end
+
+field_i = field;
+
+if (isfield(field,'FD'))
+ for n=1:numel(field.FD.values)
+ field_i.FD.values{n} = field.FD.values{n}(ind_range{1},ind_range{2},ind_range{3},:);
+ end
+end
+
+if (isfield(field,'TD'))
+ for n=1:numel(field.TD.values)
+ field_i.TD.values{n} = field.TD.values{n}(ind_range{1},ind_range{2},ind_range{3},:);
+ end
+end
diff --git a/openEMS/matlab/GetField_SubSampling.m b/openEMS/matlab/GetField_SubSampling.m
new file mode 100644
index 0000000..9c792e0
--- /dev/null
+++ b/openEMS/matlab/GetField_SubSampling.m
@@ -0,0 +1,63 @@
+function [field_i mesh_i] = GetField_SubSampling(field, mesh, subsampling, varargin)
+% [field_i mesh_i] = GetField_SubSampling(field, mesh, subsampling, varargin)
+%
+% Get a sub-sampled field, e.g. read by ReadHDF5Dump
+%
+% sub-sampling e.g. skipping every second line in x/r direction: [2 1 1]
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5Dump ReadHDF5FieldData ReadHDF5Mesh
+
+if (~isnumeric(subsampling) || numel(subsampling)~=3)
+ error('openEMS:GetField_Interpolation: numLines for interpolation must be a vector...');
+end
+
+x = mesh.lines{1};
+y = mesh.lines{2};
+z = mesh.lines{3};
+
+ss_idx{1} = 1:subsampling(1):numel(x);
+ss_idx{2} = 1:subsampling(2):numel(y);
+ss_idx{3} = 1:subsampling(3):numel(z);
+
+x_i = x(ss_idx{1});
+y_i = y(ss_idx{2});
+z_i = z(ss_idx{3});
+
+field_i = field;
+mesh_i = mesh;
+mesh_i.lines{1} = x_i;
+mesh_i.lines{2} = y_i;
+mesh_i.lines{3} = z_i;
+
+% store original indices
+if (isfield(mesh_i,'original_indices'))
+ for n=1:3
+ mesh_i.original_indices{n} = mesh_i.original_indices{n}(ss_idx{n});
+ end
+else
+ mesh_i.original_indices = ss_idx;
+end
+
+if (isfield(field,'TD'))
+ field_i.TD = subsample_fields(field.TD,ss_idx);
+ field_i.TD.time = field.TD.time;
+ field_i.TD.names= field.TD.names;
+end
+
+if (isfield(field,'FD'))
+ field_i.FD = subsample_fields(field.FD,ss_idx);
+ field_i.FD.frequency = field.FD.frequency;
+ field_i.FD.DataType = field.FD.DataType;
+end
+
+return
+
+function field_i = subsample_fields(field, ss_idx)
+
+for n=1:numel(field.values)
+ field_i.values{n} = field.values{n}(ss_idx{1},ss_idx{2},ss_idx{3},:);
+end
diff --git a/openEMS/matlab/GetField_TD2FD.m b/openEMS/matlab/GetField_TD2FD.m
new file mode 100644
index 0000000..014c6d6
--- /dev/null
+++ b/openEMS/matlab/GetField_TD2FD.m
@@ -0,0 +1,48 @@
+function field = GetField_TD2FD(field, freq)
+% function field = GetField_TD2FD(field, freq)
+%
+% Transforms time-domain field data into the frequency domain
+% Autocorrects the half-timestep offset of the H-field
+%
+% example:
+% freq = linspace(0,1e9,100); %target frequency vector (Hz)
+% field = ReadHDF5FieldData('tmp/Ht.h5');
+% field_FD = GetField_TD2FD(field, freq);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5FieldData
+
+if (~isfield(field,'TD'))
+ warning('openEMS:GetField_TD2FD','field has no time domain data... skipping FD transformation...');
+ return
+end
+
+t = field.TD.time;
+dt = t(2)-t(1);
+
+clear field.FD
+
+field.FD.frequency = freq;
+
+for nf = 1:numel(freq)
+ field.FD.values{nf} = 0;
+end
+
+numTS = numel(field.TD.values);
+
+for n=1:numTS
+ for nf = 1:numel(freq)
+ f = freq(nf);
+ field.FD.values{nf} = field.FD.values{nf} + field.TD.values{n}.*exp(-1i*2*pi*f*t(n)) * 2 * dt;
+ % t(n) is absolute time and therefore the half-timestep offset of
+ % the H-field is automatically compensated
+ % openEMS output: E-fields start at t=0
+ % openEMS output: H-fields start at t=delta_t/2
+ end
+end
+
+field.FD.DataType=1;
+
diff --git a/openEMS/matlab/InitCylindricalFDTD.m b/openEMS/matlab/InitCylindricalFDTD.m
new file mode 100644
index 0000000..9da649f
--- /dev/null
+++ b/openEMS/matlab/InitCylindricalFDTD.m
@@ -0,0 +1,21 @@
+function FDTD = InitCylindricalFDTD(NrTS, endCrit, varargin)
+% function FDTD = InitCylindricalFDTD(NrTS, endCrit, varargin)
+%
+% see also InitFDTD
+%
+% e.g FDTD = InitCylindricalFDTD(5e5,1e-6,'OverSampling',10)
+%
+% WARNING: This function is depreciated, use InitFDTD with 'CoordSystem',1
+% e.g.: InitFDTD(5e5,1e-6,'OverSampling',10, 'CoordSystem',1)
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+warning('InitCylindricalFDTD: This function is depreciated, use InitFDTD with ''CoordSystem'',1');
+
+FDTD = InitFDTD(NrTS, endCrit, varargin{:});
+
+FDTD.ATTRIBUTE.CylinderCoords=1;
+
+
diff --git a/openEMS/matlab/InitFDTD.m b/openEMS/matlab/InitFDTD.m
new file mode 100644
index 0000000..dba5120
--- /dev/null
+++ b/openEMS/matlab/InitFDTD.m
@@ -0,0 +1,64 @@
+function FDTD = InitFDTD(varargin)
+% function FDTD = InitFDTD(varargin)
+%
+% Inititalize the FDTD data-structure.
+%
+% optional field arguments for usage with openEMS:
+% NrTS: max. number of timesteps to simulate (e.g. default=1e9)
+% EndCriteria: end criteria, e.g. 1e-5, simulations stops if energy has
+% decayed by this value (<1e-4 is recommended, default=1e-5)
+% MaxTime: max. real time in seconds to simulate
+% OverSampling: nyquist oversampling of time domain dumps
+% CoordSystem: choose coordinate system (0 Cartesian, 1 Cylindrical)
+% MultiGrid: define a cylindrical sub-grid radius
+% TimeStep: force to use a given timestep (dangerous!)
+% TimeStepFactor: reduce the timestep by a given factor (>0 to <=1)
+% TimeStepMethod: 1 or 3 chose timestep method (1=CFL, 3=Rennigs (default))
+% CellConstantMaterial: set to 1 to assume a material is constant inside
+% a cell (material probing in cell center)
+%
+% examples:
+% %default init with 1e9 max. timesteps and -50dB end-criteria
+% FDTD = InitFDTD();
+%
+% %init with 1e6 max. timesteps and -60dB end-criteria
+% FDTD = InitFDTD('NrTS', 1e6, 'EndCriteria', 1e-6);
+%
+% %cylindrical FDTD simulation
+% FDTD = InitFDTD('CoordSystem', 1);
+%
+% See also InitCSX
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig (c) 2010-2013
+
+% default values
+NrTS = 1e9;
+endCrit = 1e-5;
+
+% legacy support
+if ((nargin==1) && (isnumeric(varargin{1})))
+ NrTS = varargin{1};
+ warning('openEMS:InitFDTD',['Syntax for InitFDTD has changed, use: "InitFDTD(''NrTS'', ' num2str(NrTS) ')" instead! Legacy support enabled.']);
+elseif ((nargin>1) && (isnumeric(varargin{1})) && (isnumeric(varargin{2})))
+ NrTS = varargin{1};
+ endCrit = varargin{2};
+ varargin(1:2) = [];
+ warning('openEMS:InitFDTD',['Syntax for InitFDTD has changed, use: "InitFDTD(''NrTS'', ' num2str(NrTS) ', ''EndCriteria'', ' num2str(endCrit) ')" instead! Legacy support enabled.']);
+end
+
+for n=1:numel(varargin)/2
+ if strcmpi(varargin{2*n-1},'CoordSystem')==1
+ FDTD.ATTRIBUTE.CylinderCoords=varargin{2*n}==1;
+ elseif strcmpi(varargin{2*n-1},'NrTS')==1
+ NrTS=varargin{2*n};
+ elseif strcmpi(varargin{2*n-1},'EndCriteria')==1
+ endCrit=varargin{2*n};
+ else
+ FDTD.ATTRIBUTE.(varargin{2*n-1})=varargin{2*n};
+ end
+end
+
+FDTD.ATTRIBUTE.NumberOfTimesteps=NrTS;
+FDTD.ATTRIBUTE.endCriteria=endCrit;
diff --git a/openEMS/matlab/InitQueue.m b/openEMS/matlab/InitQueue.m
new file mode 100644
index 0000000..feec5cc
--- /dev/null
+++ b/openEMS/matlab/InitQueue.m
@@ -0,0 +1,90 @@
+function [queue] = InitQueue(varargin)
+% function [queue] = InitQueue(varargin)
+%
+% Use this function to initialize a queue to run one or more matlab scripts
+% in parallel.
+% This can be used to efficiently run an openEMS parameter sweep in parallel
+% on multiple remote machines.
+%
+% Options:
+% DependPath: Add multiple paths, your script may depend on
+% UseOctave: Enable/Disable octave usage
+% MaxThreads: max. number of parallel executions
+%
+% Note:
+% - Currently only Linux/Unix is supported
+% - By default Octave is used to spawn parallel functions (saves
+% licenses), but this can be changed by:
+% [queue] = InitQueue('UseOctave', 0);
+% You may need to change this, if your script is not octave compatible
+% - To efficiently run openEMS in parallel, you need to run it on several
+% machines using a SSH.host_list setting --> See also RunOpenEMS
+%
+% Example:
+% %serial version:
+% for n=1:10
+% % manipulate parameter etc.
+% [result1(n) result2(n)] = Parallel_Func_Name(param1, param2);
+% end
+%
+% %parallel version:
+% queue = InitQueue('DependPath',{'/opt/openEMS/CSXCAD/matlab', ...
+% '/opt/openEMS/openEMS/matlab'});
+% for n=1:10
+% % manipulate parameter etc.
+% queue = Add2Queue(queue, 'Parallel_Func_Name', {param1, param2});
+% end
+%
+% % wait for all to finish
+% [queue] = FinishQueue(queue);
+%
+% % retrieve result
+% for n=1:numel(stub_sweep)
+% [result1(n) result2(n)] = ResultsQueue(queue,n);
+% end
+%
+% See also: Add2Queue, FinishQueue, ResultsQueue, RunOpenEMS,
+% RunOpenEMS_Parallel, FindFreeSSH
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if ~isunix
+ error 'your OS is not supported (Unix only)'
+end
+
+queue.use_octave = exist('OCTAVE_VERSION','builtin') ~= 0;
+
+queue.verbose = 1;
+
+queue.maxThreads = Inf;
+
+% add current path
+queue.DependPath = ['addpath(''' pwd ''');'];
+
+for n=1:2:nargin
+ if strcmp(varargin{n},'DependPath');
+ for m=1:numel(varargin{n+1})
+ queue.DependPath = [queue.DependPath 'addpath(''' varargin{n+1}{m} ''');'];
+ end
+ end
+ if strcmp(varargin{n},'UseOctave');
+ queue.use_octave = varargin{n+1};
+ end
+ if strcmp(varargin{n},'MaxThreads');
+ queue.maxThreads = varargin{n+1};
+ end
+end
+
+
+% set binaries and options
+if (queue.use_octave)
+ queue.bin = ['export LD_LIBRARY_PATH=""; octave'];
+ queue.bin_options = [' --silent --eval'];
+else
+ queue.bin = [matlabroot '/bin/matlab'];
+ queue.bin_options = [' -nodesktop -nosplash -r'];
+end
+
+queue.jobs_finished = [];
diff --git a/openEMS/matlab/PlotHDF5FieldData.m b/openEMS/matlab/PlotHDF5FieldData.m
new file mode 100644
index 0000000..9aaf899
--- /dev/null
+++ b/openEMS/matlab/PlotHDF5FieldData.m
@@ -0,0 +1,94 @@
+function PlotHDF5FieldData(file, PlotArgs)
+% function PlotHDF5FieldData(file, PlotArgs)
+%
+% e.g.
+% PlotArgs.slice = {0 [10 20] 0};
+% PlotArgs.pauseTime=0.01;
+% PlotArgs.component=2;
+% PlotArgs.Limit = 'auto';
+%
+% PlotHDF5FieldData('tmp/Et.h5',PlotArgs)
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+component = PlotArgs.component;
+
+if (isfield(PlotArgs,'pauseTime'))
+ pauseT = PlotArgs.pauseTime;
+else
+ pauseT = 0.01;
+end
+
+mesh = ReadHDF5Mesh(file);
+fields = ReadHDF5FieldData(file);
+
+if (mesh.type==0)
+ % cartesian mesh
+ [X Y Z] = meshgrid(mesh.lines{1},mesh.lines{2},mesh.lines{3});
+ for n=1:numel(fields.TD.values)
+ % since Matlab 7.1SP3 the field needs to be reordered
+ fields.TD.values{n} = permute(fields.TD.values{n},[2 1 3 4]); % reorder: y,x,z (or y,x)
+ end
+else
+ disp(['PlotHDF5FieldData:: Error: unknown mesh type ' num2str(mesh.type)]);
+end
+
+max_amp = 0;
+
+if (component>0)
+ for n=1:numel(fields.TD.values)
+ Field{n} = fields.TD.values{n}(:,:,:,component);
+ end
+else
+ for n=1:numel(fields.TD.values)
+ fx = fields.TD.values{n}(:,:,:,1);
+ fy = fields.TD.values{n}(:,:,:,2);
+ fz = fields.TD.values{n}(:,:,:,3);
+ Field{n} = sqrt(fx.^2 + fy.^2 + fz.^2);
+ end
+end
+
+for n=1:numel(Field)
+ amp = max(max(max(abs(Field{n}))));
+ if (amp>max_amp)
+ max_amp = amp;
+ end
+end
+
+if (max_amp==0)
+ disp('max found amplitude was 0 --> nothing to plot');
+ return
+end
+
+for n=1:numel(Field)
+ if size(Field{n},3) > 1
+ % Field is a volume
+ hsurfaces = slice(X,Y,Z, Field{n} , PlotArgs.slice{:});
+ set(hsurfaces,'FaceColor','interp','EdgeColor','none');
+ else
+ % Field is already a 2D cut
+ pcolor(X,Y,Field{n});
+ shading( 'interp' );
+ xlabel( 'x' );
+ ylabel( 'y' );
+ end
+ title(fields.TD.names{n});
+ %view(3)
+ axis equal
+ if (isfield(PlotArgs,'Limit'))
+ if ~ischar(PlotArgs.Limit)
+ caxis(PlotArgs.Limit);
+ elseif strcmp(PlotArgs.Limit,'auto')
+ if (component>0)
+ caxis([-max_amp,max_amp]);
+ else
+ caxis([0,max_amp]);
+ end
+ end
+ end
+
+ drawnow
+ pause(pauseT)
+end
diff --git a/openEMS/matlab/ReadHDF5Attribute.m b/openEMS/matlab/ReadHDF5Attribute.m
new file mode 100644
index 0000000..3361ee9
--- /dev/null
+++ b/openEMS/matlab/ReadHDF5Attribute.m
@@ -0,0 +1,33 @@
+function attr = ReadHDF5Attribute(file, groupname, attr_name)
+% attr = ReadHDF5Attribute(file, groupname, attr_name)
+%
+% internal function for openEMS to read hdf5 attributes
+%
+% See also: ReadHDF5ComplexData
+%
+% openEMS Matlab/Octave interface
+% -----------------------
+% author: Thorsten Liebig, 2012
+
+
+if isOctave
+ if (exist('h5readatt_octave')==0)
+ warning('openEMS:ReadHDF5Attribute','function "h5readatt_octave" not found, trying to run "setup"');
+ try
+ setup
+ catch
+ error('openEMS:ReadHDF5Attribute','running "setup" failed...');
+ end
+ end
+ attr = double(h5readatt_octave(file,groupname,attr_name));
+else
+ %check for different matlab versions
+ if verLessThan('matlab','7.9')
+ attr = double(hdf5read(file,[groupname '/' attr_name]));
+ elseif verLessThan('matlab','7.12')
+ attr = double(hdf5read(file,groupname,attr_name));
+ else
+ attr = double(h5readatt(file,groupname,attr_name));
+ end
+
+end \ No newline at end of file
diff --git a/openEMS/matlab/ReadHDF5Dump.m b/openEMS/matlab/ReadHDF5Dump.m
new file mode 100644
index 0000000..9fc8c43
--- /dev/null
+++ b/openEMS/matlab/ReadHDF5Dump.m
@@ -0,0 +1,92 @@
+function [field mesh] = ReadHDF5Dump(file, varargin)
+%[field mesh] = ReadHDF5Dump(file, varargin)
+%
+% Read a hdf5 field dump, including an interpolation and frequency domain
+% transformation.
+%
+% For more information about the output, refer to the help of
+% ReadHDF5Mesh and ReadHDF5FieldData
+%
+% possible arguments:
+% 'Range' see GetField_Range
+% 'Interpolation' see GetField_Interpolation
+% 'SubSampling' see GetField_SubSampling
+% 'Frequency' see GetField_TD2FD
+% 'CloseAlpha': 0 (default) / 1
+%
+% example:
+% [field mesh] = ReadHDF5Dump('Et.h5');
+% or
+% [field mesh] = ReadHDF5Dump('Et.h5','Range',{[0 100],[-20 20],[50 90]});
+% or
+% [field mesh] = ReadHDF5Dump('Et.h5','Interpolation',[21 1 101],'Frequency',300e6);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5Mesh ReadHDF5FieldData GetField_Interpolation GetField_SubSampling
+% GetField_TD2FD GetField_Range
+
+field = ReadHDF5FieldData(file);
+mesh = ReadHDF5Mesh(file);
+
+if (nargin<2)
+ return
+end
+
+% evaluate arguments in a specific order
+for n=1:2:(nargin-1)
+ if (strcmp(varargin{n},'Range')==1);
+ [field mesh] = GetField_Range(field, mesh, varargin{n+1});
+ end
+end
+
+for n=1:2:(nargin-1)
+ if (strcmp(varargin{n},'SubSampling')==1);
+ [field mesh] = GetField_SubSampling(field,mesh,varargin{n+1});
+ end
+end
+
+for n=1:2:(nargin-1)
+ if (strcmp(varargin{n},'Interpolation')==1);
+ [field mesh] = GetField_Interpolation(field,mesh,varargin{n+1});
+ end
+end
+
+for n=1:2:(nargin-1)
+ if (strcmp(varargin{n},'Frequency')==1);
+ field = GetField_TD2FD(field,varargin{n+1});
+ end
+end
+
+for n=1:2:(nargin-1)
+ if (strcmp(varargin{n},'CloseAlpha')==1);
+ if ((varargin{n+1}==1) && (mesh.type==1) && (range(mesh.lines{2})<2*pi))
+ mesh.lines{2}(end+1)=mesh.lines{2}(1)+2*pi;
+ if (isfield(field,'TD'))
+ for n = 1:numel(field.TD.values)
+ field.TD.values{n}(:,end+1,:,:) = field.TD.values{n}(:,1,:,:);
+ end
+ end
+ if (isfield(field,'FD'))
+ for n = 1:numel(field.FD.values)
+ field.FD.values{n}(:,end+1,:,:) = field.FD.values{n}(:,1,:,:);
+ end
+ end
+ if (isfield(mesh,'original_indices'))
+ if (~isempty(mesh.original_indices))
+ mesh.original_indices{2} = [mesh.original_indices{2} 1];
+ end
+ else
+ mesh.original_indices = {1:numel(mesh.lines{1}),[1:numel(mesh.lines{2}) 1],[1:numel(mesh.lines{3})]};
+ end
+ end
+ end
+end
+
+end
+
+function rng = range(x)
+ rng = max(x)-min(x);
+end \ No newline at end of file
diff --git a/openEMS/matlab/ReadHDF5FieldData.m b/openEMS/matlab/ReadHDF5FieldData.m
new file mode 100644
index 0000000..c45f9ad
--- /dev/null
+++ b/openEMS/matlab/ReadHDF5FieldData.m
@@ -0,0 +1,119 @@
+function hdf_fielddata = ReadHDF5FieldData(file)
+% function hdf_fielddata = ReadHDF5FieldData(file)
+%
+% returns:
+% % time domain data (if exist)
+% hdf_fielddata.TD.time
+% hdf_fielddata.TD.names
+% hdf_fielddata.TD.values
+% hdf_fielddata.TD.DataType (0 --> real value data)
+%
+% % frequency domain data (if exist)
+% hdf_fielddata.FD.frequency
+% hdf_fielddata.FD.values
+% hdf_fielddata.FD.DataType (0 / 1 --> real / complex value data)
+%
+% example: values of timestep 12:
+% hdf_fielddata.TD.values{12}: array (x,y,z,polarization)
+%
+% plot z-field component along y-direction for timestep 12:
+% plot( hdf_fielddata.TD.values{12}(1,:,1,3) )
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5Mesh ReadHDF5Dump
+
+if isOctave
+ hdf_fielddata = ReadHDF5FieldData_octave(file);
+ return
+end
+
+info = hdf5info(file);
+TD.names = {};
+hdf_fielddata = [];
+
+for n=1:numel(info.GroupHierarchy.Groups)
+ if strcmp(info.GroupHierarchy.Groups(n).Name,'/FieldData')
+ %found /FieldData, look for either TD or FD data
+ for nGroup=1:numel(info.GroupHierarchy.Groups(n).Groups)
+ %search and read TD data
+ if strcmp(info.GroupHierarchy.Groups(n).Groups(nGroup).Name,'/FieldData/TD')
+ for m=1:numel(info.GroupHierarchy.Groups(n).Groups(nGroup).Datasets)
+ TD.names{m} = info.GroupHierarchy.Groups(n).Groups(nGroup).Datasets(m).Name;
+ for a = 1:numel(info.GroupHierarchy.Groups(n).Groups(nGroup).Datasets(m).Attributes)
+ str = regexp(info.GroupHierarchy.Groups(n).Groups(nGroup).Datasets(m).Attributes(a).Name,'\w/*\w*','match');
+ TD.(str{end})(m) = double(info.GroupHierarchy.Groups(n).Groups(nGroup).Datasets(m).Attributes(a).Value);
+ end
+ end
+ end
+ end
+
+ end
+end
+
+if (numel(TD.names)>0)
+ hdf_fielddata.TD=TD;
+ hdf_fielddata.TD.DataType = 0; %real value data
+ for n=1:numel(hdf_fielddata.TD.names)
+ hdf_fielddata.TD.values{n} = double(hdf5read(file,hdf_fielddata.TD.names{n}));
+ end
+end
+
+% extract FD data
+try
+ hdf_fielddata.FD.frequency = ReadHDF5Attribute(file,'/FieldData/FD','frequency');
+catch err
+% disp(err)
+ return
+end
+
+for n=1:numel(hdf_fielddata.FD.frequency)
+ try
+ hdf_fielddata.FD.values{n} = double(hdf5read(file,['/FieldData/FD/f' int2str(n-1) '_real']) + 1i*hdf5read(file,['/FieldData/FD/f' int2str(n-1) '_imag']));
+ hdf_fielddata.FD.DataType = 1; %complex value data
+ catch
+ try
+ hdf_fielddata.FD.values{n} = double(hdf5read(file,['/FieldData/FD/f' int2str(n-1)]));
+ hdf_fielddata.FD.DataType = 0; %real value data
+ catch
+ error('openEMS:ReadHDF5FieldData','FD data invalid...')
+ end
+ end
+end
+
+function hdf_fielddata = ReadHDF5FieldData_octave(file)
+hdf = load( '-hdf5', file );
+if ~isfield(hdf,'FieldData')
+ error('no field data found')
+end
+if isfield(hdf.FieldData,'TD')
+ %read TD data
+ hdf_fielddata_names = fieldnames(hdf.FieldData.TD);
+ for n=1:numel(hdf_fielddata_names)
+ hdf_fielddata.TD.values{n} = hdf.FieldData.TD.(hdf_fielddata_names{n});
+ hdf_fielddata.TD.names{n} = ['/FieldData/TD/' hdf_fielddata_names{n}(2:end)];
+ hdf_fielddata.TD.time(n) = ReadHDF5Attribute(file, hdf_fielddata.TD.names{n},'time');
+ end
+ hdf_fielddata.TD.DataType = 0; %real value data
+end
+if isfield(hdf.FieldData,'FD')
+ %read FD data
+ hdf_fielddata.FD.frequency = ReadHDF5Attribute(file,'/FieldData/FD/','frequency');
+ try %try reading complex data
+ for n=1:numel(hdf_fielddata.FD.frequency)
+ hdf_fielddata.FD.values{n} = double(hdf.FieldData.FD.(['f' int2str(n-1) '_real']) +1i*hdf.FieldData.FD.(['f' int2str(n-1) '_imag']) );
+ end
+ hdf_fielddata.FD.DataType = 1; %complex value data
+ catch
+ try %try reading real value data
+ for n=1:numel(hdf_fielddata.FD.frequency)
+ hdf_fielddata.FD.values{n} = double(hdf.FieldData.FD.(['f' int2str(n-1)]));
+ end
+ hdf_fielddata.FD.DataType = 0; %real value data
+ catch
+ error('openEMS:ReadHDF5FieldData','FD data invalid...')
+ end
+ end
+end
diff --git a/openEMS/matlab/ReadHDF5Mesh.m b/openEMS/matlab/ReadHDF5Mesh.m
new file mode 100644
index 0000000..b276391
--- /dev/null
+++ b/openEMS/matlab/ReadHDF5Mesh.m
@@ -0,0 +1,80 @@
+function hdf_mesh = ReadHDF5Mesh(file)
+% function hdf_mesh = ReadHDF5Mesh(file)
+%
+% Get the raw mesh data stored in the hdf5 dump file created by openEMS
+%
+% returns:
+% hdf_mesh.type (0-> cartesian, 1-> cylindrical mesh type)
+% hdf_mesh.names (e.g. 'Mesh/y')
+% hdf_mesh.lines (e.g. [0,1,2,3,4])
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also ReadHDF5FieldData
+
+isOctave = exist('OCTAVE_VERSION','builtin') ~= 0;
+if isOctave
+ hdf_mesh = ReadHDF5Mesh_octave(file);
+ return
+end
+
+info = hdf5info(file);
+
+for n=1:numel(info.GroupHierarchy.Groups)
+ if strcmp(info.GroupHierarchy.Groups(n).Name,'/Mesh')
+ for m=1:numel(info.GroupHierarchy.Groups(n).Datasets)
+ names{m} = info.GroupHierarchy.Groups(n).Datasets(m).Name;
+ end
+ end
+end
+
+hdf_mesh.names = names;
+for n=1:numel(names)
+ hdf_mesh.lines{n} = double(hdf5read(file,names{n}));
+end
+
+if (strcmp(names{1},'/Mesh/alpha'))
+ % alpha and rho are in the wrong order, flip to have rho, alpha, z
+ hdf_mesh.names(1:2) = fliplr(hdf_mesh.names(1:2));
+ hdf_mesh.lines(1:2) = fliplr(hdf_mesh.lines(1:2));
+ hdf_mesh.type=1;
+ return
+end
+if (strcmp(names{1},'/Mesh/phi'))
+ % reorder coordinates
+ hdf_mesh.names = hdf_mesh.names([2 3 1]);
+ hdf_mesh.lines = hdf_mesh.lines([2 3 1]);
+ hdf_mesh.type=2;
+ return
+end
+
+hdf_mesh.type=0;
+
+
+function hdf_mesh = ReadHDF5Mesh_octave(file)
+hdf = load( '-hdf5', file );
+hdf_mesh.names = fieldnames(hdf.Mesh);
+hdf_mesh.type = 0; % cartesian mesh
+for n=1:numel(hdf_mesh.names)
+ hdf_mesh.lines{n} = hdf.Mesh.(hdf_mesh.names{n});
+ hdf_mesh.names{n} = ['/Mesh/' hdf_mesh.names{n}];
+ if strcmp(hdf_mesh.names{n},'/Mesh/alpha')
+ hdf_mesh.type = 1; % cylindrical mesh
+ end
+ if strcmp(hdf_mesh.names{n},'/Mesh/phi')
+ hdf_mesh.type = 2; % cylindrical mesh
+ end
+end
+
+if (hdf_mesh.type==1)
+ % alpha and rho are in the wrong order, flip to have rho, alpha, z
+ hdf_mesh.names(1:2) = fliplr(hdf_mesh.names(1:2));
+ hdf_mesh.lines(1:2) = fliplr(hdf_mesh.lines(1:2));
+end
+if (hdf_mesh.type==2)
+ % alpha and rho are in the wrong order, flip to have rho, alpha, z
+ hdf_mesh.names = hdf_mesh.names([2 3 1]);
+ hdf_mesh.lines = hdf_mesh.lines([2 3 1]);
+end
diff --git a/openEMS/matlab/ReadUI.m b/openEMS/matlab/ReadUI.m
new file mode 100644
index 0000000..23fe342
--- /dev/null
+++ b/openEMS/matlab/ReadUI.m
@@ -0,0 +1,107 @@
+function UI = ReadUI(files, path, freq, varargin)
+% function UI = ReadUI(files, path, freq, varargin)
+%
+% read current and voltages from multiple files found in path
+%
+% returns voltages/currents in time and frequency-domain
+%
+% remarks on the frequency-domain:
+% - all signals are assumed to start at t=0
+% - currents that e.g. start at t = +delta_t/2 will be phase shifted by
+% exp(-j*w*t(1))
+%
+% optional parameter:
+% freq: frequency-domain values will be calculated according to 'freq'
+% if 'freq' is not given, a (zero padded) FFT will be used
+%
+% optional key,value pairs:
+% 'AR' : auto-regressive model to improve FD accuracy
+% values: order to use within an AR model or 'auto'
+%
+% % examples:
+% U = ReadUI({'ut1_1','ut1_2'},'tmp' );
+% I = ReadUI('it1' ,'tmp',[0.5e9 1e9 1.5e9]);
+%
+% % using the auto-regressive model
+% U = ReadUI('port_ut1' , 'tmp', 'AR', 'auto');
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+%
+% See also DFT_time2freq, AR_estimate
+
+if (nargin<2)
+ path ='';
+end
+
+AR_order = 0;
+SignalType = 'pulse';
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'AR')==1)
+ AR_order = varargin{n+1};
+ elseif strcmpi(varargin{n},'SignalType')
+ SignalType = varargin{n+1};
+ else
+ warning('CSXCAD:ReadUI', ['"' varargin{n} '" is an unknown argument']);
+ end
+end
+
+if strcmpi(SignalType,'periodic') && AR_order>0
+ error 'auto-regressive model not compatible with periodic signals'
+end
+
+if (ischar(files))
+ filenames{1}=files;
+else
+ filenames=files;
+end
+
+UI.TD = {};
+UI.FD = {};
+for n=1:numel(filenames)
+ tmp = load( fullfile(path,filenames{n}) );
+ t = tmp(:,1)';
+ val = tmp(:,2)';
+
+ UI.TD{n}.t = t;
+ UI.TD{n}.val = val;
+
+ if (numel(tmp(1,:))>2)
+ UI.TD{n}.additional = tmp(:,3:end)';
+ end
+
+ if (nargin<3) || isempty(freq)
+ if strcmpi(SignalType,'periodic')
+ warning 'ReadUI: periodic signal type not supported by FFT'
+ end
+ [UI.FD{n}.f,UI.FD{n}.val] = FFT_time2freq( t,val );
+ else
+ UI.FD{n}.f = freq;
+ if strcmpi(AR_order,'auto')
+ AR_order = 2;
+ EC = -1;
+ while 1
+ [val_ar t_ar UI.FD{n}.val EC] = AR_estimate( t, val, freq, AR_order);
+ if (EC==11)
+ AR_order = AR_order*2;
+ else
+ break;
+ end
+ end
+ if (EC~=0)
+ warning('CSXCAD:ReadUI','AR estimation failed, skipping...')
+ UI.FD{n}.val = DFT_time2freq( t, val, freq, SignalType );
+ end
+ elseif (AR_order<=0)
+ UI.FD{n}.val = DFT_time2freq( t, val, freq, SignalType );
+ else
+ [val_ar t_ar UI.FD{n}.val EC] = AR_estimate( t, val, freq, AR_order);
+ if (EC~=0)
+ warning('CSXCAD:ReadUI','AR estimation failed, skipping...')
+ UI.FD{n}.val = DFT_time2freq( t, val, freq, SignalType );
+ end
+ end
+ end
+end
diff --git a/openEMS/matlab/ResultsQueue.m b/openEMS/matlab/ResultsQueue.m
new file mode 100644
index 0000000..cc9f745
--- /dev/null
+++ b/openEMS/matlab/ResultsQueue.m
@@ -0,0 +1,24 @@
+function [varargout] = ResultsQueue(queue, n)
+% function [varargout] = ResultsQueue(queue, n)
+%
+% Use this function to retrieve the results from a finished queue.
+%
+% For more details see: InitQueue
+%
+% See also: InitQueue, FinishQueue, Add2Queue, RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if n>numel(queue.jobs)
+ error 'ResultsQueue:job is missing'
+end
+
+if (nargout>numel(queue.jobs{n}.outargs))
+ error 'not enough job output arguments'
+end
+
+for k=1:numel(queue.jobs{n}.outargs)
+ varargout{k} = queue.jobs{n}.outargs{k};
+end
diff --git a/openEMS/matlab/RunOpenEMS.m b/openEMS/matlab/RunOpenEMS.m
new file mode 100644
index 0000000..a4947e3
--- /dev/null
+++ b/openEMS/matlab/RunOpenEMS.m
@@ -0,0 +1,186 @@
+function RunOpenEMS(Sim_Path, Sim_File, opts, Settings)
+% function RunOpenEMS(Sim_Path, Sim_File, <opts, Settings>)
+%
+% Run an openEMS simulation.
+%
+% arguments:
+% Sim_Path: specifiy the simulation folder (folder must exist!)
+% Sim_File: xml-filename to simulate, created by WriteOpenEMS
+%
+% optional arguments
+%
+% opts: list of openEMS options
+% possible options:
+% --disable-dumps Disable all field dumps for faster simulation
+% --debug-material Dump material distribution to a vtk file for debugging
+% --debug-PEC Dump metal distribution to a vtk file for debugging
+% --debug-operator Dump operator to vtk file for debugging
+% --debug-boxes Dump e.g. probe boxes to vtk file for debugging
+% --debug-CSX Write CSX geometry file to debugCSX.xml
+% --engine=<type> Choose engine type
+% --engine=fastest fastest available engine (default)
+% --engine=basic basic FDTD engine
+% --engine=sse engine using sse vector extensions
+% --engine=sse_compressed engine using compressed operator + sse vector extensions
+% --engine=MPI engine using compressed operator + sse vector extensions + MPI parallel processing
+% --engine=multithreaded engine using compressed operator + sse vector extensions + MPI + multithreading
+% --numThreads=<n> Force use n threads for multithreaded engine
+% --no-simulation only run preprocessing; do not simulate
+% --dump-statistics dump simulation statistics to 'openEMS_run_stats.txt' and 'openEMS_stats.txt'
+%
+% Additional global arguments
+% --showProbeDiscretization Show probe discretization information
+% --nativeFieldDumps Dump all fields using the native field components
+% -v,-vv,-vvv Set debug level: 1 to 3
+%
+%
+% settings: list of Matlab settings
+% possible settings:
+% Settings.LogFile = 'openEMS.log'
+% Settings.Silent = 0
+%
+% additional remote simulation settings
+% Note: ssh only on unix with working ssh client or windows with putty client
+% openEMS Linux server or Windows with cygwin necessary
+% Settings.SSH.host = '<hostname or ip>'
+% Settings.SSH.bin = '<path_to_openEMS>/openEMS.sh'
+% ssh optional:
+% Settings.SSH.host_list = {'list','of','hosts'}; %searches for a free host
+% %on Windows needed additionally
+% Settings.SSH.Putty.Path = '<path_to>\putty';
+% Settings.SSH.Putty.Key = '<path_to>\putty_private_key.ppk';
+%
+% MPI settings:
+% Settings.MPI.xxx --> help RunOpenEMS_MPI
+%
+%
+% example:
+% %create CSX and FDTD
+% WriteOpenEMS('/tmp/path_to_run_in/myfile.xml', FDTD, CSX)
+% RunOpenEMS('/tmp/path_to_run_in','myfile.xml','-v')
+%
+% See also WriteOpenEMS FindFreeSSH InitCSX InitFDTD RunOpenEMS_MPI
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if nargin < 2
+ error 'specify the Sim_Path and Sim_file to simulate'
+end
+
+if nargin < 3
+ opts = '';
+end
+
+if (nargin<4)
+ Settings = [];
+end
+
+if (isfield(Settings,'MPI') && isunix)
+ if (Settings.MPI.NrProc>1)
+ RunOpenEMS_MPI(Sim_Path, Sim_File, opts, Settings);
+ return;
+ end
+end
+
+ssh_command = 'ssh';
+scp_command = 'scp';
+scp_options = '';
+ssh_options = '';
+
+enable_ssh = 0;
+enable_ssh = isfield(Settings,'SSH') && isunix;
+
+if ~isunix
+ enable_ssh = isfield(Settings,'SSH') && isfield(Settings.SSH,'Putty');
+ if (enable_ssh)
+ ssh_command = [Settings.SSH.Putty.Path '/plink '];
+ ssh_options = [ssh_options ' -i ' Settings.SSH.Putty.Key];
+
+ scp_command = [Settings.SSH.Putty.Path '/pscp '];
+ scp_options = [scp_options ' -i ' Settings.SSH.Putty.Key];
+ end
+end
+
+savePath = pwd;
+cd(Sim_Path);
+
+if (enable_ssh)
+ scp_options = [scp_options ' -C'];
+ ssh_options = [ssh_options ' -x -C'];
+
+ % ssh options: no X forwarding; no password prompt (use pub keys!); no host checking
+ if (isunix)
+ ssh_options = [ssh_options ' -o "PasswordAuthentication no" -o "StrictHostKeyChecking no"'];
+ scp_options = [scp_options ' -o "PasswordAuthentication no" -o "StrictHostKeyChecking no"'];
+ end
+
+ if isfield(Settings.SSH,'host_list')
+ host = FindFreeSSH(Settings.SSH.host_list, Settings);
+ if ~isempty(host)
+ Settings.SSH.host = host;
+ else
+ error('openEMS:RunOpenEMS', 'unable to find host, abort openEMS');
+ end
+ end
+
+ % create a tmp working dir
+ [status, result] = system([ssh_command ' ' ssh_options ' ' Settings.SSH.host ' "mktemp -d /tmp/openEMS_XXXXXXXXXXXX"']);
+ if (status~=0)
+ disp(result);
+ error('openEMS:RunOpenEMS','mktemp failed to create tmp directory!');
+ end
+ ssh_work_path = strtrim(result); %remove tailing \n
+
+ disp(['Running remote openEMS on ' Settings.SSH.host ' at working dir: ' ssh_work_path]);
+
+ %copy openEMS all simulation files to the ssh host
+ [stat, res] = system([scp_command ' ' scp_options ' * ' Settings.SSH.host ':' ssh_work_path '/']);
+ if (stat~=0)
+ disp(res);
+ error('openEMS:RunOpenEMS','scp failed!');
+ end
+
+ %run openEMS (with log file if requested)
+ if isfield(Settings,'LogFile') && isunix
+ append_unix = [' 2>&1 | tee ' Settings.LogFile];
+ else
+ append_unix = [];
+ end
+ status = system([ssh_command ' ' ssh_options ' ' Settings.SSH.host ' "cd ' ssh_work_path ' && ' Settings.SSH.bin ' ' Sim_File ' ' opts '"' append_unix]);
+ if (status~=0)
+ disp(result);
+ error('openEMS:RunOpenEMS','ssh openEMS failed!');
+ end
+
+ disp( 'Remote simulation done... copying back results and cleaning up...' );
+
+ %copy back all results
+ [stat, res] = system([scp_command ' -r ' scp_options ' ' Settings.SSH.host ':' ssh_work_path '/* ' pwd '/']);
+ if (stat~=0);
+ disp(res);
+ error('openEMS:RunOpenEMS','scp failed!');
+ end
+
+ %cleanup
+ [stat, res] = system([ssh_command ' ' ssh_options ' ' Settings.SSH.host ' rm -r ' ssh_work_path]);
+ if (stat~=0);
+ disp(res);
+ warning('openEMS:RunOpenEMS','remote cleanup failed!');
+ end
+else
+ args = [Sim_File ' ' opts];
+ if isfield(Settings,'LogFile') && isfield(Settings,'Silent')
+ invoke_openEMS(args,Settings.LogFile,Settings.Silent);
+ elseif isfield(Settings,'LogFile')
+ invoke_openEMS(args,Settings.LogFile);
+ elseif isfield(Settings,'Silent')
+ invoke_openEMS(args,[],Settings.Silent);
+ else
+ invoke_openEMS(args);
+ end
+end
+
+cd(savePath);
+return
diff --git a/openEMS/matlab/RunOpenEMS_MPI.m b/openEMS/matlab/RunOpenEMS_MPI.m
new file mode 100644
index 0000000..495f7e5
--- /dev/null
+++ b/openEMS/matlab/RunOpenEMS_MPI.m
@@ -0,0 +1,125 @@
+function RunOpenEMS_MPI(Sim_Path, Sim_File, opts, Settings)
+% function RunOpenEMS_MPI(Sim_Path, Sim_File, NrProc, opts, Settings)
+%
+% Run an openEMS simulation with MPI support
+%
+% % mpi binary path on all nodes needed
+% Settings.MPI.Binary = '/opt/openEMS/openEMS';
+% % number of processes to run
+% Settings.MPI.NrProc = 3;
+% % define the mpi hosts :
+% Settings.MPI.Hosts = {'host1','host2','host3'};
+%
+% RunOpenEMS(Sim_Path, Sim_File, NrProc, opts, Settings)
+%
+% See also SetupMPI, WriteOpenEMS, RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if (isunix ~= 1)
+ error 'MPI version of openEMS currently only available using Linux'
+end
+
+if nargin < 4
+ error 'missing arguments: specify the Sim_Path, Sim_file, opts and Settings...'
+end
+
+NrProc = Settings.MPI.NrProc;
+
+if (NrProc<2)
+ error('openEMS:RunOpenEMS_MPI','MPI number of processes to small...');
+end
+
+if ~isfield(Settings,'MPI')
+ error('openEMS:RunOpenEMS_MPI','MPI settings not found...');
+end
+
+savePath = pwd;
+cd(Sim_Path);
+
+scp_options = '-C -o "PasswordAuthentication no" -o "StrictHostKeyChecking no"';
+ssh_options = [scp_options ' -x'];
+
+if isfield(Settings.MPI,'Hosts')
+ Remote_Nodes = Settings.MPI.Hosts;
+ HostList = '';
+ for n=1:numel(Remote_Nodes)
+ remote_name = Remote_Nodes{n};
+
+ if (n==1)
+ [status, result] = unix(['ssh ' ssh_options ' ' remote_name ' "mktemp -d /tmp/openEMS_MPI_XXXXXXXXXXXX"']);
+ if (status~=0)
+ disp(result);
+ error('openEMS:RunOpenEMS','mktemp failed to create tmp directory!');
+ end
+ work_path = strtrim(result); %remove tailing \n
+ HostList = remote_name;
+ else
+ [status, result] = unix(['ssh ' ssh_options ' ' remote_name ' "mkdir ' work_path '"']);
+ if (status~=0)
+ disp(result);
+ error('openEMS:RunOpenEMS',['mkdir failed to create tmp directory on remote ' remote_name ' !']);
+ end
+ HostList = [HostList ',' remote_name];
+ end
+
+ [stat, res] = unix(['scp ' scp_options ' * ' remote_name ':' work_path '/']);
+ if (stat~=0)
+ disp(res);
+ error('openEMS:RunOpenEMS',['scp to remote ' remote_name ' failed!']);
+ end
+ end
+end
+
+
+%run openEMS (with log file if requested)
+if isfield(Settings,'LogFile')
+ append_unix = [' 2>&1 | tee ' Settings.LogFile];
+else
+ append_unix = [];
+end
+
+if ~isfield(Settings.MPI,'GlobalArgs')
+ Settings.MPI.GlobalArgs = '';
+end
+
+if isfield(Settings.MPI,'Hosts')
+ disp(['Running remote openEMS_MPI in working dir: ' work_path]);
+ [status] = system(['mpiexec -host ' HostList ' -n ' int2str(NrProc) ' -wdir ' work_path ' ' Settings.MPI.Binary ' ' Sim_File ' ' opts ' ' append_unix]);
+else
+ disp('Running local openEMS_MPI');
+ [status] = system(['mpiexec ' Settings.MPI.GlobalArgs ' -n ' int2str(NrProc) ' ' Settings.MPI.Binary ' ' Sim_File ' ' opts ' ' append_unix]);
+end
+
+if (status~=0)
+ error('openEMS:RunOpenEMS','mpirun openEMS failed!');
+end
+
+if isfield(Settings.MPI,'Hosts')
+ disp( 'Remote simulation done... copying back results and cleaning up...' );
+
+ if (strncmp(work_path,'/tmp/',5)~=1) % savety precaution...
+ error('openEMS:RunOpenEMS','working path invalid for deletion');
+ end
+
+ for n=1:numel(Remote_Nodes)
+ remote_name = Remote_Nodes{n};
+ disp(['Copy data from remote node: ' remote_name]);
+ [stat, res] = unix(['scp -r ' scp_options ' ' remote_name ':' work_path '/* ''' pwd '''/']);
+ if (stat~=0);
+ disp(res);
+ error('openEMS:RunOpenEMS','remote scp failed!');
+ end
+
+ %cleanup
+ [stat, res] = unix(['ssh ' ssh_options ' ' remote_name ' rm -r ' work_path]);
+ if (stat~=0);
+ disp(res);
+ warning('openEMS:RunOpenEMS','remote cleanup failed!');
+ end
+ end
+end
+
+cd(savePath);
diff --git a/openEMS/matlab/RunOpenEMS_Parallel.m b/openEMS/matlab/RunOpenEMS_Parallel.m
new file mode 100644
index 0000000..cd5d4bd
--- /dev/null
+++ b/openEMS/matlab/RunOpenEMS_Parallel.m
@@ -0,0 +1,92 @@
+function [stdout, stderr] = RunOpenEMS_Parallel(Sim_Paths, Sim_Files, opts, Settings, varargin)
+% function [stdout, stderr] = RunOpenEMS_Parallel(Sim_Paths, Sim_Files, opts, Settings, varargin)
+%
+% Run multiple openEMS simulations in parallel, distributed on multiple
+% machines using a ssh host_list! (currently on Linux only)
+%
+% This function relies on InitQueue etc.
+%
+% input:
+% Sim_Paths: cell array of pathes to simulate by RunOpenEMS
+% Sim_Files: filename or cell array of filenames to simulate
+% opts: openEMS options. sa RunOpenEMS
+% Settings: use the settings to define multiple host for simulation
+% e.g.: Settings.SSH.bin ='<path_to_openEMS>/openEMS.sh';
+% Settings.SSH.host_list = {'list','of','hosts'};
+%
+% Note: If no SSH host_list is defined, this function will skip the
+% parallel run and switch back to a default RunOpenEMS!
+%
+% See also RunOpenEMS, FindFreeSSH, InitQueue
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig 2011
+
+pause_queue = 5; %pause between consecutive runs (needed for FindFreeSSH)
+
+skip_parallel = 0;
+
+% currently only supporting linux, run conventional RunOpenEMS
+if ~isunix
+ warning 'your OS is not supported (Unix only), running default RunOpenEMS';
+ skip_parallel = 1;
+end
+
+% in case only one path is given, run conventional RunOpenEMS
+if ischar(Sim_Paths)
+ warning 'only a single path given, running default RunOpenEMS'
+ skip_parallel = 1;
+end
+
+% in case SSH.host_list is not defined, run conventional RunOpenEMS
+if ~isfield(Settings,'SSH')
+ warning 'SSH options missing, running default RunOpenEMS'
+ skip_parallel = 1;
+elseif ~isfield(Settings.SSH,'host_list')
+ warning 'SSH.host_list option missing, running default RunOpenEMS'
+ skip_parallel = 1;
+end
+
+if (skip_parallel)
+ for n=1:numel(Sim_Paths)
+ if iscell(Sim_Files)
+ Sim_File = Sim_Files{n};
+ else
+ Sim_File = Sim_Files;
+ end
+ RunOpenEMS(Sim_Paths{n}, Sim_Files, opts, Settings)
+ end
+ stdout = [];
+ stderr = [];
+ return
+end
+
+if ~iscell(Sim_Paths)
+ error('RunOpenEMS_Parallel:needs a cell array of Sim_Paths to simulate');
+end
+
+% get the path to this file
+[dir] = fileparts( mfilename('fullpath') );
+
+queue = InitQueue('DependPath',{dir}, varargin{:});
+
+% spawn multiple simulations
+for n=1:numel(Sim_Paths)
+ if iscell(Sim_Files)
+ Sim_File = Sim_Files{n};
+ else
+ Sim_File = Sim_Files;
+ end
+
+ queue = Add2Queue(queue,'RunOpenEMS',{Sim_Paths{n}, Sim_File, opts, Settings});
+ disp(['openEMS simulation #' int2str(n) ' in directory: ' Sim_Paths{n} ' started!']);
+ pause(pause_queue);
+end
+
+[queue] = FinishQueue(queue);
+
+for n=1:numel(Sim_Paths)
+ stdout{n} = queue.jobs{n}.stdout;
+ stderr{n} = queue.jobs{n}.stderr;
+end
diff --git a/openEMS/matlab/SetBoundaryCond.m b/openEMS/matlab/SetBoundaryCond.m
new file mode 100644
index 0000000..fbfbd4c
--- /dev/null
+++ b/openEMS/matlab/SetBoundaryCond.m
@@ -0,0 +1,68 @@
+function FDTD = SetBoundaryCond(FDTD, BC, varargin)
+% FDTD = SetBoundaryCond(FDTD, BC, varargin)
+%
+% BC = [xmin xmax ymin ymax zmin zmax];
+% or BC = {xmin xmax ymin ymax zmin zmax};
+% ?min/?max:
+% 0 = PEC or 'PEC'
+% 1 = PMC or 'PMC'
+% 2 = MUR-ABC or 'MUR'
+% 3 = PML-ABC or 'PML_x' with pml size x => 4..50
+%
+% example:
+% BC = [ 1 1 0 0 2 3 ] %using numbers or
+% BC = {'PMC' 'PMC' 'PEC' 'PEC' 'MUR' 'PML_8'} %usign equivalent strings
+%
+% mur-abc definitions
+% define a phase-velocity to be used by the mur-abc
+% useful e.g. for dispersive waveguides
+% FDTD = SetBoundaryCond(FDTD,BC,'MUR_PhaseVelocity',299792457.93272);
+%
+%
+% pml definitions
+% arguments: 'PML_Grading','gradFunction'
+% Define the pml grading grading function.
+% Predefined variables in this grading function are:
+% D = depth in the pml in meter
+% dl = mesh delta inside the pml in meter
+% W = width (length) of the pml in meter
+% N = number of cells for the pml
+% Z = wave impedance at the current depth and position
+%
+% example:
+% FDTD = SetBoundaryCond(FDTD,BC);
+% or
+% FDTD = SetBoundaryCond(FDTD,BC,'PML_Grading','-log(1e-6)*log(2.5)/(2*dl*pow(2.5,W/dl)-1) * pow(2.5, D/dl) / Z');
+%
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+if (numel(BC)~=6)
+ error('openEMS:SetBoundaryCond','wrong number of boundary conditions');
+end
+
+if isnumeric(BC)
+ FDTD.BoundaryCond.ATTRIBUTE.xmin=BC(1);
+ FDTD.BoundaryCond.ATTRIBUTE.xmax=BC(2);
+ FDTD.BoundaryCond.ATTRIBUTE.ymin=BC(3);
+ FDTD.BoundaryCond.ATTRIBUTE.ymax=BC(4);
+ FDTD.BoundaryCond.ATTRIBUTE.zmin=BC(5);
+ FDTD.BoundaryCond.ATTRIBUTE.zmax=BC(6);
+elseif iscell(BC)
+ FDTD.BoundaryCond.ATTRIBUTE.xmin=BC{1};
+ FDTD.BoundaryCond.ATTRIBUTE.xmax=BC{2};
+ FDTD.BoundaryCond.ATTRIBUTE.ymin=BC{3};
+ FDTD.BoundaryCond.ATTRIBUTE.ymax=BC{4};
+ FDTD.BoundaryCond.ATTRIBUTE.zmin=BC{5};
+ FDTD.BoundaryCond.ATTRIBUTE.zmax=BC{6};
+else
+ error('openEMS:SetBoundaryCond','unknown boundary condition type');
+end
+
+
+for n=1:(nargin-2)/2
+ FDTD.BoundaryCond.ATTRIBUTE.(varargin{2*n-1}) = varargin{2*n};
+end
+ \ No newline at end of file
diff --git a/openEMS/matlab/SetCustomExcite.m b/openEMS/matlab/SetCustomExcite.m
new file mode 100644
index 0000000..6f87a49
--- /dev/null
+++ b/openEMS/matlab/SetCustomExcite.m
@@ -0,0 +1,21 @@
+function FDTD = SetCustomExcite(FDTD,f0,funcStr)
+% function FDTD = SetCustomExcite(FDTD,f0,funcStr)
+%
+% f0 : nyquist rate
+% funcStr : string desribing the excitation function e(t)
+%
+% see also SetSinusExcite SetGaussExcite
+%
+% e.g for a ramped sinus excite...
+% T = 1/f0;
+% FDTD = SetCustomExcite(FDTD,1e9,..
+% [ '(1-exp(-1*(t/' num2str(T) ')^2) ) * sin(2*pi*' num2str(f0) '*t)' ]);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+FDTD.Excitation.ATTRIBUTE.Type=10;
+FDTD.Excitation.ATTRIBUTE.f0=f0;
+FDTD.Excitation.ATTRIBUTE.Function=funcStr;
+FDTD.ATTRIBUTE.f_max=f0;
diff --git a/openEMS/matlab/SetDiracExcite.m b/openEMS/matlab/SetDiracExcite.m
new file mode 100644
index 0000000..18a342d
--- /dev/null
+++ b/openEMS/matlab/SetDiracExcite.m
@@ -0,0 +1,3 @@
+function FDTD = SetDiracExcite(FDTD)
+
+FDTD.Excitation.ATTRIBUTE.Type=2;
diff --git a/openEMS/matlab/SetGaussExcite.m b/openEMS/matlab/SetGaussExcite.m
new file mode 100644
index 0000000..be650ba
--- /dev/null
+++ b/openEMS/matlab/SetGaussExcite.m
@@ -0,0 +1,18 @@
+function FDTD = SetGaussExcite(FDTD,f0,fc)
+% function FDTD = SetGaussExcite(FDTD,f0,fc);
+%
+% f0 : center frequency
+% fc : 20dB cutoff frequency --> bandwidth is 2*fc
+%
+% see also SetSinusExcite SetCustomExcite
+%
+% e.g FDTD = SetGaussExcite(FDTD,1e9,1e8);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+FDTD.Excitation.ATTRIBUTE.Type=0;
+FDTD.Excitation.ATTRIBUTE.f0=f0;
+FDTD.Excitation.ATTRIBUTE.fc=fc;
+FDTD.ATTRIBUTE.f_max=f0+fc;
diff --git a/openEMS/matlab/SetSinusExcite.m b/openEMS/matlab/SetSinusExcite.m
new file mode 100644
index 0000000..22aadde
--- /dev/null
+++ b/openEMS/matlab/SetSinusExcite.m
@@ -0,0 +1,14 @@
+function FDTD = SetSinusExcite(FDTD,f0)
+% function FDTD = SetSinusExcite(FDTD,f0)
+%
+% see also SetGaussExcite SetCustomExcite
+%
+% e.g FDTD = SetSinusExcite(FDTD,1e9);
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+FDTD.Excitation.ATTRIBUTE.Type=1;
+FDTD.Excitation.ATTRIBUTE.f0=f0;
+FDTD.ATTRIBUTE.f_max=f0;
diff --git a/openEMS/matlab/SetStepExcite.m b/openEMS/matlab/SetStepExcite.m
new file mode 100644
index 0000000..ff87e4f
--- /dev/null
+++ b/openEMS/matlab/SetStepExcite.m
@@ -0,0 +1,3 @@
+function FDTD = SetStepExcite(FDTD)
+
+FDTD.Excitation.ATTRIBUTE.Type=3;
diff --git a/openEMS/matlab/SetupMPI.m b/openEMS/matlab/SetupMPI.m
new file mode 100644
index 0000000..51d6f65
--- /dev/null
+++ b/openEMS/matlab/SetupMPI.m
@@ -0,0 +1,17 @@
+function FDTD = SetupMPI(FDTD, varargin)
+% function FDTD = SetupMPI(FDTD, varargin);
+%
+% % example, split the FDTD mesh in 2 equal parts in x-direction
+% % and split the FDTD mesh in 3 parts in z-direction, split at z=-500 and z=500
+% % this will need a Settings.MPI.NrProc of 2*3=6
+% FDTD = SetupMPI(FDTD,'SplitN_X',2 ,'SplitPos_Z', '-500,500');
+%
+% See also RunOpenEMS_MPI
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+for n=1:(nargin-1)/2
+ FDTD.MPI.ATTRIBUTE.(varargin{2*n-1})=varargin{2*n};
+end
diff --git a/openEMS/matlab/Tutorials/Bent_Patch_Antenna.m b/openEMS/matlab/Tutorials/Bent_Patch_Antenna.m
new file mode 100644
index 0000000..33d5cac
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Bent_Patch_Antenna.m
@@ -0,0 +1,197 @@
+%
+% Tutorials / bent patch antenna
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Bent_Patch_Antenna
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2013-2015 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% patch width in alpha-direction
+patch.width = 32; % resonant length in alpha-direction
+patch.radius = 50; % radius
+patch.length = 40; % patch length in z-direction
+
+%substrate setup
+substrate.epsR = 3.38;
+substrate.kappa = 1e-3 * 2*pi*2.45e9 * EPS0*substrate.epsR;
+substrate.width = 80;
+substrate.length = 90;
+substrate.thickness = 1.524;
+substrate.cells = 4;
+
+%setup feeding
+feed.pos = -5.5; %feeding position in x-direction
+feed.width = 2; %feeding port width
+feed.R = 50; %feed resistance
+
+% size of the simulation box
+SimBox.rad = 2*100;
+SimBox.height = 1.5*200;
+
+%% setup FDTD parameter & excitation function
+FDTD = InitFDTD('CoordSystem', 1); % init a cylindrical FDTD
+f0 = 2e9; % center frequency
+fc = 1e9; % 20 dB corner frequency
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+% init a cylindrical mesh
+CSX = InitCSX('CoordSystem',1);
+
+% calculate some width as an angle in radiant
+patch_ang_width = patch.width/(patch.radius+substrate.thickness);
+substr_ang_width = substrate.width/patch.radius;
+feed_angle = feed.pos/patch.radius;
+
+%% create patch
+CSX = AddMetal( CSX, 'patch' ); % create a perfect electric conductor (PEC)
+start = [patch.radius+substrate.thickness -patch_ang_width/2 -patch.length/2 ];
+stop = [patch.radius+substrate.thickness patch_ang_width/2 patch.length/2 ];
+CSX = AddBox(CSX,'patch',10,start,stop); % add a box-primitive to the metal property 'patch'
+
+%% create substrate
+CSX = AddMaterial( CSX, 'substrate' );
+CSX = SetMaterialProperty( CSX, 'substrate', 'Epsilon', substrate.epsR, 'Kappa', substrate.kappa );
+start = [patch.radius -substr_ang_width/2 -substrate.length/2];
+stop = [patch.radius+substrate.thickness substr_ang_width/2 substrate.length/2];
+CSX = AddBox( CSX, 'substrate', 0, start, stop);
+
+%% save current density oon the patch
+CSX = AddDump(CSX, 'Jt_patch','DumpType',3,'FileType',1);
+start = [patch.radius+substrate.thickness -substr_ang_width/2 -substrate.length/2];
+stop = [patch.radius+substrate.thickness +substr_ang_width/2 substrate.length/2];
+CSX = AddBox( CSX, 'Jt_patch', 0, start, stop );
+
+%% create ground (not really necessary, only for esthetic reasons)
+CSX = AddMetal( CSX, 'gnd' ); % create a perfect electric conductor (PEC)
+start = [patch.radius -substr_ang_width/2 -substrate.length/2];
+stop = [patch.radius +substr_ang_width/2 +substrate.length/2];
+CSX = AddBox(CSX,'gnd',10,start,stop);
+
+%% apply the excitation & resist as a current source
+start = [patch.radius feed_angle 0];
+stop = [patch.radius+substrate.thickness feed_angle 0];
+[CSX port] = AddLumpedPort(CSX, 50 ,1 ,feed.R, start, stop, [1 0 0], true);
+
+
+%% finalize the mesh
+% detect all edges
+mesh = DetectEdges(CSX);
+
+% add the simulation domain size
+mesh.r = [mesh.r patch.radius+[-20 SimBox.rad]];
+mesh.a = [mesh.a -0.75*pi 0.75*pi];
+mesh.z = [mesh.z -SimBox.height/2 SimBox.height/2];
+
+% add some lines for the substrate
+mesh.r = [mesh.r patch.radius+linspace(0,substrate.thickness,substrate.cells)];
+
+% generate a smooth mesh with max. cell size: lambda_min / 20
+max_res = c0 / (f0+fc) / unit / 20;
+max_ang = max_res/(SimBox.rad+patch.radius); % max res in radiant
+mesh = SmoothMesh(mesh, [max_res max_ang max_res], 1.4);
+
+disp(['Num of cells: ' num2str(numel(mesh.r)*numel(mesh.a)*numel(mesh.z))]);
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create nf2ff, keep some distance to the boundary conditions, e.g. 8 cells pml
+start = [mesh.r(4) mesh.a(8) mesh.z(8)];
+stop = [mesh.r(end-9) mesh.a(end-9) mesh.z(end-9)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop, 'Directions',[1 1 1 1 1 1]);
+
+%% prepare simulation folder & run
+Sim_Path = ['tmp_' mfilename];
+Sim_CSX = [mfilename '.xml'];
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+% show the structure
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+% run openEMS
+RunOpenEMS( Sim_Path, Sim_CSX);
+
+%% postprocessing & do the plots
+freq = linspace( max([1e9,f0-fc]), f0+fc, 501 );
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+P_in = 0.5*real(port.uf.tot .* conj(port.if.tot)); % antenna feed power
+
+% plot feed point impedance
+figure
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+drawnow
+
+%find resonance frequncy from s11
+f_res_ind = find(s11==min(s11));
+f_res = freq(f_res_ind);
+
+%%
+disp('dumping resonant current distribution to vtk file, use Paraview to visualize');
+ConvertHDF5_VTK([Sim_Path '/Jt_patch.h5'],[Sim_Path '/Jf_patch'],'Frequency',f_res,'FieldName','J-Field');
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% calculate the far field at phi=0 degree
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, [-180:2:180]*pi/180, 0,'Center',[patch.radius+substrate.thickness 0 0]*unit, 'Outfile','pattern_phi_0.h5');
+% normalized directivity as polar plot
+figure
+polarFF(nf2ff,'xaxis','theta','param',1,'normalize',1)
+
+% calculate the far field at phi=0 degree
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, pi/2, (-180:2:180)*pi/180,'Center',[patch.radius+substrate.thickness 0 0]*unit, 'Outfile','pattern_theta_90.h5');
+% normalized directivity as polar plot
+figure
+polarFF(nf2ff,'xaxis','phi','param',1,'normalize',1)
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(nf2ff.Dmax) ' (' num2str(10*log10(nf2ff.Dmax)) ' dBi)'] );
+disp( ['efficiency: nu_rad = ' num2str(100*nf2ff.Prad./real(P_in(f_res_ind))) ' %']);
+
+drawnow
+
+%%
+disp( 'calculating 3D far field pattern and dumping to vtk (use Paraview to visualize)...' );
+thetaRange = (0:2:180);
+phiRange = (0:2:360) - 180;
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180,'Verbose',1,'Outfile','3D_Pattern.h5','Center',[patch.radius+substrate.thickness 0 0]*unit);
+
+figure
+plotFF3D(nf2ff,'logscale',-20);
+
diff --git a/openEMS/matlab/Tutorials/CRLH_Extraction.m b/openEMS/matlab/Tutorials/CRLH_Extraction.m
new file mode 100644
index 0000000..e0bc361
--- /dev/null
+++ b/openEMS/matlab/Tutorials/CRLH_Extraction.m
@@ -0,0 +1,155 @@
+%
+% Tutorials / CRLH_Extraction
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_CRLH_Extraction
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2011-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+
+feed_length = 30000;
+
+substrate_thickness = [1524 101 254];
+substrate_epsr = [3.48 3.48 3.48];
+
+CRLH.LL = 14e3; %CRLH totel (line) length
+CRLH.LW = 4e3; %CRLH unit cell width (without the stubs)
+CRLH.GLB = 1950; %CRLH gap width bottom layer
+CRLH.GLT = 4700; %CRLH gap width top layer
+CRLH.SL = 7800; %CRLH stub length (bottom layer, both sides)
+CRLH.SW = 1000; %CRLH stub width (bottom layer, both sides)
+CRLH.VR = 250; %CRLH via hole radius (stub -> ground)
+CRLH.TopSig = sum(substrate_thickness); %top layer height
+CRLH.BottomSig = CRLH.TopSig - substrate_thickness(end); %bottom layer height
+
+% frequency range of interest
+f_start = 0.8e9;
+f_stop = 6e9;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD();
+FDTD = SetGaussExcite( FDTD, (f_start+f_stop)/2, (f_stop-f_start)/2 );
+BC = {'PML_8' 'PML_8' 'MUR' 'MUR' 'PEC' 'PML_8'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% Setup a basic mesh and create the CRLH unit cell
+CSX = InitCSX();
+resolution = c0/(f_stop*sqrt(max(substrate_epsr)))/unit /30; % resolution of lambda/30
+
+mesh.x = [-feed_length-CRLH.LL/2 0 feed_length+CRLH.LL/2];
+mesh.y = [-30000 0 30000];
+substratelines = cumsum(substrate_thickness);
+mesh.z = [0 cumsum(substrate_thickness) linspace(substratelines(end-1),substratelines(end),4) 20000];
+
+% create the CRLH unit cell (will define additional fixed mesh lines)
+[CSX mesh] = CreateCRLH(CSX, mesh, CRLH, resolution/4);
+
+% Smooth the given mesh
+mesh = SmoothMesh(mesh, resolution, 1.5, 'algorithm',[1 3]);
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% Setup the substrate layer
+substratelines = [0 substratelines];
+for n=1:numel(substrate_thickness)
+ CSX = AddMaterial( CSX, ['substrate' int2str(n)] );
+ CSX = SetMaterialProperty( CSX, ['substrate' int2str(n)], 'Epsilon', substrate_epsr(n) );
+ start = [mesh.x(1), mesh.y(1), substratelines(n)];
+ stop = [mesh.x(end), mesh.y(end), substratelines(n+1)];
+ CSX = AddBox( CSX, ['substrate' int2str(n)], 0, start, stop );
+end
+
+%% add the feeding MSL ports
+CSX = AddMetal( CSX, 'PEC' );
+portstart = [ mesh.x(1) , -CRLH.LW/2, substratelines(end)];
+portstop = [ -CRLH.LL/2, CRLH.LW/2, 0];
+[CSX,port{1}] = AddMSLPort( CSX, 999, 1, 'PEC', portstart, portstop, 0, [0 0 -1], 'ExcitePort', true, 'FeedShift', 10*resolution(1), 'MeasPlaneShift', feed_length/2);
+
+portstart = [ mesh.x(end) , -CRLH.LW/2, substratelines(end)];
+portstop = [ +CRLH.LL/2, CRLH.LW/2, 0];
+[CSX,port{2}] = AddMSLPort( CSX, 999, 2, 'PEC', portstart, portstop, 0, [0 0 -1], 'MeasPlaneShift', feed_length/2 );
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = 'tmp';
+Sim_CSX = 'CRLH.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX );
+
+%% post-processing
+close all
+f = linspace( f_start, f_stop, 1601 );
+port = calcPort( port, Sim_Path, f, 'RefPlaneShift', feed_length);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,20*log10(abs(s11)),'k-','LineWidth',2);
+hold on;
+grid on;
+plot(f/1e9,20*log10(abs(s21)),'r--','LineWidth',2);
+l = legend('S_{11}','S_{21}','Location','Best');
+set(l,'FontSize',12);
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (GHz) \rightarrow','FontSize',12);
+ylim([-40 2]);
+
+%% extract parameter
+A = ((1+s11).*(1-s11) + s21.*s21)./(2*s21);
+C = ((1-s11).*(1-s11) - s21.*s21)./(2*s21) ./ port{2}.ZL;
+
+Y = C;
+Z = 2*(A-1)./C;
+
+iZ = imag(Z);
+iY = imag(Y);
+
+fse = interp1(iZ,f,0);
+fsh = interp1(iY,f,0);
+
+df = f(2)-f(1);
+fse_idx = find(f>fse,1);
+fsh_idx = find(f>fsh,1);
+
+LR = 0.5*(iZ(fse_idx)-iZ(fse_idx-1))./(2*pi*df);
+CL = 1/(2*pi*fse)^2/LR;
+
+CR = 0.5*(iY(fsh_idx)-iY(fsh_idx-1))./(2*pi*df);
+LL = 1/(2*pi*fsh)^2/CR;
+
+disp([' Series tank: CL = ' num2str(CL*1e12,3) 'pF; LR = ' num2str(LR*1e9,3) 'nH -> f_se = ' num2str(fse*1e-9,3) 'GHz ']);
+disp([' Shunt tank: CR = ' num2str(CR*1e12,3) 'pF; LL = ' num2str(LL*1e9,3) 'nH -> f_sh = ' num2str(fsh*1e-9,3) 'GHz ']);
+
+%% calculate analytical wave-number of an inf-array of cells
+w = 2*pi*f;
+wse = 2*pi*fse;
+wsh = 2*pi*fsh;
+beta_calc = real(acos(1-(w.^2-wse^2).*(w.^2-wsh^2)./(2*w.^2/CR/LR)));
+
+%%
+figure
+beta = -angle(s21)/CRLH.LL/unit;
+plot(abs(beta)*CRLH.LL*unit/pi,f*1e-9,'k-','LineWidth',2)
+grid on;
+hold on;
+plot(beta_calc/pi,f*1e-9,'c--','LineWidth',2)
+plot(real(port{2}.beta)*CRLH.LL*unit/pi,f*1e-9,'g-','LineWidth',2)
+ylim([1 6])
+xlabel('|\beta| p / \pi \rightarrow','FontSize',12)
+ylabel('frequency (GHz) \rightarrow','FontSize',12)
+l = legend('\beta_{CRLH, 1 cell}','\beta_{CRLH, \infty cells}','\beta_{MSL}','Location','East');
+set(l,'FontSize',12);
diff --git a/openEMS/matlab/Tutorials/CRLH_LeakyWaveAnt.m b/openEMS/matlab/Tutorials/CRLH_LeakyWaveAnt.m
new file mode 100644
index 0000000..a8359b7
--- /dev/null
+++ b/openEMS/matlab/Tutorials/CRLH_LeakyWaveAnt.m
@@ -0,0 +1,168 @@
+%
+% Tutorials / CRLH_LeakyWaveAnt
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_CRLH_Leaky_Wave_Antenna
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2011-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+
+feed_length = 20000;
+
+substrate_thickness = [1524 101 254];
+substrate_epsr = [3.48 3.48 3.48];
+substrate_tanD = [1 1 1]*1e-3;
+
+N_Cells = 8; %number of CRLH unit cells
+
+CRLH.LL = 14e3; %CRLH totel (line) length
+CRLH.LW = 4e3; %CRLH unit cell width (without the stubs)
+CRLH.GLB = 1950; %CRLH gap width bottom layer
+CRLH.GLT = 4700; %CRLH gap width top layer
+CRLH.SL = 7800; %CRLH stub length (bottom layer, both sides)
+CRLH.SW = 1000; %CRLH stub width (bottom layer, both sides)
+CRLH.VR = 250; %CRLH via hole radius (stub -> ground)
+CRLH.TopSig = sum(substrate_thickness); %top layer height
+CRLH.BottomSig = CRLH.TopSig - substrate_thickness(end); %bottom layer height
+
+substrate_width = CRLH.LW + 2*CRLH.SL;
+Air_Spacer = 30000;
+
+% frequency range of interest
+f_start = 1e9;
+f_stop = 6e9;
+
+% frequencies to calculate the 3D radiation pattern
+f_rad = (1.9:0.05:4.2)*1e9;
+nf2ff_resolution = c0/max(f_rad)/unit/15;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD('EndCriteria', 1e-3);
+FDTD = SetGaussExcite( FDTD, (f_start+f_stop)/2, (f_stop-f_start)/2 );
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% Setup a basic mesh and create the CRLH unit cell
+CSX = InitCSX();
+resolution = c0/(f_stop*sqrt(max(substrate_epsr)))/unit /30; % resolution of lambda/30
+
+mesh.x = [-feed_length-(N_Cells*CRLH.LL)/2-Air_Spacer -feed_length-(N_Cells*CRLH.LL)/2 0 feed_length+(N_Cells*CRLH.LL)/2 feed_length+(N_Cells*CRLH.LL)/2+Air_Spacer];
+mesh.y = [-Air_Spacer-substrate_width/2 0 Air_Spacer+substrate_width/2];
+substratelines = cumsum(substrate_thickness);
+mesh.z = [-0.5*Air_Spacer 0 cumsum(substrate_thickness) linspace(substratelines(end-1),substratelines(end),4) Air_Spacer];
+
+% create the CRLH unit cells (will define additional fixed mesh lines)
+pos_x = -(N_Cells*CRLH.LL)/2 + CRLH.LL/2;
+for n=1:N_Cells
+ [CSX mesh] = CreateCRLH(CSX, mesh, CRLH, resolution/4, [pos_x 0 0]);
+ pos_x = pos_x + CRLH.LL;
+end
+
+% Smooth the given mesh
+mesh = SmoothMesh(mesh, resolution, 1.5, 'algorithm',[1 3]);
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% Setup the substrate layer
+substratelines = [0 substratelines];
+for n=1:numel(substrate_thickness)
+ CSX = AddMaterial( CSX, ['substrate' int2str(n)] );
+ CSX = SetMaterialProperty( CSX, ['substrate' int2str(n)], 'Epsilon', substrate_epsr(n), 'Kappa', substrate_tanD(n)*substrate_epsr(n)*EPS0*2*pi*3e9 );
+ start = [-feed_length-(N_Cells*CRLH.LL)/2, -substrate_width/2, substratelines(n)];
+ stop = [+feed_length+(N_Cells*CRLH.LL)/2, substrate_width/2, substratelines(n+1)];
+ CSX = AddBox( CSX, ['substrate' int2str(n)], 0, start, stop );
+end
+
+%% add the feeding MSL ports
+%ground plane
+CSX = AddMetal( CSX, 'ground' );
+start = [-feed_length-(N_Cells*CRLH.LL)/2, -substrate_width/2, 0];
+stop = [+feed_length+(N_Cells*CRLH.LL)/2, substrate_width/2, 0];
+CSX = AddBox( CSX, 'ground', 0, start, stop );
+
+CSX = AddMetal( CSX, 'PEC' );
+portstart = [ -feed_length-(N_Cells*CRLH.LL)/2 , -CRLH.LW/2, substratelines(end)];
+portstop = [ -(N_Cells*CRLH.LL)/2, CRLH.LW/2, 0];
+[CSX,port{1}] = AddMSLPort( CSX, 999, 1, 'PEC', portstart, portstop, 0, [0 0 -1], 'ExcitePort', true, 'MeasPlaneShift', feed_length/2, 'Feed_R', 50);
+
+portstart = [ feed_length+(N_Cells*CRLH.LL)/2 , -CRLH.LW/2, substratelines(end)];
+portstop = [ +(N_Cells*CRLH.LL)/2, CRLH.LW/2, 0];
+[CSX,port{2}] = AddMSLPort( CSX, 999, 2, 'PEC', portstart, portstop, 0, [0 0 -1], 'MeasPlaneShift', feed_length/2, 'Feed_R', 50 );
+
+%% nf2ff calc
+start = [mesh.x(1) mesh.y(1) mesh.z(1) ] + 10*resolution;
+stop = [mesh.x(end) mesh.y(end) mesh.z(end)] - 10*resolution;
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop, 'OptResolution', nf2ff_resolution);
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = 'tmp_CRLH_LeakyWave';
+Sim_CSX = 'CRLH.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX );
+
+%% post-processing
+close all
+f = linspace( f_start, f_stop, 1601 );
+port = calcPort( port, Sim_Path, f, 'RefPlaneShift', feed_length*unit);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,20*log10(abs(s11)),'k-','LineWidth',2);
+hold on;
+grid on;
+plot(f/1e9,20*log10(abs(s21)),'r--','LineWidth',2);
+l = legend('S_{11}','S_{21}','Location','Best');
+set(l,'FontSize',12);
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (GHz) \rightarrow','FontSize',12);
+ylim([-40 2]);
+
+drawnow
+
+%% calculate 3D pattern
+phi = 0:2:360;
+theta = 0:2:180;
+
+disp( 'calculating 3D far field pattern...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_rad, theta*pi/180, phi*pi/180, 'Outfile','3D_Pattern.h5', 'Mode', 0,'Verbose',1);
+
+%%
+P_in = interp1(f, port{1}.P_acc, f_rad);
+
+figure()
+
+[AX,H1,H2] = plotyy(f_rad/1e9,nf2ff.Dmax',f_rad/1e9,100*nf2ff.Prad'./P_in,'plot');
+grid on
+xlabel( 'frequency (GHz)' );
+set(get(AX(1),'Ylabel'),'String','directivity (dBi)')
+set(get(AX(2),'Ylabel'),'String','radiation efficiency (%)')
+set(H1,'Linewidth',2)
+set(H2,'Linewidth',2)
+set(H1,'Marker','*')
+set(H2,'Marker','s')
+
+drawnow
+
+%%
+disp( 'dumping 3D far field pattern to vtk, use Paraview to visualize...' );
+for n=1:numel(f_rad)
+ E_far_normalized_3D = nf2ff.E_norm{n} / max(max(nf2ff.E_norm{n})) * nf2ff.Dmax(n);
+ DumpFF2VTK( [Sim_Path '/FF_Pattern_' int2str(f_rad(n)/1e6) 'MHz.vtk'],E_far_normalized_3D,theta,phi,'scale',1e-3);
+end
+
diff --git a/openEMS/matlab/Tutorials/Circ_Waveguide.m b/openEMS/matlab/Tutorials/Circ_Waveguide.m
new file mode 100644
index 0000000..d61a713
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Circ_Waveguide.m
@@ -0,0 +1,105 @@
+%
+% Tutorials / Circ_Waveguide
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Circular_Waveguide
+%
+% Tested with
+% - Matlab 2011a / Octave 3.4.3
+% - openEMS v0.0.31
+%
+% (C) 2010-2013 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-3; %drawing unit in mm
+
+% waveguide dimensions
+length = 2000;
+rad = 350; %waveguide radius in mm
+
+% frequency range of interest
+f_start = 300e6;
+f_stop = 500e6;
+
+mesh_res = [10 2*pi/49.999 10]; %targeted mesh resolution
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD('EndCriteria',1e-4,'CoordSystem',1);
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+
+% boundary conditions
+BC = [0 0 0 0 3 3]; %pml in pos. and neg. z-direction
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX('CoordSystem',1); % init a cylindrical mesh
+mesh.r = SmoothMeshLines([0 rad], mesh_res(1)); %mesh in radial direction
+mesh.a = SmoothMeshLines([0 2*pi], mesh_res(2)); % mesh in aziumthal dir.
+mesh.z = SmoothMeshLines([0 length], mesh_res(3));
+CSX = DefineRectGrid(CSX, unit,mesh);
+
+%% apply the waveguide port %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start=[mesh.r(1) mesh.a(1) mesh.z(8)];
+stop =[mesh.r(end) mesh.a(end) mesh.z(15)];
+[CSX, port{1}] = AddCircWaveGuidePort( CSX, 0, 1, start, stop, rad*unit, 'TE11', 0, 1);
+
+start=[mesh.r(1) mesh.a(1) mesh.z(end-13)];
+stop =[mesh.r(end) mesh.a(end) mesh.z(end-14)];
+[CSX, port{2}] = AddCircWaveGuidePort( CSX, 0, 2, start, stop, rad*unit, 'TE11');
+
+%% define dump box... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et','FileType',1,'SubSampling','4,4,4');
+start = [mesh.r(1) mesh.a(1) mesh.z(1)];
+stop = [mesh.r(end) mesh.a(end) mesh.z(end)];
+CSX = AddBox(CSX,'Et',0 , start,stop);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Sim_Path = 'tmp';
+Sim_CSX = 'circ_wg.xml';
+
+[status, message, messageid] = rmdir(Sim_Path,'s');
+[status, message, messageid] = mkdir(Sim_Path);
+
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+RunOpenEMS(Sim_Path, Sim_CSX)
+
+%% postproc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+freq = linspace(f_start,f_stop,201);
+port = calcPort( port, Sim_Path, freq);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+ZL = port{1}.uf.tot./port{1}.if.tot;
+
+
+%% plot s-parameter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+plot(freq*1e-6,20*log10(abs(s11)),'k-','Linewidth',2);
+xlim([freq(1) freq(end)]*1e-6);
+grid on;
+hold on;
+plot(freq*1e-6,20*log10(abs(s21)),'r--','Linewidth',2);
+l = legend('S_{11}','S_{21}','Location','Best');
+set(l,'FontSize',12);
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (MHz) \rightarrow','FontSize',12);
+
+%% compare analytic and numerical wave-impedance %%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+plot(freq*1e-6,real(ZL),'Linewidth',2);
+hold on;
+grid on;
+plot(freq*1e-6,imag(ZL),'r--','Linewidth',2);
+plot(freq*1e-6,port{1}.ZL,'g-.','Linewidth',2);
+ylabel('ZL (\Omega)','FontSize',12);
+xlabel('frequency (MHz) \rightarrow','FontSize',12);
+xlim([freq(1) freq(end)]*1e-6);
+l = legend('\Re(Z_L)','\Im(Z_L)','Z_L analytic','Location','Best');
+set(l,'FontSize',12);
+
diff --git a/openEMS/matlab/Tutorials/Conical_Horn_Antenna.m b/openEMS/matlab/Tutorials/Conical_Horn_Antenna.m
new file mode 100644
index 0000000..f266993
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Conical_Horn_Antenna.m
@@ -0,0 +1,180 @@
+%
+% Tutorials / conical horn antenna
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Conical_Horn_Antenna
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2011-2015 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% horn radius
+horn.radius = 20;
+% horn length in z-direction
+horn.length = 50;
+
+horn.feed_length = 50;
+
+horn.thickness = 2;
+
+% horn opening angle
+horn.angle = 20*pi/180;
+
+% size of the simulation box
+SimBox = [100 100 100]*2;
+
+% frequency range of interest
+f_start = 10e9;
+f_stop = 20e9;
+
+% frequency of interest
+f0 = 15e9;
+
+%% setup FDTD parameter & excitation function
+FDTD = InitFDTD( 'NrTS', 30000, 'EndCriteria', 1e-4 );
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+% currently, openEMS cannot automatically generate a mesh
+max_res = c0 / (f_stop) / unit / 15; % cell size: lambda/20
+CSX = InitCSX();
+
+%create fixed lines for the simulation box, substrate and port
+mesh.x = [-SimBox(1)/2 -horn.radius 0 horn.radius SimBox(1)/2];
+mesh.x = SmoothMeshLines( mesh.x, max_res, 1.4); % create a smooth mesh between specified fixed mesh lines
+
+mesh.y = mesh.x;
+
+%create fixed lines for the simulation box and given number of lines inside the substrate
+mesh.z = [-horn.feed_length 0 SimBox(3) ];
+mesh.z = SmoothMeshLines( mesh.z, max_res, 1.4 );
+
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create horn
+% horn + waveguide, defined by a rotational polygon
+CSX = AddMetal(CSX, 'Conical_Horn');
+p(1,1) = horn.radius+horn.thickness; % x-coord point 1
+p(2,1) = -horn.feed_length; % z-coord point 1
+p(1,end+1) = horn.radius+horn.thickness; % x-coord point 1
+p(2,end) = 0; % z-coord point 1
+p(1,end+1) = horn.radius+horn.thickness + sin(horn.angle)*horn.length; % x-coord point 2
+p(2,end) = horn.length; % y-coord point 2
+p(1,end+1) = horn.radius + sin(horn.angle)*horn.length; % x-coord point 2
+p(2,end) = horn.length; % y-coord point 2
+p(1,end+1) = horn.radius; % x-coord point 1
+p(2,end) = 0; % z-coord point 1
+p(1,end+1) = horn.radius; % x-coord point 1
+p(2,end) = -horn.feed_length; % z-coord point 1
+CSX = AddRotPoly(CSX,'Conical_Horn',10,'x',p,'z');
+
+% horn aperture
+A = pi*((horn.radius + sin(horn.angle)*horn.length)*unit)^2;
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start=[-horn.radius -horn.radius mesh.z(10) ];
+stop =[+horn.radius +horn.radius mesh.z(1)+horn.feed_length/2 ];
+[CSX, port] = AddCircWaveGuidePort( CSX, 0, 1, start, stop, horn.radius*unit, 'TE11', 0, 1);
+
+%%
+CSX = AddDump(CSX,'Exc_dump');
+start=[-horn.radius -horn.radius mesh.z(8)];
+stop =[+horn.radius +horn.radius mesh.z(8)];
+CSX = AddBox(CSX,'Exc_dump',0,start,stop);
+
+%% nf2ff calc
+start = [mesh.x(9) mesh.y(9) mesh.z(9)];
+stop = [mesh.x(end-8) mesh.y(end-8) mesh.z(end-8)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop, 'Directions', [1 1 1 1 0 1]);
+
+%% prepare simulation folder
+Sim_Path = 'tmp';
+Sim_CSX = 'horn_ant.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+%% run openEMS
+RunOpenEMS( Sim_Path, Sim_CSX);
+
+%% postprocessing & do the plots
+freq = linspace(f_start,f_stop,201);
+
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e9, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+ylim([-60 0]);
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / GHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+drawnow
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+thetaRange = (0:2:359) - 180;
+disp( 'calculating far field at phi=[0 90] deg...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, thetaRange*pi/180, [0 90]*pi/180);
+
+Dlog=10*log10(nf2ff.Dmax);
+G_a = 4*pi*A/(c0/f0)^2;
+e_a = nf2ff.Dmax/G_a;
+
+% display some antenna parameter
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(Dlog) ' dBi'] );
+disp( ['aperture efficiency: e_a = ' num2str(e_a*100) '%'] );
+
+%%
+% normalized directivity
+figure
+plotFFdB(nf2ff,'xaxis','theta','param',[1 2]);
+drawnow
+% D_log = 20*log10(nf2ff.E_norm{1}/max(max(nf2ff.E_norm{1})));
+% D_log = D_log + 10*log10(nf2ff.Dmax);
+% plot( nf2ff.theta, D_log(:,1) ,'k-', nf2ff.theta, D_log(:,2) ,'r-' );
+
+% polar plot
+figure
+polarFF(nf2ff,'xaxis','theta','param',[1 2],'logscale',[-40 20], 'xtics', 12);
+drawnow
+% polar( nf2ff.theta, nf2ff.E_norm{1}(:,1) )
+
+%% calculate 3D pattern
+phiRange = sort( unique( [-180:5:-100 -100:2.5:-50 -50:1:50 50:2.5:100 100:5:180] ) );
+thetaRange = sort( unique([ 0:1:50 50:2.:100 100:5:180 ]));
+
+disp( 'calculating 3D far field...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, thetaRange*pi/180, phiRange*pi/180, 'Verbose',2,'Outfile','nf2ff_3D.h5');
+
+figure
+plotFF3D(nf2ff); % plot liear 3D far field
+
+%%
+E_far_normalized = nf2ff.E_norm{1}/max(nf2ff.E_norm{1}(:));
+DumpFF2VTK([Sim_Path '/Conical_Horn_Pattern.vtk'],E_far_normalized,thetaRange,phiRange,'scale',1e-3);
diff --git a/openEMS/matlab/Tutorials/CreateCRLH.m b/openEMS/matlab/Tutorials/CreateCRLH.m
new file mode 100644
index 0000000..6c10732
--- /dev/null
+++ b/openEMS/matlab/Tutorials/CreateCRLH.m
@@ -0,0 +1,55 @@
+function [CSX mesh] = CreateCRLH(CSX, mesh, CRLH, resolution, translate)
+% function [CSX mesh] = CreateCRLH(CSX, mesh, CRLH, resolution, translate)
+%
+% support function to create a CRLH unit cell
+%
+% currently used by Tutorials/CRLH_Extraction
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.23
+%
+% (C) 2011 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+if (nargin<5)
+ translate = [0 0 0];
+end
+
+CSX = AddMetal(CSX, 'metal_top');
+one_two_third = [-resolution/3 2*resolution/3];
+
+start = [-CRLH.LL/2 -CRLH.LW/2 CRLH.TopSig]+translate;
+stop = [-CRLH.GLT/2 CRLH.LW/2 CRLH.TopSig]+translate;
+CSX = AddBox(CSX, 'metal_top', 10, start, stop);
+mesh.x = [mesh.x start(1) stop(1)+one_two_third];
+mesh.y = [mesh.y start(2)-one_two_third stop(2)+one_two_third];
+
+start = [+CRLH.LL/2 -CRLH.LW/2 CRLH.TopSig]+translate;
+stop = [+CRLH.GLT/2 CRLH.LW/2 CRLH.TopSig]+translate;
+CSX = AddBox(CSX, 'metal_top', 10, start, stop);
+mesh.x = [mesh.x start(1) stop(1)-one_two_third];
+
+CSX = AddMetal(CSX, 'metal_bot');
+start = [-(CRLH.LL-CRLH.GLB)/2 -CRLH.LW/2 CRLH.BottomSig]+translate;
+stop = [+(CRLH.LL-CRLH.GLB)/2 CRLH.LW/2 CRLH.BottomSig]+translate;
+CSX = AddBox(CSX, 'metal_bot', 10, start, stop);
+mesh.x = [mesh.x start(1)-one_two_third stop(1)+one_two_third];
+
+start = [-CRLH.SW/2 -CRLH.LW/2-CRLH.SL CRLH.BottomSig]+translate;
+stop = [+CRLH.SW/2 CRLH.LW/2+CRLH.SL CRLH.BottomSig]+translate;
+CSX = AddBox(CSX, 'metal_bot', 10, start, stop);
+mesh.x = [mesh.x start(1)-one_two_third stop(1)+one_two_third];
+mesh.y = [mesh.y start(2) stop(2)];
+
+CSX = AddMetal(CSX, 'via');
+start = [0 -CRLH.LW/2-CRLH.SL+CRLH.SW/2 0]+translate;
+stop = [0 -CRLH.LW/2-CRLH.SL+CRLH.SW/2 CRLH.BottomSig]+translate;
+CSX = AddCylinder(CSX, 'via', 10, start, stop, CRLH.VR);
+mesh.x = [mesh.x start(1)+[-1 0 1]*CRLH.VR];
+mesh.y = [mesh.y start(2)+[-1 0 1]*CRLH.VR];
+
+start(2) = -start(2);
+stop(2) = -stop(2);
+CSX = AddCylinder(CSX, 'via', 10, start, stop, CRLH.VR);
+mesh.y = [mesh.y start(2)+[-1 0 1]*CRLH.VR];
+end \ No newline at end of file
diff --git a/openEMS/matlab/Tutorials/CylindricalWave_CC.m b/openEMS/matlab/Tutorials/CylindricalWave_CC.m
new file mode 100644
index 0000000..d55c470
--- /dev/null
+++ b/openEMS/matlab/Tutorials/CylindricalWave_CC.m
@@ -0,0 +1,104 @@
+%
+% Tutorials / CylindricalWave_CC
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_2D_Cylindrical_Wave
+%
+% Tested with
+% - Matlab 2011a/ Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2011-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants
+mesh_res = 10; %desired mesh resolution
+radius = 2560; %simulation domain radius
+split = ['80,160,320,640,1280']; %radii to split the mesh into sub-grids
+split_N = 5; %number of nested sub-grids
+heigth = mesh_res*4;
+
+f0 = 1e9;
+
+exite_offset = 1300;
+excite_angle = 45;
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(100000,1e-4,'CoordSystem',1,'MultiGrid',split);
+FDTD = SetGaussExcite(FDTD,f0,f0/2);
+BC = [0 3 0 0 0 0]; % pml in positive r-direction
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 50 mesh lines for the inner most mesh
+% increase the total number of meshlines in alpha direcion for all sub-grids
+N_alpha = 50 * 2^split_N + 1;
+
+CSX = InitCSX('CoordSystem',1);
+mesh.r = SmoothMeshLines([0 radius],mesh_res);
+mesh.a = linspace(-pi,pi,N_alpha);
+mesh.z = SmoothMeshLines([-heigth/2 0 heigth/2],mesh_res);
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+%% add the dipol %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start = [exite_offset excite_angle/180*pi-0.001 -20];
+stop = [exite_offset excite_angle/180*pi+0.001 20];
+if (exite_offset==0)
+ start(2) = mesh.a(1);
+ stop(2) = mesh.a(1);
+end
+CSX = AddExcitation(CSX,'excite',1,[0 0 1]);
+CSX = AddBox(CSX,'excite',0 ,start,stop);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start = [mesh.r(1) mesh.a(1) 0];
+stop = [mesh.r(end-8) mesh.a(end) 0];
+
+% time domain vtk dump
+CSX = AddDump(CSX,'Et_ra','DumpType',0,'FileType',0,'SubSampling','4,10,1');
+CSX = AddBox(CSX,'Et_ra',0 , start,stop);
+
+% frequency domain hdf5 dump
+CSX = AddDump(CSX,'Ef_ra','DumpType',10,'FileType',1,'SubSampling','2,2,2','Frequency',f0);
+CSX = AddBox(CSX,'Ef_ra',0 , start,stop);
+
+%% write/run the openEMS compatible xml-file
+Sim_Path = 'tmp';
+Sim_CSX = '2D_CC_Wave.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+RunOpenEMS(Sim_Path, Sim_CSX);
+
+%%
+disp('use Paraview to visualize the vtk field dump...');
+
+%%
+[field mesh_h5] = ReadHDF5Dump([Sim_Path '/Ef_ra.h5']);
+
+r = mesh_h5.lines{1};
+a = mesh_h5.lines{2};
+a(end+1) = a(1); %closeup mesh for visualization
+[R A] = ndgrid(r,a);
+X = R.*cos(A);
+Y = R.*sin(A);
+
+Ez = squeeze(field.FD.values{1}(:,:,1,3));
+Ez(:,end+1) = Ez(:,1); %closeup mesh for visualization
+
+E_max = max(max(abs(Ez))); %get maximum E_z amplitude
+
+while 1
+ for ph = linspace(0,360,41) %animate phase from 0..360 degree
+ surf(X,Y,real(Ez*exp(1j*ph*pi/180)),'EdgeColor','none')
+ caxis([-E_max E_max]/10)
+ zlim([-E_max E_max])
+ pause(0.3)
+ end
+end
diff --git a/openEMS/matlab/Tutorials/Dipole_SAR.m b/openEMS/matlab/Tutorials/Dipole_SAR.m
new file mode 100644
index 0000000..a172117
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Dipole_SAR.m
@@ -0,0 +1,221 @@
+%
+% Tutorials / Dipole SAR + Power budget
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Dipole_SAR
+%
+% Tested with
+% - openEMS v0.0.33
+%
+% (C) 2013-2015 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+
+%% prepare simulation folder
+Sim_Path = 'tmp_Dipole_SAR';
+Sim_CSX = 'Dipole_SAR.xml';
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all lengths in mm
+
+feed.R = 50; % feed resistance
+
+%% define phantom
+phantom{1}.name='skin';
+phantom{1}.epsR = 50;
+phantom{1}.kappa = 0.65; % S/m
+phantom{1}.density = 1100; % kg/m^3
+phantom{1}.radius = [80 100 100]; % ellipsoide
+phantom{1}.center = [100 0 0];
+
+phantom{2}.name='headbone';
+phantom{2}.epsR = 13;
+phantom{2}.kappa = 0.1; % S/m
+phantom{2}.density = 2000; % kg/m^3
+phantom{2}.radius = [75 95 95]; % ellipsoide
+phantom{2}.center = [100 0 0];
+
+phantom{3}.name='brain';
+phantom{3}.epsR = 60;
+phantom{3}.kappa = 0.7; % S/m
+phantom{3}.density = 1040; % kg/m^3
+phantom{3}.radius = [65 85 85]; % ellipsoide
+phantom{3}.center = [100 0 0];
+
+%% setup FDTD parameter & excitation function
+f0 = 1e9; % center frequency
+lambda0 = c0/f0;
+
+f_stop = 1.5e9; % 20 dB corner frequency
+lambda_min = c0/f_stop;
+
+mesh_res_air = lambda_min/20/unit;
+mesh_res_phantom = 2.5;
+
+dipole_length = 0.46*lambda0/unit;
+disp(['Lambda-half dipole length: ' num2str(dipole_length) 'mm'])
+
+%%
+FDTD = InitFDTD();
+FDTD = SetGaussExcite( FDTD, 0, f_stop );
+% apply PML-8 boundary conditions in all directions
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+CSX = InitCSX();
+
+%% Dipole
+CSX = AddMetal( CSX, 'Dipole' ); % create a perfect electric conductor (PEC)
+CSX = AddBox(CSX, 'Dipole', 1, [0 0 -dipole_length/2], [0 0 dipole_length/2]);
+
+% mesh lines for the dipole
+mesh.x = 0;
+mesh.y = 0;
+mesh.z = [-dipole_length/2-[-1/3 2/3]*mesh_res_phantom dipole_length/2+[-1/3 2/3]*mesh_res_phantom];
+
+%% add the dielectrics
+for n=1:numel(phantom)
+ CSX = AddMaterial( CSX, phantom{n}.name );
+ CSX = SetMaterialProperty( CSX, phantom{n}.name, 'Epsilon', phantom{n}.epsR, 'Kappa', phantom{n}.kappa, 'Density', phantom{n}.density);
+ CSX = AddSphere( CSX, phantom{n}.name, 10+n, [0 0 0], 1,'Transform',{'Scale',phantom{n}.radius, 'Translate', phantom{n}.center} );
+
+ %% mesh lines for the dielectrics
+ mesh.x = [mesh.x phantom{n}.radius(1)*[-1 1]+phantom{n}.center(1) ];
+ mesh.y = [mesh.y phantom{n}.radius(2)*[-1 1]+phantom{n}.center(2) ];
+ mesh.z = [mesh.z phantom{n}.radius(3)*[-1 1]+phantom{n}.center(3) ];
+end
+
+%% apply the excitation & resist as a current source
+[CSX port] = AddLumpedPort(CSX, 100, 1, feed.R, [-0.1 -0.1 -mesh_res_phantom/2], [0.1 0.1 +mesh_res_phantom/2], [0 0 1], true);
+
+% mesh lines for the port
+mesh.z = [mesh.z -mesh_res_phantom/2 +mesh_res_phantom/2];
+
+%% smooth the mesh over the dipole and phantom
+mesh = SmoothMesh(mesh, mesh_res_phantom);
+
+%% add lines for the air-box
+mesh.x = [mesh.x -200 250+100];
+mesh.y = [mesh.y -250 250];
+mesh.z = [mesh.z -250 250];
+
+% smooth the final mesh (incl. air box)
+mesh = SmoothMesh(mesh, mesh_res_air, 1.2);
+
+%% dump SAR
+start = [-10 -100 -100];
+stop = [180 100 100];
+CSX = AddDump( CSX, 'SAR', 'DumpType', 20, 'Frequency', f0,'FileType',1,'DumpMode',2);
+CSX = AddBox( CSX, 'SAR', 0, start, stop);
+
+%% nf2ff calc
+start = [mesh.x(1) mesh.y(1) mesh.z(1)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop, 'OptResolution', lambda_min/15/unit);
+
+%%
+% add 10 equidistant cells (air)
+% around the structure to keep the pml away from the nf2ff box
+mesh = AddPML( mesh, 10 );
+
+% Define the mesh
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%%
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+ [status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+ % write openEMS compatible xml-file
+ WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+ % show the structure
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+ % run openEMS
+ RunOpenEMS( Sim_Path, Sim_CSX );
+end
+
+
+%% postprocessing & make the plots
+freq = linspace(500e6, 1500e6, 501 );
+port = calcPort(port, Sim_Path, freq);
+
+s11 = port.uf.ref./port.uf.inc;
+Zin = port.uf.tot./port.if.tot;
+
+Pin_f0 = interp1(freq, port.P_acc, f0);
+
+%%
+% plot feed point impedance
+figure
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e9, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'S_{11} (dB)' );
+
+%% read SAR and visualize
+SAR_field = ReadHDF5Dump([Sim_Path '/SAR.h5']);
+
+SAR = SAR_field.FD.values{1};
+ptotal = ReadHDF5Attribute([Sim_Path '/SAR.h5'],'/FieldData/FD/f0','power');
+
+%% calculate 3D pattern
+phi = 0:3:360;
+theta = 0:3:180;
+
+disp( 'calculating 3D far field pattern...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, theta*pi/180, phi*pi/180, 'Outfile','3D_Pattern.h5');
+
+%%
+disp(['max SAR: ' num2str(max(SAR(:))/Pin_f0) ' W/kg normalized to 1 W accepted power']);
+disp(['accepted power: ' num2str(Pin_f0) ' W (100 %)']);
+disp(['radiated power: ' num2str(nf2ff.Prad) ' W ( ' num2str(round(100*(nf2ff.Prad) / Pin_f0)) ' %)']);
+disp(['absorbed power: ' num2str(ptotal) ' W ( ' num2str(round(100*(ptotal) / Pin_f0)) ' %)']);
+disp(['power budget: ' num2str(100*(nf2ff.Prad + ptotal) / Pin_f0) ' %']);
+
+%% plot on a x/y-plane
+[SAR_field SAR_mesh] = ReadHDF5Dump([Sim_Path '/SAR.h5'],'Range',{[],[],0});
+figure
+[X Y] = ndgrid(SAR_mesh.lines{1},SAR_mesh.lines{2});
+h = pcolor(X,Y,log10(SAR_field.FD.values{1}/abs(Pin_f0)));
+title( 'logarithmic SAR on an xy-plane' );
+xlabel('x -->')
+ylabel('y -->')
+axis equal tight
+set(h,'EdgeColor','none');
+
+%% plot on a x/z-plane
+[SAR_field SAR_mesh] = ReadHDF5Dump([Sim_Path '/SAR.h5'],'Range',{[],0,[]});
+figure
+[X Z] = ndgrid(SAR_mesh.lines{1},SAR_mesh.lines{3});
+h = pcolor(X,Z,log10(squeeze(SAR_field.FD.values{1}))/abs(Pin_f0));
+title( 'logarithmic SAR on an xz-plane' );
+xlabel('x -->')
+ylabel('z -->')
+axis equal tight
+set(h,'EdgeColor','none');
+
+%% dump SAR to vtk file
+disp(['Full local/normalized SAR has been dumped to vtk file! Use Paraview to visualize']);
+ConvertHDF5_VTK([Sim_Path '/SAR.h5'],[Sim_Path '/SAR'],'weight',1/abs(Pin_f0),'FieldName','SAR_local' );
+
diff --git a/openEMS/matlab/Tutorials/Helical_Antenna.m b/openEMS/matlab/Tutorials/Helical_Antenna.m
new file mode 100644
index 0000000..b94ebd6
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Helical_Antenna.m
@@ -0,0 +1,202 @@
+%
+% Tutorials / helical antenna
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Helical_Antenna
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2012-2015 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+post_proc_only = 0;
+
+close all
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+f0 = 2.4e9; % center frequency, frequency of interest!
+lambda0 = round(c0/f0/unit); % wavelength in mm
+fc = 0.5e9; % 20 dB corner frequency
+
+Helix.radius = 20; % --> diameter is ~ lambda/pi
+Helix.turns = 10; % --> expected gain is G ~ 4 * 10 = 40 (16dBi)
+Helix.pitch = 30; % --> pitch is ~ lambda/4
+Helix.mesh_res = 3;
+
+gnd.radius = lambda0/2;
+
+% feeding
+feed.heigth = 3;
+feed.R = 120; %feed impedance
+
+% size of the simulation box
+SimBox = [1 1 1.5]*2*lambda0;
+
+%% setup FDTD parameter & excitation function
+FDTD = InitFDTD( );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'PML_8'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+max_res = floor(c0 / (f0+fc) / unit / 20); % cell size: lambda/20
+CSX = InitCSX();
+
+% create helix mesh
+mesh.x = SmoothMeshLines([-Helix.radius 0 Helix.radius],Helix.mesh_res);
+% add the air-box
+mesh.x = [mesh.x -SimBox(1)/2-gnd.radius SimBox(1)/2+gnd.radius];
+% create a smooth mesh between specified fixed mesh lines
+mesh.x = SmoothMeshLines( mesh.x, max_res, 1.4);
+
+% copy x-mesh to y-direction
+mesh.y = mesh.x;
+
+% create helix mesh in z-direction
+mesh.z = SmoothMeshLines([0 feed.heigth Helix.turns*Helix.pitch+feed.heigth],Helix.mesh_res);
+% add the air-box
+mesh.z = unique([mesh.z -SimBox(3)/2 max(mesh.z)+SimBox(3)/2 ]);
+% create a smooth mesh between specified fixed mesh lines
+mesh.z = SmoothMeshLines( mesh.z, max_res, 1.4 );
+
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create helix using the wire primitive
+CSX = AddMetal( CSX, 'helix' ); % create a perfect electric conductor (PEC)
+
+ang = linspace(0,2*pi,21);
+coil_x = Helix.radius*cos(ang);
+coil_y = Helix.radius*sin(ang);
+coil_z = ang/2/pi*Helix.pitch;
+
+helix.x=[];
+helix.y=[];
+helix.z=[];
+zpos = feed.heigth;
+for n=0:Helix.turns-1
+ helix.x = [helix.x coil_x];
+ helix.y = [helix.y coil_y];
+ helix.z = [helix.z coil_z+zpos];
+ zpos = zpos + Helix.pitch;
+end
+clear p
+p(1,:) = helix.x;
+p(2,:) = helix.y;
+p(3,:) = helix.z;
+CSX = AddCurve(CSX, 'helix', 0, p);
+
+%% create ground circular ground
+CSX = AddMetal( CSX, 'gnd' ); % create a perfect electric conductor (PEC)
+% add a box using cylindrical coordinates
+start = [0 0 0];
+stop = [gnd.radius 2*pi 0];
+CSX = AddBox(CSX,'gnd',10,start,stop,'CoordSystem',1);
+
+%% apply the excitation & resist as a current source
+start = [Helix.radius 0 0];
+stop = [Helix.radius 0 feed.heigth];
+[CSX port] = AddLumpedPort(CSX, 5 ,1 ,feed.R, start, stop, [0 0 1], true);
+
+%%nf2ff calc
+start = [mesh.x(11) mesh.y(11) mesh.z(11)];
+stop = [mesh.x(end-10) mesh.y(end-10) mesh.z(end-10)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop, 'OptResolution', lambda0/15);
+
+%% prepare simulation folder
+Sim_Path = 'tmp_Helical_Ant';
+Sim_CSX = 'Helix_Ant.xml';
+
+if (post_proc_only==0)
+ [status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+ [status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+ %% write openEMS compatible xml-file
+ WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+ %% show the structure
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+ %% run openEMS
+ RunOpenEMS( Sim_Path, Sim_CSX);
+end
+
+%% postprocessing & do the plots
+freq = linspace( f0-fc, f0+fc, 501 );
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+
+% plot feed point impedance
+figure
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+drawnow
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%find resonance frequncy from s11
+f_res = f0;
+
+% get accepted antenna power at frequency f0
+P_in_0 = interp1(freq, port.P_acc, f0);
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+thetaRange = unique([0:0.5:90 90:180]);
+phiRange = (0:2:360) - 180;
+disp( 'calculating the 3D far field...' );
+
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180,'Mode',0,'Outfile','3D_Pattern.h5','Verbose',1);
+
+theta_HPBW = interp1(nf2ff.E_norm{1}(:,1)/max(nf2ff.E_norm{1}(:,1)),thetaRange,1/sqrt(2))*2;
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(nf2ff.Dmax) ' (' num2str(10*log10(nf2ff.Dmax)) ' dBi)'] );
+disp( ['efficiency: nu_rad = ' num2str(100*nf2ff.Prad./P_in_0) ' %']);
+disp( ['theta_HPBW = ' num2str(theta_HPBW) ' °']);
+
+
+%%
+directivity = nf2ff.P_rad{1}/nf2ff.Prad*4*pi;
+directivity_CPRH = abs(nf2ff.E_cprh{1}).^2./max(nf2ff.E_norm{1}(:)).^2*nf2ff.Dmax;
+directivity_CPLH = abs(nf2ff.E_cplh{1}).^2./max(nf2ff.E_norm{1}(:)).^2*nf2ff.Dmax;
+
+%%
+figure
+plot(thetaRange, 10*log10(directivity(:,1)'),'k-','LineWidth',2);
+hold on
+grid on
+xlabel('theta (deg)');
+ylabel('directivity (dBi)');
+plot(thetaRange, 10*log10(directivity_CPRH(:,1)'),'g--','LineWidth',2);
+plot(thetaRange, 10*log10(directivity_CPLH(:,1)'),'r-.','LineWidth',2);
+legend('norm','CPRH','CPLH');
+
+%% dump to vtk
+DumpFF2VTK([Sim_Path '/3D_Pattern.vtk'],directivity,thetaRange,phiRange,'scale',1e-3);
+DumpFF2VTK([Sim_Path '/3D_Pattern_CPRH.vtk'],directivity_CPRH,thetaRange,phiRange,'scale',1e-3);
+DumpFF2VTK([Sim_Path '/3D_Pattern_CPLH.vtk'],directivity_CPLH,thetaRange,phiRange,'scale',1e-3);
+
diff --git a/openEMS/matlab/Tutorials/Horn_Antenna.m b/openEMS/matlab/Tutorials/Horn_Antenna.m
new file mode 100644
index 0000000..d463734
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Horn_Antenna.m
@@ -0,0 +1,202 @@
+%
+% Tutorials / horn antenna
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Horn_Antenna
+%
+% Tested with
+% - Matlab 2011a / Octave 3.6.4
+% - openEMS v0.0.31
+%
+% (C) 2011,2012,2013 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% horn width in x-direction
+horn.width = 20;
+% horn height in y-direction
+horn.height = 30;
+% horn length in z-direction
+horn.length = 50;
+
+horn.feed_length = 50;
+
+horn.thickness = 2;
+
+% horn opening angle in x, y
+horn.angle = [20 20]*pi/180;
+
+% size of the simulation box
+SimBox = [200 200 200];
+
+% frequency range of interest
+f_start = 10e9;
+f_stop = 20e9;
+
+% frequency of interest
+f0 = 15e9;
+
+%waveguide TE-mode definition
+TE_mode = 'TE10';
+a = horn.width;
+b = horn.height;
+
+%% setup FDTD parameter & excitation function
+FDTD = InitFDTD('EndCriteria', 1e-4);
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+% currently, openEMS cannot automatically generate a mesh
+max_res = c0 / (f_stop) / unit / 15; % cell size: lambda/20
+CSX = InitCSX();
+
+%create fixed lines for the simulation box, substrate and port
+mesh.x = [-SimBox(1)/2 -a/2 a/2 SimBox(1)/2];
+mesh.x = SmoothMeshLines( mesh.x, max_res, 1.4); % create a smooth mesh between specified fixed mesh lines
+
+mesh.y = [-SimBox(2)/2 -b/2 b/2 SimBox(2)/2];
+mesh.y = SmoothMeshLines( mesh.y, max_res, 1.4 );
+
+%create fixed lines for the simulation box and given number of lines inside the substrate
+mesh.z = [-horn.feed_length 0 SimBox(3)-horn.feed_length ];
+mesh.z = SmoothMeshLines( mesh.z, max_res, 1.4 );
+
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create horn
+% horn feed rect waveguide
+CSX = AddMetal(CSX, 'horn');
+start = [-a/2-horn.thickness -b/2 mesh.z(1)];
+stop = [-a/2 b/2 0];
+CSX = AddBox(CSX,'horn',10,start,stop);
+start = [a/2+horn.thickness -b/2 mesh.z(1)];
+stop = [a/2 b/2 0];
+CSX = AddBox(CSX,'horn',10,start,stop);
+start = [-a/2-horn.thickness b/2+horn.thickness mesh.z(1)];
+stop = [ a/2+horn.thickness b/2 0];
+CSX = AddBox(CSX,'horn',10,start,stop);
+start = [-a/2-horn.thickness -b/2-horn.thickness mesh.z(1)];
+stop = [ a/2+horn.thickness -b/2 0];
+CSX = AddBox(CSX,'horn',10,start,stop);
+
+% horn opening
+p(2,1) = a/2;
+p(1,1) = 0;
+p(2,2) = a/2 + sin(horn.angle(1))*horn.length;
+p(1,2) = horn.length;
+p(2,3) = -a/2 - sin(horn.angle(1))*horn.length;
+p(1,3) = horn.length;
+p(2,4) = -a/2;
+p(1,4) = 0;
+CSX = AddLinPoly( CSX, 'horn', 10, 1, -horn.thickness/2, p, horn.thickness, 'Transform', {'Rotate_X',horn.angle(2),'Translate',['0,' num2str(-b/2-horn.thickness/2) ',0']});
+CSX = AddLinPoly( CSX, 'horn', 10, 1, -horn.thickness/2, p, horn.thickness, 'Transform', {'Rotate_X',-horn.angle(2),'Translate',['0,' num2str(b/2+horn.thickness/2) ',0']});
+
+p(1,1) = b/2+horn.thickness;
+p(2,1) = 0;
+p(1,2) = b/2+horn.thickness + sin(horn.angle(2))*horn.length;
+p(2,2) = horn.length;
+p(1,3) = -b/2-horn.thickness - sin(horn.angle(2))*horn.length;
+p(2,3) = horn.length;
+p(1,4) = -b/2-horn.thickness;
+p(2,4) = 0;
+CSX = AddLinPoly( CSX, 'horn', 10, 0, -horn.thickness/2, p, horn.thickness, 'Transform', {'Rotate_Y',-horn.angle(2),'Translate',[ num2str(-a/2-horn.thickness/2) ',0,0']});
+CSX = AddLinPoly( CSX, 'horn', 10, 0, -horn.thickness/2, p, horn.thickness, 'Transform', {'Rotate_Y',+horn.angle(2),'Translate',[ num2str(a/2+horn.thickness/2) ',0,0']});
+
+% horn aperture
+A = (a + 2*sin(horn.angle(1))*horn.length)*unit * (b + 2*sin(horn.angle(2))*horn.length)*unit;
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start=[-a/2 -b/2 mesh.z(8) ];
+stop =[ a/2 b/2 mesh.z(1)+horn.feed_length/2 ];
+[CSX, port] = AddRectWaveGuidePort( CSX, 0, 1, start, stop, 2, a*unit, b*unit, TE_mode, 1);
+
+%% nf2ff calc
+start = [mesh.x(9) mesh.y(9) mesh.z(9)];
+stop = [mesh.x(end-8) mesh.y(end-8) mesh.z(end-8)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop, 'Directions', [1 1 1 1 0 1]);
+
+%% prepare simulation folder
+Sim_Path = 'tmp_Horn_Antenna';
+Sim_CSX = 'horn_ant.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS([Sim_Path '/' Sim_CSX], FDTD, CSX);
+
+%% show the structure
+CSXGeomPlot([Sim_Path '/' Sim_CSX]);
+
+%% run openEMS
+RunOpenEMS(Sim_Path, Sim_CSX);
+
+%% postprocessing & do the plots
+freq = linspace(f_start,f_stop,201);
+
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+
+plot( freq/1e9, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+ylim([-60 0]);
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / GHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+drawnow
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+thetaRange = (0:2:359) - 180;
+disp( 'calculating far field at phi=[0 90] deg...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, thetaRange*pi/180, [0 90]*pi/180);
+
+Dlog=10*log10(nf2ff.Dmax);
+G_a = 4*pi*A/(c0/f0)^2;
+e_a = nf2ff.Dmax/G_a;
+
+% display some antenna parameter
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(Dlog) ' dBi'] );
+disp( ['aperture efficiency: e_a = ' num2str(e_a*100) '%'] );
+
+%%
+% normalized directivity
+figure
+plotFFdB(nf2ff,'xaxis','theta','param',[1 2]);
+drawnow
+% D_log = 20*log10(nf2ff.E_norm{1}/max(max(nf2ff.E_norm{1})));
+% D_log = D_log + 10*log10(nf2ff.Dmax);
+% plot( nf2ff.theta, D_log(:,1) ,'k-', nf2ff.theta, D_log(:,2) ,'r-' );
+
+% polar plot
+figure
+polarFF(nf2ff,'xaxis','theta','param',[1 2],'logscale',[-40 20], 'xtics', 12);
+drawnow
+% polar( nf2ff.theta, nf2ff.E_norm{1}(:,1) )
+
+%% calculate 3D pattern
+phiRange = sort( unique( [-180:5:-100 -100:2.5:-50 -50:1:50 50:2.5:100 100:5:180] ) );
+thetaRange = sort( unique([ 0:1:50 50:2.:100 100:5:180 ]));
+
+disp( 'calculating 3D far field...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, thetaRange*pi/180, phiRange*pi/180, 'Verbose',2,'Outfile','nf2ff_3D.h5');
+
+figure
+plotFF3D(nf2ff);
+
+%%
+E_far_normalized = nf2ff.E_norm{1}/max(nf2ff.E_norm{1}(:));
+DumpFF2VTK([Sim_Path '/Horn_Pattern.vtk'],E_far_normalized,thetaRange,phiRange,'scale',1e-3);
diff --git a/openEMS/matlab/Tutorials/MRI_LP_Birdcage.m b/openEMS/matlab/Tutorials/MRI_LP_Birdcage.m
new file mode 100644
index 0000000..2434f03
--- /dev/null
+++ b/openEMS/matlab/Tutorials/MRI_LP_Birdcage.m
@@ -0,0 +1,320 @@
+%
+% Tutorials / 3T MRI Low Pass Birdcage coil
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_MRI_LP_Birdcage
+%
+% Estimated time to run: ~7h @ ~65MC/s
+% Memory requirement (RAM): ~ 700MB
+%
+% Tested with
+% - openEMS v0.0.33
+% - Matlab 7.12.0 (R2011a)
+%
+% (C) 2013-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+
+close all
+clear
+clc
+
+% simulation setup
+f0 = 128e6;
+excite.f_0 = 75e6; % excite gaussian pulse center frequency
+excite.f_c = 75e6; % excite gaussian pulse cutoff frequency
+
+postproc_only = 0; % set to 1 to perform only post processing
+GeomPlot = 1; % set to 0 to skip geometry viewer
+
+% bore setup
+Bore.rad = 320;
+Bore.length = 1600;
+
+% birdcage setup
+BC.N_rungs = 8;
+BC.rad = 120;
+BC.stripwidth = 10;
+BC.portwidth = BC.stripwidth/2;
+BC.portlength = BC.stripwidth/2;
+BC.length = 250;
+BC.cap = 2.6e-12;
+
+% feed amplitude and phase at given rungs
+BC.feed_pos = [1 3];
+BC.feed_amp = [1 -1j];
+
+%% define the human body model (virtual family)
+% set file name for human body model to create with "Convert_VF_DiscMaterial"
+% the file name should contain a full path
+body_model_file = [pwd '/Ella_centered_' num2str(f0/1e6) 'MHz.h5'];
+
+% convert only part of the model (head/shoulder section)
+body_model_range = {[],[],[-0.85 0]};
+
+body_mesh_res = 2.5; % should be something like: BC.stripwidth/4
+
+% paths to virtual family voxel models (VFVM), adept to your install!
+VF_raw_filesuffix = '/tmp/Ella_26y_V2_1mm';
+VF_mat_db_file = '/tmp/DB_h5_20120711_SEMCADv14.8.h5';
+
+% delete(body_model_file); % uncomment to delete old model if something changed
+
+% convert model (if it does not exist)
+Convert_VF_DiscMaterial(VF_raw_filesuffix, VF_mat_db_file, body_model_file, ...
+ 'Frequency', f0, 'Center', 1, ...
+ 'Range', body_model_range);
+
+% rotate model to face the nose in +y-dir, and translate
+body_model_transform = {'Rotate_X',pi,'Rotate_Z',pi, ...
+ 'Translate',[0,5,-720]};
+
+%% some internal parameter
+physical_constants % load important physical constans
+end_crit = 1e-5; %abort simulation at -50dB energy drop
+unit = 1e-3; %drawing unit used
+
+%capacity footprint is 4mm x 4mm
+lambda_min = c0/(excite.f_0+excite.f_c);
+
+% meshing options
+% desired mesh resolution
+mesh_res([1 3]) = min(15,lambda_min/20/unit);
+mesh_res(2) = body_mesh_res / BC.rad;
+
+%% setup FDTD parameter & excitation function
+FDTD = InitFDTD('CoordSystem', 1, ... %init a cylindrical FDTD setup
+ 'EndCriteria', 1e-4, ... % with an end criteria of -40dB (1e-4)
+ 'MultiGrid', '10,20',... % add two cylindrical sub-grids at a radius of 10 and 20 mm
+ 'CellConstantMaterial', 1); % assume a material is constant inside
+ % a cell (material probing in cell center)
+
+% define the excitation time-signal (unmodulated gaussian pulse)
+FDTD = SetGaussExcite(FDTD,excite.f_0,excite.f_c);
+
+% define & set boundary conditions
+% - pml in +/- z-direction
+% - boundaries in -r and +/- alpha direction disabled (full cylindrical mesh)
+% - PEC boundary in +r-direction to model bore RF shield
+FDTD = SetBoundaryCond(FDTD, [0 0 0 0 3 3]);
+
+
+%% setup CSXCAD geometry & mesh (cylindrical)
+CSX = InitCSX('CoordSystem',1);
+
+% init empty mesh structure
+mesh.r = [];
+mesh.a = [];
+mesh.z = [];
+
+%% Create metal bird cage and rung capacities
+CSX = AddMetal(CSX,'metal');
+CSX = AddLumpedElement(CSX,'caps','z','C',BC.cap);
+
+da_Strip = BC.stripwidth/BC.rad; % width of a strip in radiant
+da_Caps = BC.portwidth/BC.rad; % width of a cap/port in radiant
+da_Segs = 2*pi/BC.N_rungs; % width of a rung in radiant
+
+a_start = -pi-da_Segs/2; % starting angle
+
+w0 = 2*pi*f0;
+T0 = 1/f0;
+
+% port counter
+port_Nr = 1;
+
+a0 = a_start;
+
+for n=1:BC.N_rungs
+ start = [BC.rad a0+da_Segs/2-da_Caps/2 -0.5*BC.portlength];
+ stop = [BC.rad a0+da_Segs/2+da_Caps/2 +0.5*BC.portlength];
+ CSX = AddBox(CSX,'caps',1, start, stop);
+
+ start = [BC.rad a0+da_Segs/2-da_Caps/2 0.5*BC.length-BC.stripwidth/2-BC.portlength];
+ stop = [BC.rad a0+da_Segs/2+da_Caps/2 0.5*BC.length-BC.stripwidth/2];
+ if (~isempty(intersect(n, BC.feed_pos)) && (BC.feed_amp(port_Nr)~=0)) % active port
+ exc_amp = abs(BC.feed_amp(port_Nr));
+
+ % calculate time delay to achieve a given phase shift at f0
+ T = -angle(BC.feed_amp(port_Nr)) / w0;
+ if T<0
+ T = T + T0;
+ end
+ [CSX port{port_Nr}] = AddLumpedPort(CSX, 100, port_Nr, 50, start, stop, [0 0 1]*exc_amp, true,'Delay',T);
+
+ %increase port count
+ port_Nr = port_Nr+1;
+
+ start = [BC.rad a0+da_Segs/2-da_Strip/2 0.5*BC.length-BC.stripwidth/2-BC.portlength];
+ elseif ~isempty(intersect(n, BC.feed_pos)) % passive port
+ [CSX port{port_Nr}] = AddLumpedPort(CSX, 100, port_Nr, 50, start, stop, [0 0 1], false);
+
+ %increase port count
+ port_Nr = port_Nr+1;
+
+ start = [BC.rad a0+da_Segs/2-da_Strip/2 0.5*BC.length-BC.stripwidth/2-BC.portlength];
+ else
+ start = [BC.rad a0+da_Segs/2-da_Strip/2 0.5*BC.length];
+ end
+
+ % the start z-coordinate depends on the port (see above)
+ stop = [BC.rad a0+da_Segs/2+da_Strip/2 0.5*BC.portlength];
+ CSX = AddBox(CSX,'metal',1, start, stop);
+
+ start = [BC.rad a0+da_Segs/2-da_Strip/2 -0.5*BC.length];
+ stop = [BC.rad a0+da_Segs/2+da_Strip/2 -0.5*BC.portlength];
+ CSX = AddBox(CSX,'metal',1, start, stop);
+
+ % some additonal mesh lines
+ mesh.a = [mesh.a a0+da_Segs/2];
+
+ a0 = a0 + da_Segs;
+end
+
+% create metal top ring
+start = [BC.rad a_start -(BC.length-BC.stripwidth)/2];
+stop = [BC.rad a_start+2*pi -(BC.length+BC.stripwidth)/2];
+CSX = AddBox(CSX,'metal',1, start, stop);
+
+% create metal bottom ring
+start = [BC.rad a_start (BC.length-BC.stripwidth)/2];
+stop = [BC.rad a_start+2*pi (BC.length+BC.stripwidth)/2];
+CSX = AddBox(CSX,'metal',1, start, stop);
+
+%% create smooth mesh
+mesh = DetectEdges(CSX, mesh);
+mesh.r = [0 SmoothMeshLines([body_mesh_res*1.5 mesh.r], body_mesh_res)];
+mesh.z = SmoothMeshLines(mesh.z, body_mesh_res);
+
+mesh.r = [mesh.r Bore.rad]; %mesh lines in radial direction
+mesh.z = [-Bore.length/2 mesh.z Bore.length/2]; %mesh lines in z-direction
+
+mesh = SmoothMesh(mesh, mesh_res, 1.5);
+
+%% check the cell limit
+numCells = numel(mesh.r)*numel(mesh.a)*numel(mesh.z);
+
+%% define human body model
+CSX = AddDiscMaterial(CSX, 'body_model', 'File', body_model_file, 'Scale', 1/unit, 'Transform', body_model_transform);
+start = [mesh.r(1) mesh.a(1) mesh.z(1)];
+stop = [mesh.r(end) mesh.a(end) mesh.z(end)];
+CSX = AddBox(CSX, 'body_model', 0, start, stop);
+
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start = [0 mesh.a(1) -BC.length/2];
+stop = [BC.rad mesh.a(end) +BC.length/2];
+
+CSX = AddDump(CSX,'Ef','FileType',1,'DumpType',10,'DumpMode',2,'Frequency',f0);
+CSX = AddBox(CSX,'Ef',0 , start,stop);
+
+CSX = AddDump(CSX,'Hf','FileType',1,'DumpType',11,'DumpMode',2,'Frequency',f0);
+CSX = AddBox(CSX,'Hf',0 , start,stop);
+
+CSX = AddDump(CSX,'SAR','FileType',1,'DumpType',20,'DumpMode',2,'Frequency',f0);
+CSX = AddBox(CSX,'SAR',0 , start,stop);
+
+start = [0 mesh.a(1) 0];
+stop = [BC.rad mesh.a(end) 0];
+CSX = AddDump(CSX,'Ht','FileType',1,'DumpType',1,'DumpMode',2);
+CSX = AddBox(CSX,'Ht',0 , start,stop);
+
+%% finalize mesh
+% add some lines for the pml in +/- z- direction
+mesh = AddPML(mesh, [0 0 0 0 10 10], 1);
+
+% define the mesh
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%% Write file & run openEMS
+Sim_Path = ['tmp_' mfilename];
+
+if (postproc_only==0)
+ [status, message, messageid] = rmdir(Sim_Path,'s'); %delete old results
+ [status, message, messageid] = mkdir(Sim_Path); %create folder
+
+ WriteOpenEMS([Sim_Path '/BirdCage.xml'],FDTD,CSX);
+end
+
+if (GeomPlot==1)
+ CSXGeomPlot( [Sim_Path '/BirdCage.xml'] , ['--export-polydata-vtk=' Sim_Path ' --RenderDiscMaterial -v']);
+end
+
+if (postproc_only==0)
+ RunOpenEMS(Sim_Path, 'BirdCage.xml');
+end
+
+%%
+freq = linspace(excite.f_0-excite.f_c,excite.f_0+excite.f_c,201);
+port = calcPort(port, Sim_Path, freq);
+
+close all
+s11 = port{1}.uf.ref./port{1}.uf.inc;
+s22 = port{2}.uf.ref./port{2}.uf.inc;
+
+% the s-parameter may be larger than 1 (0dB) since all ports are excited
+% and do not have a perfect port isolation
+plot(freq*1e-6,20*log10(abs(s11)),'Linewidth',2)
+hold on
+grid on
+plot(freq*1e-6,20*log10(abs(s22)),'r--','Linewidth',2)
+legend('s11','s22');
+
+%% read SAR values on a xy-plane (range)
+[SAR SAR_mesh] = ReadHDF5Dump([Sim_Path '/SAR.h5'],'Range',{[],[],0},'CloseAlpha',1);
+SAR = SAR.FD.values{1};
+
+% SAR plot
+figure()
+[R A] = ndgrid(SAR_mesh.lines{1},SAR_mesh.lines{2});
+X = R.*cos(A);Y = R.*sin(A);
+colormap('hot');
+h = pcolor(X,Y,(squeeze(SAR)));
+% h = pcolor(X,Y,log10(squeeze(SAR)));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('y -->');
+title('local SAR');
+axis equal tight
+
+%% plot B1+/- on an xy-plane
+[H_field H_mesh] = ReadHDF5Dump([Sim_Path '/Hf.h5'],'Range',{[0 0.1],[],0},'CloseAlpha',1);
+% create a 2D grid to plot on
+[R A] = ndgrid(H_mesh.lines{1},H_mesh.lines{2});
+X = R.*cos(A);
+Y = R.*sin(A);
+
+% calc Bx,By (from Br and Ba), B1p, B1m
+Bx = MUE0*(H_field.FD.values{1}(:,:,:,1).*cos(A) - H_field.FD.values{1}(:,:,:,2).*sin(A));
+By = MUE0*(H_field.FD.values{1}(:,:,:,1).*sin(A) + H_field.FD.values{1}(:,:,:,2).*cos(A));
+B1p = 0.5*(Bx+1j*By);
+B1m = 0.5*(Bx-1j*By);
+
+Dump2VTK([Sim_Path '/B1p_xy.vtk'], abs(B1p), H_mesh, 'B-Field');
+Dump2VTK([Sim_Path '/B1m_xy.vtk'], abs(B1m), H_mesh, 'B-Field');
+
+maxB1 = max([abs(B1p(:)); abs(B1m(:))]);
+
+% B1+ plot
+figure()
+subplot(1,2,1);
+h = pcolor(X,Y,abs(B1p));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('y -->');
+title('B_1^+ field (dB)');
+caxis([0 maxB1]);
+axis equal tight
+
+% B1- plot
+subplot(1,2,2);
+h = pcolor(X,Y,abs(B1m));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('y -->');
+title('B_1^- field (dB)');
+caxis([0 maxB1]);
+axis equal tight
+
+%%
+ConvertHDF5_VTK([Sim_Path '/Hf.h5'],[Sim_Path '/Hf_xy'],'Range',{[],[],0},'CloseAlpha',1)
+ConvertHDF5_VTK([Sim_Path '/SAR.h5'],[Sim_Path '/SAR_xy'],'Range',{[],[],0},'CloseAlpha',1)
diff --git a/openEMS/matlab/Tutorials/MRI_Loop_Coil.m b/openEMS/matlab/Tutorials/MRI_Loop_Coil.m
new file mode 100644
index 0000000..088f8f3
--- /dev/null
+++ b/openEMS/matlab/Tutorials/MRI_Loop_Coil.m
@@ -0,0 +1,334 @@
+%
+% Tutorials / 7T MRI Loop Coil
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_MRI_Loop_Coil
+%
+% Tested with
+% - openEMS v0.0.33
+% - Matlab 7.12.0 (R2011a)
+%
+% (C) 2013-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants; %get some physical constants like c0 and MUE0
+unit = 1e-3; % all length in mm
+
+% Loop-Coil parameter
+loop.length = 80; % length of the loop (in z-direction)
+loop.width = 60; % width of the loop (in y-direction)
+loop.strip_width = 5; % metal strip width
+loop.strip_N_cells = 3; % number of cells over the strip length
+loop.air_gap = loop.strip_width/3; % air gap width for lumped capacitors
+loop.pos_x = -130; % position of loop
+loop.C_gap = 5.4e-12; % lumped cap value
+loop.port_R = 10; % feeding port resistance
+
+%% define the human body model (virtual family)
+% set file name for human body model to create with "Convert_VF_DiscMaterial"
+% the file name should contain a full path
+body_model_file = [pwd '/Ella_centered_298MHz.h5'];
+
+% convert only part of the model (head/shoulder section)
+body_model_range = {[],[],[-0.85 -0.4]};
+
+% paths to virtual family voxel models (VFVM), adept to your install!
+VF_raw_filesuffix = '/tmp/Ella_26y_V2_1mm';
+VF_mat_db_file = '/tmp/DB_h5_20120711_SEMCADv14.8.h5';
+
+% delete(body_model_file); % uncomment to delete old model if something changed
+
+% convert model (if it does not exist)
+Convert_VF_DiscMaterial(VF_raw_filesuffix, VF_mat_db_file, body_model_file, ...
+ 'Frequency', 298e6, 'Center', 1, ...
+ 'Range', body_model_range);
+
+% rotate model to face the nose in x-dir, and translate
+body_model_transform = {'Rotate_X',pi,'Rotate_Z',pi/2, ...
+ 'Translate',[0,5,-720]};
+
+% the head should + part of shoulder should fit this box
+body_box.start = [-120 -150 -200];
+body_box.stop = [+100 +150 +130];
+
+% box with high res mesh
+mesh_box.start = [-120 -80 -120];
+mesh_box.stop = [+100 +80 +120];
+mesh_box.resolution = 2;
+
+%% some mesh parameter
+Air_Box = 150; % size of the surrounding air box (150mm)
+
+%% setup FDTD parameter & excitation function
+% init FDTD structure
+FDTD = InitFDTD( 'EndCriteria', 1e-4, 'CellConstantMaterial', 0);
+
+% define gaussian pulse excitation signal
+f0 = 298e6; % center frequency
+fc = 300e6; % 20 dB corner frequency
+FDTD = SetGaussExcite( FDTD, f0, fc );
+
+% setup boundary conditions
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+CSX = InitCSX();
+
+%% create loop
+% setup all properties needed
+CSX = AddMetal( CSX, 'loop' );
+CSX = AddLumpedElement( CSX, 'caps_y', 1, 'C', loop.C_gap);
+CSX = AddLumpedElement( CSX, 'caps_z', 2, 'C', loop.C_gap);
+
+% horizontal (y-direction) strips
+start = [loop.pos_x -loop.width/2 -loop.length/2];
+stop = [loop.pos_x -loop.air_gap/2 -loop.length/2+loop.strip_width];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+start = [loop.pos_x -loop.width/2 loop.length/2 ];
+stop = [loop.pos_x -loop.air_gap/2 loop.length/2-loop.strip_width];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+start = [loop.pos_x loop.width/2 -loop.length/2];
+stop = [loop.pos_x loop.air_gap/2 -loop.length/2+loop.strip_width];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+start = [loop.pos_x loop.width/2 loop.length/2 ];
+stop = [loop.pos_x loop.air_gap/2 loop.length/2-loop.strip_width];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+% vertical (z-direction) strips
+start = [loop.pos_x -loop.width/2 -loop.length/2+loop.strip_width];
+stop = [loop.pos_x -loop.width/2+loop.strip_width -loop.air_gap/2];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+start = [loop.pos_x -loop.width/2 loop.length/2-loop.strip_width];
+stop = [loop.pos_x -loop.width/2+loop.strip_width loop.air_gap/2];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+start = [loop.pos_x loop.width/2 -loop.length/2+loop.strip_width];
+stop = [loop.pos_x loop.width/2-loop.strip_width -loop.air_gap/2];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+start = [loop.pos_x loop.width/2 loop.length/2-loop.strip_width ];
+stop = [loop.pos_x loop.width/2-loop.strip_width loop.air_gap/2];
+CSX = AddBox(CSX,'loop',10,start,stop);
+
+% add the lumped capacities
+start = [loop.pos_x -loop.width/2+loop.strip_width/2-loop.air_gap/2 -loop.air_gap/2];
+stop = [loop.pos_x -loop.width/2+loop.strip_width/2+loop.air_gap/2 +loop.air_gap/2];
+CSX = AddBox(CSX,'caps_z',10,start,stop);
+
+start = [loop.pos_x loop.width/2-loop.strip_width/2-loop.air_gap/2 -loop.air_gap/2];
+stop = [loop.pos_x loop.width/2-loop.strip_width/2+loop.air_gap/2 +loop.air_gap/2];
+CSX = AddBox(CSX,'caps_z',10,start,stop);
+
+start = [loop.pos_x -loop.air_gap/2 loop.length/2-loop.strip_width/2-loop.air_gap/2];
+stop = [loop.pos_x +loop.air_gap/2 loop.length/2-loop.strip_width/2+loop.air_gap/2];
+CSX = AddBox(CSX,'caps_y',10,start,stop);
+
+% add a lumped port as excitation
+start = [loop.pos_x -loop.air_gap/2 -loop.length/2+loop.strip_width/2-loop.air_gap/2];
+stop = [loop.pos_x +loop.air_gap/2 -loop.length/2+loop.strip_width/2+loop.air_gap/2];
+[CSX port] = AddLumpedPort(CSX, 100, 1, loop.port_R, start, stop, [0 1 0], true);
+
+%% define human body model
+CSX = AddDiscMaterial(CSX, 'body_model', 'File', body_model_file, 'Scale', 1/unit, 'Transform', body_model_transform);
+CSX = AddBox(CSX, 'body_model', 0, body_box.start, body_box.stop);
+
+%% finalize mesh
+% create loop mesh
+mesh = DetectEdges(CSX);
+
+% add a dense homegeneous mesh inside the human body model
+mesh.x = [mesh.x mesh_box.start(1) mesh_box.stop(1)];
+mesh.y = [mesh.y mesh_box.start(2) mesh_box.stop(2)];
+mesh.z = [mesh.z mesh_box.start(3) mesh_box.stop(3)];
+
+% add lines in x-dir for the loop and a cell centered around 0
+mesh.x = [mesh.x loop.pos_x -mesh_box.resolution/2 mesh_box.resolution/2];
+
+% smooth the mesh for the loop & body
+mesh = SmoothMesh(mesh, mesh_box.resolution);
+
+% add air spacer
+mesh.x = [-Air_Box+mesh.x(1) mesh.x mesh.x(end)+Air_Box];
+mesh.y = [-Air_Box+mesh.y(1) mesh.y mesh.y(end)+Air_Box];
+mesh.z = [-Air_Box+mesh.z(1) mesh.z mesh.z(end)+Air_Box];
+
+mesh = SmoothMesh(mesh, c0 / (f0+fc) / unit / 10, 1.5, 'algorithm', 1);
+
+%% Add Dump boxes (2D boxes) for H and SAR on xy- and xz-plane
+CSX = AddDump(CSX,'Hf_xy','DumpType',11,'FileType',1,'Frequency',f0);
+CSX = AddBox(CSX,'Hf_xy',0, body_box.start.*[1 1 0], body_box.stop.*[1 1 0]);
+CSX = AddDump(CSX,'SAR_xy','DumpType',20,'DumpMode',2,'FileType',1,'Frequency',f0);
+CSX = AddBox(CSX,'SAR_xy',0, body_box.start.*[1 1 0], body_box.stop.*[1 1 0]);
+
+CSX = AddDump(CSX,'Hf_xz','DumpType',11,'FileType',1,'Frequency',f0);
+CSX = AddBox(CSX,'Hf_xz',0, body_box.start.*[1 0 1], body_box.stop.*[1 0 1]);
+CSX = AddDump(CSX,'SAR_xz','DumpType',20,'DumpMode',2,'FileType',1,'Frequency',f0);
+CSX = AddBox(CSX,'SAR_xz',0, body_box.start.*[1 0 1], body_box.stop.*[1 0 1]);
+
+%% add 10 lines in all direction to make space for PML or MUR absorbing
+%% boundary conditions
+mesh = AddPML(mesh, 10);
+
+%% finaly define the FDTD mesh grid
+disp(['number of cells: ' num2str(1e-6*numel(mesh.x)*numel(mesh.y)*numel(mesh.z)) ' Mcells'])
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% prepare simulation folder
+Sim_Path = ['tmp_' mfilename];
+Sim_CSX = [mfilename '.xml'];
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure and export as vtk data automatically
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] , ['--export-polydata-vtk=' Sim_Path ' --RenderDiscMaterial -v']);
+
+%% run openEMS
+RunOpenEMS( Sim_Path, Sim_CSX);
+
+%% postprocessing & do the plots
+freq = linspace( f0-fc, f0+fc, 501 );
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+
+% get the feeding power for frequency f0
+P0_in = interp1(freq, port.P_acc, f0);
+
+%%
+% plot reflection coefficient S11
+figure
+h = plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}| (dB)' );
+
+% plot feed point admittance
+figure
+h = plot( freq/1e6, real(1./Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(1./Zin), 'r--', 'Linewidth', 2 );
+title( 'feed port admittance' );
+xlabel( 'frequency f (MHz)' );
+ylabel( 'admittance Y_{in} (S)' );
+legend( 'real', 'imag' );
+
+%% read SAR values on a xy-plane (range)
+[SAR SAR_mesh] = ReadHDF5Dump([Sim_Path '/SAR_xy.h5']);
+SAR = SAR.FD.values{1}/P0_in;
+
+% SAR plot
+figure()
+subplot(1,2,1);
+[X Y] = ndgrid(SAR_mesh.lines{1},SAR_mesh.lines{2});
+colormap('hot');
+h = pcolor(X,Y,(squeeze(SAR)));
+% h = pcolor(X,Y,log10(squeeze(SAR)));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('y -->');
+title('local SAR');
+axis equal tight
+
+%% read SAR values on a xz-plane (range)
+[SAR SAR_mesh] = ReadHDF5Dump([Sim_Path '/SAR_xz.h5']);
+SAR = SAR.FD.values{1}/P0_in;
+
+% SAR plot
+subplot(1,2,2);
+[X Z] = ndgrid(SAR_mesh.lines{1},SAR_mesh.lines{3});
+colormap('hot');
+h = pcolor(X,Z,(squeeze(SAR)));
+% h = pcolor(X,Y,log10(squeeze(SAR)));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('z -->');
+title('local SAR');
+axis equal tight
+
+%% plot B1+/- on an xy-plane
+[H_field H_mesh] = ReadHDF5Dump([Sim_Path '/Hf_xy.h5']);
+% calc Bx,By, B1p, B1m normalize to the input-power
+Bx = MUE0*H_field.FD.values{1}(:,:,:,1)/sqrt(P0_in);
+By = MUE0*H_field.FD.values{1}(:,:,:,2)/sqrt(P0_in);
+B1p = 0.5*(Bx+1j*By);
+B1m = 0.5*(Bx-1j*By);
+% create a 2D grid to plot on
+[X Y] = ndgrid(H_mesh.lines{1},H_mesh.lines{2});
+
+Dump2VTK([Sim_Path '/B1p_xy.vtk'], abs(B1p), H_mesh, 'B-Field');
+Dump2VTK([Sim_Path '/B1m_xy.vtk'], abs(B1m), H_mesh, 'B-Field');
+
+% B1+ plot
+figure()
+subplot(1,2,1);
+h = pcolor(X,Y,log10(abs(B1p)));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('y -->');
+title('B_1^+ field (dB)');
+axis equal tight
+
+% B1- plot
+subplot(1,2,2);
+h = pcolor(X,Y,log10(abs(B1m)));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('y -->');
+title('B_1^- field (dB)');
+axis equal tight
+
+%% plot B1+/- on an xz-plane
+[H_field H_mesh] = ReadHDF5Dump([Sim_Path '/Hf_xz.h5']);
+% calc Bx,By, B1p, B1m normalize to the input-power
+Bx = MUE0*H_field.FD.values{1}(:,:,:,1)/sqrt(P0_in);
+By = MUE0*H_field.FD.values{1}(:,:,:,2)/sqrt(P0_in);
+B1p = 0.5*(Bx+1j*By);
+B1m = 0.5*(Bx-1j*By);
+% create a 2D grid to plot on
+[X Z] = ndgrid(H_mesh.lines{1},H_mesh.lines{3});
+
+Dump2VTK([Sim_Path '/B1p_xz.vtk'], abs(B1p), H_mesh, 'B-Field');
+Dump2VTK([Sim_Path '/B1m_xz.vtk'], abs(B1m), H_mesh, 'B-Field');
+
+% B1+ plot
+figure()
+subplot(1,2,1);
+h = pcolor(X,Z,log10(squeeze(abs(B1p))));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('z -->');
+title('B_1^+ field (dB)');
+axis equal tight
+
+% B1- plot
+subplot(1,2,2);
+h = pcolor(X,Z,log10(squeeze(abs(B1m))));
+set(h,'EdgeColor','none');
+xlabel('x -->');
+ylabel('z -->');
+title('B_1^- field (dB)');
+axis equal tight
+
+%% dump to vtk to view in Paraview
+ConvertHDF5_VTK([Sim_Path '/SAR_xy.h5'],[Sim_Path '/SAR_xy'], 'weight', 1/P0_in, 'FieldName', 'SAR');
+ConvertHDF5_VTK([Sim_Path '/SAR_xz.h5'],[Sim_Path '/SAR_xz'], 'weight', 1/P0_in, 'FieldName', 'SAR');
+
+%%
+ConvertHDF5_VTK([Sim_Path '/Hf_xy.h5'],[Sim_Path '/B1_xy'], 'weight', MUE0/sqrt(P0_in), 'FieldName', 'B1-field');
+ConvertHDF5_VTK([Sim_Path '/Hf_xz.h5'],[Sim_Path '/B1_xz'], 'weight', MUE0/sqrt(P0_in), 'FieldName', 'B1-field');
diff --git a/openEMS/matlab/Tutorials/MSL_NotchFilter.m b/openEMS/matlab/Tutorials/MSL_NotchFilter.m
new file mode 100644
index 0000000..612456c
--- /dev/null
+++ b/openEMS/matlab/Tutorials/MSL_NotchFilter.m
@@ -0,0 +1,92 @@
+%
+% Tutorials / MSL_NotchFilter
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Microstrip_Notch_Filter
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2011-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+MSL_length = 50000;
+MSL_width = 600;
+substrate_thickness = 254;
+substrate_epr = 3.66;
+stub_length = 12e3;
+f_max = 7e9;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD();
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = {'PML_8' 'PML_8' 'MUR' 'MUR' 'PEC' 'MUR'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+resolution = c0/(f_max*sqrt(substrate_epr))/unit /50; % resolution of lambda/50
+mesh.x = SmoothMeshLines( [0 MSL_width/2+[2*resolution/3 -resolution/3]/4], resolution/4, 1.5 ,0 );
+mesh.x = SmoothMeshLines( [-MSL_length -mesh.x mesh.x MSL_length], resolution, 1.5 ,0 );
+mesh.y = SmoothMeshLines( [0 MSL_width/2+[-resolution/3 +resolution/3*2]/4], resolution/4 , 1.5 ,0);
+mesh.y = SmoothMeshLines( [-15*MSL_width -mesh.y mesh.y stub_length+[-resolution/3 +resolution/3*2]/4 15*MSL_width+stub_length], resolution, 1.3 ,0);
+mesh.z = SmoothMeshLines( [linspace(0,substrate_thickness,5) 10*substrate_thickness], resolution );
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% substrate
+CSX = AddMaterial( CSX, 'RO4350B' );
+CSX = SetMaterialProperty( CSX, 'RO4350B', 'Epsilon', substrate_epr );
+start = [mesh.x(1), mesh.y(1), 0];
+stop = [mesh.x(end), mesh.y(end), substrate_thickness];
+CSX = AddBox( CSX, 'RO4350B', 0, start, stop );
+
+%% MSL port
+CSX = AddMetal( CSX, 'PEC' );
+portstart = [ mesh.x(1), -MSL_width/2, substrate_thickness];
+portstop = [ 0, MSL_width/2, 0];
+[CSX,port{1}] = AddMSLPort( CSX, 999, 1, 'PEC', portstart, portstop, 0, [0 0 -1], 'ExcitePort', true, 'FeedShift', 10*resolution, 'MeasPlaneShift', MSL_length/3);
+
+portstart = [mesh.x(end), -MSL_width/2, substrate_thickness];
+portstop = [0 , MSL_width/2, 0];
+[CSX,port{2}] = AddMSLPort( CSX, 999, 2, 'PEC', portstart, portstop, 0, [0 0 -1], 'MeasPlaneShift', MSL_length/3 );
+
+%% Filter-stub
+start = [-MSL_width/2, MSL_width/2, substrate_thickness];
+stop = [ MSL_width/2, MSL_width/2+stub_length, substrate_thickness];
+CSX = AddBox( CSX, 'PEC', 999, start, stop );
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = 'tmp';
+Sim_CSX = 'msl.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX );
+
+%% post-processing
+close all
+f = linspace( 1e6, f_max, 1601 );
+port = calcPort( port, Sim_Path, f, 'RefImpedance', 50);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,20*log10(abs(s11)),'k-','LineWidth',2);
+hold on;
+grid on;
+plot(f/1e9,20*log10(abs(s21)),'r--','LineWidth',2);
+legend('S_{11}','S_{21}');
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (GHz) \rightarrow','FontSize',12);
+ylim([-40 2]);
+
diff --git a/openEMS/matlab/Tutorials/Parallel_Plate_Waveguide.m b/openEMS/matlab/Tutorials/Parallel_Plate_Waveguide.m
new file mode 100644
index 0000000..cbf76c0
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Parallel_Plate_Waveguide.m
@@ -0,0 +1,51 @@
+%
+% Tutorials / Parallel_Plate_Waveguide
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Parallel_Plate_Waveguide
+%
+% Tested with
+% - Matlab 2011a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2011,2012 Sebastian Held <sebastian.held@gmx.de>
+% (C) 2011-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+% init and define FDTD parameter
+FDTD = InitFDTD(100,0,'OverSampling',50);
+FDTD = SetSinusExcite(FDTD,10e6);
+BC = {'PMC' 'PMC' 'PEC' 'PEC' 'MUR' 'MUR'};
+FDTD = SetBoundaryCond(FDTD,BC);
+
+% init and define FDTD mesh
+CSX = InitCSX();
+mesh.x = -10:10;
+mesh.y = -10:10;
+mesh.z = -10:30;
+CSX = DefineRectGrid(CSX, 1, mesh);
+
+% define the excitation
+CSX = AddExcitation(CSX,'excitation',0,[0 1 0]);
+CSX = AddBox(CSX,'excitation',0,[-10 -10 0],[10 10 0]);
+
+% define a time domain e-field dump box
+CSX = AddDump(CSX,'Et','DumpMode',0);
+CSX = AddBox(CSX,'Et',0,[-10 0 -10],[10 0 30]);
+
+% remove old simulation results (if exist)
+rmdir('tmp','s');mkdir('tmp');
+
+% write openEMS xml data file
+WriteOpenEMS('tmp/tmp.xml',FDTD,CSX);
+
+% view defined structure
+CSXGeomPlot( 'tmp/tmp.xml' );
+
+% run openEMS simulation
+RunOpenEMS('tmp','tmp.xml','');
+
+disp('use Paraview to visualize the FDTD result...');
diff --git a/openEMS/matlab/Tutorials/Patch_Antenna_Array.m b/openEMS/matlab/Tutorials/Patch_Antenna_Array.m
new file mode 100644
index 0000000..ed12c67
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Patch_Antenna_Array.m
@@ -0,0 +1,170 @@
+function [port nf2ff] = Patch_Antenna_Array(Sim_Path, postproc_only, show_structure, xpos, caps, resist, active )
+% [port nf2ff] = Patch_Antenna_Array(Sim_Path, postproc_only, show_structure, xpos, caps, resist, active )
+%
+% Script to setup the patch array as described in [1].
+% Run main script in Patch_Antenna_Phased_Array.m instead!
+%
+% Sim_Path: Simulation path
+% postproc_only: set to post process only 0/1
+% show_structure: show the strucuture in AppCSXCAD 0/1
+% xpos: the x-position for each antenna is defined
+% caps: the port capacity (will override active port)
+% resist: port resitance
+% active: switch port active
+%
+% References:
+% [1] Y. Yusuf and X. Gong, “A low-cost patch antenna phased array with
+% analog beam steering using mutual coupling and reactive loading,” IEEE
+% Antennas Wireless Propag. Lett., vol. 7, pp. 81–84, 2008.
+%
+% Tested with
+% - Matlab 2011a
+% - openEMS v0.0.31
+%
+% (C) 2013 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+% example
+% xpos = [-41 0 41];
+% caps = [0.2e-12 0 0.2e-12];
+% active = [0 1 0];
+% resist = [50 50 50];
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% patch geometry setup
+patch.W = 35; % width
+patch.L = 28.3; % length
+patch.Ws = 3.8; % width of feeding stub
+patch.Gs = 1; % width of feeding gab
+patch.l = 6; % length of feeding stub
+patch.y0 = 10; % depth of feeding stub into into patch
+
+% patch resonance frequency
+f0 = 3e9;
+
+%substrate setup
+substrate.name = 'Ro3003';
+substrate.epsR = 3;
+substrate.kappa = 0.0013 * 2*pi*f0 * EPS0*substrate.epsR;
+substrate.thickness = 1.524;
+substrate.cells = 4;
+
+substrate.width = patch.W + max(xpos) - min(xpos) + 4*patch.l;
+substrate.length = 3*patch.l + patch.L;
+
+% size of the simulation box
+AirSpacer = [50 50 30];
+
+edge_res = [-1/3 2/3]*1;
+
+%% setup FDTD parameter & excitation function
+fc = 2e9; % 20 dB corner frequency
+FDTD = InitFDTD( 'EndCriteria', 1e-4 );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = [1 1 1 1 1 1]*3;
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+CSX = InitCSX();
+
+mesh.x = [];
+mesh.y = [];
+mesh.z = [];
+
+%% create patch
+CSX = AddMetal( CSX, 'patch' ); % create a perfect electric conductor (PEC)
+
+for port_nr=1:numel(xpos)
+ start = [xpos(port_nr)-patch.W/2 patch.l substrate.thickness];
+ stop = [xpos(port_nr)-patch.Ws/2-patch.Gs patch.l+patch.L substrate.thickness];
+ CSX = AddBox(CSX,'patch',10, start, stop);
+ mesh.x = [mesh.x xpos(port_nr)-patch.W/2-edge_res];
+
+ start = [xpos(port_nr)+patch.W/2 patch.l substrate.thickness];
+ stop = [xpos(port_nr)+patch.Ws/2+patch.Gs patch.l+patch.L substrate.thickness];
+ CSX = AddBox(CSX,'patch',10, start, stop);
+ mesh.x = [mesh.x xpos(port_nr)+patch.W/2+edge_res];
+
+ mesh.y = [mesh.y patch.l-edge_res patch.l+patch.L+edge_res];
+
+ start = [xpos(port_nr)-patch.Ws/2-patch.Gs patch.l+patch.y0 substrate.thickness];
+ stop = [xpos(port_nr)+patch.Ws/2+patch.Gs patch.l+patch.L substrate.thickness];
+ CSX = AddBox(CSX,'patch',10, start, stop);
+
+ % feed line
+ start = [xpos(port_nr)-patch.Ws/2 patch.l+patch.y0 substrate.thickness];
+ stop = [xpos(port_nr)+patch.Ws/2 0 substrate.thickness];
+ CSX = AddBox(CSX,'patch',10, start, stop);
+
+ mesh.x = [mesh.x xpos(port_nr)+linspace(-patch.Ws/2-patch.Gs,-patch.Ws/2,3) xpos(port_nr)+linspace(patch.Ws/2,patch.Ws/2+patch.Gs,3)];
+
+ start = [xpos(port_nr)-patch.Ws/2 0 0];
+ stop = [xpos(port_nr)+patch.Ws/2 0 substrate.thickness];
+ if (caps(port_nr)>0)
+ CSX = AddLumpedElement(CSX, ['C_' num2str(port_nr)], 2, 'C', caps(port_nr));
+ CSX = AddBox(CSX,['C_' num2str(port_nr)],10, start, stop);
+
+ [CSX port{port_nr}] = AddLumpedPort(CSX, 5 ,port_nr ,inf, start, stop, [0 0 1], 0);
+ else
+ % feed port
+ [CSX port{port_nr}] = AddLumpedPort(CSX, 5 ,port_nr, resist(port_nr), start, stop, [0 0 1], active(port_nr));
+ end
+end
+
+%% create substrate
+CSX = AddMaterial( CSX, substrate.name );
+CSX = SetMaterialProperty( CSX, substrate.name, 'Epsilon', substrate.epsR, 'Kappa', substrate.kappa );
+start = [-substrate.width/2 0 0];
+stop = [ substrate.width/2 substrate.length substrate.thickness];
+CSX = AddBox( CSX, substrate.name, 0, start, stop );
+
+mesh.x = [mesh.x start(1) stop(1)];
+mesh.y = [mesh.y start(2) stop(2)];
+
+% add extra cells to discretize the substrate thickness
+mesh.z = [linspace(0,substrate.thickness,substrate.cells+1) mesh.z];
+
+%% create ground (same size as substrate)
+CSX = AddMetal( CSX, 'gnd' ); % create a perfect electric conductor (PEC)
+start(3)=0;
+stop(3) =0;
+CSX = AddBox(CSX,'gnd',10,start,stop);
+
+%% finalize the mesh
+% generate a smooth mesh with max. cell size: lambda_min / 20
+mesh = SmoothMesh(mesh, 2, 1.3);
+mesh.x = [mesh.x min(mesh.x)-AirSpacer(1) max(mesh.x)+AirSpacer(1)];
+mesh.y = [mesh.y min(mesh.y)-AirSpacer(2) max(mesh.y)+AirSpacer(2)];
+mesh.z = [mesh.z min(mesh.z)-AirSpacer(3) max(mesh.z)+2*AirSpacer(3)];
+
+mesh = SmoothMesh(mesh, c0 / (f0+fc) / unit / 20, 1.3);
+
+%% add a nf2ff calc box; size is 3 cells away from MUR boundary condition
+start = [mesh.x(4) mesh.y(4) mesh.z(4)];
+stop = [mesh.x(end-3) mesh.y(end-3) mesh.z(end-3)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop);
+
+mesh = AddPML(mesh,(BC==3)*8);
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%% prepare simulation folder
+Sim_CSX = 'patch_array.xml';
+
+if (postproc_only==0)
+ [status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+ [status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+ %% write openEMS compatible xml-file
+ WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+ %% show the structure
+ if (show_structure>0)
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+ end
+
+ %% run openEMS
+ RunOpenEMS( Sim_Path, Sim_CSX);
+end
+
diff --git a/openEMS/matlab/Tutorials/Patch_Antenna_Phased_Array.m b/openEMS/matlab/Tutorials/Patch_Antenna_Phased_Array.m
new file mode 100644
index 0000000..873f345
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Patch_Antenna_Phased_Array.m
@@ -0,0 +1,166 @@
+%
+% Tutorials / Patch Antenna Phased Array
+%
+% Describtion at:
+%
+% Tested with
+% - Matlab 2011a
+% - Octave 4.0
+% - openEMS v0.0.33
+%
+% References:
+% [1] Y. Yusuf and X. Gong, “A low-cost patch antenna phased array with
+% analog beam steering using mutual coupling and reactive loading,” IEEE
+% Antennas Wireless Propag. Lett., vol. 7, pp. 81–84, 2008.
+% [2] S. Otto, S. Held, A. Rennings, and K. Solbach,
+% "Array and multiport antenna farfield simulation using
+% EMPIRE, MATLAB and ADS," 39th European Microwave Conf. (EuMC 2009),
+% Sept. 29 – Oct. 1, Rome, Italy, pp. 1547-1550, 2009.
+% [3] K. Karlsson, J. Carlsson, I. Belov, G. Nilsson, and P.-S. Kildal,
+% “Optimization of antenna diversity gain by combining full-wave and
+% circuit simulations,” in Proc. Second European Conference on Antennas
+% and Propagation EuCAP 2007, 11–16 Nov. 2007, pp. 1–5.
+%
+% (C) 2013-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+
+close all
+clear
+clc
+
+% we need the "Cuircuit Toolbox"
+addpath('C:\CTB');
+% get the latest version from:
+% using git: https://github.com/thliebig/CTB
+% or zip: https://github.com/thliebig/CTB/archive/master.zip
+
+% set this to 0 to NOT run a reference simulation with the given C2 and C3
+% for comparison
+do_reference_simulation = 1;
+
+% set to 1 if you want to run AppCSXCAD to see the simulated structure
+show_structure = 1;
+
+% set this to 1, to force openEMS to run again even if the data already exist
+force_rerun = 0;
+
+% frequency range of interest
+f = linspace( 1e9, 5e9, 1601 );
+
+% resonant frequency for far-field calculations
+f0 = 3e9;
+
+% capacities for port 2 and 3 to shift the far-field pattern
+C2 = 0.2e-12;
+C3 = 0.2e-12;
+
+Sim_Path_Root = ['tmp_' mfilename];
+
+%% calculate the full S-parameter set for all 3 patch antennas running 3
+% individual openEMS simulations in which one antenna is active and the
+% other two a passive (50 Ohm load) respectively
+xpos = [0 -41 41]; % x-center position of the 3 antennas
+caps = [0 0 0];
+resist = [50 50 50];
+
+spara = [];
+color_code = {'k-','r--','m-.'};
+
+for n=1:3
+ active = [0 0 0];
+ active(n) = 1; % activate antenna n
+ Sim_Path = [Sim_Path_Root '_' num2str(n)]; % create an individual path
+ [port{n} nf2ff{n}] = Patch_Antenna_Array(Sim_Path, ((exist(Sim_Path,'dir')>0) && (force_rerun==0)), show_structure, xpos, caps, resist, active);
+ port{n} = calcPort( port{n}, Sim_Path, f, 'RefImpedance', 50);
+ nf2ff{n} = CalcNF2FF(nf2ff{n}, Sim_Path, f0, [-180:2:180]*pi/180, 0);
+
+ figure
+ hold on
+ grid on
+ for p=1:3
+ I(p,n) = interp1(f, port{n}{p}.if.tot,f0);
+ P_in(p) = 0.5*interp1(f, port{n}{n}.uf.inc,f0)*conj(interp1(f, port{n}{n}.if.inc,f0));
+ spara(p,n,:) = port{n}{p}.uf.ref./ port{n}{n}.uf.inc;
+ plot(f, squeeze(20*log10(abs(spara(p,n,:)))),color_code{p},'Linewidth',2);
+ end
+end
+
+%% export sparameter to touchstone file
+write_touchstone('s',f,spara,[Sim_Path_Root '.s3p']);
+
+% instructions for Qucs:
+% load the written touchstone file
+% attach C2 and C3 to port 2 and 3
+% attach a signal port to port 1
+% probe the currents going into port 1 to 3
+
+% example currents for ports 1 to 3 for C2 = 0.2pF and C3=0.2pF
+I_qucs(1,1) = 0.00398-0.000465j;
+I_qucs(2,1) = 2.92e-5-0.000914j;
+I_qucs(3,1) = 2.92e-5-0.000914j;
+
+disp(['I2/I1: Qucs: ' num2str(I_qucs(2)/I_qucs(1)) ' (defined manually)'])
+disp(['I3/I1: Qucs: ' num2str(I_qucs(3)/I_qucs(1)) ' (defined manually)'])
+
+%% Calculate the currents of port 1 to 3 using Matlab [1]
+z = s2z(spara);
+
+Z2 = 1/(1j*2*pi*f0*C2);
+Z3 = 1/(1j*2*pi*f0*C3);
+
+z23(1,1) = interp1(f,squeeze(z(2,2,:)),f0) + Z2;
+z23(1,2) = interp1(f,squeeze(z(2,3,:)),f0);
+z23(2,1) = interp1(f,squeeze(z(3,2,:)),f0);
+z23(2,2) = interp1(f,squeeze(z(3,3,:)),f0) + Z3;
+
+%set input/feeding current of port 1 to 1mA
+I_out(1,1) = 1e-3;
+% calc current for port 2 and 3
+I_out([2 3],1) = z23\[-interp1(f,squeeze(z(2,1,:)),f0);-interp1(f,squeeze(z(3,1,:)),f0)]*I_out(1);
+
+disp(['I2/I1: Matlab: ' num2str(I_out(2)/I_out(1))])
+disp(['I3/I1: Matlab: ' num2str(I_out(3)/I_out(1))])
+
+
+%% do a referenc simulation for the given C2/C3 values
+if (do_reference_simulation)
+ active = [1 0 0];
+ caps = [0 C2 C3];
+ resist = [50 inf inf];
+ Sim_Path = [Sim_Path_Root '_C2=' num2str(C2*1e12) '_C3=' num2str(C3*1e12)];
+ [port_ref nf2ff_ref] = Patch_Antenna_Array(Sim_Path, ((exist(Sim_Path,'dir')>0) && (force_rerun==0)), show_structure, xpos, caps, resist, active);
+ port_ref = calcPort( port_ref, Sim_Path, f, 'RefImpedance', 50);
+ nf2ff_ref = CalcNF2FF(nf2ff_ref, Sim_Path, f0, [-180:2:180]*pi/180, 0);
+
+ % extract currents from referenc simulation
+ for p=1:3
+ I_ref(p,1) = interp1(f, port_ref{p}.if.tot,f0);
+ end
+
+ disp(['I2/I1: openEMS: ' num2str(I_ref(2)/I_ref(1))])
+ disp(['I3/I1: openEMS: ' num2str(I_ref(3)/I_ref(1))])
+end
+
+%% calculate and apply weighting cooefficients [3]
+% calculate
+coeff = I\I_out;
+
+% apply
+E_ff_phi = 0*nf2ff{1}.E_phi{1};
+E_ff_theta = 0*nf2ff{1}.E_phi{1};
+for n=1:3
+ E_ff_phi = E_ff_phi + coeff(n)*nf2ff{n}.E_phi{1};
+ E_ff_theta = E_ff_theta + coeff(n)*nf2ff{n}.E_theta{1};
+end
+
+%% plot far-field patterns
+figure
+polar([-180:2:180]'*pi/180,abs(E_ff_phi(:))/max(abs(E_ff_phi(:))));
+hold on
+if (do_reference_simulation)
+ polar([-180:2:180]'*pi/180,abs(nf2ff_ref.E_norm{1}(:,1))/max(abs(nf2ff_ref.E_norm{1}(:,1))),'r--');
+end
+title('normalized far-field pattern','Interpreter', 'none')
+legend('calculated','reference')
+
+
diff --git a/openEMS/matlab/Tutorials/RCS_Sphere.m b/openEMS/matlab/Tutorials/RCS_Sphere.m
new file mode 100644
index 0000000..b8bb5bc
--- /dev/null
+++ b/openEMS/matlab/Tutorials/RCS_Sphere.m
@@ -0,0 +1,138 @@
+%
+% Tutorials / radar cross section of a metal sphere
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_RCS_Sphere
+%
+% Tested with
+% - Matlab 2013a / Octave 3.8.1
+% - openEMS v0.0.32
+%
+% (C) 2012-2014 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+sphere.rad = 200;
+
+inc_angle = 0 /180*pi; %incident angle (to x-axis) in rad
+
+% size of the simulation box
+SimBox = 1000;
+PW_Box = 750;
+
+%% setup FDTD parameter & excitation function
+f_start = 50e6; % start frequency
+f_stop = 1000e6; % stop frequency
+f0 = 500e6;
+
+FDTD = InitFDTD( );
+FDTD = SetGaussExcite( FDTD, 0.5*(f_start+f_stop), 0.5*(f_stop-f_start) );
+BC = [1 1 1 1 1 1]*3; % set boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+max_res = c0 / f_stop / unit / 20; % cell size: lambda/20
+CSX = InitCSX();
+
+%create mesh
+smooth_mesh = SmoothMeshLines([0 SimBox/2], max_res);
+mesh.x = unique([-smooth_mesh smooth_mesh]);
+mesh.y = mesh.x;
+mesh.z = mesh.x;
+
+%% create metal sphere
+CSX = AddMetal( CSX, 'sphere' ); % create a perfect electric conductor (PEC)
+CSX = AddSphere(CSX,'sphere',10,[0 0 0],sphere.rad);
+
+%% plane wave excitation
+k_dir = [cos(inc_angle) sin(inc_angle) 0]; % plane wave direction
+E_dir = [0 0 1]; % plane wave polarization --> E_z
+
+CSX = AddPlaneWaveExcite(CSX, 'plane_wave', k_dir, E_dir, f0);
+start = [-PW_Box/2 -PW_Box/2 -PW_Box/2];
+stop = -start;
+CSX = AddBox(CSX, 'plane_wave', 0, start, stop);
+
+%% dump boxes
+CSX = AddDump(CSX, 'Et');
+start = [mesh.x(1) mesh.y(1) 0];
+stop = [mesh.x(end) mesh.y(end) 0];
+CSX = AddBox(CSX, 'Et', 0, start, stop);
+
+%%nf2ff calc
+start = [mesh.x(1) mesh.y(1) mesh.z(1)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop);
+
+% add 8 lines in all direction as pml spacing
+mesh = AddPML(mesh,8);
+
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% prepare simulation folder
+Sim_Path = 'Sphere_RCS';
+Sim_CSX = 'Sphere_RCS.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+%% run openEMS
+RunOpenEMS( Sim_Path, Sim_CSX);
+
+%%
+disp('Use Paraview to display the elctric fields dumped by openEMS');
+
+%%
+EF = ReadUI( 'et', Sim_Path, f0 ); % time domain/freq domain voltage
+Pin = 0.5*norm(E_dir)^2/Z0 .* abs(EF.FD{1}.val).^2;
+
+%%
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, pi/2, [-180:2:180]*pi/180, 'Mode',1);
+RCS = 4*pi./Pin(1).*nf2ff.P_rad{1}(:);
+polar(nf2ff.phi,RCS);
+xlabel('x -->');
+ylabel('y -->');
+hold on
+grid on
+
+drawnow
+
+%%
+freq = linspace(f_start,f_stop,100);
+EF = ReadUI( 'et', Sim_Path, freq ); % time domain/freq domain voltage
+Pin = 0.5*norm(E_dir)^2/Z0 .* abs(EF.FD{1}.val).^2;
+
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, freq, pi/2, pi+inc_angle, 'Mode',1);
+for fn=1:numel(freq)
+ back_scat(fn) = 4*pi./Pin(fn).*nf2ff.P_rad{fn}(1);
+end
+
+%%
+figure
+plot(freq/1e6,back_scat,'Linewidth',2);
+grid on;
+xlabel('frequency (MHz) \rightarrow');
+ylabel('RCS (m^2) \rightarrow');
+title('radar cross section');
+
+%%
+figure
+lambda = c0./freq;
+semilogy(sphere.rad*unit./lambda,back_scat/(pi*sphere.rad*unit*sphere.rad*unit),'Linewidth',2);
+ylim([10^-2 10^1])
+grid on;
+xlabel('sphere radius / wavelength \rightarrow');
+ylabel('RCS / (\pi a^2) \rightarrow');
+title('normalized radar cross section');
diff --git a/openEMS/matlab/Tutorials/Rect_Waveguide.m b/openEMS/matlab/Tutorials/Rect_Waveguide.m
new file mode 100644
index 0000000..3b1a79a
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Rect_Waveguide.m
@@ -0,0 +1,121 @@
+%
+% Tutorials / Rect_Waveguide
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Rectangular_Waveguide
+%
+% Tested with
+% - Octave 4.0.0
+% - openEMS v0.0.33
+%
+% (C) 2010-2015 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; %drawing unit in um
+
+% waveguide dimensions
+% WR42
+a = 10700; %waveguide width
+b = 4300; %waveguide heigth
+length = 50000;
+
+% frequency range of interest
+f_start = 20e9;
+f_0 = 24e9;
+f_stop = 26e9;
+lambda0 = c0/f_0/unit;
+
+%waveguide TE-mode definition
+TE_mode = 'TE10';
+
+%targeted mesh resolution
+mesh_res = lambda0./[30 30 30];
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD('NrTS',1e4, 'OverSampling', 5);
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+
+% boundary conditions
+BC = [0 0 0 0 3 3]; %pml in pos. and neg. z-direction
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = SmoothMeshLines([0 a], mesh_res(1));
+mesh.y = SmoothMeshLines([0 b], mesh_res(2));
+mesh.z = SmoothMeshLines([0 length], mesh_res(3));
+CSX = DefineRectGrid(CSX, unit,mesh);
+
+%% apply the waveguide port %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start=[mesh.x(1) mesh.y(1) mesh.z(11)];
+stop =[mesh.x(end) mesh.y(end) mesh.z(15)];
+[CSX, port{1}] = AddRectWaveGuidePort( CSX, 0, 1, start, stop, 'z', a*unit, b*unit, TE_mode, 1);
+
+start=[mesh.x(1) mesh.y(1) mesh.z(end-13)];
+stop =[mesh.x(end) mesh.y(end) mesh.z(end-14)];
+[CSX, port{2}] = AddRectWaveGuidePort( CSX, 0, 2, start, stop, 'z', a*unit, b*unit, TE_mode);
+
+%% define dump box... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et','FileType',1,'SubSampling','2,2,2');
+start = [mesh.x(1) mesh.y(1) mesh.z(1)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end)];
+CSX = AddBox(CSX,'Et',0 , start,stop);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Sim_Path = 'tmp_mod';
+Sim_CSX = 'rect_wg.xml';
+
+[status, message, messageid] = rmdir(Sim_Path,'s');
+[status, message, messageid] = mkdir(Sim_Path);
+
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+RunOpenEMS(Sim_Path, Sim_CSX)
+
+%% postproc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+freq = linspace(f_start,f_stop,201);
+port = calcPort(port, Sim_Path, freq);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+ZL = port{1}.uf.tot./port{1}.if.tot;
+ZL_a = port{1}.ZL; % analytic waveguide impedance
+
+%% plot s-parameter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+plot(freq*1e-6,20*log10(abs(s11)),'k-','Linewidth',2);
+xlim([freq(1) freq(end)]*1e-6);
+grid on;
+hold on;
+plot(freq*1e-6,20*log10(abs(s21)),'r--','Linewidth',2);
+l = legend('S_{11}','S_{21}','Location','Best');
+set(l,'FontSize',12);
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (MHz) \rightarrow','FontSize',12);
+
+%% compare analytic and numerical wave-impedance %%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+plot(freq*1e-6,real(ZL),'Linewidth',2);
+hold on;
+grid on;
+plot(freq*1e-6,imag(ZL),'r--','Linewidth',2);
+plot(freq*1e-6,ZL_a,'g-.','Linewidth',2);
+ylabel('ZL (\Omega)','FontSize',12);
+xlabel('frequency (MHz) \rightarrow','FontSize',12);
+xlim([freq(1) freq(end)]*1e-6);
+l = legend('\Re(Z_L)','\Im(Z_L)','Z_L analytic','Location','Best');
+set(l,'FontSize',12);
+
+%% Plot the field dumps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+dump_file = [Sim_Path '/Et.h5'];
+PlotArgs.slice = {a/2*unit b/2*unit 0};
+PlotArgs.pauseTime=0.01;
+PlotArgs.component=0;
+PlotArgs.Limit = 'auto';
+PlotHDF5FieldData(dump_file, PlotArgs)
diff --git a/openEMS/matlab/Tutorials/Simple_Patch_Antenna.m b/openEMS/matlab/Tutorials/Simple_Patch_Antenna.m
new file mode 100644
index 0000000..ee2a8f0
--- /dev/null
+++ b/openEMS/matlab/Tutorials/Simple_Patch_Antenna.m
@@ -0,0 +1,180 @@
+%
+% Tutorials / simple patch antenna
+%
+% Describtion at:
+% http://openems.de/index.php/Tutorial:_Simple_Patch_Antenna
+%
+% Tested with
+% - Matlab 2013a / Octave 4.0
+% - openEMS v0.0.33
+%
+% (C) 2010-2015 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% patch width in x-direction
+patch.width = 32; % resonant length
+% patch length in y-direction
+patch.length = 40;
+
+%substrate setup
+substrate.epsR = 3.38;
+substrate.kappa = 1e-3 * 2*pi*2.45e9 * EPS0*substrate.epsR;
+substrate.width = 60;
+substrate.length = 60;
+substrate.thickness = 1.524;
+substrate.cells = 4;
+
+%setup feeding
+feed.pos = -6; %feeding position in x-direction
+feed.R = 50; %feed resistance
+
+% size of the simulation box
+SimBox = [200 200 150];
+
+%% setup FDTD parameter & excitation function
+f0 = 2e9; % center frequency
+fc = 1e9; % 20 dB corner frequency
+FDTD = InitFDTD( 'NrTs', 30000 );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+CSX = InitCSX();
+
+%initialize the mesh with the "air-box" dimensions
+mesh.x = [-SimBox(1)/2 SimBox(1)/2];
+mesh.y = [-SimBox(2)/2 SimBox(2)/2];
+mesh.z = [-SimBox(3)/3 SimBox(3)*2/3];
+
+%% create patch
+CSX = AddMetal( CSX, 'patch' ); % create a perfect electric conductor (PEC)
+start = [-patch.width/2 -patch.length/2 substrate.thickness];
+stop = [ patch.width/2 patch.length/2 substrate.thickness];
+CSX = AddBox(CSX,'patch',10,start,stop); % add a box-primitive to the metal property 'patch'
+
+%% create substrate
+CSX = AddMaterial( CSX, 'substrate' );
+CSX = SetMaterialProperty( CSX, 'substrate', 'Epsilon', substrate.epsR, 'Kappa', substrate.kappa );
+start = [-substrate.width/2 -substrate.length/2 0];
+stop = [ substrate.width/2 substrate.length/2 substrate.thickness];
+CSX = AddBox( CSX, 'substrate', 0, start, stop );
+
+% add extra cells to discretize the substrate thickness
+mesh.z = [linspace(0,substrate.thickness,substrate.cells+1) mesh.z];
+
+%% create ground (same size as substrate)
+CSX = AddMetal( CSX, 'gnd' ); % create a perfect electric conductor (PEC)
+start(3)=0;
+stop(3) =0;
+CSX = AddBox(CSX,'gnd',10,start,stop);
+
+%% apply the excitation & resist as a current source
+start = [feed.pos 0 0];
+stop = [feed.pos 0 substrate.thickness];
+[CSX port] = AddLumpedPort(CSX, 5 ,1 ,feed.R, start, stop, [0 0 1], true);
+
+%% finalize the mesh
+% detect all edges except of the patch
+mesh = DetectEdges(CSX, mesh,'ExcludeProperty','patch');
+% detect and set a special 2D metal edge mesh for the patch
+mesh = DetectEdges(CSX, mesh,'SetProperty','patch','2D_Metal_Edge_Res', c0/(f0+fc)/unit/50);
+% generate a smooth mesh with max. cell size: lambda_min / 20
+mesh = SmoothMesh(mesh, c0/(f0+fc)/unit/20);
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%% add a nf2ff calc box; size is 3 cells away from MUR boundary condition
+start = [mesh.x(4) mesh.y(4) mesh.z(4)];
+stop = [mesh.x(end-3) mesh.y(end-3) mesh.z(end-3)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop);
+
+%% prepare simulation folder
+Sim_Path = 'tmp_Patch_Ant';
+Sim_CSX = 'patch_ant.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+%% run openEMS
+RunOpenEMS( Sim_Path, Sim_CSX);
+
+%% postprocessing & do the plots
+freq = linspace( max([1e9,f0-fc]), f0+fc, 501 );
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+
+% plot feed point impedance
+figure
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+drawnow
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%find resonance frequncy from s11
+f_res_ind = find(s11==min(s11));
+f_res = freq(f_res_ind);
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+disp( 'calculating far field at phi=[0 90] deg...' );
+
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, [-180:2:180]*pi/180, [0 90]*pi/180);
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(nf2ff.Dmax) ' (' num2str(10*log10(nf2ff.Dmax)) ' dBi)'] );
+disp( ['efficiency: nu_rad = ' num2str(100*nf2ff.Prad./port.P_inc(f_res_ind)) ' %']);
+
+% normalized directivity as polar plot
+figure
+polarFF(nf2ff,'xaxis','theta','param',[1 2],'normalize',1)
+
+% log-scale directivity plot
+figure
+plotFFdB(nf2ff,'xaxis','theta','param',[1 2])
+% conventional plot approach
+% plot( nf2ff.theta*180/pi, 20*log10(nf2ff.E_norm{1}/max(nf2ff.E_norm{1}(:)))+10*log10(nf2ff.Dmax));
+
+drawnow
+
+%%
+disp( 'calculating 3D far field pattern and dumping to vtk (use Paraview to visualize)...' );
+thetaRange = (0:2:180);
+phiRange = (0:2:360) - 180;
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180,'Verbose',1,'Outfile','3D_Pattern.h5');
+
+figure
+plotFF3D(nf2ff,'logscale',-20);
+
+
+E_far_normalized = nf2ff.E_norm{1} / max(nf2ff.E_norm{1}(:)) * nf2ff.Dmax;
+DumpFF2VTK([Sim_Path '/3D_Pattern.vtk'],E_far_normalized,thetaRange,phiRange,'scale',1e-3);
diff --git a/openEMS/matlab/Tutorials/readme b/openEMS/matlab/Tutorials/readme
new file mode 100644
index 0000000..a80dfa6
--- /dev/null
+++ b/openEMS/matlab/Tutorials/readme
@@ -0,0 +1 @@
+* Find the tutorial describtions at http://openems.de/index.php/Tutorials
diff --git a/openEMS/matlab/WriteHDF5.m b/openEMS/matlab/WriteHDF5.m
new file mode 100644
index 0000000..df6a8d7
--- /dev/null
+++ b/openEMS/matlab/WriteHDF5.m
@@ -0,0 +1,73 @@
+function WriteHDF5(filename,hdf_fielddata,hdf_mesh)
+% function WriteHDF5(filename,hdf_fielddata,hdf_mesh)
+%
+% input:
+% hdf_fielddata.time
+% hdf_fielddata.names
+% hdf_fielddata.values
+% hdf_mesh.type
+% hdf_mesh.names
+% hdf_mesh.lines
+%
+% openEMS matlab interface
+% -----------------------
+% (C) 2010 Sebastian Held <sebastian.held@uni-due.de>
+% See also ReadHDF5FieldData ReadHDF5Mesh
+
+isOctave = exist('OCTAVE_VERSION','builtin') ~= 0;
+if isOctave
+ WriteHDF5_octave(filename,hdf_fielddata,hdf_mesh);
+ return
+end
+
+writemode = 'overwrite';
+if isfield( hdf_fielddata, 'TD' )
+ % this is a time domain data set
+ time = hdf_fielddata.TD.time;
+ for n=1:numel(time)
+ name = ['/FieldData/TD/' int2str(n)];
+ [details.Location, details.Name] = fileparts(name);
+ attribute_details.AttachedTo = name;
+ attribute_details.AttachType = 'dataset';
+ attribute_details.Name = 'time';
+ hdf5write( filename, details, hdf_fielddata.TD.values{n}, ...
+ attribute_details, time(n), ...
+ 'WriteMode', writemode );
+ writemode = 'append';
+ end
+end
+if isfield( hdf_fielddata, 'FD' )
+ % this is a frequency domain data set
+ freq = hdf_fielddata.FD.frequency;
+ for n=1:numel(freq)
+ name = ['/FieldData/FD/f' int2str(n-1) '_real'];
+ [details.Location, details.Name] = fileparts(name);
+ hdf5write( filename, details, real(hdf_fielddata.FD.values{n}), ...
+ 'WriteMode', writemode );
+ name = ['/FieldData/FD/f' int2str(n-1) '_imag'];
+ [details.Location, details.Name] = fileparts(name);
+ hdf5write( filename, details, imag(hdf_fielddata.FD.values{n}), ...
+ 'WriteMode', 'append' );
+ writemode = 'append';
+ end
+ name = '/FieldData/FD';
+ [details.Location, details.Name] = fileparts(name);
+ attribute_details.AttachedTo = name;
+ attribute_details.AttachType = 'group';
+ attribute_details.Name = 'frequency';
+ hdf5write( filename, attribute_details, freq, ...
+ 'WriteMode', 'append' );
+end
+
+names = hdf_mesh.names; % names is a cell array
+for n=1:numel(names)
+ [details.Location, details.Name, ext] = fileparts(names{n});
+ details.Name = [details.Name ext];
+ hdf5write( filename, details, hdf_mesh.lines{n}, ...
+ 'WriteMode', 'append' );
+end
+
+
+
+function WriteHDF5_octave(filename,hdf_fielddata,hdf_mesh)
+error 'not yet implemented'
diff --git a/openEMS/matlab/WriteOpenEMS.m b/openEMS/matlab/WriteOpenEMS.m
new file mode 100644
index 0000000..d7c9cbd
--- /dev/null
+++ b/openEMS/matlab/WriteOpenEMS.m
@@ -0,0 +1,19 @@
+function WriteOpenEMS(filename, FDTD, CSX)
+% function WriteOpenEMS(filename, FDTD, CSX)
+%
+% Write the FDTD and CSX structures to a file.
+%
+% example:
+% CSX = InitCSX();
+% FDTD = InitFDTD();
+% WriteOpenEMS('test.xml',FDTD,CSX)
+%
+% See also InitFDTD InitCSX CSXGeomPlot
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig
+
+openEMS.FDTD = FDTD;
+openEMS.ContinuousStructure = CSX;
+struct_2_xml(filename,openEMS,'openEMS'); \ No newline at end of file
diff --git a/openEMS/matlab/calcLumpedPort.m b/openEMS/matlab/calcLumpedPort.m
new file mode 100644
index 0000000..69dba69
--- /dev/null
+++ b/openEMS/matlab/calcLumpedPort.m
@@ -0,0 +1,107 @@
+function [port] = calcLumpedPort( port, SimDir, f, varargin)
+% [port] = calcLumpedPort( port, SimDir, f, varargin)
+%
+% Calculate voltages and currents of given lumped port.
+%
+% The port has to be created by e.g. AddLumpedPort().
+%
+% input:
+% port: return value of e.g. AddMSLPort()
+% SimDir: directory, where the simulation files are
+% f: frequency vector for DFT
+%
+% variable input:
+% 'RefImpedance': - use a given reference impedance to calculate inc and
+% ref voltages and currents
+% - default is given port or calculated line impedance
+% 'SwitchDirection': 0/1, switch assumed direction of propagation
+%
+% output:
+% % output signals/values in time domain (TD):
+% port.ut.tot total voltage (time-domain)
+% port.ut.time voltage time vector
+% port.it.tot total current (time-domain)
+% port.it.time current time vector
+%
+% % output signals/values in frequency domain (FD):
+% port.f the given frequency fector
+% port.uf.tot/inc/ref total, incoming and reflected voltage
+% port.if.tot/inc/ref total, incoming and reflected current
+%
+% example:
+% port{1} = calcLumpedPort( port{1}, Sim_Path, f, 'RefImpedance', 50);
+%
+% openEMS matlab interface
+% -----------------------
+% (C) 2012 Thorsten Liebig <thorsten.liebig@gmx.de>
+%
+% See also AddLumpedPort, calcPort
+
+if (iscell(port))
+ for n=1:numel(port)
+ port{n}=calcLumpedPort(port{n}, SimDir, f, varargin{:});
+ end
+ return;
+end
+
+if (strcmpi(port.type,'Lumped')~=1 && strcmpi(port.type,'Curve')~=1)
+ error('openEMS:calcLumpedPort','error, type is not a lumped port');
+end
+
+
+%% read optional arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%set defaults
+ref_ZL = port.Feed_R;
+switch_dir = 1;
+
+UI_args = {};
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'RefImpedance')==1);
+ ref_ZL = varargin{n+1};
+ elseif (strcmpi(varargin{n},'SwitchDirection')==1);
+ if (varargin{n+1})
+ switch_dir = -1;
+ end
+ else
+ UI_args(end+1) = varargin(n);
+ UI_args(end+1) = varargin(n+1);
+ end
+end
+
+port.ZL_ref = ref_ZL;
+
+% read time domain data
+U = ReadUI( port.U_filename, SimDir, f, UI_args{:} );
+I = ReadUI( port.I_filename, SimDir, f, UI_args{:} );
+
+% store the original frequency domain waveforms
+u_f = U.FD{1}.val;
+i_f = switch_dir*I.FD{1}.val;
+
+port.ut.time = U.TD{1}.t;
+port.ut.tot = U.TD{1}.val;
+
+port.it.time = I.TD{1}.t;
+port.it.tot = switch_dir*I.TD{1}.val;
+
+port.Zin = u_f./i_f;
+
+port.f = f;
+uf_inc = 0.5 * ( u_f + i_f .* ref_ZL );
+if_inc = 0.5 * ( i_f + u_f ./ ref_ZL );
+
+uf_ref = u_f - uf_inc;
+if_ref = if_inc - i_f;
+
+port.uf.tot = u_f;
+port.uf.inc = uf_inc;
+port.uf.ref = uf_ref;
+
+port.if.tot = i_f;
+port.if.inc = if_inc;
+port.if.ref = if_ref;
+
+port.raw.U = U;
+port.raw.I = I;
diff --git a/openEMS/matlab/calcPort.m b/openEMS/matlab/calcPort.m
new file mode 100644
index 0000000..9b56955
--- /dev/null
+++ b/openEMS/matlab/calcPort.m
@@ -0,0 +1,82 @@
+function [port] = calcPort( port, SimDir, f, varargin)
+% [port] = calcPort( port, SimDir, f, varargin)
+%
+% Calculate:
+% - voltages and currents
+% - the propagation constant and the characteristic impedance (if applicable)
+%
+% The port has to be created by e.g. AddMSLPort(), AddLumpedPort() or AddCurvePort
+%
+% input:
+% port: return value of AddMSLPort()
+% SimDir: directory, where the simulation files are
+% f: frequency vector for DFT
+%
+% variable input:
+% 'RefImpedance': - use a given reference impedance to calculate inc and
+% ref voltages and currents
+% - default is given port or calculated line impedance
+% 'RefPlaneShift': for transmission lines only, See also calcTLPort for
+% more details
+% 'SwitchDirection': 0/1, switch assumed direction of propagation
+% 'SignalType': 'pulse' (default) or 'periodic'
+%
+% output:
+% % output signals/values in time domain (TD):
+% port.ut.tot total voltage (time-domain)
+% port.ut.time voltage time vector
+% port.it.tot total current (time-domain)
+% port.it.time current time vector
+%
+% % output signals/values in frequency domain (FD):
+% port.f the given frequency fector
+% port.uf.tot/inc/ref total, incoming and reflected voltage
+% port.if.tot/inc/ref total, incoming and reflected current
+% port.ZL_ref used refernce impedance
+%
+% port.P_inc incoming power
+% port.P_ref reflected power
+% port.P_acc accepted power (incoming minus reflected,
+% may be negative for passive ports)
+%
+% if port is a transmission line port:
+% port.beta: propagation constant
+% port.ZL: characteristic line impedance
+%
+% example:
+% port = calcPort(port, Sim_Path, f, 'RefImpedance', 50);
+%
+% openEMS matlab interface
+% -----------------------
+% (C) 2012 Thorsten Liebig <thorsten.liebig@gmx.de>
+%
+% See also AddMSLPort, AddLumpedPort, AddCurvePort, calcTLPort, calcLumpedPort
+
+if (iscell(port))
+ for n=1:numel(port)
+ port{n}=calcPort(port{n}, SimDir, f, varargin{:});
+ end
+ return;
+end
+
+if isempty(port)
+ return;
+end
+
+if (strcmpi(port.type,'MSL') || strcmpi(port.type,'Coaxial') || strcmpi(port.type,'StripLine') || strcmpi(port.type,'CPW'))
+ port = calcTLPort( port, SimDir, f, varargin{:});
+elseif strcmpi(port.type,'WaveGuide')
+ port = calcWGPort( port, SimDir, f, varargin{:});
+elseif (strcmpi(port.type,'Lumped') || strcmpi(port.type,'Curve'))
+ port = calcLumpedPort( port, SimDir, f, varargin{:});
+else
+ error 'unknown port type'
+end
+
+% calc some more port parameter
+% incoming power
+port.P_inc = 0.5*real(port.uf.inc.*conj(port.if.inc));
+% reflected power
+port.P_ref = 0.5*real(port.uf.ref.*conj(port.if.ref));
+% accepted power (incoming - reflected)
+port.P_acc = 0.5*real(port.uf.tot.*conj(port.if.tot));
diff --git a/openEMS/matlab/calcTLPort.m b/openEMS/matlab/calcTLPort.m
new file mode 100644
index 0000000..3a631ba
--- /dev/null
+++ b/openEMS/matlab/calcTLPort.m
@@ -0,0 +1,173 @@
+function [port] = calcTLPort( port, SimDir, f, varargin)
+% [port] = calcTLPort( port, SimDir, f, varargin)
+%
+% Calculate voltages and currents, the propagation constant beta
+% and the characteristic impedance ZL of the given transmission line port.
+%
+% The port has to be created by e.g. AddMSLPort().
+%
+% input:
+% port: return value of e.g. AddMSLPort()
+% SimDir: directory, where the simulation files are
+% f: frequency vector for DFT
+%
+% variable input:
+% 'RefImpedance': - use a given reference impedance to calculate inc and
+% ref voltages and currents
+% - default is given port or calculated line impedance
+% 'RefPlaneShift': - use a given reference plane shift from port beginning
+% for a desired phase correction
+% - default is the measurement plane
+% - the plane shift has to be given in drawing units!
+% 'SwitchDirection': 0/1, switch assumed direction of propagation
+%
+% output:
+% % output signals/values in time domain (TD):
+% port.ut.tot total voltage (time-domain)
+% port.ut.time voltage time vector
+% port.it.tot total current (time-domain)
+% port.it.time current time vector
+%
+% % output signals/values in frequency domain (FD):
+% port.f the given frequency fector
+% port.uf.tot/inc/ref total, incoming and reflected voltage
+% port.if.tot/inc/ref total, incoming and reflected current
+% port.beta: propagation constant
+% port.ZL: characteristic line impedance
+% port.ZL_ref used refernce impedance
+%
+% example:
+% port{1} = calcTLPort( port{1}, Sim_Path, f, 'RefImpedance', 50);
+%
+% reference: W. K. Gwarek, "A Differential Method of Reflection Coefficient Extraction From FDTD Simulations",
+% IEEE Microwave and Guided Wave Letters, Vol. 6, No. 5, May 1996
+%
+% openEMS matlab interface
+% -----------------------
+% (C) 2010 Sebastian Held <sebastian.held@uni-due.de>
+%
+% See also AddMSLPort, calcPort
+
+if (iscell(port))
+ for n=1:numel(port)
+ port{n}=calcTLPort(port{n}, SimDir, f, varargin{:});
+ end
+ return;
+end
+
+if ((strcmpi(port.type,'MSL')~=1) && (strcmpi(port.type,'Coaxial')~=1) && (strcmpi(port.type,'StripLine')~=1) && (strcmpi(port.type,'CPW')~=1))
+ error('openEMS:calcTLPort','error, type is not a transmission line port');
+end
+
+% check
+if abs((port.v_delta(1) - port.v_delta(2)) / port.v_delta(1))>1e-6
+ warning( 'openEMS:calcPort:mesh', 'mesh is not equidistant; expect degraded accuracy' );
+end
+
+
+%% read optional arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%set defaults
+ref_ZL = -1;
+ref_shift = nan;
+switch_dir = 1;
+
+UI_args = {};
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'RefPlaneShift')==1);
+ ref_shift = varargin{n+1};
+ elseif (strcmp(varargin{n},'RefImpedance')==1);
+ ref_ZL = varargin{n+1};
+ elseif (strcmpi(varargin{n},'SwitchDirection')==1);
+ if (varargin{n+1})
+ switch_dir = -1;
+ end
+ else
+ UI_args(end+1) = varargin(n);
+ UI_args(end+1) = varargin(n+1);
+ end
+end
+
+if ((strcmpi(port.type,'StripLine')==1) || (strcmpi(port.type,'CPW')==1))
+ U1 = ReadUI( port.U_filename(:,1), SimDir, f, UI_args{:} );
+ U2 = ReadUI( port.U_filename(:,1), SimDir, f, UI_args{:} );
+ U = U1;
+ for n=1:3
+ U.TD{n}.val = U1.TD{n}.val+U2.TD{n}.val;
+ U.FD{n}.val = U1.FD{n}.val+U2.FD{n}.val;
+ end
+else
+ U = ReadUI( port.U_filename, SimDir, f, UI_args{:} );
+end
+% read time domain data (multiples files)
+I = ReadUI( port.I_filename, SimDir, f, UI_args{:} );
+
+% time domain signals
+port.ut.time = U.TD{2}.t;
+port.ut.tot = U.TD{2}.val;
+
+port.it.time = I.TD{1}.t;
+port.it.tot = switch_dir*(I.TD{1}.val + I.TD{2}.val) / 2; % interpolate to same position as v
+
+% store the original frequency domain waveforms
+u_f = U.FD{2}.val;
+i_f = switch_dir*(I.FD{1}.val + I.FD{2}.val) / 2; % shift to same position as v
+
+f = U.FD{2}.f;
+Et = U.FD{2}.val;
+dEt = (U.FD{3}.val - U.FD{1}.val) / (sum(abs(port.v_delta(1:2))) * port.drawingunit);
+Ht = (I.FD{1}.val + I.FD{2}.val)/2; % space averaging: Ht is now defined at the same pos as Et
+dHt = (I.FD{2}.val - I.FD{1}.val) / (abs(port.i_delta(1)) * port.drawingunit);
+
+beta = sqrt( - dEt .* dHt ./ (Ht .* Et) );
+beta(real(beta) < 0) = -beta(real(beta) < 0); % determine correct sign (unlike the paper)
+
+% determine ZL
+ZL = sqrt(Et .* dEt ./ (Ht .* dHt));
+
+% if (strcmpi(port.type,'Coaxial'))
+% port.ZL = Z0/2/pi/ref_index*log(port.r_o/port.r_i);
+% end
+
+% reference plane shift (lossless)
+if ~isnan(ref_shift)
+ ref_shift = ref_shift * port.LengthScale;
+ % shift to the beginning of MSL
+ ref_shift = ref_shift - port.measplanepos;
+ ref_shift = ref_shift * port.drawingunit;
+
+ % store the shifted frequency domain waveforms
+ phase = real(beta)*ref_shift;
+ U.FD{1}.val = u_f .* cos(-phase) + 1i * i_f.*ZL .* sin(-phase);
+ I.FD{1}.val = i_f .* cos(-phase) + 1i * u_f./ZL .* sin(-phase);
+
+ u_f = U.FD{1}.val;
+ i_f = I.FD{1}.val;
+end
+
+if (ref_ZL < 0)
+ ref_ZL = ZL;
+end
+
+port.ZL = ZL;
+port.beta = beta;
+port.ZL_ref = ref_ZL;
+
+port.f = f;
+uf_inc = 0.5 * ( u_f + i_f .* ref_ZL );
+if_inc = 0.5 * ( i_f + u_f ./ ref_ZL );
+
+uf_ref = u_f - uf_inc;
+if_ref = if_inc - i_f;
+
+port.uf.tot = u_f;
+port.uf.inc = uf_inc;
+port.uf.ref = uf_ref;
+
+port.if.tot = i_f;
+port.if.inc = if_inc;
+port.if.ref = if_ref;
+
+port.raw.U = U;
+port.raw.I = I;
diff --git a/openEMS/matlab/calcWGPort.m b/openEMS/matlab/calcWGPort.m
new file mode 100644
index 0000000..ba845af
--- /dev/null
+++ b/openEMS/matlab/calcWGPort.m
@@ -0,0 +1,145 @@
+function [port] = calcWGPort( port, SimDir, f, varargin)
+% [port] = calcWGPort( port, SimDir, f, varargin)
+%
+% Calculate voltages and currents, the propagation constant beta
+% and the characteristic impedance ZL of the given waveguide port.
+%
+% The port has to be created by e.g. AddWaveGuidePort().
+%
+% input:
+% port: return value of e.g. AddWaveGuidePort()
+% SimDir: directory, where the simulation files are
+% f: frequency vector for DFT
+%
+% variable input:
+% 'RefImpedance': - use a given reference impedance to calculate inc and
+% ref voltages and currents
+% - default is given port or calculated line impedance
+% 'RefPlaneShift': - use a given reference plane shift from port beginning
+% for a desired phase correction
+% - default is the measurement plane at the end of the
+% port
+% - the plane shift has to be given in drawing units!
+% 'RefractiveIndex': set a material refractive index
+% 'SwitchDirection': 0/1, switch assumed direction of propagation
+%
+% output:
+% % output signals/values in time domain (TD):
+% port.ut.tot total voltage (time-domain)
+% port.ut.time voltage time vector
+% port.it.tot total current (time-domain)
+% port.it.time current time vector
+%
+% % output signals/values in frequency domain (FD):
+% port.f the given frequency fector
+% port.uf.tot/inc/ref total, incoming and reflected voltage
+% port.if.tot/inc/ref total, incoming and reflected current
+% port.beta: propagation constant
+% port.ZL: characteristic line impedance
+% port.ZL_ref used reference impedance
+%
+% example:
+% port{1} = calcWGPort( port{1}, Sim_Path, f, 'RefImpedance', 50);
+%
+% openEMS matlab interface
+% -----------------------
+% (C) 2013 Thorsten Liebig (thorsten.liebig@gmx.de)
+%
+% See also AddWaveGuidePort, calcPort
+
+if (iscell(port))
+ for n=1:numel(port)
+ port{n}=calcWGPort(port{n}, SimDir, f, varargin{:});
+ end
+ return;
+end
+
+if (strcmpi(port.type,'WaveGuide')~=1)
+ error('openEMS:calcWGPort','error, type is not a waveguide port');
+end
+
+%set defaults
+ref_ZL = -1;
+ref_shift = nan;
+ref_index = 1;
+switch_dir = 1;
+
+UI_args = {};
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'RefPlaneShift')==1);
+ ref_shift = varargin{n+1};
+ elseif (strcmp(varargin{n},'RefImpedance')==1);
+ ref_ZL = varargin{n+1};
+ elseif (strcmp(varargin{n},'RefractiveIndex')==1);
+ ref_index = varargin{n+1};
+ elseif (strcmpi(varargin{n},'SwitchDirection')==1);
+ if (varargin{n+1})
+ switch_dir = -1;
+ end
+ else
+ UI_args(end+1) = varargin(n);
+ UI_args(end+1) = varargin(n+1);
+ end
+end
+
+% read time domain data
+U = ReadUI( port.U_filename, SimDir, f, UI_args{:} );
+I = ReadUI( port.I_filename, SimDir, f, UI_args{:} );
+
+% store the original frequency domain waveforms
+u_f = U.FD{1}.val;
+i_f = I.FD{1}.val * switch_dir;
+
+% time domain signal
+port.ut.time = U.TD{1}.t;
+port.ut.tot = U.TD{1}.val;
+
+port.it.time = I.TD{1}.t;
+port.it.tot = switch_dir*I.TD{1}.val;
+
+
+physical_constants
+k = 2*pi*f/C0*ref_index;
+fc = C0*port.kc/2/pi/ref_index;
+port.beta = sqrt(k.^2 - port.kc^2);
+port.ZL = k * Z0 ./ port.beta; %analytic waveguide impedance
+
+% reference plane shift (lossless)
+if ~isnan(ref_shift)
+ % shift relative to the beginning of the waveguide
+ ref_shift = ref_shift - port.measplanepos;
+ ref_shift = ref_shift * port.drawingunit;
+
+ % store the shifted frequency domain waveforms
+ phase = real(beta)*ref_shift;
+ u_f_shift = u_f .* cos(-phase) + 1i * i_f.*port.ZL .* sin(-phase);
+ i_f_shift = i_f .* cos(-phase) + 1i * u_f./port.ZL .* sin(-phase);
+
+ u_f = u_f_shift;
+ i_f = i_f_shift;
+end
+
+if (ref_ZL < 0)
+ ref_ZL = port.ZL;
+end
+
+port.ZL_ref = ref_ZL;
+
+port.f = f;
+uf_inc = 0.5 * ( u_f + i_f .* ref_ZL );
+if_inc = 0.5 * ( i_f + u_f ./ ref_ZL );
+
+uf_ref = u_f - uf_inc;
+if_ref = if_inc - i_f;
+
+port.uf.tot = u_f;
+port.uf.inc = uf_inc;
+port.uf.ref = uf_ref;
+
+port.if.tot = i_f;
+port.if.inc = if_inc;
+port.if.ref = if_ref;
+
+port.raw.U = U;
+port.raw.I = I;
diff --git a/openEMS/matlab/calc_ypar.m b/openEMS/matlab/calc_ypar.m
new file mode 100644
index 0000000..f6ae1bd
--- /dev/null
+++ b/openEMS/matlab/calc_ypar.m
@@ -0,0 +1,69 @@
+function Y = calc_ypar( f, ports, Sim_Path_Prefix )
+% Y = calc_ypar( f, ports, Sim_Path_Prefix )
+%
+% f: frequency vector (Hz)
+% ports: cell array of ports (see AddMSLPort() and AddLumpedPort())
+% Sim_Path_Prefix: prefix of the simulation dirs (will be postfixed by
+% excitation port number)
+%
+% This function calculates the Y-matrix representation of the ports
+%
+% It is assumed that each port (inside ports) is excited and the
+% corresponding simulation was carried out at Sim_Path + portnr (e.g. for
+% port 2: '/tmp/sim2')
+%
+% Sebastian Held <sebastian.held@uni-due.de>
+% Jun 9 2010
+%
+% See also AddMSLPort AddLumpedPort
+
+% sanitize input arguments
+f = reshape(f,1,[]); % make it a row vector
+
+% prepare result matrix
+maxportnr = max( cellfun(@(x) x.nr, ports) );
+Y = ones(maxportnr,maxportnr,numel(f)) * NaN;
+U = ones(maxportnr,maxportnr,numel(f)) * NaN;
+I = ones(maxportnr,maxportnr,numel(f)) * NaN;
+
+% read time domain simulation results
+for runnr = 1:numel(ports)
+ Sim_Path = [Sim_Path_Prefix num2str(ports{runnr}.nr)];
+ for pnr = 1:numel(ports)
+ if isfield( ports{pnr}, 'v_delta' )
+ % this is an MSLPort
+ temp_U = ReadUI( ['port_ut' num2str(ports{pnr}.nr) 'B'], Sim_Path );
+ temp = ReadUI( {['port_it' num2str(ports{pnr}.nr) 'A'],['port_it' num2str(ports{pnr}.nr) 'B']}, Sim_Path );
+ temp_I.TD{1}.t = temp.TD{1}.t;
+ temp_I.TD{1}.val = (temp.TD{1}.val + temp.TD{2}.val) / 2; % space averaging
+ else
+ % this is a lumped port
+ temp_U = ReadUI( ['port_ut' num2str(ports{pnr}.nr)], Sim_Path );
+ temp_I = ReadUI( ['port_it' num2str(ports{pnr}.nr)], Sim_Path );
+
+% % correct the orientation of the probes (FIXME to be done inside
+% % openEMS)
+% temp_U.TD{1}.val = temp_U.TD{1}.val * (-ports{pnr}.direction);
+ end
+
+% % correct the orientation of the probes (FIXME to be done inside
+% % openEMS)
+% temp_I.TD{1}.val = temp_I.TD{1}.val * ports{pnr}.direction;
+% if runnr == 5 % DEBUG
+% temp_I.TD{1}.val = temp_I.TD{1}.val * -1;
+% end
+
+ % time domain -> frequency domain
+ U(ports{pnr}.nr,ports{runnr}.nr,:) = DFT_time2freq( temp_U.TD{1}.t, temp_U.TD{1}.val, f );
+ I(ports{pnr}.nr,ports{runnr}.nr,:) = DFT_time2freq( temp_I.TD{1}.t, temp_I.TD{1}.val, f );
+
+ % compensate H-field time advance
+ delta_t_2 = temp_I.TD{1}.t(1) - temp_U.TD{1}.t(1); % half time-step (s)
+ I(ports{pnr}.nr,ports{runnr}.nr,:) = squeeze(I(ports{pnr}.nr,ports{runnr}.nr,:)).' .* exp(-1i*2*pi*f*delta_t_2);
+ end
+end
+
+% calc Y-parameters
+for a=1:numel(f)
+ Y(:,:,a) = I(:,:,a) / U(:,:,a);
+end
diff --git a/openEMS/matlab/examples/__deprecated__/MSL2.m b/openEMS/matlab/examples/__deprecated__/MSL2.m
new file mode 100644
index 0000000..31a2600
--- /dev/null
+++ b/openEMS/matlab/examples/__deprecated__/MSL2.m
@@ -0,0 +1,254 @@
+%
+% EXAMPLE / microstrip / MSL2
+%
+% This example shows how to use the MSL-port.
+% The MSL is excited at the center of the computational volume. The
+% boundary at xmin is an absorbing boundary (Mur) and at xmax an electric
+% wall. The reflection coefficient at this wall is S11 = -1.
+% Direction of propagation is x.
+%
+% This example demonstrates:
+% - simple microstrip geometry (made of PEC)
+% - MSL port
+% - MSL analysis
+%
+% You may modify the PEC boundary condition at xmax to become a MUR
+% boundary. This resembles a matched microstrip line.
+%
+% Tested with
+% - Matlab 2009b
+% - Octave 3.3.52
+% - openEMS v0.0.14
+%
+% (C) 2010 Sebastian Held <sebastian.held@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches
+postproc_only = 0;
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+MSL_length = 10000;
+MSL_width = 1000;
+substrate_thickness = 254;
+substrate_epr = 3.66;
+
+% mesh_res = [200 0 0];
+
+%% prepare simulation folder
+Sim_Path = 'tmp';
+Sim_CSX = 'msl2.xml';
+if ~postproc_only
+ [status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+ [status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+end
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+max_timesteps = 20000;
+min_decrement = 1e-6;
+f_max = 7e9;
+FDTD = InitFDTD( max_timesteps, min_decrement, 'OverSampling', 10 );
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = {'MUR' 'MUR' 'PEC' 'PEC' 'PEC' 'PMC'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+resolution = c0/(f_max*sqrt(substrate_epr))/unit /50; % resolution of lambda/50
+mesh.x = SmoothMeshLines( [-MSL_length MSL_length], resolution );
+mesh.y = SmoothMeshLines( [-4*MSL_width -MSL_width/2 MSL_width/2 4*MSL_width], resolution );
+mesh.z = SmoothMeshLines( [linspace(0,substrate_thickness,5) 10*substrate_thickness], resolution );
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% substrate
+CSX = AddMaterial( CSX, 'RO4350B' );
+CSX = SetMaterialProperty( CSX, 'RO4350B', 'Epsilon', substrate_epr );
+start = [mesh.x(1), mesh.y(1), 0];
+stop = [mesh.x(end), mesh.y(end), substrate_thickness];
+CSX = AddBox( CSX, 'RO4350B', 0, start, stop );
+
+%% MSL port
+CSX = AddMetal( CSX, 'PEC' );
+portstart = [ 0, -MSL_width/2, substrate_thickness];
+portstop = [ MSL_length, MSL_width/2, 0];
+[CSX,portstruct] = AddMSLPort( CSX, 999, 1, 'PEC', portstart, portstop, [1 0 0], [0 0 1], [], 'excite' );
+
+%% MSL
+start = [-MSL_length, -MSL_width/2, substrate_thickness];
+stop = [ 0, MSL_width/2, substrate_thickness];
+CSX = AddBox( CSX, 'PEC', 999, start, stop ); % priority needs to be higher than
+
+%% define dump boxes
+start = [mesh.x(1), mesh.y(1), substrate_thickness/2];
+stop = [mesh.x(end), mesh.y(end), substrate_thickness/2];
+CSX = AddDump( CSX, 'Et_', 'DumpType', 0,'DumpMode', 2 ); % cell interpolated
+CSX = AddBox( CSX, 'Et_', 0, start, stop );
+CSX = AddDump( CSX, 'Ht_', 'DumpType', 1,'DumpMode', 2 ); % cell interpolated
+CSX = AddBox( CSX, 'Ht_', 0, start, stop );
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure
+if ~postproc_only
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+end
+
+%% run openEMS
+openEMS_opts = '';
+openEMS_opts = [openEMS_opts ' --engine=fastest'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+% openEMS_opts = [openEMS_opts ' --debug-PEC'];
+if ~postproc_only
+ RunOpenEMS( Sim_Path, Sim_CSX, openEMS_opts );
+end
+
+
+%% postprocess
+f = linspace( 1e6, f_max, 1601 );
+U = ReadUI( {'port_ut1A','port_ut1B','port_ut1C','et'}, 'tmp/', f );
+I = ReadUI( {'port_it1A','port_it1B'}, 'tmp/', f );
+
+% Z = (U.FD{1}.val+U.FD{2}.val)/2 ./ I.FD{1}.val;
+% plot( f*1e-9, [real(Z);imag(Z)],'Linewidth',2);
+% xlabel('frequency (GHz)');
+% ylabel('impedance (Ohm)');
+% grid on;
+% legend( {'real','imaginary'}, 'location', 'northwest' )
+% title( 'line impedance (will fail in case of reflections!)' );
+
+figure
+ax = plotyy( U.TD{1}.t/1e-6, [U.TD{1}.val;U.TD{2}.val;U.TD{3}.val], U.TD{4}.t/1e-6, U.TD{4}.val );
+xlabel( 'time (us)' );
+ylabel( 'amplitude (V)' );
+grid on
+title( 'Time domain voltage probes and excitation signal' );
+legend( {'ut1A','ut1B','ut1C','excitation'} );
+% now make the y-axis symmetric to y=0 (align zeros of y1 and y2)
+y1 = ylim(ax(1));
+y2 = ylim(ax(2));
+ylim( ax(1), [-max(abs(y1)) max(abs(y1))] );
+ylim( ax(2), [-max(abs(y2)) max(abs(y2))] );
+
+figure
+plot( I.TD{1}.t/1e-6, [I.TD{1}.val;I.TD{2}.val] );
+xlabel( 'time (us)' );
+ylabel( 'amplitude (A)' );
+grid on
+title( 'Time domain current probes' );
+legend( {'it1A','it1B'} );
+
+figure
+ax = plotyy( U.FD{1}.f/1e9, abs([U.FD{1}.val;U.FD{2}.val;U.FD{3}.val]), U.FD{1}.f/1e9, angle([U.FD{1}.val;U.FD{2}.val;U.FD{3}.val])/pi*180 );
+xlabel( 'frequency (GHz)' );
+ylabel( ax(1), 'amplitude (A)' );
+ylabel( ax(2), 'phase (deg)' );
+grid on
+title( 'Frequency domain voltage probes' );
+legend( {'abs(uf1A)','abs(uf1B)','abs(uf1C)','angle(uf1A)','angle(uf1B)','angle(uf1C)'} );
+
+figure
+ax = plotyy( I.FD{1}.f/1e9, abs([I.FD{1}.val;I.FD{2}.val]), I.FD{1}.f/1e9, angle([I.FD{1}.val;I.FD{2}.val])/pi*180 );
+xlabel( 'frequency (GHz)' );
+ylabel( ax(1), 'amplitude (A)' );
+ylabel( ax(2), 'phase (deg)' );
+grid on
+title( 'Frequency domain current probes' );
+legend( {'abs(if1A)','abs(if1B)','angle(if1A)','angle(if1B)'} );
+
+%% port analysis
+[U,I,beta,ZL] = calcPort( portstruct, Sim_Path, f );
+%% attention! the reflection coefficient S11 is normalized to ZL!
+
+figure
+plot( sin(0:0.01:2*pi), cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+hold on
+plot( 0.5+0.5*sin(0:0.01:2*pi), 0.5*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+plot( [-1 1], [0 0], 'Color', [.7 .7 .7] );
+plot( S11, 'k' );
+plot( real(S11(1)), imag(S11(1)), '*r' );
+axis equal
+title( 'Reflection coefficient S11 at the measurement plane' );
+
+figure
+plot( sin(0:0.01:2*pi), cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+hold on
+plot( 0.5+0.5*sin(0:0.01:2*pi), 0.5*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+plot( [-1 1], [0 0], 'Color', [.7 .7 .7] );
+Z = vi.FD.v.val ./ vi.FD.i.val;
+S11_ = (Z-ZL) ./ (Z+ZL);
+plot( S11_, 'k' );
+plot( real(S11_(1)), imag(S11_(1)), '*r' );
+axis equal
+title( {'Reflection coefficient S11 at the measurement plane' 'calculated from voltages and currents'} );
+
+figure
+plot( f/1e9, [real(S11);imag(S11)], 'Linewidth',2 );
+legend( {'Re(S11)', 'Im(S11)'} );
+ylabel( 'amplitude' );
+xlabel( 'frequency (GHz)' );
+title( 'Reflection coefficient S11 at the measurement plane' );
+
+figure
+plotyy( f/1e9, 20*log10(abs(S11)), f/1e9, angle(S11)/pi*180 );
+legend( {'|S11|', 'angle(S11)'} );
+xlabel( 'frequency (GHz)' );
+ylabel( '|S11| (dB)' );
+title( 'Reflection coefficient S11 at the measurement plane' );
+
+figure
+plot( f/1e9, [real(beta);imag(beta)], 'Linewidth',2 );
+legend( 'Re(beta)', 'Im(beta)' );
+ylabel( 'propagation constant beta (1/m)' );
+xlabel( 'frequency (GHz)' );
+title( 'Propagation constant of the MSL' );
+
+figure
+plot( f/1e9, [real(ZL);imag(ZL)], 'Linewidth',2);
+xlabel('frequency (GHz)');
+ylabel('impedance (Ohm)');
+grid on;
+legend( {'real','imaginary'}, 'location', 'northeast' )
+title( 'Characteristic line impedance ZL' );
+
+%% reference plane shift (to the end of the port)
+ref_shift = abs(portstop(1) - portstart(1));
+[U, I,beta,ZL] = calcPort( portstruct, Sim_Path, f );
+%%
+
+figure
+plotyy( f/1e9, 20*log10(abs(S11)), f/1e9, angle(S11)/pi*180 );
+legend( {'abs(S11)', 'angle(S11)'} );
+xlabel( 'frequency (GHz)' );
+title( 'Reflection coefficient S11 at the reference plane (at the electric wall)' );
+
+figure
+plot( sin(0:0.01:2*pi), cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+hold on
+plot( 0.5+0.5*sin(0:0.01:2*pi), 0.5*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+plot( [-1 1], [0 0], 'Color', [.7 .7 .7] );
+plot( S11, 'k' );
+plot( real(S11(1)), imag(S11(1)), '*r' );
+axis equal
+title( 'Reflection coefficient S11 at the reference plane (at the electric wall)' );
+
+figure
+plot( sin(0:0.01:2*pi), cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+hold on
+plot( 0.5+0.5*sin(0:0.01:2*pi), 0.5*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+plot( [-1 1], [0 0], 'Color', [.7 .7 .7] );
+Z = vi.FD.v.val_shifted ./ vi.FD.i.val_shifted;
+S11_ = (Z-ZL) ./ (Z+ZL);
+plot( S11_, 'k' );
+plot( real(S11_(1)), imag(S11_(1)), '*r' );
+axis equal
+title( {'Reflection coefficient S11 at the reference plane (at the electric wall)' 'calculated from shifted voltages and currents'} );
+
+%% visualize electric and magnetic fields
+% you will find vtk dump files in the simulation folder (tmp/)
+% use paraview to visualize them
diff --git a/openEMS/matlab/examples/antennas/Bi_Quad_Antenna.m b/openEMS/matlab/examples/antennas/Bi_Quad_Antenna.m
new file mode 100644
index 0000000..80ae97f
--- /dev/null
+++ b/openEMS/matlab/examples/antennas/Bi_Quad_Antenna.m
@@ -0,0 +1,139 @@
+%
+% Tutorials / bi-quad antenna
+%
+% Tested with
+% - Octave 3.8.1
+% - openEMS v0.0.32
+%
+% (C) 2011-2014 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+quad_size = 110;
+port_length = 10;
+quad_mesh = 5;
+
+Feed_R = 75;
+
+% size of the simulation box
+SimBox = [800 800 400];
+
+% frequency range of interest
+f_start = 400e6;
+f_stop = 1000e6;
+
+% frequency of interest
+f0 = 700e6;
+freq = linspace(f_start,f_stop,201);
+
+%% setup FDTD parameter & excitation function
+FDTD = InitFDTD( 'endCriteria', 1e-4 );
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+CSX = InitCSX();
+
+%create fixed lines for the antenna outline and port
+mesh.x = [-quad_size*sqrt(2) -quad_size/sqrt(2) 0 quad_size/sqrt(2) quad_size*sqrt(2)];
+mesh.y = [-quad_size/sqrt(2) -port_length/2 0 port_length/2 quad_size/sqrt(2)];
+mesh.z = [0];
+
+mesh = SmoothMesh(mesh, quad_mesh, 1.3);
+
+% add air box
+mesh.x = [mesh.x -SimBox(1)/2 SimBox(1)/2];
+mesh.y = [mesh.y -SimBox(2)/2 SimBox(2)/2];
+mesh.z = [-SimBox(3)/2 0 SimBox(3)/2];
+
+max_res = c0 / (f_stop) / unit / 20; % cell size: lambda/20
+mesh = SmoothMesh(mesh, max_res, 1.4);
+
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create bi-quad
+points(1,1) = 0;
+points(2,1) = port_length/2;
+points(3,1) = 0;
+points(1,end+1) = quad_size/sqrt(2);
+points(2,end) = quad_size/sqrt(2);
+points(1,end+1) = quad_size*sqrt(2);
+points(2,end) = 0;
+points(1,end+1) = quad_size/sqrt(2);
+points(2,end) = -quad_size/sqrt(2);
+points(1,end+1) = 0;
+points(2,end) = -port_length/2;
+points(1,end+1) = -quad_size/sqrt(2);
+points(2,end) = -quad_size/sqrt(2);
+points(1,end+1) = -quad_size*sqrt(2);
+points(2,end) = 0;
+points(1,end+1) = -quad_size/sqrt(2);
+points(2,end) = quad_size/sqrt(2);
+points(1,end+1) = 0;
+points(2,end) = port_length/2;
+
+% create a thin metal wire...
+CSX = AddMetal(CSX,'metal'); %create PEC with propName 'metal'
+CSX = AddCurve(CSX,'metal',10, points);
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start = [0 -port_length/2 0];
+stop = [0 port_length/2 0];
+[CSX port] = AddLumpedPort(CSX,10,0,Feed_R,start,stop,[0 1 0], true);
+
+%% nf2ff calc
+start = [mesh.x(9) mesh.y(9) mesh.z(9)];
+stop = [mesh.x(end-8) mesh.y(end-8) mesh.z(end-8)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop);
+
+%% prepare simulation folder
+Sim_Path = 'tmp';
+Sim_CSX = 'bi_quad_ant.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS([Sim_Path '/' Sim_CSX], FDTD, CSX);
+
+%% show the structure
+CSXGeomPlot([Sim_Path '/' Sim_CSX]);
+
+%% run openEMS
+RunOpenEMS(Sim_Path, Sim_CSX);
+
+%% postprocessing & do the plots
+port = calcPort(port, Sim_Path, freq);
+s11 = port.uf.ref ./ port.uf.inc;
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e9, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+ylim([-30 0]);
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / GHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+%% calculate 3D far field pattern
+phiRange = -180:2.5:180;
+thetaRange = 0:2.5:180;
+
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f0, thetaRange*pi/180, phiRange*pi/180);
+
+disp( ['directivity: Dmax = ' num2str(10*log10(nf2ff.Dmax)) ' dBi'] );
+
+% plot far-field pattern with Matlab
+figure
+plotFF3D(nf2ff, 'logscale', -20)
+
+%%
+disp( 'Dumping far-field pattern to vtk (use Paraview to visualize)...' );
+DumpFF2VTK('Bi_Quad_Pattern.vtk', nf2ff.E_norm{1} / max(nf2ff.E_norm{1}(:)) * nf2ff.Dmax, thetaRange, phiRange, 'scale', 0.05);
diff --git a/openEMS/matlab/examples/antennas/Patch_Antenna.m b/openEMS/matlab/examples/antennas/Patch_Antenna.m
new file mode 100644
index 0000000..2011d6f
--- /dev/null
+++ b/openEMS/matlab/examples/antennas/Patch_Antenna.m
@@ -0,0 +1,218 @@
+%
+% EXAMPLE / antennas / patch antenna
+%
+% This example demonstrates how to:
+% - calculate the reflection coefficient of a patch antenna
+%
+%
+% Tested with
+% - Matlab 2009b
+% - Octave 3.3.52
+% - openEMS v0.0.23
+%
+% (C) 2010,2011 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+draw_3d_pattern = 0; % this may take a while...
+use_pml = 0; % use pml boundaries instead of mur
+openEMS_opts = '';
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% width in x-direction
+% length in y-direction
+% main radiation in z-direction
+patch.width = 32.86; % resonant length
+patch.length = 41.37;
+
+substrate.epsR = 3.38;
+substrate.kappa = 1e-3 * 2*pi*2.45e9 * EPS0*substrate.epsR;
+substrate.width = 60;
+substrate.length = 60;
+substrate.thickness = 1.524;
+substrate.cells = 4;
+
+feed.pos = -5.5;
+feed.width = 2;
+feed.R = 50; % feed resistance
+
+% size of the simulation box
+SimBox = [100 100 25];
+
+%% prepare simulation folder
+Sim_Path = 'tmp';
+Sim_CSX = 'patch_ant.xml';
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+ [status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+end
+
+%% setup FDTD parameter & excitation function
+max_timesteps = 30000;
+min_decrement = 1e-5; % equivalent to -50 dB
+f0 = 0e9; % center frequency
+fc = 3e9; % 20 dB corner frequency (in this case 0 Hz - 3e9 Hz)
+FDTD = InitFDTD( 'NrTS', max_timesteps, 'EndCriteria', min_decrement );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % boundary conditions
+if (use_pml>0)
+ BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'}; % use pml instead of mur
+end
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+% currently, openEMS cannot automatically generate a mesh
+max_res = c0 / (f0+fc) / unit / 20; % cell size: lambda/20
+CSX = InitCSX();
+mesh.x = [-SimBox(1)/2 SimBox(1)/2 -substrate.width/2 substrate.width/2 feed.pos];
+% add patch mesh with 2/3 - 1/3 rule
+mesh.x = [mesh.x -patch.width/2-max_res/2*0.66 -patch.width/2+max_res/2*0.33 patch.width/2+max_res/2*0.66 patch.width/2-max_res/2*0.33];
+mesh.x = SmoothMeshLines( mesh.x, max_res, 1.4); % create a smooth mesh between specified mesh lines
+mesh.y = [-SimBox(2)/2 SimBox(2)/2 -substrate.length/2 substrate.length/2 -feed.width/2 feed.width/2];
+% add patch mesh with 2/3 - 1/3 rule
+mesh.y = [mesh.y -patch.length/2-max_res/2*0.66 -patch.length/2+max_res/2*0.33 patch.length/2+max_res/2*0.66 patch.length/2-max_res/2*0.33];
+mesh.y = SmoothMeshLines( mesh.y, max_res, 1.4 );
+mesh.z = [-SimBox(3)/2 linspace(0,substrate.thickness,substrate.cells) SimBox(3) ];
+mesh.z = SmoothMeshLines( mesh.z, max_res, 1.4 );
+mesh = AddPML( mesh, [8 8 8 8 8 8] ); % add equidistant cells (air around the structure)
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create patch
+CSX = AddMetal( CSX, 'patch' ); % create a perfect electric conductor (PEC)
+start = [-patch.width/2 -patch.length/2 substrate.thickness];
+stop = [ patch.width/2 patch.length/2 substrate.thickness];
+CSX = AddBox(CSX,'patch',10,start,stop);
+
+%% create substrate
+CSX = AddMaterial( CSX, 'substrate' );
+CSX = SetMaterialProperty( CSX, 'substrate', 'Epsilon', substrate.epsR, 'Kappa', substrate.kappa );
+start = [-substrate.width/2 -substrate.length/2 0];
+stop = [ substrate.width/2 substrate.length/2 substrate.thickness];
+CSX = AddBox( CSX, 'substrate', 0, start, stop );
+
+%% create ground (same size as substrate)
+CSX = AddMetal( CSX, 'gnd' ); % create a perfect electric conductor (PEC)
+start(3)=0;
+stop(3) =0;
+CSX = AddBox(CSX,'gnd',10,start,stop);
+
+%% apply the excitation & resist as a current source
+start = [feed.pos-.1 -feed.width/2 0];
+stop = [feed.pos+.1 +feed.width/2 substrate.thickness];
+[CSX] = AddLumpedPort(CSX, 5 ,1 ,feed.R, start, stop, [0 0 1], true);
+
+%% dump magnetic field over the patch antenna
+CSX = AddDump( CSX, 'Ht_', 'DumpType', 1, 'DumpMode', 2); % cell interpolated
+start = [-patch.width -patch.length substrate.thickness+1];
+stop = [ patch.width patch.length substrate.thickness+1];
+CSX = AddBox( CSX, 'Ht_', 0, start, stop );
+
+%%nf2ff calc
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', -SimBox/2, SimBox/2);
+
+if (postprocessing_only==0)
+ %% write openEMS compatible xml-file
+ WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+ %% show the structure
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+ %% run openEMS
+ RunOpenEMS( Sim_Path, Sim_CSX, openEMS_opts );
+end
+
+%% postprocessing & do the plots
+freq = linspace( max([1e9,f0-fc]), f0+fc, 501 );
+U = ReadUI( {'port_ut1','et'}, 'tmp/', freq ); % time domain/freq domain voltage
+I = ReadUI( 'port_it1', 'tmp/', freq ); % time domain/freq domain current (half time step is corrected)
+
+% plot time domain voltage
+figure
+[ax,h1,h2] = plotyy( U.TD{1}.t/1e-9, U.TD{1}.val, U.TD{2}.t/1e-9, U.TD{2}.val );
+set( h1, 'Linewidth', 2 );
+set( h1, 'Color', [1 0 0] );
+set( h2, 'Linewidth', 2 );
+set( h2, 'Color', [0 0 0] );
+grid on
+title( 'time domain voltage' );
+xlabel( 'time t / ns' );
+ylabel( ax(1), 'voltage ut1 / V' );
+ylabel( ax(2), 'voltage et / V' );
+% now make the y-axis symmetric to y=0 (align zeros of y1 and y2)
+y1 = ylim(ax(1));
+y2 = ylim(ax(2));
+ylim( ax(1), [-max(abs(y1)) max(abs(y1))] );
+ylim( ax(2), [-max(abs(y2)) max(abs(y2))] );
+
+% plot feed point impedance
+figure
+Zin = U.FD{1}.val ./ I.FD{1}.val;
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+uf_inc = 0.5*(U.FD{1}.val + I.FD{1}.val * 50);
+if_inc = 0.5*(I.FD{1}.val - U.FD{1}.val / 50);
+uf_ref = U.FD{1}.val - uf_inc;
+if_ref = I.FD{1}.val - if_inc;
+s11 = uf_ref ./ uf_inc;
+plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+P_in = 0.5*U.FD{1}.val .* conj( I.FD{1}.val );
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+f_res_ind = find(s11==min(s11));
+f_res = freq(f_res_ind);
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+thetaRange = (0:2:359) - 180;
+phiRange = [0 90];
+disp( 'calculating far field at phi=[0 90] deg...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180);
+
+Dlog=10*log10(nf2ff.Dmax);
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(Dlog) ' dBi'] );
+disp( ['efficiency: nu_rad = ' num2str(100*nf2ff.Prad./real(P_in(f_res_ind))) ' %']);
+
+% display phi
+figure
+plotFFdB(nf2ff,'xaxis','theta','param',[1 2]);
+drawnow
+
+if (draw_3d_pattern==0)
+ return
+end
+
+%% calculate 3D pattern
+phiRange = 0:2:360;
+thetaRange = 0:2:180;
+disp( 'calculating 3D far field...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180, 'Verbose',2,'Outfile','nf2ff_3D.h5');
+figure
+plotFF3D(nf2ff);
+
+
+%% visualize magnetic fields
+% you will find vtk dump files in the simulation folder (tmp/)
+% use paraview to visulaize them
diff --git a/openEMS/matlab/examples/antennas/Patch_Antenna_Array.m b/openEMS/matlab/examples/antennas/Patch_Antenna_Array.m
new file mode 100644
index 0000000..40b3b46
--- /dev/null
+++ b/openEMS/matlab/examples/antennas/Patch_Antenna_Array.m
@@ -0,0 +1,256 @@
+%
+% EXAMPLE / antennas / patch antenna array
+%
+% This example demonstrates how to:
+% - calculate the reflection coefficient of a patch antenna array
+%
+%
+% Tested with
+% - Matlab 2009b
+% - Octave 3.3.52
+% - openEMS v0.0.23
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+draw_3d_pattern = 0; % this may take a (very long) while...
+use_pml = 0; % use pml boundaries instead of mur
+openEMS_opts = '';
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% width in x-direction
+% length in y-direction
+% main radiation in z-direction
+patch.width = 32.86; % resonant length
+patch.length = 41.37;
+
+% define array size and dimensions
+array.xn = 4;
+array.yn = 4;
+array.x_spacing = patch.width * 3;
+array.y_spacing = patch.length * 3;
+
+substrate.epsR = 3.38;
+substrate.kappa = 1e-3 * 2*pi*2.45e9 * EPS0*substrate.epsR;
+substrate.width = 60 + (array.xn-1) * array.x_spacing;
+substrate.length = 60 + (array.yn-1) * array.y_spacing;
+substrate.thickness = 1.524;
+substrate.cells = 4;
+
+feed.pos = -5.5;
+feed.width = 2;
+feed.R = 50; % feed resistance
+
+% size of the simulation box around the array
+SimBox = [50+substrate.width 50+substrate.length 25];
+
+%% prepare simulation folder
+Sim_Path = 'tmp';
+Sim_CSX = 'patch_array.xml';
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+ [status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+end
+
+%% setup FDTD parameter & excitation function
+max_timesteps = 30000;
+min_decrement = 1e-5; % equivalent to -50 dB
+f0 = 0e9; % center frequency
+fc = 3e9; % 10 dB corner frequency (in this case 0 Hz - 3e9 Hz)
+FDTD = InitFDTD( 'NrTS', max_timesteps, 'EndCriteria', min_decrement );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % boundary conditions
+if (use_pml>0)
+ BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'}; % use pml instead of mur
+end
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+% currently, openEMS cannot automatically generate a mesh
+max_res = c0 / (f0+fc) / unit / 20; % cell size: lambda/20
+CSX = InitCSX();
+mesh.x = [-SimBox(1)/2 SimBox(1)/2 -substrate.width/2 substrate.width/2];
+mesh.y = [-SimBox(2)/2 SimBox(2)/2 -substrate.length/2 substrate.length/2];
+
+mesh.z = [-SimBox(3)/2 linspace(0,substrate.thickness,substrate.cells) SimBox(3) ];
+mesh.z = SmoothMeshLines( mesh.z, max_res, 1.4 );
+
+for xn=1:array.xn
+ for yn=1:array.yn
+ midX = (array.xn/2 - xn + 1/2) * array.x_spacing;
+ midY = (array.yn/2 - yn + 1/2) * array.y_spacing;
+
+ % feeding mesh
+ mesh.x = [mesh.x midX+feed.pos];
+ mesh.y = [mesh.y midY-feed.width/2 midY+feed.width/2];
+
+ % add patch mesh with 2/3 - 1/3 rule
+ mesh.x = [mesh.x midX-patch.width/2-max_res/2*0.66 midX-patch.width/2+max_res/2*0.33 midX+patch.width/2+max_res/2*0.66 midX+patch.width/2-max_res/2*0.33];
+ % add patch mesh with 2/3 - 1/3 rule
+ mesh.y = [mesh.y midY-patch.length/2-max_res/2*0.66 midY-patch.length/2+max_res/2*0.33 midY+patch.length/2+max_res/2*0.66 midY+patch.length/2-max_res/2*0.33];
+ end
+end
+mesh.x = SmoothMeshLines( mesh.x, max_res, 1.4); % create a smooth mesh between specified mesh lines
+mesh.y = SmoothMeshLines( mesh.y, max_res, 1.4 );
+
+mesh = AddPML( mesh, [8 8 8 8 8 8] ); % add equidistant cells (air around the structure)
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create substrate
+CSX = AddMaterial( CSX, 'substrate' );
+CSX = SetMaterialProperty( CSX, 'substrate', 'Epsilon', substrate.epsR, 'Kappa', substrate.kappa);
+start = [-substrate.width/2 -substrate.length/2 0];
+stop = [ substrate.width/2 substrate.length/2 substrate.thickness];
+CSX = AddBox( CSX, 'substrate', 0, start, stop );
+
+%% create ground (same size as substrate)
+CSX = AddMetal( CSX, 'gnd' ); % create a perfect electric conductor (PEC)
+start(3)=0;
+stop(3) =0;
+CSX = AddBox(CSX,'gnd',10,start,stop);
+%%
+CSX = AddMetal( CSX, 'patch' ); % create a perfect electric conductor (PEC)
+number = 1;
+for xn=1:array.xn
+ for yn=1:array.yn
+
+ midX = (array.xn/2 - xn + 1/2) * array.x_spacing;
+ midY = (array.yn/2 - yn + 1/2) * array.y_spacing;
+
+ % create patch
+ start = [midX-patch.width/2 midY-patch.length/2 substrate.thickness];
+ stop = [midX+patch.width/2 midY+patch.length/2 substrate.thickness];
+ CSX = AddBox(CSX,'patch',10,start,stop);
+
+ % apply the excitation & resist as a current source
+ start = [midX+feed.pos-feed.width/2 midY-feed.width/2 0];
+ stop = [midX+feed.pos+feed.width/2 midY+feed.width/2 substrate.thickness];
+ [CSX] = AddLumpedPort(CSX, 5, number,feed.R, start, stop,[0 0 1],true);
+ number=number+1;
+ end
+end
+
+%%nf2ff calc
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', -SimBox/2, SimBox/2);
+
+if (postprocessing_only==0)
+ %% write openEMS compatible xml-file
+ WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+ %% show the structure
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+ %% run openEMS
+ RunOpenEMS( Sim_Path, Sim_CSX, openEMS_opts );
+end
+
+%% postprocessing & do the plots
+freq = linspace( max([1e9,f0-fc]), f0+fc, 501 );
+U = ReadUI( {'port_ut1','et'}, 'tmp/', freq ); % time domain/freq domain voltage
+I = ReadUI( 'port_it1', 'tmp/', freq ); % time domain/freq domain current (half time step is corrected)
+
+% plot time domain voltage
+figure
+[ax,h1,h2] = plotyy( U.TD{1}.t/1e-9, U.TD{1}.val, U.TD{2}.t/1e-9, U.TD{2}.val );
+set( h1, 'Linewidth', 2 );
+set( h1, 'Color', [1 0 0] );
+set( h2, 'Linewidth', 2 );
+set( h2, 'Color', [0 0 0] );
+grid on
+title( 'time domain voltage' );
+xlabel( 'time t / ns' );
+ylabel( ax(1), 'voltage ut1 / V' );
+ylabel( ax(2), 'voltage et / V' );
+% now make the y-axis symmetric to y=0 (align zeros of y1 and y2)
+y1 = ylim(ax(1));
+y2 = ylim(ax(2));
+ylim( ax(1), [-max(abs(y1)) max(abs(y1))] );
+ylim( ax(2), [-max(abs(y2)) max(abs(y2))] );
+
+% plot feed point impedance
+figure
+Zin = U.FD{1}.val ./ I.FD{1}.val;
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+uf_inc = 0.5*(U.FD{1}.val + I.FD{1}.val * 50);
+if_inc = 0.5*(I.FD{1}.val - U.FD{1}.val / 50);
+uf_ref = U.FD{1}.val - uf_inc;
+if_ref = I.FD{1}.val - if_inc;
+s11 = uf_ref ./ uf_inc;
+plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+%%
+number = 1;
+P_in = 0;
+for xn=1:array.xn
+ for yn=1:array.yn
+
+ U = ReadUI( ['port_ut' int2str(number)], 'tmp/', freq ); % time domain/freq domain voltage
+ I = ReadUI( ['port_it' int2str(number)], 'tmp/', freq ); % time domain/freq domain current (half time step is corrected)
+
+ P_in = P_in + 0.5*U.FD{1}.val .* conj( I.FD{1}.val );
+ number=number+1;
+ end
+end
+
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+f_res_ind = find(s11==min(s11));
+f_res = freq(f_res_ind);
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+thetaRange = (0:2:359) - 180;
+phiRange = [0 90];
+r = 1; % evaluate fields at radius r
+disp( 'calculating far field at phi=[0 90] deg...' );
+
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180);
+
+Dlog=10*log10(nf2ff.Dmax);
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(Dlog) ' dBi'] );
+disp( ['efficiency: nu_rad = ' num2str(100*nf2ff.Prad./real(P_in(f_res_ind))) ' %']);
+
+% display phi
+figure
+plotFFdB(nf2ff,'xaxis','theta','param',[1 2]);
+drawnow
+
+if (draw_3d_pattern==0)
+ return
+end
+
+%% calculate 3D pattern
+phiRange = 0:3:360;
+thetaRange = unique([0:0.5:15 10:3:180]);
+disp( 'calculating 3D far field...' );
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180, 'Verbose',2,'Outfile','nf2ff_3D.h5');
+figure
+plotFF3D(nf2ff);
+
+%% visualize magnetic fields
+% you will find vtk dump files in the simulation folder (tmp/)
+% use paraview to visulaize them
diff --git a/openEMS/matlab/examples/antennas/infDipol.m b/openEMS/matlab/examples/antennas/infDipol.m
new file mode 100644
index 0000000..0a43bc8
--- /dev/null
+++ b/openEMS/matlab/examples/antennas/infDipol.m
@@ -0,0 +1,121 @@
+%
+% infinitesimal dipole example
+%
+
+close all
+clear
+clc
+
+postprocessing_only = 0;
+
+physical_constants
+
+% setup the simulation
+drawingunit = 1e-6; % specify everything in um
+Sim_Path = 'tmp';
+Sim_CSX = 'tmp.xml';
+
+f_max = 1e9;
+lambda = c0/f_max;
+
+% setup geometry values
+dipole_length = lambda/50 /drawingunit;
+
+
+dipole_orientation = 3; % 1,2,3: x,y,z
+
+
+CSX = InitCSX();
+
+% create an equidistant mesh
+mesh.x = -dipole_length*10:dipole_length/2:dipole_length*10;
+mesh.y = -dipole_length*10:dipole_length/2:dipole_length*10;
+mesh.z = -dipole_length*10:dipole_length/2:dipole_length*10;
+
+% excitation
+ex_vector = [0 0 0];
+ex_vector(dipole_orientation) = 1;
+start = ex_vector * -dipole_length/2;
+stop = ex_vector * dipole_length/2;
+CSX = AddExcitation( CSX, 'infDipole', 1, ex_vector );
+% enlarge the box to be sure that one mesh line is covered by it
+start = start - [0.1 0.1 0.1] * dipole_length/2;
+stop = stop + [0.1 0.1 0.1] * dipole_length/2;
+CSX = AddBox( CSX, 'infDipole', 1, start, stop );
+
+% NFFF contour
+start = [mesh.x(1) mesh.y(1) mesh.z(1) ];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end) ];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop);
+
+% add space for PML
+mesh = AddPML( mesh, [8 8 8 8 8 8] );
+% define the mesh
+CSX = DefineRectGrid( CSX, drawingunit, mesh );
+
+if ~postprocessing_only
+ % setup FDTD parameters & excitation function
+ max_timesteps = 2000;
+ min_decrement = 1e-6;
+ FDTD = InitFDTD( 'NrTS', max_timesteps, 'EndCriteria', min_decrement, 'OverSampling',10 );
+ FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+ BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'};
+ FDTD = SetBoundaryCond( FDTD, BC );
+
+ % Write openEMS compatible xml-file
+ [~,~,~] = rmdir(Sim_Path,'s');
+ [~,~,~] = mkdir(Sim_Path);
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+ % take a view at the "structure"
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+ % define openEMS options and start simulation
+ openEMS_opts = '';
+ RunOpenEMS( Sim_Path, Sim_CSX, openEMS_opts );
+end
+
+%% post processing
+disp( ' ' );
+disp( ' ********************************************************** ' );
+disp( ' ' );
+
+% calculate the far field at phi=0 degrees and at phi=90 degrees
+thetaRange = 0:0.5:359;
+disp( 'calculating far field at phi=[0 90] deg..' );
+nf2ff = CalcNF2FF( nf2ff, Sim_Path, f_max, thetaRange/180*pi, [0 pi/2], 'Mode', 1 );
+Prad = nf2ff.Prad;
+Dmax = nf2ff.Dmax;
+
+theta_HPBW = interp1(nf2ff.E_norm{1}(find(thetaRange<90),1)/max(nf2ff.E_norm{1}(find(thetaRange<90),1)),thetaRange(find(thetaRange<90)),1/sqrt(2))*2;
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(Prad)] );
+disp( ['directivity: Dmax = ' num2str(Dmax)] );
+disp( ['theta_HPBW = ' num2str(theta_HPBW) ' °']);
+
+% display polar plot for the e-field magnitude for phi = 0 & 90 deg
+figure
+polarFF(nf2ff,'xaxis','theta','param',[1 2]);
+
+%% calculate the far field at theta=90 degrees
+phiRange = 0:2:359;
+disp( 'calculating far field at theta=90 deg..' );
+nf2ff = CalcNF2FF( nf2ff, Sim_Path, f_max, 90/180*pi, phiRange/180*pi, 'Mode', 1 );
+
+% display polar plot
+figure
+polarFF(nf2ff,'xaxis','phi','param',1);
+
+%% calculate 3D pattern
+phiRange = 0:5:360;
+thetaRange = 0:5:180;
+disp( 'calculating 3D far field...' );
+nf2ff = CalcNF2FF( nf2ff, Sim_Path, f_max, thetaRange/180*pi, phiRange/180*pi, 'Mode', 1 );
+figure
+plotFF3D(nf2ff)
+
+%%
+E_far_normalized = nf2ff.E_norm{1} / max(nf2ff.E_norm{1}(:));
+DumpFF2VTK([Sim_Path '/FF_pattern.vtk'],E_far_normalized, thetaRange, phiRange);
+disp(['view the farfield pattern "' Sim_Path '/FF_pattern.vtk" using paraview' ]);
diff --git a/openEMS/matlab/examples/antennas/inverted_f.m b/openEMS/matlab/examples/antennas/inverted_f.m
new file mode 100644
index 0000000..175f94c
--- /dev/null
+++ b/openEMS/matlab/examples/antennas/inverted_f.m
@@ -0,0 +1,205 @@
+%
+% EXAMPLE / antennas / inverted-f antenna (ifa) 2.4GHz
+%
+% This example demonstrates how to:
+% - calculate the reflection coefficient of an ifa
+% - calculate farfield of an ifa
+%
+% Tested with
+% - Octave 3.7.5
+% - openEMS v0.0.30+ (git 10.07.2013)
+%
+% (C) 2013 Stefan Mahr <dac922@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% substrate.width
+% _______________________________________________ __ substrate.
+% | A ifa.l |\ __ thickness
+% | |ifa.e __________________________ | |
+% | | | ___ _________________| w2 | |
+% | | ifa.h | | || | |
+% |_V_____________|___|___||______________________| |
+% | .w1 .wf\ | |
+% | |.fp| \ | |
+% | | feed point | |
+% | | | | substrate.length
+% |<- substrate.width/2 ->| | |
+% | | |
+% |_______________________________________________| |
+% \_______________________________________________\|
+%
+% Note: It's not checked whether your settings make sense, so check
+% graphical output carefully.
+%
+substrate.width = 80; % width of substrate
+substrate.length = 80; % length of substrate
+substrate.thickness = 1.5; % thickness of substrate
+substrate.cells = 4; % use 4 cells for meshing substrate
+
+ifa.h = 8; % height of short circuit stub
+ifa.l = 22.5; % length of radiating element
+ifa.w1 = 4; % width of short circuit stub
+ifa.w2 = 2.5; % width of radiating element
+ifa.wf = 1; % width of feed element
+ifa.fp = 4; % position of feed element relative to short
+ % circuit stub
+ifa.e = 10; % distance to edge
+
+
+% substrate setup
+substrate.epsR = 4.3;
+substrate.kappa = 1e-3 * 2*pi*2.45e9 * EPS0*substrate.epsR;
+
+%setup feeding
+feed.R = 50; %feed resistance
+
+%open AppCSXCAD and show ifa
+show = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% size of the simulation box
+SimBox = [substrate.width*2 substrate.length*2 150];
+
+%% setup FDTD parameter & excitation function
+f0 = 2.5e9; % center frequency
+fc = 1e9; % 20 dB corner frequency
+
+FDTD = InitFDTD('NrTS', 60000 );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % boundary conditions
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+CSX = InitCSX();
+
+%initialize the mesh with the "air-box" dimensions
+mesh.x = [-SimBox(1)/2 SimBox(1)/2];
+mesh.y = [-SimBox(2)/2 SimBox(2)/2];
+mesh.z = [-SimBox(3)/2 SimBox(3)/2];
+
+%% create substrate
+CSX = AddMaterial( CSX, 'substrate');
+CSX = SetMaterialProperty( CSX, 'substrate', 'Epsilon',substrate.epsR, 'Kappa', substrate.kappa);
+start = [-substrate.width/2 -substrate.length/2 0];
+stop = [ substrate.width/2 substrate.length/2 substrate.thickness];
+CSX = AddBox( CSX, 'substrate', 1, start, stop );
+% add extra cells to discretize the substrate thickness
+mesh.z = [linspace(0,substrate.thickness,substrate.cells+1) mesh.z];
+
+%% create ground plane
+CSX = AddMetal( CSX, 'groundplane' ); % create a perfect electric conductor (PEC)
+start = [-substrate.width/2 -substrate.length/2 substrate.thickness];
+stop = [ substrate.width/2 substrate.length/2-ifa.e substrate.thickness];
+CSX = AddBox(CSX, 'groundplane', 10, start,stop);
+
+%% create ifa
+CSX = AddMetal( CSX, 'ifa' ); % create a perfect electric conductor (PEC)
+tl = [0,substrate.length/2-ifa.e,substrate.thickness]; % translate
+start = [0 0.5 0] + tl;
+stop = start + [ifa.wf ifa.h-0.5 0];
+CSX = AddBox( CSX, 'ifa', 10, start, stop); % feed element
+start = [-ifa.fp 0 0] + tl;
+stop = start + [-ifa.w1 ifa.h 0];
+CSX = AddBox( CSX, 'ifa', 10, start, stop); % short circuit stub
+start = [(-ifa.fp-ifa.w1) ifa.h 0] + tl;
+stop = start + [ifa.l -ifa.w2 0];
+CSX = AddBox( CSX, 'ifa', 10, start, stop); % radiating element
+
+ifa_mesh = DetectEdges(CSX, [], 'SetProperty','ifa');
+mesh.x = [mesh.x SmoothMeshLines(ifa_mesh.x, 0.5)];
+mesh.y = [mesh.y SmoothMeshLines(ifa_mesh.y, 0.5)];
+
+%% apply the excitation & resist as a current source
+start = [0 0 0] + tl;
+stop = start + [ifa.wf 0.5 0];
+[CSX port] = AddLumpedPort(CSX, 5 ,1 ,feed.R, start, stop, [0 1 0], true);
+
+%% finalize the mesh
+% generate a smooth mesh with max. cell size: lambda_min / 20
+mesh = DetectEdges(CSX, mesh);
+mesh = SmoothMesh(mesh, c0 / (f0+fc) / unit / 20);
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%% add a nf2ff calc box; size is 3 cells away from MUR boundary condition
+start = [mesh.x(4) mesh.y(4) mesh.z(4)];
+stop = [mesh.x(end-3) mesh.y(end-3) mesh.z(end-3)];
+[CSX nf2ff] = CreateNF2FFBox(CSX, 'nf2ff', start, stop);
+
+%% prepare simulation folder
+Sim_Path = 'tmp_IFA';
+Sim_CSX = 'IFA.xml';
+
+try confirm_recursive_rmdir(false,'local'); end
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure
+if (show == 1)
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+end
+
+
+%% run openEMS
+RunOpenEMS( Sim_Path, Sim_CSX); %RunOpenEMS( Sim_Path, Sim_CSX, '--debug-PEC -v');
+
+%% postprocessing & do the plots
+freq = linspace( max([1e9,f0-fc]), f0+fc, 501 );
+port = calcPort(port, Sim_Path, freq);
+
+Zin = port.uf.tot ./ port.if.tot;
+s11 = port.uf.ref ./ port.uf.inc;
+P_in = real(0.5 * port.uf.tot .* conj( port.if.tot )); % antenna feed power
+
+% plot feed point impedance
+figure
+plot( freq/1e6, real(Zin), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Zin), 'r--', 'Linewidth', 2 );
+title( 'feed point impedance' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'impedance Z_{in} / Ohm' );
+legend( 'real', 'imag' );
+
+% plot reflection coefficient S11
+figure
+plot( freq/1e6, 20*log10(abs(s11)), 'k-', 'Linewidth', 2 );
+grid on
+title( 'reflection coefficient S_{11}' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'reflection coefficient |S_{11}|' );
+
+drawnow
+
+%% NFFF contour plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%find resonance frequncy from s11
+f_res_ind = find(s11==min(s11));
+f_res = freq(f_res_ind);
+
+%%
+disp( 'calculating 3D far field pattern and dumping to vtk (use Paraview to visualize)...' );
+thetaRange = (0:2:180);
+phiRange = (0:2:360) - 180;
+nf2ff = CalcNF2FF(nf2ff, Sim_Path, f_res, thetaRange*pi/180, phiRange*pi/180,'Verbose',1,'Outfile','3D_Pattern.h5');
+
+plotFF3D(nf2ff)
+
+% display power and directivity
+disp( ['radiated power: Prad = ' num2str(nf2ff.Prad) ' Watt']);
+disp( ['directivity: Dmax = ' num2str(nf2ff.Dmax) ' (' num2str(10*log10(nf2ff.Dmax)) ' dBi)'] );
+disp( ['efficiency: nu_rad = ' num2str(100*nf2ff.Prad./real(P_in(f_res_ind))) ' %']);
+
+E_far_normalized = nf2ff.E_norm{1} / max(nf2ff.E_norm{1}(:)) * nf2ff.Dmax;
+DumpFF2VTK([Sim_Path '/3D_Pattern.vtk'],E_far_normalized,thetaRange,phiRange,1e-3);
diff --git a/openEMS/matlab/examples/optimizer/optimizer_asco.m b/openEMS/matlab/examples/optimizer/optimizer_asco.m
new file mode 100644
index 0000000..e405653
--- /dev/null
+++ b/openEMS/matlab/examples/optimizer/optimizer_asco.m
@@ -0,0 +1,36 @@
+%
+% asco optimizer example -- optimize the turn number of a coil
+%
+% You need asco from http://asco.sf.net
+% This is the main script.
+% - optimizer_simfun.m starts the simulator with a parameter set from
+% asco
+%
+% The goal is evaluated inside optimizer_simfun() to get as close to 2 uH.
+
+% clear
+clear
+close all
+clc
+
+% setup the parameters
+params = [];
+params(end+1).name = 'turns';
+params(end).range = [1 30];
+params(end).value = 4;
+params(end).step = 1;
+params(end).active = 1; % this parameter is to be optimized
+
+% setup the simulation function
+folder = fileparts( mfilename('fullpath') );
+options.simfun = [folder '/optimizer_simfun.m'];
+
+% additional options
+% options.octave_exe = 'octave'; % must be newer than 3.2.4 (3.3.54 works)
+options.clean = 1;
+
+% start the optimization
+[params_opt,result] = optimize( 'opttmp', params, options, 'asco' );
+
+% display best value
+disp( ['ASCO found the optimum turn number: ' num2str(params_opt(1).value) ' result: ' num2str(result)] );
diff --git a/openEMS/matlab/examples/optimizer/optimizer_simfun.m b/openEMS/matlab/examples/optimizer/optimizer_simfun.m
new file mode 100644
index 0000000..14152de
--- /dev/null
+++ b/openEMS/matlab/examples/optimizer/optimizer_simfun.m
@@ -0,0 +1,134 @@
+function result = optimizer_simfun( folder, params )
+%
+% simulation function
+%
+% the variable params contains the simulation parameters
+
+disp( [mfilename ': SIMULATING...'] );
+
+if nargin == 0
+ % visualize the structure if called without parameters
+ folder = 'tmp';
+ params.turns = 10;
+end
+
+oldpwd = pwd;
+[a,a,a] = mkdir( folder );
+cd( folder );
+
+% create the structure
+f_max = 50e6;
+structure( params, 'tmp.xml', f_max );
+
+if nargin == 0
+ % visualize the structure
+ CSXGeomPlot('tmp.xml');
+ return;
+end
+
+% start simulation
+RunOpenEMS( '.', 'tmp.xml', '--engine=fastest' );
+
+% postprocess the results
+L = postproc( 'tmp.xml', f_max );
+disp( ['DONE. L = ' num2str(L(1)/1e-6) ' uH'] );
+
+% calculate result
+goal = 2e-6; % specify the goal: 2 uH
+result = abs(goal - L(1)); % costs must not be negative
+
+% restore curent folder
+cd( oldpwd );
+
+
+
+
+% -------------------------------------------------------------------------
+% -------------------------------------------------------------------------
+
+function CSX = structure( params, filename, f_max )
+% CSX = structure( params, filename )
+
+unit = 1e-3; % specify length in mm
+lambda = 3e8/f_max;
+resolution = lambda/15/unit;
+mesh_size = 1.5;
+radius = 10;
+turns = params.turns;
+height = 4 * turns;
+feed_length = 10;
+
+CSX = InitCSX();
+
+%% create coil
+p1 = create_coil( radius, height, turns );
+p = p1(:,end) + [feed_length;0;0];
+p1 = [p1 p];
+p = p1(:,1) + [feed_length;0;0];
+p1 = [p p1];
+CSX = AddMetal(CSX,'PEC1');
+CSX = AddCurve(CSX, 'PEC1', 0, p1);
+
+%% create mesh
+extraspace = 5*radius;
+mesh.x = linspace(-radius,radius,ceil(2*radius/mesh_size));
+mesh.x = [mesh.x mesh.x(1)-extraspace mesh.x(end)+extraspace];
+mesh.x = [mesh.x p1(1,1) p1(1,1)-mesh_size p1(1,1)+mesh_size];
+mesh.x = SmoothMeshLines2( mesh.x, resolution );
+mesh.y = linspace(-radius,radius,ceil(2*radius/mesh_size));
+mesh.y = [mesh.y mesh.y(1)-extraspace mesh.y(end)+extraspace];
+mesh.y = SmoothMeshLines2( mesh.y, resolution );
+mesh.z = linspace(0,height,ceil(height/mesh_size));
+mesh.z = [mesh.z mesh.z(1)-extraspace mesh.z(end)+extraspace];
+% mesh.z = [mesh.z p1(3,1) p1(3,1)-mesh_size p1(3,1)+mesh_size];
+mesh.z = SmoothMeshLines2( mesh.z, resolution );
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+
+%% create port
+[CSX,port] = AddCurvePort( CSX, 10, 1, 50, p1(:,1), p1(:,end), 'excite' );
+
+if nargin > 1
+ max_timesteps = 100000;
+ min_decrement = 1e-5;
+ FDTD = InitFDTD( max_timesteps, min_decrement );
+ FDTD = SetGaussExcite( FDTD, 0, f_max );
+ BC = {'PEC' 'PEC' 'PEC' 'PEC' 'PMC' 'PMC'};
+ FDTD = SetBoundaryCond( FDTD, BC );
+
+ WriteOpenEMS( filename, FDTD, CSX );
+end
+
+
+function p = create_coil(coil_rad,coil_length,coil_turns,coil_res,winding_direction,direction,offset,angle_offset)
+if nargin < 8, angle_offset = 0; end
+if nargin < 7, offset = [0; 0; 0]; end
+if nargin < 6, direction = +1; end
+if nargin < 5, winding_direction = +1; end
+if nargin < 4, coil_res = 30; end
+dt = 1/coil_res;
+height = 0;
+
+p = [];
+while abs(height) < coil_length
+ angle = height / (coil_length/coil_turns) * 2*pi;
+ p(1,end+1) = coil_rad * cos(angle*winding_direction+angle_offset);
+ p(2,end) = coil_rad * sin(angle*winding_direction+angle_offset);
+ p(3,end) = height * direction;
+ p(:,end) = p(:,end) + offset;
+ height = height + coil_length/coil_turns * dt;
+end
+
+
+
+function L = postproc( filename, f_max )
+freq = linspace(0,f_max,201);
+freq(1) = []; % delete DC component
+
+folder = fileparts(filename);
+U = ReadUI( 'port_ut1', folder, freq );
+I = ReadUI( 'port_it1', folder, freq );
+Z = U.FD{1}.val ./ I.FD{1}.val;
+
+L = imag(Z) ./ (2*pi*freq);
+L = reshape( L, 1, [] ); % row vector
diff --git a/openEMS/matlab/examples/other/Helix.m b/openEMS/matlab/examples/other/Helix.m
new file mode 100644
index 0000000..18e97c9
--- /dev/null
+++ b/openEMS/matlab/examples/other/Helix.m
@@ -0,0 +1,154 @@
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+feed_length=10;
+wire_rad = sqrt(1.4/pi);
+mesh_size = wire_rad;
+coil_rad = 10;
+coil_length = 50;
+coil_turns = 8;
+coil_res = 10;
+port_length = mesh_size; %coil_length/2;
+port_resist = 1000;
+
+f_max = 100e6;
+f_excite = 300e6;
+
+%% define openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+% openEMS_opts = [openEMS_opts ' --debug-operator'];
+
+openEMS_opts = [openEMS_opts ' --disable-dumps --engine=fastest'];
+% openEMS_opts = [openEMS_opts ' --engine=sse-compressed'];
+
+Sim_Path = 'tmp';
+Sim_CSX = 'helix.xml';
+
+[status, message, messageid] = rmdir(Sim_Path,'s');
+[status,message,messageid] = mkdir(Sim_Path);
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(30000,1e-6);
+FDTD = SetGaussExcite(FDTD,f_excite/2,f_excite/2);
+BC = [1 1 1 1 1 1];
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+add_Lines = mesh_size * 1.5.^(1:10);
+add_Lines = add_Lines(find(add_Lines<(3e8/f_excite)/10*1e3));
+
+CSX = InitCSX();
+mesh.x = -coil_rad-mesh_size : mesh_size : coil_rad+mesh_size+feed_length;
+mesh.x = [mesh.x(1)-add_Lines mesh.x mesh.x(end)+add_Lines ];
+mesh.y = -coil_rad-mesh_size : mesh_size : coil_rad+mesh_size;
+mesh.y = [mesh.y(1)-add_Lines mesh.y mesh.y(end)+add_Lines ];
+mesh.z = -mesh_size : mesh_size : coil_length+mesh_size;
+mesh.z = [mesh.z(1)-add_Lines mesh.z mesh.z(end)+add_Lines ];
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+%% build/define helix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddMaterial(CSX,'copper');
+CSX = SetMaterialProperty(CSX,'copper','Kappa',56e6);
+
+dt = 1.0/coil_res;
+height=0;
+wire.Vertex = {};
+p(1,1) = coil_rad + feed_length;
+p(2,1) = 0;
+p(3,1) = 0.5*(coil_length-port_length);
+p(1,2) = coil_rad + feed_length;
+p(2,2) = 0;
+p(3,2) = 0;
+count=2;
+for n=0:coil_turns-1
+ for m=0:coil_res
+ count = count + 1;
+ p(1,count) = coil_rad * cos(2*pi*dt*m);
+ p(2,count) = coil_rad * sin(2*pi*dt*m);
+ p(3,count) = height + coil_length/coil_turns * dt*m;
+ end
+ height = height + coil_length/coil_turns;
+end
+p(1,count+1) = coil_rad + feed_length;
+p(2,count+1) = 0;
+p(3,count+1) = coil_length;
+p(1,count+2) = coil_rad + feed_length;
+p(2,count+2) = 0;
+p(3,count+2) = 0.5*(coil_length+port_length);
+CSX = AddWire(CSX, 'copper', 0, p, wire_rad);
+
+%% apply the excitation & resist as a current source%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddMaterial(CSX,'resist');
+kappa = port_length/port_resist/wire_rad^2/pi/1e-3;
+CSX = SetMaterialProperty(CSX,'resist','Kappa',kappa);
+
+start=[coil_rad+feed_length 0 (coil_length-port_length)/2];
+stop=[coil_rad+feed_length 0 (coil_length+port_length)/2];
+%start(3)=(coil_length-port_length)/2;stop(3)=(coil_length+port_length)/2;
+CSX = AddCylinder(CSX,'resist',5 ,start,stop,wire_rad);
+
+CSX = AddExcitation(CSX,'excite',0,[0 0 1]);
+CSX = AddCylinder(CSX,'excite', 0 ,start,stop,wire_rad);
+
+%% define voltage calc boxes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%voltage calc
+CSX = AddProbe(CSX,'ut1',0);
+CSX = AddBox(CSX,'ut1', 0 ,stop,start);
+
+%current calc
+CSX = AddProbe(CSX,'it1',1);
+start(3) = coil_length/2+mesh_size;stop(3) = coil_length/2+mesh_size;
+start(1) = start(1)-2;start(2) = start(2)-2;
+stop(1) = stop(1)+2;stop(2) = stop(2)+2;
+CSX = AddBox(CSX,'it1', 0 ,start,stop);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et_');
+start = [mesh.x(1) , 0 , mesh.z(1)];
+stop = [mesh.x(end) , 0 , mesh.z(end)];
+CSX = AddBox(CSX,'Et_',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht_','DumpType',1);
+start = [mesh.x(1) , 0 , mesh.z(1)];
+stop = [mesh.x(end) , 0 , mesh.z(end)];
+CSX = AddBox(CSX,'Ht_',0 , start,stop);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+%% run openEMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+
+%% postproc & do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+U = ReadUI('ut1','tmp/');
+I = ReadUI('it1','tmp/');
+
+Z = U.FD{1}.val./I.FD{1}.val;
+f = U.FD{1}.f;
+L = imag(Z)./(f*2*pi);
+R = real(Z);
+ind = find(f<f_max);
+
+subplot(2,1,1);
+plot(f(ind)*1e-6,L(ind)*1e9,'Linewidth',2);
+xlabel('frequency (MHz)');
+ylabel('coil inductance (nH)');
+grid on;
+subplot(2,1,2);
+plot(f(ind)*1e-6,R(ind),'Linewidth',2);
+hold on
+plot(f(ind)*1e-6,imag(Z(ind)),'r','Linewidth',2);
+xlabel('frequency (MHz)');
+ylabel('resistance (Ohm)');
+grid on;
+legend( {'real','imaginary'}, 'location', 'northwest' )
+
+figure
+plot(U.TD{1}.t/1e-6,U.TD{1}.val,'Linewidth',2);
+xlabel('time (us)');
+ylabel('amplitude (V)');
+grid on;
diff --git a/openEMS/matlab/examples/other/LumpedElement.m b/openEMS/matlab/examples/other/LumpedElement.m
new file mode 100644
index 0000000..d44094c
--- /dev/null
+++ b/openEMS/matlab/examples/other/LumpedElement.m
@@ -0,0 +1,158 @@
+%
+% EXAMPLE / other / lumped elements
+%
+% This example demonstrates how to:
+% - use lumped elements
+%
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.21-3
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+f_max = 100e6;
+f_excite = 300e6;
+SimBox = 100;
+mesh_size = 2;
+
+Lumped.R = 1000;
+Lumped.C = 10e-12;
+
+% the parasitice inductance of the feeding has to be deduced with a R=0
+% simulation
+parasitic_L = 63e-9;
+
+%% define openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+% openEMS_opts = [openEMS_opts ' --debug-operator'];
+
+Sim_Path = 'tmp';
+Sim_CSX = 'lumped.xml';
+
+[status, message, messageid] = rmdir(Sim_Path,'s');
+[status,message,messageid] = mkdir(Sim_Path);
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(30000,1e-6);
+FDTD = SetGaussExcite(FDTD,f_excite/2,f_excite/2);
+BC = [1 1 1 1 1 1];
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = SmoothMeshLines([-SimBox/2,+SimBox/2],mesh_size);
+mesh.y = SmoothMeshLines([-SimBox/2,+SimBox/2],mesh_size);
+mesh.z = SmoothMeshLines([-SimBox/2,+SimBox/2],mesh_size);
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+
+%% create structure
+% insert curve port
+start = [ 10 -10 0];
+stop = [ 10 10 0];
+CSX = AddCurvePort(CSX,0,1,100,start,stop,'excite');
+
+% insert lumped element
+CSX = AddLumpedElement( CSX, 'Capacitor', 1, 'C', Lumped.C, 'R', Lumped.R);
+start = [ -14 -4 -4];
+stop = [ -6 4 4];
+CSX = AddBox( CSX, 'Capacitor', 0, start, stop );
+
+% insert feeding wire
+CSX = AddMetal(CSX,'metal');
+%first point
+points(1,1) = -10;
+points(2,1) = 4;
+points(3,1) = 0;
+%second point
+points(1,2) = -10;
+points(2,2) = 15;
+points(3,2) = 0;
+%3 point
+points(1,end+1) = 10;
+points(2,end) = 15;
+points(3,end) = 0;
+%4 point
+points(1,end+1) = 10;
+points(2,end) = 10;
+points(3,end) = 0;
+CSX = AddCurve(CSX,'metal', 10, points);
+
+points(2,:) = -1*points(2,:);
+CSX = AddCurve(CSX,'metal', 10, points);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+% CSXGeomPlot([Sim_Path '/' Sim_CSX]);
+
+%% run openEMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+
+%% postproc & do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+f = linspace(1e6,f_max,1001);
+w = 2*pi*f;
+% read currents and voltages
+U = ReadUI('port_ut1','tmp/',f);
+I = ReadUI('port_it1','tmp/',f);
+
+% calculate analytic impedance
+if (Lumped.R>=0)
+ Z_a = Lumped.R*(1-1i*w*Lumped.C*Lumped.R)./(1+(w*Lumped.C*Lumped.R).^2);
+else
+ Z_a = -1i./(w*Lumped.C);
+end
+
+% calculate numerical impedance
+Z = U.FD{1}.val./I.FD{1}.val;
+
+% remove parasitic feeding effects
+Z = Z - 1i*w*parasitic_L;
+
+L = imag(Z)./w;
+C = -1./(w.*imag(Z));
+C(find(C<0)) = nan;
+L(find(L<0)) = nan;
+R = real(Z);
+
+subplot(2,1,1);
+plot(f*1e-6,C*1e12,'Linewidth',2);
+xlabel('frequency (MHz)');
+ylabel('capacitance (pF)');
+grid on;
+subplot(2,1,2);
+plot(f*1e-6,L*1e9,'Linewidth',2);
+xlabel('frequency (MHz)');
+ylabel('inductance (nH)');
+grid on;
+
+figure();
+plot(f*1e-6,R,'Linewidth',2);
+hold on
+plot(f*1e-6,imag(Z),'r--','Linewidth',2);
+
+plot(f*1e-6,real(Z_a),'g-.','Linewidth',1);
+plot(f*1e-6,imag(Z_a),'m--','Linewidth',1);
+
+xlabel('frequency (MHz)');
+ylabel('resistance (Ohm)');
+grid on;
+legend( '\Re\{Z\}','\Im\{Z\}','\Re\{Z_{analytisch}\}','\Im\{Z_{analytisch}\}', 'location', 'northeast' )
+
+figure();
+errorR = (R-real(Z_a))./R*100;
+errorX = (imag(Z)-imag(Z_a))./imag(Z)*100;
+plot(f*1e-6,errorR,'Linewidth',2);
+hold on
+grid on;
+plot(f*1e-6,errorX,'r--','Linewidth',2);
+xlabel('frequency (MHz)');
+ylabel('error (%)');
diff --git a/openEMS/matlab/examples/other/Metamaterial_PlaneWave_Drude.m b/openEMS/matlab/examples/other/Metamaterial_PlaneWave_Drude.m
new file mode 100644
index 0000000..db72b3e
--- /dev/null
+++ b/openEMS/matlab/examples/other/Metamaterial_PlaneWave_Drude.m
@@ -0,0 +1,147 @@
+%%%%%%%%%%%%%%%%%%%%%%%
+% example demonstrating double drude meta-material
+%
+% tested with openEMS v0.0.28
+%
+% author: Thorsten Liebig @ 2010,2012
+%%%%%%%%%%%%%%%%%%%%%%%
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+postproc_only = 0; %set to 1 if the simulation is already done
+
+Settings = [];
+Settings.LogFile = 'openEMS.log';
+
+pic_size = round([1400 1400/4]); %define the animation picture size
+
+%simulation domain setup (in mm)
+length = 500;
+width = 10;
+mesh_res = 0.5; % mesh resolution
+height = 3*mesh_res; % hight is ony 3 lines with PEC (top/bottom) --> quasi 2D
+
+%FDTD setup
+f0 = 5e9; %center frequency
+f_BW = f0/sqrt(2); %bandwidth
+MTM.eps_R = 1;
+MTM.mue_R = 1;
+MTM.f0 = f0; %plasma frequency of the drude material
+MTM.relaxTime = 5e-9; %relaxation time (smaller number results in greater losses, set to 0 to disable)
+MTM.length = 250; %length of the metamaterial
+N_TS = 5e4; %number of timesteps
+endCriteria = 1e-5; %stop simulation if signal is at -50dB
+
+%constants
+physical_constants
+
+%% define openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '-vvv';
+
+Sim_Path = 'MTM_PW_Drude';
+Sim_CSX = 'MTM_PW_Drude.xml';
+
+if (postproc_only==0)
+
+ if (exist(Sim_Path,'dir'))
+ rmdir(Sim_Path,'s');
+ end
+ mkdir(Sim_Path);
+
+ %% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ FDTD = InitFDTD(N_TS,endCriteria,'OverSampling',10);
+ FDTD = SetGaussExcite(FDTD,0,2*f0);
+ BC = [1 1 0 0 2 2];
+ FDTD = SetBoundaryCond(FDTD,BC);
+
+ %% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ CSX = InitCSX();
+ mesh.x = -width/2 : mesh_res : width/2;
+ mesh.y = -height/2 : mesh_res : height/2;
+ mesh.z = -length/2 : mesh_res : length/2;
+ CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+ %% apply the plane wave excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ start=[-width/2 -height/2 ,mesh.z(3)];
+ stop=[width/2 height/2 mesh.z(3)];
+ CSX = AddExcitation(CSX,'excite',0,[0 1 0]); % excite E_y
+ CSX = AddBox(CSX,'excite',0 ,start,stop);
+
+ %% apply drude material %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ CSX = AddLorentzMaterial(CSX,'drude');
+ CSX = SetMaterialProperty(CSX,'drude','Epsilon',MTM.eps_R,'EpsilonPlasmaFrequency',MTM.f0,'EpsilonRelaxTime',MTM.relaxTime);
+ CSX = SetMaterialProperty(CSX,'drude','Mue',MTM.mue_R,'MuePlasmaFrequency',MTM.f0,'MueRelaxTime',MTM.relaxTime);
+ start=[mesh.x(1) mesh.y(1) -MTM.length/2];
+ stop =[mesh.x(end) mesh.y(end) MTM.length/2];
+ CSX = AddBox(CSX,'drude', 10 ,start,stop);
+
+ %% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ CSX = AddDump(CSX,'Et','FileType',1,'SubSampling','10,10,1');
+ start = [mesh.x(2) ,0 , mesh.z(1)];
+ stop = [mesh.x(end-1) , 0 , mesh.z(end)];
+ CSX = AddBox(CSX,'Et',0 , start,stop);
+
+ %% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+ %% run openEMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts, Settings);
+
+end
+
+%% plot the drude type material dependency
+f = linspace(0.1*f0,2*f0,501);
+w = 2*pi*f;
+epsr = MTM.eps_R * (1 - (2*pi*MTM.f0)^2./( w.^2 - 1j*w./MTM.relaxTime ));
+muer = MTM.mue_R * (1 - (2*pi*MTM.f0)^2./( w.^2 - 1j*w./MTM.relaxTime ));
+plot(f,real(epsr),'Linewidth',2);
+hold on
+grid on
+plot(f,imag(epsr),'r--','Linewidth',2);
+plot(f,real(muer),'c-.','Linewidth',2);
+plot(f,imag(muer),'m-.','Linewidth',2);
+ylim([-10 MTM.eps_R])
+% l=legend('\Re \epsilon_r','\Im \epsilon_r','\Re \mue_r','\Im \mue_r');
+l=legend('$\Re\{\varepsilon_r\}$','$\Im\{\varepsilon_r\}$','$\Re\{\mu_r\}$','$\Im\{\mu_r\}$');
+set(l,'Interpreter','latex','Fontsize',12)
+
+%% plot E-fields
+freq = [f0/sqrt(2) f0 f0*sqrt(2)];
+field = ReadHDF5FieldData([Sim_Path '/Et.h5']);
+mesh_h5 = ReadHDF5Mesh([Sim_Path '/Et.h5']);
+
+ET = ReadUI('et',Sim_Path);
+ef = DFT_time2freq(ET.TD{1}.t,ET.TD{1}.val,freq);
+
+field_FD = GetField_TD2FD(field, freq);
+
+mesh.x = linspace(-500,500,numel(mesh_h5.lines{1})); %make animation wider...
+mesh.y = mesh_h5.lines{2};
+mesh.z = mesh_h5.lines{3};
+
+[X Z] = meshgrid(mesh.x,mesh.z);
+X = X';
+Z = Z';
+
+for n=1:numel(field_FD.FD.values)
+ Ec{n} = squeeze(field_FD.FD.values{n}/ef(n));
+end
+
+%%
+figure('Position',[10 100 pic_size(1) pic_size(2)]);
+phase = linspace(0,2*pi,21);
+disp('press CTRL+C to stop animation');
+while (1)
+ for ph = phase(1:end-1)
+ for n=1:numel(Ec)
+ subplot(1,numel(Ec),n)
+ E = real(Ec{n}.*exp(1j*ph));
+ surf(X,Z,E(:,:,2));
+ title(['f_0 = ' num2str(freq(n)*1e-9) ' GHz'])
+ end
+ pause(0.1);
+ end
+end
diff --git a/openEMS/matlab/examples/other/PML_reflection_analysis.m b/openEMS/matlab/examples/other/PML_reflection_analysis.m
new file mode 100644
index 0000000..f243a83
--- /dev/null
+++ b/openEMS/matlab/examples/other/PML_reflection_analysis.m
@@ -0,0 +1,196 @@
+%
+% fake-PML parallel plate waveguide example
+%
+% this example analyzes the reflection coefficient of a vacuum-pml
+% interface
+%
+
+%
+% currently this example uses a normal material with a certain conductivity
+% profile and not a pml
+%
+
+close all
+% clear
+clc
+
+physical_constants
+
+
+postprocessing_only = 0;
+
+
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+drawingunit = 1e-6; % specify everything in um
+
+length = 10000;
+epr = 1;
+
+mesh_res = [200 200 200];
+max_timesteps = 100000;
+min_decrement = 1e-6;
+f_max = 8e9;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD( max_timesteps, min_decrement );
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = [0 0 1 1 0 0];
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% mesh grading
+N_pml = 8;
+pml_delta = cumsum(mesh_res(1) * 1.0 .^ (1:N_pml));
+% pml_delta = cumsum([200 200 200 200 200]);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = 0 : mesh_res(1) : length;
+mesh.x = [mesh.x(1) - fliplr(pml_delta), mesh.x];
+mesh.y = -2*mesh_res(2) : mesh_res(2) : 2*mesh_res(2);
+mesh.z = 0 : mesh_res(3) : 4*mesh_res(3);
+CSX = DefineRectGrid( CSX, drawingunit, mesh );
+
+%% fake pml %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+g = 2; % 2..3
+R0 = 1e-6; % requested analytical reflection coefficient
+Zm = sqrt(MUE0/(EPS0*epr)); % calculate reflection for substrate/pml interface
+delta = pml_delta(end) * drawingunit;
+deltal = mean(diff(pml_delta)) * drawingunit;
+kappa0 = -log(R0)*log(g)/( 2*Zm*deltal*(g^(delta/deltal)-1) );
+
+% kappa0 = 1.05;
+CSX = AddMaterial( CSX, 'pml_xmin' );
+CSX = SetMaterialProperty( CSX, 'pml_xmin', 'Epsilon', epr );
+CSX = SetMaterialProperty( CSX, 'pml_xmin', 'Kappa', kappa0 );
+CSX = SetMaterialProperty( CSX, 'pml_xmin', 'Sigma', kappa0 * MUE0/(EPS0*epr) );
+CSX = SetMaterialWeight( CSX, 'pml_xmin', 'Kappa', [num2str(g) '^((abs(x-100)-' num2str(abs(mesh.x(N_pml+1))) ')/(' num2str(deltal) '/' num2str(drawingunit) '))'] ); % g^(rho/deltal)*kappa0
+CSX = SetMaterialWeight( CSX, 'pml_xmin', 'Sigma', [num2str(g) '^((abs(x-100)-' num2str(abs(mesh.x(N_pml+1))) ')/(' num2str(deltal) '/' num2str(drawingunit) '))'] );
+start = [mesh.x(1), mesh.y(1), mesh.z(1)];
+stop = [100, mesh.y(end), mesh.z(end)];
+CSX = AddBox( CSX, 'pml_xmin', 1, start, stop );
+
+figure
+x = [-fliplr(pml_delta) 50];
+plot( x, kappa0 * g.^((abs(x-50)-abs(mesh.x(N_pml+1)))./(deltal/drawingunit)) ,'x-');
+xlabel( 'x / m' );
+ylabel( 'kappa' );
+figure
+title( 'conductivity profile inside the material' );
+
+%% excitation
+CSX = AddExcitation( CSX, 'excitation1', 0, [0 0 1]);
+idx = interp1( mesh.x, 1:numel(mesh.x), length*2/3, 'nearest' );
+start = [mesh.x(idx), mesh.y(1), mesh.z(1)];
+stop = [mesh.x(idx), mesh.y(end), mesh.z(end)];
+CSX = AddBox( CSX, 'excitation1', 0, start, stop );
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump( CSX, 'Et_', 'DumpMode', 2 );
+start = [mesh.x(1), mesh.y(1), mesh.z(3)];
+stop = [mesh.x(end), mesh.y(end), mesh.z(3)];
+CSX = AddBox( CSX, 'Et_', 0, start, stop );
+
+CSX = AddDump( CSX, 'Ht_', 'DumpType', 1, 'DumpMode', 2 );
+CSX = AddBox( CSX, 'Ht_', 0, start, stop );
+
+% hdf5 file
+CSX = AddDump( CSX, 'E', 'DumpType', 0, 'DumpMode', 2, 'FileType', 1 );
+idx = interp1( mesh.x, 1:numel(mesh.x), length*1/3, 'nearest' );
+start = [mesh.x(idx), mesh.y(3), mesh.z(1)];
+stop = [mesh.x(idx), mesh.y(3), mesh.z(end)];
+CSX = AddBox( CSX, 'E', 0, start, stop );
+
+% hdf5 file
+CSX = AddDump( CSX, 'H', 'DumpType', 1, 'DumpMode', 2, 'FileType', 1 );
+idx = interp1( mesh.x, 1:numel(mesh.x), length*1/3, 'nearest' );
+start = [mesh.x(idx), mesh.y(1), mesh.z(3)];
+stop = [mesh.x(idx), mesh.y(end), mesh.z(3)];
+CSX = AddBox( CSX, 'H', 0, start, stop );
+
+%% define openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-operator'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+% openEMS_opts = [openEMS_opts ' --showProbeDiscretization'];
+openEMS_opts = [openEMS_opts ' --engine=fastest'];
+
+Sim_Path = 'tmp';
+Sim_CSX = 'PML_reflection_analysis.xml';
+
+if ~postprocessing_only
+ [~,~,~] = rmdir(Sim_Path,'s');
+ [~,~,~] = mkdir(Sim_Path);
+end
+
+%% Write openEMS compatible xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+%% cd to working dir and run openEMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~postprocessing_only
+ savePath = pwd;
+ cd(Sim_Path); %cd to working dir
+ args = [Sim_CSX ' ' openEMS_opts];
+ invoke_openEMS(args);
+ cd(savePath)
+end
+
+
+%% postproc & do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% E_coords = ReadHDF5Mesh( [Sim_Path '/E.h5'] );
+% H_coords = ReadHDF5Mesh( [Sim_Path '/H.h5'] );
+E = ReadHDF5FieldData( [Sim_Path '/E.h5'] );
+H = ReadHDF5FieldData( [Sim_Path '/H.h5'] );
+E_val = cellfun( @(x) squeeze(x(1,1,:,3)), E.values, 'UniformOutput', false );
+H_val = cellfun( @(x) squeeze(x(1,:,1,2)), H.values, 'UniformOutput', false );
+E_val = cell2mat(E_val);
+H_val = cell2mat(H_val.');
+
+% pick center point
+Et = E_val(3,:);
+Ht = H_val(:,3).';
+
+delta_t_2 = H.time(1) - E.time(1); % half time-step (s)
+
+% create finer frequency resolution
+f = linspace( 0, f_max, 1601 );
+Ef = DFT_time2freq( E.time, Et, f );
+Hf = DFT_time2freq( H.time, Ht, f );
+Hf = Hf .* exp(-1i*2*pi*f*delta_t_2); % compensate half time-step advance of H-field
+
+% H is now time interpolated, but the position is not corrected with
+% respect to E
+
+% figure
+% plot( E.time/1e-6, Et );
+% xlabel('time (us)');
+% ylabel('amplitude (V)');
+% grid on;
+% title( 'Time domain voltage probe' );
+%
+% figure
+% plot( H.time/1e-6, Ht );
+% xlabel('time (us)');
+% ylabel('amplitude (A)');
+% grid on;
+% title( 'Time domain current probe' );
+
+
+Z0 = sqrt(MUE0/EPS0); % line impedance
+Z = Ef ./ Hf; % impedance at measurement plane
+gamma = (Z - Z0) ./ (Z + Z0);
+
+plot( f/1e9, 20*log10(abs(gamma)),'Linewidth',2);
+xlabel('frequency (GHz)');
+ylabel('reflection coefficient gamma (dB)');
+grid on;
+title( 'Reflection Coefficient' );
+
+if exist('ref_1','var')
+ hold on
+ plot( f/1e9, ref_1,'--','Linewidth',2, 'Color', [1 0 0]);
+ hold off
+end
+ref_1 = 20*log10(abs(gamma));
diff --git a/openEMS/matlab/examples/other/PlaneWave.m b/openEMS/matlab/examples/other/PlaneWave.m
new file mode 100644
index 0000000..5e0d3e8
--- /dev/null
+++ b/openEMS/matlab/examples/other/PlaneWave.m
@@ -0,0 +1,69 @@
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+length = 5000;
+width = 300;
+height = 200;
+mesh_res = 15;
+abs_length = mesh_res*10;
+
+EPS0 = 8.85418781762e-12;
+MUE0 = 1.256637062e-6;
+
+%% define openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+openEMS_opts = [openEMS_opts ' --engine=fastest'];
+
+Sim_Path = 'tmp';
+Sim_CSX = 'plane_wave.xml';
+
+if (exist(Sim_Path,'dir'))
+ rmdir(Sim_Path,'s');
+end
+mkdir(Sim_Path);
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(5000,1e-5,'OverSampling',10);
+FDTD = SetGaussExcite(FDTD,0.5e9,0.5e9);
+BC = [1 1 0 0 2 2];
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = -width/2 : mesh_res : width/2;
+mesh.y = -height/2 : mesh_res : height/2;
+mesh.z = 0 : mesh_res : length;
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start=[-width/2 -height/2 mesh.z(3)];
+stop =[ width/2 height/2 mesh.z(3)];
+CSX = AddExcitation(CSX,'excite',0,[0 1 0]);
+CSX = AddBox(CSX,'excite',0 ,start,stop);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et','FileType',1,'SubSampling','4,4,4');
+start = [mesh.x(1) , mesh.y(1) , mesh.z(1)];
+stop = [mesh.x(end) , mesh.y(end) , mesh.z(end)];
+CSX = AddBox(CSX,'Et',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht','DumpType',1,'FileType',1,'SubSampling','4,4,4','DumpMode',2);
+CSX = AddBox(CSX,'Ht',0,start,stop);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+%% run openEMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+
+%% do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PlotArgs.slice = {mesh.x(round(end/2)) mesh.y(round(end/2)) mesh.z(round(end/2))};
+PlotArgs.pauseTime=0.01;
+PlotArgs.component=1;
+PlotArgs.Limit = 'auto';
+
+PlotHDF5FieldData('tmp/Ht.h5',PlotArgs)
diff --git a/openEMS/matlab/examples/other/gauss_excitation_test.m b/openEMS/matlab/examples/other/gauss_excitation_test.m
new file mode 100644
index 0000000..a7e166e
--- /dev/null
+++ b/openEMS/matlab/examples/other/gauss_excitation_test.m
@@ -0,0 +1,72 @@
+%
+% this script evaluates the same gaussian excitation function, as openEMS does
+%
+
+clear
+close all
+clc
+
+f0 = 0e9;
+fc = 10e9;
+dT = 1e-12; % sample time-step
+
+
+sigma = 1/sqrt(8/9)/pi/fc;
+t0 = sqrt(18)/sqrt(8/9)/pi/fc;
+
+len = 2 * 9/(2*pi*fc) / dT; % gauss length
+
+for n=1:len
+ t_(n) = (n-1)*dT;
+ ex(n) = cos(2*pi*f0*((n-1)*dT - 9/(2*pi*fc))) .* exp(-((t_(n)-t0)/sigma)^2/2);
+end
+
+plot(t_/1e-9,ex)
+xlabel( 'time (ns)' );
+ylabel( 'amplitude' );
+
+
+disp( ['Amplitude at t=0: ' num2str(20*log10(abs(ex(1))/1)) ' dB'] );
+
+val = DFT_time2freq( t_, ex, [f0-fc f0 f0+fc] );
+disp( ['Amplitude at f=f0-fc: ' num2str(20*log10(abs(val(1))/abs(val(2)))) ' dB'] );
+disp( ['Amplitude at f=f0+fc: ' num2str(20*log10(abs(val(3))/abs(val(2)))) ' dB'] );
+
+% calculate frequency domain via slow DFT
+freq = linspace(f0-fc,f0+fc,1000);
+val = DFT_time2freq( t_, ex, freq );
+figure
+plot( freq/1e9, abs(val) )
+
+% overlay the FFT result
+[f,val_fft] = FFT_time2freq( t_, ex );
+val_fft = val_fft((f0-fc<=f) & (f<=f0+fc));
+f = f((f0-fc<=f) & (f<=f0+fc));
+hold on
+plot( f/1e9, abs(val_fft), 'r' )
+hold on
+
+if (f0==0)
+ Fw = sigma*sqrt(2*pi)*exp(-0.5*(sigma*2*pi*f).^2);
+ plot( f/1e9, 2*abs(Fw), 'g--' )
+ legend('dft','fft','analytic')
+else
+ legend('dft','fft')
+end
+
+xlim([0 max(f)/1e9])
+
+xlabel( 'frequency (GHz)' );
+ylabel( 'amplitude' );
+
+
+% dB
+figure
+val = val(freq>=0);
+freq = freq(freq>=0);
+plot( freq/1e9, 20*log10(abs(val)/max(abs(val))), 'r' )
+xlabel( 'frequency (GHz)' );
+ylabel( 'amplitude (dB)' );
+
+
+
diff --git a/openEMS/matlab/examples/other/resistance_sheet.m b/openEMS/matlab/examples/other/resistance_sheet.m
new file mode 100644
index 0000000..b63c00e
--- /dev/null
+++ b/openEMS/matlab/examples/other/resistance_sheet.m
@@ -0,0 +1,207 @@
+%
+% resistance "sheet" example
+%
+% this example calculates the reflection coefficient of a sheet resistance
+% at the end of a parallel plate wave guide
+%
+% play around with the R and epr values
+%
+
+close all
+clear
+clc
+
+physical_constants
+
+
+postprocessing_only = 0;
+
+
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+epr = 1; % relative permittivity of the material inside the parallel plate waveguide
+
+% define the resistance
+R = sqrt(MUE0/(EPS0*epr)); % matched load (no reflections) (vacuum: approx. 377 Ohm)
+% R = 1e-10; % short circuit (reflection coefficient = -1)
+% R = 1e10; % open circuit (reflection coefficient = 1)
+
+
+drawingunit = 1e-6; % specify everything in um
+length = 10000;
+mesh_res = [200 200 200];
+max_timesteps = 100000;
+min_decrement = 1e-6;
+f_max = 1e9;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD( max_timesteps, min_decrement );
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = [1 2 1 1 0 0]; % 0:PEC 1:PMC 2:MUR-ABC
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = 0 : mesh_res(1) : length;
+mesh.y = -2*mesh_res(2) : mesh_res(2) : 2*mesh_res(2);
+mesh.z = 0 : mesh_res(3) : 4*mesh_res(3);
+CSX = DefineRectGrid( CSX, drawingunit, mesh );
+
+%% measurement plane & reference plane
+meas_plane_xidx = interp1( mesh.x, 1:numel(mesh.x), length*1/3, 'nearest' );
+ref_plane_xidx = 3;
+
+%% fill the parallel plate waveguide with material
+CSX = AddMaterial( CSX, 'm1' );
+CSX = SetMaterialProperty( CSX, 'm1', 'Epsilon', epr );
+start = [mesh.x(1), mesh.y(1), mesh.z(1)];
+stop = [mesh.x(end), mesh.y(end), mesh.z(end)];
+CSX = AddBox( CSX, 'm1', -1, start, stop );
+
+%% excitation
+CSX = AddExcitation( CSX, 'excitation1', 0, [0 0 1]);
+idx = interp1( mesh.x, 1:numel(mesh.x), length*2/3, 'nearest' );
+start = [mesh.x(idx), mesh.y(1), mesh.z(1)];
+stop = [mesh.x(idx), mesh.y(end), mesh.z(end)];
+CSX = AddBox( CSX, 'excitation1', 0, start, stop );
+
+%% define the sheet resistance
+start = [mesh.x(ref_plane_xidx-1), mesh.y(1), mesh.z(1)];
+stop = [mesh.x(ref_plane_xidx), mesh.y(end), mesh.z(end)];
+l = abs(mesh.z(end) - mesh.z(1)) * drawingunit; % length of the "sheet"
+A = abs(start(1) - stop(1)) * abs(mesh.y(end) - mesh.y(1)) * drawingunit^2; % area of the "sheet"
+kappa = l/A / R; % [kappa] = S/m
+CSX = AddMaterial( CSX, 'sheet_resistance' );
+CSX = SetMaterialProperty( CSX, 'sheet_resistance', 'Kappa', kappa );
+CSX = AddBox( CSX, 'sheet_resistance', 0, start, stop );
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump( CSX, 'Et_', 'DumpMode', 2 );
+start = [mesh.x(1), mesh.y(1), mesh.z(3)];
+stop = [mesh.x(end), mesh.y(end), mesh.z(3)];
+CSX = AddBox( CSX, 'Et_', 0, start, stop );
+
+CSX = AddDump( CSX, 'Ht_', 'DumpType', 1, 'DumpMode', 2 );
+CSX = AddBox( CSX, 'Ht_', 0, start, stop );
+
+% hdf5 file
+CSX = AddDump( CSX, 'E', 'DumpType', 0, 'DumpMode', 2, 'FileType', 1 );
+start = [mesh.x(meas_plane_xidx), mesh.y(3), mesh.z(1)];
+stop = [mesh.x(meas_plane_xidx), mesh.y(3), mesh.z(end)];
+CSX = AddBox( CSX, 'E', 0, start, stop );
+
+% hdf5 file
+CSX = AddDump( CSX, 'H', 'DumpType', 1, 'DumpMode', 2, 'FileType', 1 );
+start = [mesh.x(meas_plane_xidx), mesh.y(1), mesh.z(3)];
+stop = [mesh.x(meas_plane_xidx), mesh.y(end), mesh.z(3)];
+CSX = AddBox( CSX, 'H', 0, start, stop );
+
+%% define openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-operator'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+% openEMS_opts = [openEMS_opts ' --showProbeDiscretization'];
+openEMS_opts = [openEMS_opts ' --engine=fastest'];
+
+Sim_Path = 'tmp';
+Sim_CSX = 'tmp.xml';
+
+if ~postprocessing_only
+ [~,~,~] = rmdir(Sim_Path,'s');
+ [~,~,~] = mkdir(Sim_Path);
+end
+
+%% Write openEMS compatible xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+%% cd to working dir and run openEMS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~postprocessing_only
+ savePath = pwd;
+ cd(Sim_Path); %cd to working dir
+ args = [Sim_CSX ' ' openEMS_opts];
+ invoke_openEMS(args);
+ cd(savePath)
+end
+
+
+%% postproc & do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% E_coords = ReadHDF5Mesh( [Sim_Path '/E.h5'] );
+% H_coords = ReadHDF5Mesh( [Sim_Path '/H.h5'] );
+E = ReadHDF5FieldData( [Sim_Path '/E.h5'] );
+H = ReadHDF5FieldData( [Sim_Path '/H.h5'] );
+E_val = cellfun( @(x) squeeze(x(1,1,:,3)), E.values, 'UniformOutput', false );
+H_val = cellfun( @(x) squeeze(x(1,:,1,2)), H.values, 'UniformOutput', false );
+E_val = cell2mat(E_val);
+H_val = cell2mat(H_val.');
+
+% pick center point
+Et = E_val(3,:);
+Ht = H_val(:,3).';
+
+delta_t_2 = H.time(1) - E.time(1); % half time-step (s)
+
+% create finer frequency resolution
+f = linspace( 0, f_max, 201 );
+Ef = DFT_time2freq( E.time, Et, f );
+Hf = DFT_time2freq( H.time, Ht, f );
+Hf = Hf .* exp(-1i*2*pi*f*delta_t_2); % compensate half time-step advance of H-field
+
+% H is now time interpolated, but the position is not corrected with
+% respect to E
+
+% figure
+% plot( E.time/1e-6, Et );
+% xlabel('time (us)');
+% ylabel('amplitude (V)');
+% grid on;
+% title( 'Time domain voltage probe' );
+%
+% figure
+% plot( H.time/1e-6, Ht );
+% xlabel('time (us)');
+% ylabel('amplitude (A)');
+% grid on;
+% title( 'Time domain current probe' );
+
+
+Z0 = sqrt(MUE0/(EPS0*epr)); % line impedance
+Z = Ef ./ Hf; % impedance at measurement plane
+gamma = (Z - Z0) ./ (Z + Z0);
+
+% reference plane shift
+beta = 2*pi*f * sqrt(MUE0*(EPS0*epr)); % TEM wave
+meas_plane_x = mesh.x(meas_plane_xidx);
+ref_plane_x = mesh.x(ref_plane_xidx);
+gamma_refplane = gamma .* exp(2i*beta* (meas_plane_x-ref_plane_x)*drawingunit);
+Z_refplane = Z0 * (1+gamma_refplane)./(1-gamma_refplane);
+
+% smith chart
+figure
+if exist( 'smith', 'file' )
+ % smith chart
+ % www.ece.rutgers.edu/~orfanidi/ewa
+ % or cmt toolbox from git.ate.uni-duisburg.de
+ smith
+else
+ % poor man smith chart
+ plot( sin(0:0.01:2*pi), cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+ hold on
+% plot( 0.25+0.75*sin(0:0.01:2*pi), 0.75*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+ plot( 0.5+0.5*sin(0:0.01:2*pi), 0.5*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+% plot( 0.75+0.25*sin(0:0.01:2*pi), 0.25*cos(0:0.01:2*pi), 'Color', [.7 .7 .7] );
+ plot( [-1 1], [0 0], 'Color', [.7 .7 .7] );
+ axis equal
+end
+plot( real(gamma_refplane), imag(gamma_refplane), 'r*' );
+% plot( real(gamma), imag(gamma), 'k*' );
+title( 'reflection coefficient S11 at reference plane' )
+
+figure
+plot( f/1e9, [real(Z_refplane);imag(Z_refplane)],'Linewidth',2);
+xlabel('frequency (GHz)');
+ylabel('impedance (Ohm)');
+grid on;
+title( 'Impedance at reference plane' );
+legend( {'real','imag'} );
diff --git a/openEMS/matlab/examples/transmission_lines/CPW_Line.m b/openEMS/matlab/examples/transmission_lines/CPW_Line.m
new file mode 100644
index 0000000..6dac636
--- /dev/null
+++ b/openEMS/matlab/examples/transmission_lines/CPW_Line.m
@@ -0,0 +1,125 @@
+%
+% Tutorials / CPW_Line
+%
+% Describtion at:
+%
+% Tested with
+% - Octave 3.8.1
+% - openEMS v0.0.32
+%
+% (C) 2014 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+CPW_length = 40000;
+CPW_port_length = 10000;
+CPW_width = 1000;
+CPW_gap = 140;
+substrate_thickness = 512;
+substrate_width = 5000
+substrate_epr = 3.66;
+f_max = 10e9;
+air_spacing = 7000
+
+% use a finite line CPW waveguide
+if 1
+ feed_R = 50;
+ pml_add_cells = [8 8 8 8 8 8];
+ feed_shift_cells = 0;
+ x_spacing = air_spacing;
+else % or use a waveguide with start/end in a pml
+ feed_R = inf; % CPW ends in a pml --> disable termination resitance
+ feed_shift_cells = 10; % CPW ends in an 8 cells thick pml --> shift feed 10 cells
+ pml_add_cells = [0 0 8 8 8 8]; % do not add air-space in x-direction
+ x_spacing = 0; % do not add air-space in x-direction
+end
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD('EndCriteria', 1e-4);
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = [2 2 2 2 2 2];
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+resolution = c0/(f_max*sqrt(substrate_epr))/unit /30; % resolution of lambda/50
+edge_res = 40;
+mesh.x = SmoothMeshLines( [0 CPW_length/2 CPW_length/2+x_spacing], resolution, 1.5 ,0 );
+mesh.x = unique(sort([-mesh.x mesh.x]));
+mesh.y = SmoothMeshLines( [CPW_width/2+[-edge_res/3 +edge_res/3*2] CPW_gap+CPW_width/2+[-edge_res/3*2 +edge_res/3]], edge_res , 1.5 ,0);
+mesh.y = SmoothMeshLines( [0 mesh.y], edge_res*2, 1.3 ,0);
+mesh.y = SmoothMeshLines( [0 mesh.y substrate_width/2 substrate_width/2+air_spacing], resolution, 1.3 ,0);
+mesh.y = unique(sort([-mesh.y mesh.y]));
+mesh.z = SmoothMeshLines( [-air_spacing linspace(0,substrate_thickness,5) substrate_thickness+air_spacing], resolution );
+
+mesh = AddPML(mesh, pml_add_cells);
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% substrate
+CSX = AddMaterial( CSX, 'RO4350B' );
+CSX = SetMaterialProperty( CSX, 'RO4350B', 'Epsilon', substrate_epr );
+start = [-CPW_length/2, -substrate_width/2, 0];
+stop = [+CPW_length/2, +substrate_width/2, substrate_thickness];
+CSX = AddBox( CSX, 'RO4350B', 0, start, stop );
+
+%%
+CSX = AddMetal( CSX, 'CPW_PORT' );
+
+%% CPW port, with the measurement plane at the end of each port
+portstart = [ -CPW_length/2 , -CPW_width/2, substrate_thickness];
+portstop = [ -CPW_length/2+CPW_port_length, CPW_width/2, substrate_thickness];
+[CSX,port{1}] = AddCPWPort( CSX, 999, 1, 'CPW_PORT', portstart, portstop, CPW_gap, 'x', [0 1 0], 'ExcitePort', true, 'FeedShift', feed_shift_cells*resolution, 'MeasPlaneShift', CPW_port_length, 'Feed_R', feed_R);
+
+portstart = [ CPW_length/2 , -CPW_width/2, substrate_thickness];
+portstop = [ CPW_length/2-CPW_port_length, CPW_width/2, substrate_thickness];
+[CSX,port{2}] = AddCPWPort( CSX, 999, 2, 'CPW_PORT', portstart, portstop, CPW_gap, 'x', [0 1 0], 'MeasPlaneShift', CPW_port_length, 'Feed_R', feed_R);
+
+%% CPW
+CSX = AddMetal( CSX, 'CPW');
+start = [ -CPW_length/2+CPW_port_length, -CPW_width/2, substrate_thickness];
+stop = [ +CPW_length/2-CPW_port_length, CPW_width/2, substrate_thickness];
+CSX = AddBox(CSX, 'CPW', 999, start, stop);
+
+%% CPW grounds
+CSX = AddMetal( CSX, 'GND' );
+start = [-CPW_length/2, -CPW_width/2-CPW_gap, substrate_thickness];
+stop = [+CPW_length/2, -substrate_width/2 , substrate_thickness];
+CSX = AddBox(CSX, 'GND', 999, start, stop);
+
+start = [-CPW_length/2, +CPW_width/2+CPW_gap, substrate_thickness];
+stop = [+CPW_length/2, +substrate_width/2 , substrate_thickness];
+CSX = AddBox(CSX, 'GND', 999, start, stop);
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = 'tmp';
+Sim_CSX = 'CPW.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX );
+
+%% post-processing
+close all
+f = linspace( 1e6, f_max, 1601 );
+port = calcPort( port, Sim_Path, f, 'RefImpedance', 50);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,20*log10(abs(s11)),'k-','LineWidth',2);
+hold on;
+grid on;
+plot(f/1e9,20*log10(abs(s21)),'r--','LineWidth',2);
+legend('S_{11}','S_{21}');
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (GHz) \rightarrow','FontSize',12);
+
+
diff --git a/openEMS/matlab/examples/transmission_lines/Finite_Stripline.m b/openEMS/matlab/examples/transmission_lines/Finite_Stripline.m
new file mode 100644
index 0000000..da2b4a3
--- /dev/null
+++ b/openEMS/matlab/examples/transmission_lines/Finite_Stripline.m
@@ -0,0 +1,91 @@
+% example demonstrating the use of a stripline terminated by a resistance
+% (c) 2013 Thorsten Liebig
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+SL_length = 50000;
+SL_width = 520;
+SL_height = 500;
+substrate_thickness = SL_height;
+substrate_epr = 3.66;
+f_max = 7e9;
+
+Air_Spacer = 20000;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD();
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+resolution = c0/(f_max*sqrt(substrate_epr))/unit /50; % resolution of lambda/50
+mesh.x = SmoothMeshLines( [-SL_length/2 0 SL_length/2], resolution, 1.5 ,0 );
+mesh.y = SmoothMeshLines( [0 SL_width/2+[-resolution/3 +resolution/3*2]/4], resolution/4 , 1.5 ,0);
+mesh.y = SmoothMeshLines( [-10*SL_width -mesh.y mesh.y 10*SL_width], resolution, 1.3 ,0);
+mesh.z = linspace(0,substrate_thickness,5);
+mesh.z = sort(unique([mesh.z -mesh.z]));
+
+%% substrate
+CSX = AddMaterial( CSX, 'RO4350B' );
+CSX = SetMaterialProperty( CSX, 'RO4350B', 'Epsilon', substrate_epr );
+start = [mesh.x(1), mesh.y(1), mesh.z(1)];
+stop = [mesh.x(end), mesh.y(end), mesh.z(end)];
+CSX = AddBox( CSX, 'RO4350B', 0, start, stop );
+
+%% add air spacer
+mesh.x = [mesh.x mesh.x(1)-Air_Spacer mesh.x(end)+Air_Spacer];
+mesh.y = [mesh.y mesh.y(1)-Air_Spacer mesh.y(end)+Air_Spacer];
+mesh.z = [mesh.z mesh.z(1)-Air_Spacer mesh.z(end)+Air_Spacer];
+mesh = SmoothMesh(mesh, c0/f_max/unit/20);
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% SL port
+CSX = AddMetal( CSX, 'PEC' );
+portstart = [ -SL_length/2, -SL_width/2, 0];
+portstop = [ 0, SL_width/2, 0];
+[CSX,port{1}] = AddStripLinePort( CSX, 999, 1, 'PEC', portstart, portstop, SL_height, 'x', [0 0 -1], 'ExcitePort', true, 'Feed_R', 50, 'MeasPlaneShift', SL_length/3);
+
+portstart = [+SL_length/2, -SL_width/2, 0];
+portstop = [0 , SL_width/2, 0];
+[CSX,port{2}] = AddStripLinePort( CSX, 999, 2, 'PEC', portstart, portstop, SL_height, 'x', [0 0 -1], 'MeasPlaneShift', SL_length/3, 'Feed_R', 50);
+
+% bottom PEC plane
+CSX = AddBox(CSX, 'PEC', 999, [-SL_length/2 -10*SL_width -SL_height],[+SL_length/2 +10*SL_width -SL_height]);
+% top PEC plane
+CSX = AddBox(CSX, 'PEC', 999, [-SL_length/2 -10*SL_width SL_height],[+SL_length/2 +10*SL_width SL_height]);
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = ['tmp_' mfilename];
+Sim_CSX = 'stripline.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX );
+
+%% post-processing
+close all
+f = linspace( 1e6, f_max, 1601 );
+port = calcPort( port, Sim_Path, f, 'RefImpedance', 50);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,20*log10(abs(s11)),'k-','LineWidth',2);
+hold on;
+grid on;
+plot(f/1e9,20*log10(abs(s21)),'r--','LineWidth',2);
+legend('S_{11}','S_{21}');
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (GHz) \rightarrow','FontSize',12);
+ylim([-50 2]);
+
diff --git a/openEMS/matlab/examples/transmission_lines/MSL.m b/openEMS/matlab/examples/transmission_lines/MSL.m
new file mode 100644
index 0000000..b6ec0b3
--- /dev/null
+++ b/openEMS/matlab/examples/transmission_lines/MSL.m
@@ -0,0 +1,185 @@
+%
+% EXAMPLE / microstrip / MSL
+%
+% Microstrip line on air "substrate" in z-direction.
+%
+% This example demonstrates:
+% - simple microstrip geometry
+% - characteristic impedance
+% - material grading function
+% - geometric priority concept
+%
+%
+% Tested with
+% - Matlab 2009b
+% - Octave 3.3.52
+% - openEMS v0.0.14
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% setup the simulation
+physical_constants;
+unit = 1e-3; % all length in mm
+
+% geometry
+abs_length = 100; % absorber length
+length = 600;
+width = 400;
+height = 200;
+MSL_width = 50;
+MSL_height = 10;
+
+%% prepare simulation folder
+Sim_Path = 'tmp';
+Sim_CSX = 'msl.xml';
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+max_timesteps = 2000;
+min_decrement = 1e-5; % equivalent to -50 dB
+f0 = 2e9; % center frequency
+fc = 1e9; % 10 dB corner frequency (in this case 1e9 Hz - 3e9 Hz)
+FDTD = InitFDTD( max_timesteps, min_decrement );
+FDTD = SetGaussExcite( FDTD, f0, fc );
+BC = {'PMC' 'PMC' 'PEC' 'PMC' 'PEC' 'PEC'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh
+% very simple mesh
+CSX = InitCSX();
+resolution = c0/(f0+fc)/unit /15; % resolution of lambda/15
+mesh.x = SmoothMeshLines( [-width/2, width/2, -MSL_width/2, MSL_width/2], resolution ); % create smooth lines from fixed lines
+mesh.y = SmoothMeshLines( [linspace(0,MSL_height,5) MSL_height+1 height], resolution );
+mesh.z = SmoothMeshLines( [0 length], resolution );
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% create MSL
+% attention! the skin effect is not simulated, because the MSL is
+% discretized with only one cell!
+CSX = AddMaterial( CSX, 'copper' );
+CSX = SetMaterialProperty( CSX, 'copper', 'Kappa', 56e6 );
+start = [-MSL_width/2, MSL_height, 0];
+stop = [ MSL_width/2, MSL_height+1, length];
+priority = 100; % the geometric priority is set to 100
+CSX = AddBox( CSX, 'copper', priority, start, stop );
+
+%% add excitation below the strip
+start = [-MSL_width/2, 0 , mesh.z(1)];
+stop = [ MSL_width/2, MSL_height, mesh.z(1)];
+CSX = AddExcitation( CSX, 'excite', 0, [0 -1 0] );
+CSX = AddBox( CSX, 'excite', 0, start, stop );
+
+%% fake pml
+% this "pml" is a normal material with graded losses
+% electric and magnetic losses are related to give low reflection
+% for normally incident TEM waves
+finalKappa = 1/abs_length^2;
+finalSigma = finalKappa*MUE0/EPS0;
+CSX = AddMaterial( CSX, 'fakepml' );
+CSX = SetMaterialProperty( CSX, 'fakepml', 'Kappa', finalKappa );
+CSX = SetMaterialProperty( CSX, 'fakepml', 'Sigma', finalSigma );
+CSX = SetMaterialWeight( CSX, 'fakepml', 'Kappa', ['pow(z-' num2str(length-abs_length) ',2)'] );
+CSX = SetMaterialWeight( CSX, 'fakepml', 'Sigma', ['pow(z-' num2str(length-abs_length) ',2)'] );
+start = [mesh.x(1) mesh.y(1) length-abs_length];
+stop = [mesh.x(end) mesh.y(end) length];
+% the geometric priority is set to 0, which is lower than the priority
+% of the MSL, thus the MSL (copper) has precendence
+priority = 0;
+CSX = AddBox( CSX, 'fakepml', priority, start, stop );
+
+%% define dump boxes
+start = [mesh.x(1), MSL_height/2, mesh.z(1)];
+stop = [mesh.x(end), MSL_height/2, mesh.z(end)];
+CSX = AddDump( CSX, 'Et_', 'DumpMode', 2 ); % cell interpolated
+CSX = AddBox( CSX, 'Et_', 0, start, stop );
+CSX = AddDump( CSX, 'Ht_', 'DumpType', 1, 'DumpMode', 2 ); % cell interpolated
+CSX = AddBox( CSX, 'Ht_', 0, start, stop );
+
+%% define voltage calc box
+% voltage calc boxes will automatically snap to the next mesh-line
+CSX = AddProbe( CSX, 'ut1', 0 );
+zidx = interp1( mesh.z, 1:numel(mesh.z), length/2, 'nearest' );
+start = [0 MSL_height mesh.z(zidx)];
+stop = [0 0 mesh.z(zidx)];
+CSX = AddBox( CSX, 'ut1', 0, start, stop );
+% add a second voltage probe to compensate space offset between voltage and
+% current
+CSX = AddProbe( CSX, 'ut2', 0 );
+start = [0 MSL_height mesh.z(zidx+1)];
+stop = [0 0 mesh.z(zidx+1)];
+CSX = AddBox( CSX, 'ut2', 0, start, stop );
+
+%% define current calc box
+% current calc boxes will automatically snap to the next dual mesh-line
+CSX = AddProbe( CSX, 'it1', 1 );
+xidx1 = interp1( mesh.x, 1:numel(mesh.x), -MSL_width/2, 'nearest' );
+xidx2 = interp1( mesh.x, 1:numel(mesh.x), MSL_width/2, 'nearest' );
+xdelta = diff(mesh.x);
+yidx1 = interp1( mesh.y, 1:numel(mesh.y), MSL_height, 'nearest' );
+yidx2 = interp1( mesh.y, 1:numel(mesh.y), MSL_height+1, 'nearest' );
+ydelta = diff(mesh.y);
+zdelta = diff(mesh.z);
+start = [mesh.x(xidx1)-xdelta(xidx1-1)/2, mesh.y(yidx1)-ydelta(yidx1-1)/2, mesh.z(zidx)+zdelta(zidx)/2];
+stop = [mesh.x(xidx2)+xdelta(xidx2)/2, mesh.y(yidx2)+ydelta(yidx2)/2, mesh.z(zidx)+zdelta(zidx)/2];
+CSX = AddBox( CSX, 'it1', 0, start, stop );
+
+%% write openEMS compatible xml-file
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+
+%% show the structure
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+
+%% run openEMS
+openEMS_opts = '';
+openEMS_opts = [openEMS_opts ' --engine=fastest'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+RunOpenEMS( Sim_Path, Sim_CSX, openEMS_opts );
+
+%% postprocess
+freq = linspace( f0-fc, f0+fc, 501 );
+U = ReadUI( {'ut1','ut2','et'}, 'tmp/', freq ); % time domain/freq domain voltage
+I = ReadUI( 'it1', 'tmp/', freq ); % time domain/freq domain current (half time step offset is corrected)
+
+% plot time domain voltage
+figure
+[ax,h1,h2] = plotyy( U.TD{1}.t/1e-9, U.TD{1}.val, U.TD{3}.t/1e-9, U.TD{3}.val );
+set( h1, 'Linewidth', 2 );
+set( h1, 'Color', [1 0 0] );
+set( h2, 'Linewidth', 2 );
+set( h2, 'Color', [0 0 0] );
+grid on
+title( 'time domain voltage' );
+xlabel( 'time t / ns' );
+ylabel( ax(1), 'voltage ut1 / V' );
+ylabel( ax(2), 'voltage et / V' );
+% now make the y-axis symmetric to y=0 (align zeros of y1 and y2)
+y1 = ylim(ax(1));
+y2 = ylim(ax(2));
+ylim( ax(1), [-max(abs(y1)) max(abs(y1))] );
+ylim( ax(2), [-max(abs(y2)) max(abs(y2))] );
+
+% calculate characteristic impedance
+% arithmetic mean of ut1 and ut2 -> voltage in the middle of ut1 and ut2
+U = (U.FD{1}.val + U.FD{2}.val) / 2;
+Z = U ./ I.FD{1}.val;
+
+% plot characteristic impedance
+figure
+plot( freq/1e6, real(Z), 'k-', 'Linewidth', 2 );
+hold on
+grid on
+plot( freq/1e6, imag(Z), 'r--', 'Linewidth', 2 );
+title( 'characteristic impedance of MSL' );
+xlabel( 'frequency f / MHz' );
+ylabel( 'characteristic impedance Z / Ohm' );
+legend( 'real', 'imag' );
+
+%% visualize electric and magnetic fields
+% you will find vtk dump files in the simulation folder (tmp/)
+% use paraview to visualize them
diff --git a/openEMS/matlab/examples/transmission_lines/MSL_Losses.m b/openEMS/matlab/examples/transmission_lines/MSL_Losses.m
new file mode 100644
index 0000000..95cad7b
--- /dev/null
+++ b/openEMS/matlab/examples/transmission_lines/MSL_Losses.m
@@ -0,0 +1,102 @@
+%
+% examples / microstrip / MSL_Losses
+%
+% This example demonstrates how to model sheet conductor losses
+%
+% Tested with
+% - Matlab 2013a / Octave 3.8.1+
+% - openEMS v0.0.32
+%
+% (C) 2012-2014 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+MSL.length = 10000;
+MSL.port_dist = 5000;
+MSL.width = 225;
+MSL.conductivity = 41e6;
+MSL.thickness = 35e-6;
+
+substrate.thickness = 250;
+substrate.epr = 9.8;
+
+f_start = 0e9;
+f_stop = 25e9;
+
+lambda = c0/f_stop;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD('endCriteria',1e-4);
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PEC' 'PML_8'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+resolution = c0/(f_stop*sqrt(substrate.epr))/unit /20;
+mesh.x = SmoothMeshLines( [-MSL.length*0.5-MSL.port_dist 0 MSL.length*0.5+MSL.port_dist], resolution, 1.3 ,0 );
+mesh.y = SmoothMeshLines2( [0 MSL.width/2], resolution/6 , 1.3);
+mesh.y = SmoothMeshLines( [-0.5*lambda/unit -mesh.y mesh.y 0.5*lambda/unit], resolution, 1.4);
+mesh.z = SmoothMeshLines( [linspace(0,substrate.thickness,10) 0.5*lambda/unit], resolution );
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% substrate
+CSX = AddMaterial( CSX, 'RO4350B' );
+CSX = SetMaterialProperty( CSX, 'RO4350B', 'Epsilon', substrate.epr );
+start = [mesh.x(1), mesh.y(1), 0];
+stop = [mesh.x(end), mesh.y(end), substrate.thickness];
+CSX = AddBox( CSX, 'RO4350B', 0, start, stop );
+
+%% MSL ports and lossy line
+CSX = AddConductingSheet( CSX, 'gold', MSL.conductivity, MSL.thickness );
+portstart = [ mesh.x(1), -MSL.width/2, substrate.thickness];
+portstop = [ mesh.x(1)+MSL.port_dist, MSL.width/2, 0];
+[CSX, port{1}] = AddMSLPort( CSX, 999, 1, 'gold', portstart, portstop, 0, [0 0 -1], 'ExcitePort', true, 'FeedShift', 10*resolution, 'MeasPlaneShift', MSL.port_dist);
+
+portstart = [mesh.x(end), -MSL.width/2, substrate.thickness];
+portstop = [mesh.x(end)-MSL.port_dist, MSL.width/2, 0];
+[CSX, port{2}] = AddMSLPort( CSX, 999, 2, 'gold', portstart, portstop, 0, [0 0 -1], 'MeasPlaneShift', MSL.port_dist );
+
+start = [mesh.x(1)+MSL.port_dist, -MSL.width/2, substrate.thickness];
+stop = [mesh.x(end)-MSL.port_dist, MSL.width/2, substrate.thickness];
+CSX = AddBox(CSX,'gold',500,start,stop);
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = 'tmp';
+Sim_CSX = 'msl.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX ,'');
+
+%% post-processing
+close all
+f = linspace( f_start, f_stop, 1601 );
+port = calcPort(port, Sim_Path, f, 'RefImpedance', 50);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,-20*log10(abs(s21)),'r--','LineWidth',2);
+grid on;
+hold on;
+ylabel('-|S_21| (dB)','Interpreter','None');
+xlabel('frequency (GHz)');
+
+%% plot 35um thickness loss model curve
+% values extracted from http://wcalc.sourceforge.net/cgi-bin/microstrip.cgi
+model.f = [1 2 2.5 3 4 5 7.5 10 12.5 15 17.5 20 25 ]; % frequency in GHz
+model.loss = [3.0 4.2 4.7 5.2 5.9 6.6 8.1 9.38 10.5 11.5 12.4 13.2 14.65]; % loss in db/m
+
+plot(model.f, model.loss * MSL.length * unit ,'k-','LineWidth',1);
+legend('FDTD simulated attenuation','t=35um, loss model by E. Hammerstad & F. Bekkadal','Location','NorthWest');
+
+
diff --git a/openEMS/matlab/examples/transmission_lines/Stripline.m b/openEMS/matlab/examples/transmission_lines/Stripline.m
new file mode 100644
index 0000000..71fd774
--- /dev/null
+++ b/openEMS/matlab/examples/transmission_lines/Stripline.m
@@ -0,0 +1,78 @@
+% example demonstrating the use of a stripline terminated by the pml
+% (c) 2013 Thorsten Liebig
+
+close all
+clear
+clc
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-6; % specify everything in um
+SL_length = 50000;
+SL_width = 520;
+SL_height = 500;
+substrate_thickness = SL_height;
+substrate_epr = 3.66;
+f_max = 7e9;
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD();
+FDTD = SetGaussExcite( FDTD, f_max/2, f_max/2 );
+BC = {'PML_8' 'PML_8' 'PMC' 'PMC' 'PEC' 'PEC'};
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+resolution = c0/(f_max*sqrt(substrate_epr))/unit /50; % resolution of lambda/50
+mesh.x = SmoothMeshLines( [-SL_length/2 0 SL_length/2], resolution, 1.5 ,0 );
+mesh.y = SmoothMeshLines( [0 SL_width/2+[-resolution/3 +resolution/3*2]/4], resolution/4 , 1.5 ,0);
+mesh.y = SmoothMeshLines( [-10*SL_width -mesh.y mesh.y 10*SL_width], resolution, 1.3 ,0);
+mesh.z = linspace(0,substrate_thickness,5);
+mesh.z = sort(unique([mesh.z -mesh.z]));
+CSX = DefineRectGrid( CSX, unit, mesh );
+
+%% substrate
+CSX = AddMaterial( CSX, 'RO4350B' );
+CSX = SetMaterialProperty( CSX, 'RO4350B', 'Epsilon', substrate_epr );
+start = [mesh.x(1), mesh.y(1), mesh.z(1)];
+stop = [mesh.x(end), mesh.y(end), mesh.z(end)];
+CSX = AddBox( CSX, 'RO4350B', 0, start, stop );
+
+%% SL port
+CSX = AddMetal( CSX, 'PEC' );
+portstart = [ mesh.x(1), -SL_width/2, 0];
+portstop = [ 0, SL_width/2, 0];
+[CSX,port{1}] = AddStripLinePort( CSX, 999, 1, 'PEC', portstart, portstop, SL_height, 'x', [0 0 -1], 'ExcitePort', true, 'FeedShift', 10*resolution, 'MeasPlaneShift', SL_length/3);
+
+portstart = [mesh.x(end), -SL_width/2, 0];
+portstop = [0 , SL_width/2, 0];
+[CSX,port{2}] = AddStripLinePort( CSX, 999, 2, 'PEC', portstart, portstop, SL_height, 'x', [0 0 -1], 'MeasPlaneShift', SL_length/3 );
+
+%% write/show/run the openEMS compatible xml-file
+Sim_Path = ['tmp_' mfilename];
+Sim_CSX = 'stripline.xml';
+
+[status, message, messageid] = rmdir( Sim_Path, 's' ); % clear previous directory
+[status, message, messageid] = mkdir( Sim_Path ); % create empty simulation folder
+
+WriteOpenEMS( [Sim_Path '/' Sim_CSX], FDTD, CSX );
+CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+RunOpenEMS( Sim_Path, Sim_CSX );
+
+%% post-processing
+close all
+f = linspace( 1e6, f_max, 1601 );
+port = calcPort( port, Sim_Path, f, 'RefImpedance', 50);
+
+s11 = port{1}.uf.ref./ port{1}.uf.inc;
+s21 = port{2}.uf.ref./ port{1}.uf.inc;
+
+plot(f/1e9,20*log10(abs(s11)),'k-','LineWidth',2);
+hold on;
+grid on;
+plot(f/1e9,20*log10(abs(s21)),'r--','LineWidth',2);
+legend('S_{11}','S_{21}');
+ylabel('S-Parameter (dB)','FontSize',12);
+xlabel('frequency (GHz) \rightarrow','FontSize',12);
+ylim([-50 2]);
+
diff --git a/openEMS/matlab/examples/transmission_lines/directional_coupler.m b/openEMS/matlab/examples/transmission_lines/directional_coupler.m
new file mode 100644
index 0000000..8ba86f2
--- /dev/null
+++ b/openEMS/matlab/examples/transmission_lines/directional_coupler.m
@@ -0,0 +1,261 @@
+function directional_coupler
+%
+% EXAMPLE / microstrip / directional_coupler
+%
+% Stacked directional coupler in microstrip technology.
+%
+% This example demonstrates:
+% - simple microstrip geometry
+% - S-parameter calculation using the ypar-method
+% - display of coupler parameters
+% - display of S11 (smith chart)
+%
+%
+% Tested with
+% - Matlab 2010b
+% - Octave 3.2.4
+% - openEMS v0.0.17
+%
+% (C) 2010 Sebastian Held <sebastian.held@gmx.de>
+
+clear
+close all
+clc
+
+% sim settings
+showStructure = 1;
+runSimulation = 1;
+
+for n=1:4
+ if n > 1, showStructure = 0; end
+ ports{n} = sim( n, showStructure, runSimulation );
+end
+postprocess( ports );
+
+
+
+
+function ports = sim( simnr, showStructure, runSimulation )
+physical_constants
+
+% setup the simulation
+drawingunit = 1e-6; % specify everything in um
+Sim_Path = ['tmp' int2str(simnr)];
+Sim_CSX = 'tmp.xml';
+f_max = 100e6;
+lambda = c0/f_max;
+
+% specify the coupler
+pcb1.w = 147000;
+pcb1.h = 54500;
+pcb1.t = 1524;
+pcb1.epr = 3;
+msl1.w = 135000;
+msl1.h = 2800;
+pcb2.w = 107000;
+pcb2.h = 14000;
+pcb2.t = 1524;
+pcb2.epr = 3;
+msl2.w = 95000;
+msl2.h = 4000;
+
+
+CSX = InitCSX();
+
+% create the mesh
+mesh.x = [-pcb1.w/2 pcb1.w/2 -pcb2.w/2 pcb2.w/2 -msl1.w/2 msl1.w/2 -msl2.w/2 msl2.w/2];
+mesh.x = [mesh.x linspace(-msl2.w/2,-msl2.w/2+msl2.h, 5) linspace(msl2.w/2,msl2.w/2-msl2.h, 5)];
+mesh.y = [-pcb1.h/2 pcb1.h/2 -pcb2.h/2 pcb2.h/2 -msl1.h/2 msl1.h/2 -msl2.h/2 msl2.h/2];
+mesh.z = [linspace(0,pcb1.t,5) linspace(pcb1.t,pcb1.t+pcb2.t,5)];
+mesh.z = [mesh.z mesh.z(end)+10*(mesh.z(end)-mesh.z(1))]; % add space above pcb
+res = lambda/sqrt(max([pcb1.epr,pcb2.epr])) / 20 / drawingunit;
+mesh.x = SmoothMeshLines2(mesh.x,res);
+mesh.y = SmoothMeshLines2(mesh.y,res);
+mesh.z = SmoothMeshLines2(mesh.z,res);
+mesh = AddPML( mesh, [8 8 8 8 8 8] ); % add space for PML
+CSX = DefineRectGrid( CSX, drawingunit, mesh );
+
+%% create the structure
+
+% microstrip
+CSX = AddMetal( CSX, 'PEC' );
+start = [-msl1.w/2, -msl1.h/2, pcb1.t];
+stop = [ msl1.w/2, msl1.h/2, pcb1.t];
+priority = 100; % the geometric priority is set to 100
+CSX = AddBox( CSX, 'PEC', priority, start, stop );
+
+% ground plane
+CSX = AddMetal( CSX, 'PEC_ground' );
+start = [-pcb1.w/2, -pcb1.h/2, 0];
+stop = [ pcb1.w/2, pcb1.h/2, 0];
+CSX = AddBox( CSX, 'PEC_ground', priority, start, stop );
+
+% substrate 1
+start = [-pcb1.w/2, -pcb1.h/2, 0];
+stop = [ pcb1.w/2, pcb1.h/2, pcb1.t];
+priority = 10;
+CSX = AddMaterial( CSX, 'substrate1' );
+CSX = SetMaterialProperty( CSX, 'substrate1', 'Epsilon', pcb1.epr );
+CSX = AddBox( CSX, 'substrate1', priority, start, stop );
+
+% substrate 2
+start = [-pcb2.w/2, -pcb2.h/2, pcb1.t];
+stop = [ pcb2.w/2, pcb2.h/2, pcb1.t+pcb2.t];
+priority = 10;
+CSX = AddMaterial( CSX, 'substrate2' );
+CSX = SetMaterialProperty( CSX, 'substrate2', 'Epsilon', pcb2.epr );
+CSX = AddBox( CSX, 'substrate2', priority, start, stop );
+
+% stripline
+start = [-msl2.w/2, -msl2.h/2, pcb1.t+pcb2.t];
+stop = [ msl2.w/2, msl2.h/2, pcb1.t+pcb2.t];
+priority = 100;
+CSX = AddBox( CSX, 'PEC', priority, start, stop );
+
+% connections
+start = [-msl2.w/2, -msl2.h/2, pcb1.t+pcb2.t];
+stop = [-msl2.w/2+msl2.h, -pcb2.h/2, pcb1.t+pcb2.t];
+priority = 100;
+CSX = AddBox( CSX, 'PEC', priority, start, stop );
+start = [ msl2.w/2, -msl2.h/2, pcb1.t+pcb2.t];
+stop = [ msl2.w/2-msl2.h, -pcb2.h/2, pcb1.t+pcb2.t];
+priority = 100;
+CSX = AddBox( CSX, 'PEC', priority, start, stop );
+
+%% ports
+% this project needs 4 simulations
+for n=1:4
+ portexcite{n} = [];
+end
+portexcite{simnr} = 'excite';
+
+% port 1: input port
+start = [-msl1.w/2, 0, pcb1.t];
+stop = [-msl1.w/2, 0, 0];
+[CSX ports{1}] = AddCurvePort( CSX, 999, 1, 50, start, stop, portexcite{1} );
+% port 2: output port
+start = [msl1.w/2, 0, pcb1.t];
+stop = [msl1.w/2, 0, 0];
+[CSX ports{2}] = AddCurvePort( CSX, 999, 2, 50, start, stop, portexcite{2} );
+% port 3: coupled port
+start = [-msl2.w/2+msl2.h/2, -pcb2.h/2, pcb1.t+pcb2.t];
+stop = [-msl2.w/2+msl2.h/2, -pcb2.h/2, 0];
+[CSX ports{3}] = AddCurvePort( CSX, 999, 3, 50, start, stop, portexcite{3} );
+% port 4: isolated port
+start = [msl2.w/2-msl2.h/2, -pcb2.h/2, pcb1.t+pcb2.t];
+stop = [msl2.w/2-msl2.h/2, -pcb2.h/2, 0];
+[CSX ports{4}] = AddCurvePort( CSX, 999, 4, 50, start, stop, portexcite{4} );
+
+%% setup FDTD parameters & excitation function
+max_timesteps = 50000;
+min_decrement = 1e-6;
+FDTD = InitFDTD( max_timesteps, min_decrement );
+FDTD = SetGaussExcite( FDTD, 0, f_max );
+BC = {'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8' 'PML_8'};
+BC = {'MUR' 'MUR' 'MUR' 'MUR' 'MUR' 'MUR'}; % faster
+FDTD = SetBoundaryCond( FDTD, BC );
+
+%% Write openEMS compatible xml-file
+if runSimulation
+ [dummy,dummy,dummy] = rmdir(Sim_Path,'s');
+end
+[dummy,dummy,dummy] = mkdir(Sim_Path);
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+if showStructure
+ CSXGeomPlot( [Sim_Path '/' Sim_CSX] );
+end
+
+%% run openEMS
+openEMS_opts = '';
+openEMS_opts = [openEMS_opts ' --engine=fastest'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --debug-boxes'];
+if runSimulation
+ RunOpenEMS( Sim_Path, Sim_CSX, openEMS_opts );
+end
+
+
+
+
+function postprocess( ports )
+f = linspace( 0, 100e6, 201 );
+Y = calc_ypar( f, ports{1}, 'tmp' );
+R = 50;
+S = y2s(Y,R);
+
+% insertion loss
+IL_dB = -20 * log10(abs(squeeze(S(2,1,:))));
+
+% coupling factor
+CF_dB = -20 * log10(abs(squeeze(S(3,1,:))));
+
+% isolation
+I_dB = -20 * log10(abs(squeeze(S(4,1,:))));
+
+% directivity
+D_dB = -20 * log10(abs(squeeze(S(4,1,:) ./ S(3,1,:))));
+
+figure
+plot( f, [IL_dB CF_dB I_dB D_dB] );
+legend( {'insertion loss','coupling factor','isolation','directivity'} );
+title( ['performance of the coupler for a termination resistance of R=' num2str(R)] );
+grid on
+
+smithchart
+S11 = squeeze(S(1,1,:));
+plot( real(S11), imag(S11) );
+legend( 'S_{11}' );
+title( ['performance of the coupler for a termination resistance of R=' num2str(R)] );
+axis( [-1 1 -1 1] );
+
+
+
+function smithchart
+% smith chart
+figure
+if exist( 'smith', 'file' )
+ % smith chart
+ % www.ece.rutgers.edu/~orfanidi/ewa
+ % or cmt toolbox from git.ate.uni-duisburg.de
+ smith
+else
+ % poor man smith chart
+ color = [.6 .6 .6];
+ h = plot( sin(0:0.01:2*pi), cos(0:0.01:2*pi), 'Color', color );
+ hg = hggroup;
+ set( h,'Parent',hg );
+ hold on
+ plot( hg, 0.25+0.75*sin(0:0.01:2*pi), 0.75*cos(0:0.01:2*pi), 'Color', color );
+ plot( hg, 0.5+0.5*sin(0:0.01:2*pi), 0.5*cos(0:0.01:2*pi), 'Color', color );
+ plot( hg, 0.75+0.25*sin(0:0.01:2*pi), 0.25*cos(0:0.01:2*pi), 'Color', color );
+ plot( hg, [-1 1], [0 0], 'Color', color );
+ axis equal
+ axis off
+end
+
+
+function s = y2s(y, ZL)
+% S = y2s(Y, ZL)
+%
+% Admittance to Scattering transformation
+% for square matrices at multiple frequencies
+%
+% ZL defaults to 50 Ohm
+
+if nargin < 2
+ ZL = 50;
+end
+
+if size(size(y),2) > 2
+ nF = size(y,3);
+else
+ nF = 1;
+end
+
+I = diag(ones(1, size(y,2)))/ZL;
+
+for i=1:nF
+ %s(:,:,i) = inv(I+y(:,:,i)) * (I-y(:,:,i));
+ s(:,:,i) = (I+y(:,:,i)) \ (I-y(:,:,i));
+end
diff --git a/openEMS/matlab/examples/waveguide/Circ_Waveguide.m b/openEMS/matlab/examples/waveguide/Circ_Waveguide.m
new file mode 100644
index 0000000..9ee860e
--- /dev/null
+++ b/openEMS/matlab/examples/waveguide/Circ_Waveguide.m
@@ -0,0 +1,207 @@
+%
+% EXAMPLE / waveguide / circular waveguide
+%
+% This example demonstrates how to:
+% - setup a circular waveguide
+% - use analytic functions for waveguide excitations and voltage/current
+% calculations
+%
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.17
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+use_pml = 0; % use pml boundaries instead of mur
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numTS = 1e5; %number of timesteps
+length = 1000; %length of the waveguide
+unit = 1e-3; %drawing unit used
+rad = 300; %radius of the circular waveguide
+mesh_res = [10 10 15]; %desired mesh resolution
+
+%excitation
+f0 = 350e6; %center frequency
+f0_BW = 25e6; %bandwidth: 10dB cut-off frequency
+
+physical_constants
+
+%% TE11 mode definitions (Pozar 3rd edition)
+p11 = 1.841;
+kc = p11 / rad /unit;
+k = 2*pi*f0/C0;
+fc = C0*kc/2/pi;
+beta = sqrt(k^2 - kc^2);
+n_eff = (beta/k);
+
+kc = kc*unit; %functions must be defined in drawing units
+func_Er = [ num2str(-1/kc^2) '/rho*cos(a)*j1(' num2str(kc) '*rho)'];
+func_Ea = [ num2str(1/kc) '*sin(a)*0.5*(j0(' num2str(kc) '*rho)-jn(2,' num2str(kc) '*rho))'];
+func_Ex = ['(' func_Er '*cos(a) - ' func_Ea '*sin(a) )*(rho<' num2str(rad) ')'];
+func_Ey = ['(' func_Er '*sin(a) + ' func_Ea '*cos(a) )*(rho<' num2str(rad) ')'];
+
+func_Ha = [ num2str(-1/kc^2,'%14.13f') '/rho*cos(a)*j1(' num2str(kc,'%14.13f') '*rho)'];
+func_Hr = [ '-1*' num2str(1/kc,'%14.13f') '*sin(a)*0.5*(j0(' num2str(kc,'%14.13f') '*rho)-jn(2,' num2str(kc,'%14.13f') '*rho))'];
+func_Hx = ['(' func_Hr '*cos(a) - ' func_Ha '*sin(a) )*(rho<' num2str(rad) ')'];
+func_Hy = ['(' func_Hr '*sin(a) + ' func_Ha '*cos(a) )*(rho<' num2str(rad) ')'];
+
+%% define files and path %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Sim_Path = 'tmp';
+Sim_CSX = 'Circ_WG.xml';
+
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir(Sim_Path,'s');
+ [status, message, messageid] = mkdir(Sim_Path);
+end
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(numTS,1e-6,'OverSampling',5);
+FDTD = SetGaussExcite(FDTD,f0,f0_BW);
+BC = {'PEC','PEC','PEC','PEC','PEC','MUR'};
+if (use_pml>0)
+ BC = {'PEC','PEC','PEC','PEC','PEC','PML_8'};
+end
+FDTD = SetBoundaryCond(FDTD,BC,'MUR_PhaseVelocity',C0 / n_eff);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = -mesh_res(1)/2-rad:mesh_res(1):rad+mesh_res(1)/2;
+mesh.y = -mesh_res(2)/2-rad:mesh_res(2):rad+mesh_res(2)/2;
+mesh.z = 0 : mesh_res(3) : length;
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+start = [0,0,0];
+stop = [0,0,length];
+
+%%% fill everything with copper, priority 0
+CSX = AddMetal(CSX,'copper');
+% CSX = SetMaterialProperty(CSX,'copper','Kappa',56e6);
+CSX = AddBox(CSX,'copper',0,[mesh.x(1) mesh.y(1) mesh.z(1)],[mesh.x(end) mesh.y(end) mesh.z(end)]);
+
+%%% cut out an air cylinder as circular waveguide... priority 5
+CSX = AddMaterial(CSX,'air');
+CSX = SetMaterialProperty(CSX,'air','Epsilon',1);
+CSX = AddCylinder(CSX,'air', 5 ,start,stop,rad);
+
+CSX = AddExcitation(CSX,'excite',0,[1 1 0]);
+weight{1} = func_Ex;
+weight{2} = func_Ey;
+weight{3} = 0;
+CSX = SetExcitationWeight(CSX, 'excite', weight );
+CSX = AddCylinder(CSX,'excite', 5 ,[0 0 -0.1],[0 0 0.1],rad);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et_','SubSampling','2,2,2','FileType',0,'DumpMode',2);
+start = [mesh.x(1) , 0 , mesh.z(1)];
+stop = [mesh.x(end), 0 , mesh.z(end)];
+CSX = AddBox(CSX,'Et_',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht_','SubSampling','2,2,2','DumpType',1,'FileType',0,'DumpMode',2);
+CSX = AddBox(CSX,'Ht_',0,start,stop);
+
+%% define voltage calc boxes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%voltage calc
+start = [mesh.x(1) mesh.y(1) mesh.z(10)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(10)];
+CSX = AddProbe(CSX, 'ut1', 10, 1, [], 'ModeFunction',{func_Ex,func_Ey,0});
+CSX = AddBox(CSX, 'ut1', 0 ,start,stop);
+CSX = AddProbe(CSX,'it1', 11, 1, [], 'ModeFunction',{func_Hx,func_Hy,0});
+CSX = AddBox(CSX,'it1', 0 ,start,stop);
+
+start = [mesh.x(1) mesh.y(1) mesh.z(end-10)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end-10)];
+CSX = AddProbe(CSX, 'ut2', 10, 1, [], 'ModeFunction',{func_Ex,func_Ey,0});
+CSX = AddBox(CSX, 'ut2', 0 ,start,stop);
+CSX = AddProbe(CSX,'it2', 11, 1, [], 'ModeFunction',{func_Hx,func_Hy,0});
+CSX = AddBox(CSX,'it2', 0 ,start,stop);
+
+port_dist = mesh.z(end-10) - mesh.z(10);
+
+%% Write openEMS
+if (postprocessing_only==0)
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+ RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+end
+
+%% do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+freq = linspace(f0-f0_BW,f0+f0_BW,201);
+U = ReadUI({'ut1','ut2'},[Sim_Path '/'],freq);
+I = ReadUI({'it1','it2'},[Sim_Path '/'],freq);
+Exc = ReadUI('et',Sim_Path,freq);
+
+k = 2*pi*freq/C0;
+kc = p11 / rad /unit;
+beta = sqrt(k.^2 - kc^2);
+
+ZL_a = Z0*k./beta ;
+
+uf1 = U.FD{1}.val./Exc.FD{1}.val;
+uf2 = U.FD{2}.val./Exc.FD{1}.val;
+if1 = I.FD{1}.val./Exc.FD{1}.val;
+if2 = I.FD{2}.val./Exc.FD{1}.val;
+
+uf1_inc = 0.5 * ( uf1 + if1 .* ZL_a );
+if1_inc = 0.5 * ( if1 + uf1 ./ ZL_a );
+uf2_inc = 0.5 * ( uf2 + if2 .* ZL_a );
+if2_inc = 0.5 * ( if2 + uf2 ./ ZL_a );
+
+uf1_ref = uf1 - uf1_inc;
+if1_ref = if1 - if1_inc;
+uf2_ref = uf2 - uf2_inc;
+if2_ref = if2 - if2_inc;
+
+% plot s-parameter
+figure
+s11 = uf1_ref./uf1_inc;
+s21 = uf2_inc./uf1_inc;
+plot(freq,20*log10(abs(s11)),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('s-para (dB)');
+% ylim([-40 5]);
+grid on;
+hold on;
+plot(freq,20*log10(abs(s21)),'r','Linewidth',2);
+legend('s11','s21','Location','SouthEast');
+
+% plot line-impedance comparison
+figure()
+ZL = uf1./if1;
+plot(freq,real(ZL),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('line-impedance (\Omega)');
+grid on;
+hold on;
+plot(freq,imag(ZL),'r--','Linewidth',2);
+plot(freq,ZL_a,'g-.','Linewidth',2);
+legend('\Re\{ZL\}','\Im\{ZL\}','ZL-analytic','Location','Best');
+
+% beta compare
+figure()
+da = angle(uf1_inc)-angle(uf2_inc);
+da = mod(da,2*pi);
+beta_12 = (da)/port_dist/unit;
+plot(freq,beta_12,'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)');
+ylabel('\beta (m^{-1})');
+grid on;
+hold on;
+plot(freq,beta,'g--','Linewidth',2);
+legend('\beta-FDTD','\beta-analytic','Location','Best');
+
+%% visualize electric & magnetic fields
+disp('you will find vtk dump files in the simulation folder (tmp/)')
+disp('use paraview to visulaize them');
diff --git a/openEMS/matlab/examples/waveguide/Circ_Waveguide_CylinderCoords.m b/openEMS/matlab/examples/waveguide/Circ_Waveguide_CylinderCoords.m
new file mode 100644
index 0000000..a767c0a
--- /dev/null
+++ b/openEMS/matlab/examples/waveguide/Circ_Waveguide_CylinderCoords.m
@@ -0,0 +1,204 @@
+%
+% EXAMPLE / waveguide / circular waveguide cylindrical coordinates
+%
+% This example demonstrates how to:
+% - use cylindrical coordinates
+% - setup a circular waveguide defined by the boundary conditions of the
+% cylindrical coordinate system
+% - use analytic functions for waveguide excitations and voltage/current
+% calculations
+%
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.17
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+use_pml = 0; % use pml boundaries instead of mur
+use_MultiGrid = 1; % disable multi-grid for this example
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numTS = 1e5; %number of timesteps
+length = 1000; %length of the waveguide
+unit = 1e-3; %drawing unit used
+rad = 300; %radius of the circular waveguide
+mesh_res = [10 nan 15]; %desired mesh resolution
+N_alpha = 50; %mesh lines in azimuth direction
+
+MultiGrid_Level = [50]; % define multigrid radii (if enabled)
+
+%excitation
+f0 = 350e6; %center frequency
+f0_BW = 25e6; %bandwidth: 10dB cut-off frequency
+
+physical_constants
+
+%% TE11 mode definitions (Pozar 3rd edition)
+p11 = 1.841;
+kc = p11 / rad /unit;
+k = 2*pi*f0/C0;
+fc = C0*kc/2/pi;
+beta = sqrt(k^2 - kc^2);
+n_eff = (beta/k);
+
+kc = kc*unit; %functions must be defined in drawing units
+func_Er = [ num2str(-1/kc^2,15) '/rho*cos(a)*j1(' num2str(kc,15) '*rho)'];
+func_Ea = [ num2str(1/kc,15) '*sin(a)*0.5*(j0(' num2str(kc,15) '*rho)-jn(2,' num2str(kc,15) '*rho))'];
+func_Ha = [ num2str(-1/kc^2,'%14.13f') '/rho*cos(a)*j1(' num2str(kc,'%14.13f') '*rho)'];
+func_Hr = [ '-1*' num2str(1/kc,'%14.13f') '*sin(a)*0.5*(j0(' num2str(kc,'%14.13f') '*rho)-jn(2,' num2str(kc,'%14.13f') '*rho))'];
+
+%% define files and path %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Sim_Path = 'tmp';
+Sim_CSX = 'Circ_WG_CC.xml';
+
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir(Sim_Path,'s');
+ [status, message, messageid] = mkdir(Sim_Path);
+end
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if (use_MultiGrid==0)
+ FDTD = InitCylindricalFDTD(numTS,1e-5,'OverSampling',10);
+else
+ mg_str = num2str(MultiGrid_Level,'%d,'); %create comma-separated string
+ N_alpha = round(N_alpha * 2^numel(MultiGrid_Level));
+ FDTD = InitCylindricalFDTD(numTS,1e-5,'OverSampling',10,'MultiGrid',mg_str(1:end-1));
+end
+FDTD = SetGaussExcite(FDTD,f0,f0_BW);
+BC = {'PEC','PEC','PEC','PEC','PEC','MUR'};
+if (use_pml>0)
+ BC = {'PEC','PEC','PEC','PEC','PEC','PML_8'};
+end
+FDTD = SetBoundaryCond(FDTD,BC,'MUR_PhaseVelocity',C0 / n_eff);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX('CoordSystem',1);
+mesh.x = 0:mesh_res(1):rad;
+%define an odd number of lines in alpha-direction
+mesh.y = linspace(-pi,pi,N_alpha+mod(N_alpha+1,2))+pi/2;
+mesh.z = 0 : mesh_res(3) : length;
+CSX = DefineRectGrid(CSX, unit,mesh);
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddExcitation(CSX,'excite',0,[1 1 0]);
+weight{1} = func_Er;
+weight{2} = func_Ea;
+weight{3} = 0;
+CSX = SetExcitationWeight(CSX, 'excite', weight );
+start = [mesh.x(1) mesh.y(1) mesh.z(1)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(1)];
+CSX = AddBox(CSX,'excite', 5 ,start,stop);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et_','FileType',0,'DumpMode',2,'SubSampling','2,2,2');
+start = [mesh.x(1) , 0 , mesh.z(1)];
+stop = [mesh.x(end), 0 , mesh.z(end)];
+CSX = AddBox(CSX,'Et_',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht','FileType',0,'DumpType',1,'DumpMode',2,'SubSampling','2,2,2');
+CSX = AddBox(CSX,'Ht',0 , start,stop);
+
+%% define voltage calc boxes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start = [mesh.x(1) mesh.y(1) mesh.z(10)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(10)];
+CSX = AddProbe(CSX, 'ut1', 10, 1, [], 'ModeFunction',{func_Er,func_Ea,0});
+CSX = AddBox(CSX, 'ut1', 0 ,start,stop);
+CSX = AddProbe(CSX,'it1', 11, 1, [], 'ModeFunction',{func_Hr,func_Ha,0});
+CSX = AddBox(CSX,'it1', 0 ,start,stop);
+
+start = [mesh.x(1) mesh.y(1) mesh.z(end-10)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end-10)];
+CSX = AddProbe(CSX, 'ut2', 10, 1, [], 'ModeFunction',{func_Er,func_Ea,0});
+CSX = AddBox(CSX, 'ut2', 0 ,start,stop);
+CSX = AddProbe(CSX,'it2', 11, 1, [], 'ModeFunction',{func_Hr,func_Ha,0});
+CSX = AddBox(CSX,'it2', 0 ,start,stop);
+
+port_dist = mesh.z(end-10) - mesh.z(10);
+
+%% Write openEMS
+if (postprocessing_only==0)
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+ RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+end
+
+%% do the plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+freq = linspace(f0-f0_BW,f0+f0_BW,201);
+U = ReadUI({'ut1','ut2'},[Sim_Path '/'],freq);
+I = ReadUI({'it1','it2'},[Sim_Path '/'],freq);
+Exc = ReadUI('et',Sim_Path,freq);
+
+k = 2*pi*freq/C0;
+kc = p11 / rad /unit;
+beta = sqrt(k.^2 - kc^2);
+
+ZL_a = Z0*k./beta ;
+
+uf1 = U.FD{1}.val./Exc.FD{1}.val;
+uf2 = U.FD{2}.val./Exc.FD{1}.val;
+if1 = I.FD{1}.val./Exc.FD{1}.val;
+if2 = I.FD{2}.val./Exc.FD{1}.val;
+
+uf1_inc = 0.5 * ( uf1 + if1 .* ZL_a );
+if1_inc = 0.5 * ( if1 + uf1 ./ ZL_a );
+uf2_inc = 0.5 * ( uf2 + if2 .* ZL_a );
+if2_inc = 0.5 * ( if2 + uf2 ./ ZL_a );
+
+uf1_ref = uf1 - uf1_inc;
+if1_ref = if1 - if1_inc;
+uf2_ref = uf2 - uf2_inc;
+if2_ref = if2 - if2_inc;
+
+% plot s-parameter
+figure
+s11 = uf1_ref./uf1_inc;
+s21 = uf2_inc./uf1_inc;
+plot(freq,20*log10(abs(s11)),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('s-para (dB)');
+% ylim([-40 5]);
+grid on;
+hold on;
+plot(freq,20*log10(abs(s21)),'r','Linewidth',2);
+legend('s11','s21','Location','SouthEast');
+
+% plot line-impedance comparison
+figure()
+ZL = uf1./if1;
+plot(freq,real(ZL),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('line-impedance (\Omega)');
+grid on;
+hold on;
+plot(freq,imag(ZL),'r--','Linewidth',2);
+plot(freq,ZL_a,'g-.','Linewidth',2);
+legend('\Re\{ZL\}','\Im\{ZL\}','ZL-analytic','Location','Best');
+
+%% beta compare
+figure()
+da = angle(uf1_inc)-angle(uf2_inc);
+da = mod(da,2*pi);
+beta_12 = (da)/port_dist/unit;
+plot(freq,beta_12,'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)');
+ylabel('\beta (m^{-1})');
+grid on;
+hold on;
+plot(freq,beta,'g--','Linewidth',2);
+legend('\beta-FDTD','\beta-analytic','Location','Best');
+
+%% visualize electric & magnetic fields
+disp('you will find vtk dump files in the simulation folder (tmp/)')
+disp('use paraview to visulaize them');
diff --git a/openEMS/matlab/examples/waveguide/Coax.m b/openEMS/matlab/examples/waveguide/Coax.m
new file mode 100644
index 0000000..3db4d6a
--- /dev/null
+++ b/openEMS/matlab/examples/waveguide/Coax.m
@@ -0,0 +1,120 @@
+%
+% EXAMPLE / waveguide / coaxial cable
+%
+% This example demonstrates how to:
+% - setup a coaxial waveguide
+% - use analytic functions for waveguide excitations and voltage/current
+% calculations
+%
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.17
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+use_pml = 0; % use pml boundaries instead of mur
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numTS = 5000; %number of timesteps
+length = 1000; %length of the waveguide
+unit = 1e-3; %drawing unit used
+coax_rad_i = 100; %inner radius
+coax_rad_ai = 230; %inner radius of outer cladding
+coax_rad_aa = 240; %outer radius of outer cladding
+mesh_res = [5 5 5]; %desired mesh resolution
+
+physical_constants;
+
+%excitation
+f0 = 0.5e9;
+epsR = 1;
+
+%% create sim path %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Sim_Path = 'tmp';
+Sim_CSX = 'coax.xml';
+
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir(Sim_Path,'s');
+ [status, message, messageid] = mkdir(Sim_Path);
+end
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(numTS,1e-5);
+FDTD = SetGaussExcite(FDTD,f0,f0);
+BC = {'PEC','PEC','PEC','PEC','MUR','MUR'};
+if (use_pml>0)
+ BC = {'PEC','PEC','PEC','PEC','PML_8','PML_8'};
+end
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = -coax_rad_aa : mesh_res(1) : coax_rad_aa;
+mesh.y = mesh.x;
+mesh.z = SmoothMeshLines([0 length], mesh_res(3));
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%%% coax
+CSX = AddMetal(CSX,'copper');
+start = [0,0,0];
+stop = [0,0,length/2];
+[CSX,port{1}] = AddCoaxialPort( CSX, 10, 1, 'copper', '', start, stop, 'z', coax_rad_i, coax_rad_ai, coax_rad_aa, 'ExciteAmp', 1,'FeedShift', 10*mesh_res(1) );
+
+start = [0,0,length/2];
+stop = [0,0,length];
+[CSX,port{2}] = AddCoaxialPort( CSX, 10, 2, 'copper', '', start, stop, 'z', coax_rad_i, coax_rad_ai, coax_rad_aa );
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et_','DumpMode',2);
+start = [mesh.x(1) , 0 , mesh.z(1)];
+stop = [mesh.x(end) , 0 , mesh.z(end)];
+CSX = AddBox(CSX,'Et_',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht_','DumpType',1,'DumpMode',2);
+CSX = AddBox(CSX,'Ht_',0,start,stop);
+
+%% Write openEMS
+if (postprocessing_only==0)
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+ CSXGeomPlot([Sim_Path '/' Sim_CSX]);
+ RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+end
+
+%%
+freq = linspace(0,2*f0,201);
+port = calcPort(port, Sim_Path, freq);
+
+%% plot s-parameter
+figure
+s11 = port{1}.uf.ref./port{1}.uf.inc;
+s21 = port{2}.uf.inc./port{1}.uf.inc;
+plot(freq,20*log10(abs(s11)),'Linewidth',2);
+hold on
+grid on
+plot(freq,20*log10(abs(s21)),'r--','Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('s-para (dB)');
+
+%% plot line-impedance comparison
+figure()
+ZL_a = ones(size(freq))*Z0/2/pi/sqrt(epsR)*log(coax_rad_ai/coax_rad_i); %analytic line-impedance of a coax
+ZL = port{2}.uf.tot./port{2}.if.tot;
+plot(freq,real(port{1}.ZL),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('line-impedance (\Omega)');
+grid on;
+hold on;
+plot(freq,imag(port{1}.ZL),'r--','Linewidth',2);
+plot(freq,ZL_a,'g-.','Linewidth',2);
+legend('\Re\{ZL\}','\Im\{ZL\}','ZL-analytic','Location','Best');
diff --git a/openEMS/matlab/examples/waveguide/Coax_CylinderCoords.m b/openEMS/matlab/examples/waveguide/Coax_CylinderCoords.m
new file mode 100644
index 0000000..5e4606c
--- /dev/null
+++ b/openEMS/matlab/examples/waveguide/Coax_CylinderCoords.m
@@ -0,0 +1,190 @@
+%
+% EXAMPLE / waveguide / coaxial cable using cylindrical coordinates
+%
+% This example demonstrates how to:
+% - use cylindrical coordinates
+% - setup a coaxial waveguide
+% - use analytic functions for waveguide excitations and voltage/current
+% calculations
+%
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.17
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+close all
+clear
+clc
+
+%% switches & options...
+postprocessing_only = 0;
+use_pml = 0; % use pml boundaries instead of mur
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numTS = 1e5; %number of timesteps
+length = 1000; %length of the waveguide
+unit = 1e-3; %drawing unit used
+coax_rad_i = 100; %inner radius
+coax_rad_a = 230; %outer radius
+mesh_res = [10 nan 10]; %desired mesh resolution
+N_alpha = 71; %mesh lines in azimuth direction
+
+physical_constants;
+
+%excitation
+f0 = 0.5e9;
+epsR = 1;
+
+%% create sim path %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Sim_Path = 'tmp';
+Sim_CSX = 'coax.xml';
+
+if (postprocessing_only==0)
+ [status, message, messageid] = rmdir(Sim_Path,'s');
+ [status, message, messageid] = mkdir(Sim_Path);
+end
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitCylindricalFDTD(numTS,1e-5);
+FDTD = SetGaussExcite(FDTD,f0,f0);
+BC = {'PEC','PEC','PEC','PEC','PEC','MUR'};
+if (use_pml>0)
+ BC = {'PEC','PEC','PEC','PEC','PEC','PML_8'};
+end
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX('CoordSystem',1);
+mesh.x = coax_rad_i : mesh_res(1) : coax_rad_a;
+mesh.y = linspace(0,2*pi,N_alpha);
+mesh.z = 0 : mesh_res(3) : length;
+CSX = DefineRectGrid(CSX, unit, mesh);
+
+%% material
+CSX = AddMaterial(CSX,'fill');
+CSX = SetMaterialProperty(CSX,'fill','Epsilon',epsR);
+start = [mesh.x(1) mesh.y(1) 0];
+stop = [mesh.x(end) mesh.y(end) length];
+CSX = AddBox(CSX,'fill',0 ,start,stop);
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddExcitation(CSX,'excite',0,[1 0 0]);
+weight{1} = '1/rho';
+weight{2} = 0;
+weight{3} = 0;
+CSX = SetExcitationWeight(CSX, 'excite', weight );
+start = [coax_rad_i mesh.y(1) 0];
+stop = [coax_rad_a mesh.y(end) 0];
+CSX = AddBox(CSX,'excite',0 ,start,stop);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et_','DumpMode',0);
+start = [mesh.x(1) , 0 , mesh.z(1)];
+stop = [mesh.x(end) , 0 , mesh.z(end)];
+CSX = AddBox(CSX,'Et_',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht_','DumpType',1,'DumpMode',0);
+CSX = AddBox(CSX,'Ht_',0,start,stop);
+
+%% define voltage calc boxes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%voltage calc
+CSX = AddProbe(CSX,'ut1',0);
+start = [ coax_rad_i 0 mesh.z(10) ];
+stop = [ coax_rad_a 0 mesh.z(10) ];
+CSX = AddBox(CSX,'ut1', 0 ,start,stop);
+CSX = AddProbe(CSX,'ut2',0);
+start = [ coax_rad_i 0 mesh.z(end-10)];
+stop = [ coax_rad_a 0 mesh.z(end-10)];
+CSX = AddBox(CSX,'ut2', 0 ,start,stop);
+
+%current calc, for each position there are two currents, which will get
+%averaged to match the voltage position in between (!Yee grid!)
+CSX = AddProbe(CSX,'it1a',1);
+mid = 0.5*(coax_rad_i+coax_rad_a);
+start = [ 0 mesh.z(1) mesh.z(9) ];
+stop = [ mid mesh.z(end) mesh.z(9) ];
+CSX = AddBox(CSX,'it1a', 0 ,start,stop);
+CSX = AddProbe(CSX,'it1b',1);
+start = [ 0 mesh.z(1) mesh.z(10) ];
+stop = [ mid mesh.z(end) mesh.z(10) ];
+CSX = AddBox(CSX,'it1b', 0 ,start,stop);
+
+CSX = AddProbe(CSX,'it2a',1);
+start = [ 0 mesh.z(1) mesh.z(end-11) ];
+stop = [ mid mesh.z(end) mesh.z(end-11) ];
+CSX = AddBox(CSX,'it2a', 0 ,start,stop);
+CSX = AddProbe(CSX,'it2b',1);
+start = [ 0 mesh.z(1) mesh.z(end-10) ];
+stop = [ mid mesh.z(end) mesh.z(end-10) ];
+CSX = AddBox(CSX,'it2b', 0 ,start,stop);
+
+%% Write openEMS
+if (postprocessing_only==0)
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+ RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts);
+end
+
+%%
+freq = linspace(0,2*f0,201);
+U = ReadUI({'ut1','ut2'},[Sim_Path '/'],freq);
+I = ReadUI({'it1a','it1b','it2a','it2b'},[Sim_Path '/'],freq);
+Exc = ReadUI('et',Sim_Path,freq);
+
+%% plot voltages
+figure
+plot(U.TD{1}.t, U.TD{1}.val,'Linewidth',2);
+hold on;
+grid on;
+plot(U.TD{2}.t, U.TD{2}.val,'r--','Linewidth',2);
+xlabel('time (s)')
+ylabel('voltage (V)')
+legend('u_1(t)','u_2(t)')
+
+%% calculate incoming and reflected voltages & currents
+ZL_a = ones(size(freq))*Z0/2/pi/sqrt(epsR)*log(coax_rad_a/coax_rad_i); %analytic line-impedance of a coax
+
+uf1 = U.FD{1}.val./Exc.FD{1}.val;
+uf2 = U.FD{2}.val./Exc.FD{1}.val;
+if1 = 0.5*(I.FD{1}.val+I.FD{2}.val)./Exc.FD{1}.val;
+if2 = 0.5*(I.FD{3}.val+I.FD{4}.val)./Exc.FD{1}.val;
+
+uf1_inc = 0.5 * ( uf1 + if1 .* ZL_a );
+if1_inc = 0.5 * ( if1 + uf1 ./ ZL_a );
+uf2_inc = 0.5 * ( uf2 + if2 .* ZL_a );
+if2_inc = 0.5 * ( if2 + uf2 ./ ZL_a );
+
+uf1_ref = uf1 - uf1_inc;
+if1_ref = if1 - if1_inc;
+uf2_ref = uf2 - uf2_inc;
+if2_ref = if2 - if2_inc;
+
+% plot s-parameter
+figure
+s11 = uf1_ref./uf1_inc;
+s21 = uf2_inc./uf1_inc;
+plot(freq,20*log10(abs(s11)),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('s-para (dB)');
+% ylim([-40 5]);
+grid on;
+hold on;
+plot(freq,20*log10(abs(s21)),'r','Linewidth',2);
+legend('s11','s21','Location','SouthEast');
+
+% plot line-impedance comparison
+figure()
+ZL = uf1./if1;
+plot(freq,real(ZL),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)')
+ylabel('line-impedance (\Omega)');
+grid on;
+hold on;
+plot(freq,imag(ZL),'r--','Linewidth',2);
+plot(freq,ZL_a,'g-.','Linewidth',2);
+legend('\Re\{ZL\}','\Im\{ZL\}','ZL-analytic','Location','Best');
diff --git a/openEMS/matlab/examples/waveguide/Coax_Cylindrical_MG.m b/openEMS/matlab/examples/waveguide/Coax_Cylindrical_MG.m
new file mode 100644
index 0000000..84a1668
--- /dev/null
+++ b/openEMS/matlab/examples/waveguide/Coax_Cylindrical_MG.m
@@ -0,0 +1,155 @@
+close all
+clear
+clc
+
+%example for an cylindrical mesh, modeling a coaxial cable
+% this example is using a multi-grid approach
+
+
+%% setup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Settings = [];
+Settings.LogFile = 'openEMS.log';
+
+physical_constants
+
+f0 = 0.5e9;
+epsR = 1; %material filling
+
+length = 1000;
+port_dist = length/2;
+rad_i = 10; %inner radius
+rad_a = 200; %outer radius
+partial = 0.5; %e.g. 0.5 means only one half of a coax, should be <1 or change boundary cond.
+max_mesh = 10 / sqrt(epsR);
+max_alpha = max_mesh;
+N_alpha = ceil(rad_a * 2*pi * partial / max_alpha);
+
+%make it even...
+N_alpha = N_alpha + mod(N_alpha,2);
+%make sure it is multiple of 4, needed for 2 multi-grid steps
+N_alpha = ceil((N_alpha)/4) *4 + 1;
+
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --numThreads=1'];
+
+def_refSimu = 0; % do a reference simulation without the multi-grid
+
+%% setup done %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+if (def_refSimu>0)
+ Sim_Path = 'tmp_ref';
+else
+ Sim_Path = 'tmp';
+end
+Sim_CSX = 'coax.xml';
+
+if (exist(Sim_Path,'dir'))
+ rmdir(Sim_Path,'s');
+end
+mkdir(Sim_Path);
+
+%setup FDTD parameter
+if (def_refSimu>0)
+ FDTD = InitCylindricalFDTD(1e5,1e-5,'OverSampling',5 );
+else
+ FDTD = InitCylindricalFDTD(1e5,1e-5,'OverSampling',5 ,'MultiGrid','60,120');
+end
+FDTD = SetGaussExcite(FDTD,f0,f0);
+BC = [0 0 1 1 2 2];
+FDTD = SetBoundaryCond(FDTD,BC);
+
+mesh_res = [max_mesh 2*pi*partial/N_alpha max_mesh];
+
+%setup CSXCAD geometry
+CSX = InitCSX();
+mesh.x = SmoothMeshLines([rad_i rad_a],mesh_res(1));
+mesh.y = linspace(-pi*partial,pi*partial,N_alpha);
+mesh.z = SmoothMeshLines([0 port_dist length],mesh_res(3));
+CSX = DefineRectGrid(CSX, 1e-3,mesh);
+
+start = [rad_i mesh.y(1) mesh.z(3)];
+stop = [rad_a mesh.y(end) mesh.z(3)];
+
+CSX = AddExcitation(CSX,'excite',0,[1 0 0]);
+weight{1} = '1/rho';
+weight{2} = 0;
+weight{3} = 0;
+CSX = SetExcitationWeight(CSX, 'excite', weight );
+CSX = AddBox(CSX,'excite',0 ,start,stop);
+
+
+start = [mesh.x(1) mesh.y(1) mesh.z(1)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end)];
+CSX = AddMaterial(CSX,'material');
+CSX = SetMaterialProperty(CSX,'material','Epsilon',epsR);
+CSX = AddBox(CSX,'material',0 ,start,stop);
+
+%dump
+CSX = AddDump(CSX,'Et_rz_','DumpMode',0);
+start = [mesh.x(1) 0 mesh.z(1)];
+stop = [mesh.x(end) 0 mesh.z(end)];
+CSX = AddBox(CSX,'Et_rz_',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht_rz_','DumpType',1,'DumpMode',0);
+CSX = AddBox(CSX,'Ht_rz_',0 , start,stop);
+
+CSX = AddDump(CSX,'Et_','DumpType',0,'DumpMode',0);
+start = [mesh.x(1) mesh.y(1) length/2];
+stop = [mesh.x(end) mesh.y(end) length/2];
+CSX = AddBox(CSX,'Et_',0,start,stop);
+
+CSX = AddDump(CSX,'Ht_','DumpType',1,'DumpMode',0);
+start = [mesh.x(1) mesh.y(1) length/2];
+stop = [mesh.x(end) mesh.y(end) length/2];
+CSX = AddBox(CSX,'Ht_',0,start,stop);
+
+% voltage calc (take a voltage average to be at the same spot as the
+% current calculation)
+CSX = AddProbe(CSX,'ut1_1',0);
+start = [ rad_i 0 port_dist ];stop = [ rad_a 0 port_dist ];
+CSX = AddBox(CSX,'ut1_1', 0 ,start,stop);
+CSX = AddProbe(CSX,'ut1_2',0);
+start = [ rad_i 0 port_dist+mesh_res(3) ];stop = [ rad_a 0 port_dist+mesh_res(3) ];
+CSX = AddBox(CSX,'ut1_2', 0 ,start,stop);
+
+% current calc
+CSX = AddProbe(CSX,'it1',1);
+mid = 75;
+start = [ 0 mesh.y(1) port_dist+mesh_res(3)/2 ];stop = [ mid mesh.y(end) port_dist+mesh_res(3)/2 ];
+CSX = AddBox(CSX,'it1', 0 ,start,stop);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts, Settings)
+
+%%
+close all
+freq = linspace(0,2*f0,201);
+UI = ReadUI({'ut1_1','ut1_2','it1'},Sim_Path,freq);
+u_f = (UI.FD{1}.val + UI.FD{2}.val)/2; %averaging voltages to fit current
+i_f = UI.FD{3}.val / partial;
+
+% plot(UI.TD{1}.t,UI.TD{1}.val);
+% grid on;
+%
+% figure
+% plot(UI.TD{3}.t,UI.TD{3}.val);
+% grid on;
+
+%plot Z_L compare
+figure
+ZL = Z0/2/pi/sqrt(epsR)*log(rad_a/rad_i); %analytic line-impedance of a coax
+plot(UI.FD{1}.f,ZL*ones(size(u_f)),'g','Linewidth',3);
+hold on;
+grid on;
+Z = u_f./i_f;
+plot(UI.FD{1}.f,real(Z),'k--','Linewidth',2);
+plot(UI.FD{1}.f,imag(Z),'r-','Linewidth',2);
+xlim([0 2*f0]);
+legend('Z_L - analytic','\Re\{Z\} - FDTD','\Im\{Z\} - FDTD','Location','Best');
+
+
diff --git a/openEMS/matlab/examples/waveguide/Rect_Waveguide.m b/openEMS/matlab/examples/waveguide/Rect_Waveguide.m
new file mode 100644
index 0000000..a9601ad
--- /dev/null
+++ b/openEMS/matlab/examples/waveguide/Rect_Waveguide.m
@@ -0,0 +1,240 @@
+%
+% EXAMPLE / waveguide / Rect_Waveguide
+%
+% This example demonstrates:
+% - waveguide mode excitation
+% - waveguide mode matching
+% - pml absorbing boundaries
+%
+%
+% Tested with
+% - Matlab 2009b
+% - openEMS v0.0.17
+%
+% (C) 2010 Thorsten Liebig <thorsten.liebig@gmx.de>
+
+close all
+clear
+clc
+
+%% switches
+postproc_only = 0;
+
+%% setup the simulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+physical_constants;
+unit = 1e-3; %drawing unit in mm
+numTS = 50000; %max. number of timesteps
+
+% waveguide dimensions
+length = 1000;
+a = 1000; %waveguide width
+b = 600; %waveguide heigth
+
+%waveguide TE-mode definition
+m = 1;
+n = 0;
+
+mesh_res = [10 10 10];
+
+%% setup FDTD parameters & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+f_start = 175e6;
+f_stop = 500e6;
+
+% dump special frequencies to vtk, use paraview (www.paraview.org) to
+% animate this dumps over phase
+vtk_dump_freq = [200e6 300e6 500e6];
+
+freq = linspace(f_start,f_stop,201);
+
+k = 2*pi*freq/c0;
+kc = sqrt((m*pi/a/unit)^2 + (n*pi/b/unit)^2);
+fc = c0*kc/2/pi; %cut-off frequency
+beta = sqrt(k.^2 - kc^2); %waveguide phase-constant
+ZL_a = k * Z0 ./ beta; %analytic waveguide impedance
+
+disp([' Cutoff frequencies for this mode and wavguide is: ' num2str(fc/1e6) ' MHz']);
+
+if (f_start<fc)
+ warning('openEMS:example','f_start is smaller than the cutoff-frequency, this may result in a long simulation... ');
+end
+
+%% mode functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% by David M. Pozar, Microwave Engineering, third edition, page 113
+func_Ex = [num2str( n/b/unit) '*cos(' num2str(m*pi/a) '*x)*sin(' num2str(n*pi/b) '*y)'];
+func_Ey = [num2str(-m/a/unit) '*sin(' num2str(m*pi/a) '*x)*cos(' num2str(n*pi/b) '*y)'];
+
+func_Hx = [num2str(m/a/unit) '*sin(' num2str(m*pi/a) '*x)*cos(' num2str(n*pi/b) '*y)'];
+func_Hy = [num2str(n/b/unit) '*cos(' num2str(m*pi/a) '*x)*sin(' num2str(n*pi/b) '*y)'];
+
+%% define and openEMS options %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openEMS_opts = '';
+% openEMS_opts = [openEMS_opts ' --disable-dumps'];
+% openEMS_opts = [openEMS_opts ' --debug-material'];
+% openEMS_opts = [openEMS_opts ' --engine=basic'];
+
+Settings = [];
+Settings.LogFile = 'openEMS.log';
+
+Sim_Path = 'tmp';
+Sim_CSX = 'rect_wg.xml';
+
+if (postproc_only==0)
+ [status, message, messageid] = rmdir(Sim_Path,'s');
+ [status, message, messageid] = mkdir(Sim_Path);
+end
+
+%% setup FDTD parameter & excitation function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FDTD = InitFDTD(numTS,1e-5,'OverSampling',6);
+FDTD = SetGaussExcite(FDTD,0.5*(f_start+f_stop),0.5*(f_stop-f_start));
+BC = [0 0 0 0 0 3];
+FDTD = SetBoundaryCond(FDTD,BC);
+
+%% setup CSXCAD geometry & mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = InitCSX();
+mesh.x = SmoothMeshLines([0 a], mesh_res(1));
+mesh.y = SmoothMeshLines([0 b], mesh_res(2));
+mesh.z = SmoothMeshLines([0 length], mesh_res(3));
+CSX = DefineRectGrid(CSX, unit,mesh);
+
+%% apply the excitation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+start=[mesh.x(1) mesh.y(1) mesh.z(1) ];
+stop =[mesh.x(end) mesh.y(end) mesh.z(1) ];
+CSX = AddExcitation(CSX,'excite',0,[1 1 0]);
+weight{1} = func_Ex;
+weight{2} = func_Ey;
+weight{3} = 0;
+CSX = SetExcitationWeight(CSX,'excite',weight);
+CSX = AddBox(CSX,'excite',0 ,start,stop);
+
+%% voltage and current definitions using the mode matching probes %%%%%%%%%
+%port 1
+start = [mesh.x(1) mesh.y(1) mesh.z(15)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(15)];
+CSX = AddProbe(CSX, 'ut1', 10, 1, [], 'ModeFunction',{func_Ex,func_Ey,0});
+CSX = AddBox(CSX, 'ut1', 0 ,start,stop);
+CSX = AddProbe(CSX,'it1', 11, 1, [], 'ModeFunction',{func_Hx,func_Hy,0});
+CSX = AddBox(CSX,'it1', 0 ,start,stop);
+
+%port 2
+start = [mesh.x(1) mesh.y(1) mesh.z(end-15)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end-15)];
+CSX = AddProbe(CSX, 'ut2', 10, 1, [], 'ModeFunction',{func_Ex,func_Ey,0});
+CSX = AddBox(CSX, 'ut2', 0 ,start,stop);
+CSX = AddProbe(CSX,'it2', 11, 1, [], 'ModeFunction',{func_Hx,func_Hy,0});
+CSX = AddBox(CSX,'it2', 0 ,start,stop);
+
+port_dist = mesh.z(end-15) - mesh.z(15);
+
+%% define dump boxes... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSX = AddDump(CSX,'Et','FileType',1,'SubSampling','4,4,2');
+start = [mesh.x(1) mesh.y(1) mesh.z(1)];
+stop = [mesh.x(end) mesh.y(end) mesh.z(end)];
+CSX = AddBox(CSX,'Et',0 , start,stop);
+
+CSX = AddDump(CSX,'Ht','DumpType',1,'FileType',1,'SubSampling','4,4,2');
+CSX = AddBox(CSX,'Ht',0,start,stop);
+
+%% Write openEMS compatoble xml-file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if (postproc_only==0)
+ WriteOpenEMS([Sim_Path '/' Sim_CSX],FDTD,CSX);
+
+ RunOpenEMS(Sim_Path, Sim_CSX, openEMS_opts, Settings)
+end
+
+%% postproc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+U = ReadUI({'ut1','ut2'},[Sim_Path '/'],freq);
+I = ReadUI({'it1','it2'},[Sim_Path '/'],freq);
+Exc = ReadUI('et',Sim_Path,freq);
+
+uf1 = U.FD{1}.val./Exc.FD{1}.val;
+uf2 = U.FD{2}.val./Exc.FD{1}.val;
+if1 = I.FD{1}.val./Exc.FD{1}.val;
+if2 = I.FD{2}.val./Exc.FD{1}.val;
+
+uf1_inc = 0.5 * ( uf1 + if1 .* ZL_a );
+if1_inc = 0.5 * ( if1 + uf1 ./ ZL_a );
+uf2_inc = 0.5 * ( uf2 + if2 .* ZL_a );
+if2_inc = 0.5 * ( if2 + uf2 ./ ZL_a );
+
+uf1_ref = uf1 - uf1_inc;
+if1_ref = if1 - if1_inc;
+uf2_ref = uf2 - uf2_inc;
+if2_ref = if2 - if2_inc;
+
+%% plot s-parameter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+s11 = uf1_ref./uf1_inc;
+s21 = uf2_inc./uf1_inc;
+plot(freq,20*log10(abs(s11)),'Linewidth',2);
+xlim([freq(1) freq(end)]);
+% ylim([-40 5]);
+grid on;
+hold on;
+plot(freq,20*log10(abs(s21)),'r','Linewidth',2);
+legend('s11','s21','Location','SouthEast');
+ylabel('s-para (dB)');
+xlabel('freq (Hz)');
+
+%% compare analytic and numerical wave-impedance %%%%%%%%%%%%%%%%%%%%%%%%%%
+ZL = uf1./if1;
+figure()
+plot(freq,real(ZL),'Linewidth',2);
+hold on;
+grid on;
+plot(freq,imag(ZL),'r--','Linewidth',2);
+plot(freq,ZL_a,'g-.','Linewidth',2);
+ylabel('ZL (\Omega)');
+xlabel('freq (Hz)');
+xlim([freq(1) freq(end)]);
+legend('\Re(Z_L)','\Im(Z_L)','Z_L analytic','Location','Best');
+
+%% beta compare
+figure()
+da = unwrap(angle(uf1_inc./uf2_inc)) ;
+% da = mod(da,2*pi);
+beta_12 = (da)/port_dist/unit;
+plot(freq,beta_12,'Linewidth',2);
+xlim([freq(1) freq(end)]);
+xlabel('frequency (Hz)');
+ylabel('\beta (m^{-1})');
+grid on;
+hold on;
+plot(freq,beta,'g--','Linewidth',2);
+legend('\beta-FDTD','\beta-analytic','Location','Best');
+
+%% Plot the field dumps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dump_file = [Sim_Path '/Et.h5'];
+figure()
+PlotArgs.slice = {a/2*unit b/2*unit 0};
+PlotArgs.pauseTime=0.01;
+PlotArgs.component=0;
+PlotArgs.Limit = 'auto';
+PlotHDF5FieldData(dump_file, PlotArgs)
+
+%% dump frequency to vtk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% cleanup and create dump folder
+vtk_path = [Sim_Path '/vtk'];
+[status, message, messageid] = rmdir(vtk_path,'s');
+[status, message, messageid] = mkdir(vtk_path);
+
+disp('Dumping to vtk files... this may take a minute...')
+% define interpolation mesh
+mesh_interp{1}=mesh.x * unit;
+mesh_interp{2}=b/2 * unit;
+mesh_interp{3}=mesh.z * unit;
+[field mesh_FD] = ReadHDF5Dump(dump_file,'Interpolation',mesh_interp,'Frequency',vtk_dump_freq);
+
+% dump animated phase to vtk
+for n=1:numel(vtk_dump_freq)
+ phase = linspace(0,360,21);
+ phase = phase(1:end-1);
+ for ph = phase
+ filename = [vtk_path '/E_xz_f=' num2str(vtk_dump_freq(n)) '_p' num2str(ph) '.vtk'];
+ Dump2VTK(filename,real(field.FD.values{n}.*exp(1j*ph/180*pi)),mesh_FD,'E-Field');
+ end
+
+ filename = [vtk_path '/E_xz_f=' num2str(vtk_dump_freq(n)) '_mag.vtk'];
+ Dump2VTK(filename,abs(field.FD.values{n}),mesh_FD,'E-Field');
+end
+
+disp('done... you can open and visualize the vtk-files using Paraview (www.paraview.org)!')
diff --git a/openEMS/matlab/h5readatt_octave.cc b/openEMS/matlab/h5readatt_octave.cc
new file mode 100755
index 0000000..8bd58d0
--- /dev/null
+++ b/openEMS/matlab/h5readatt_octave.cc
@@ -0,0 +1,135 @@
+#include <octave/oct.h>
+#include <octave/ov-struct.h>
+#include "hdf5.h"
+
+// this special treatment is necessary because Win32-Octave ships with a very old hdf5 version (1.6.10)
+void CloseH5Object(hid_t obj)
+{
+#if ((H5_VERS_MAJOR == 1) && (H5_VERS_MINOR == 6))
+ // try group close, than Dataset close
+ if (H5Gclose(obj)<0)
+ H5Dclose(obj);
+#else
+ H5Oclose(obj);
+#endif
+}
+
+DEFUN_DLD (h5readatt_octave, args, nargout, "h5readatt_octave(<File_Name>,<DataSet_Name>,<Attribute_Name>)")
+{
+ octave_value retval;
+ int nargin = args.length();
+ if (nargin != 3)
+ {
+ print_usage();
+ return retval;
+ }
+ if ((args(0).is_string()==false) || (args(1).is_string()==false) || (args(2).is_string()==false))
+ {
+ print_usage();
+ return retval;
+ }
+
+ //suppress hdf5 error output
+ H5Eset_auto1(NULL, NULL);
+
+ hid_t file = H5Fopen( args(0).string_value().c_str(), H5F_ACC_RDONLY, H5P_DEFAULT );
+ if (file==-1)
+ {
+ error("h5readatt_octave: opening the given File failed");
+ return retval;
+ }
+
+#if ((H5_VERS_MAJOR == 1) && (H5_VERS_MINOR == 6))
+ // this special treatment is necessary because Win32-Octave ships with a very old hdf5 version (1.6.10)
+ hid_t obj = -1;
+ //try opening the group
+ obj = H5Gopen(file, args(1).string_value().c_str());
+ //try opening the dataset if group failed
+ if (obj==-1)
+ obj = H5Dopen(file, args(1).string_value().c_str());
+#else
+ hid_t obj = H5Oopen(file, args(1).string_value().c_str(), H5P_DEFAULT);
+#endif
+
+ if (obj==-1)
+ {
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: opening the given Object failed");
+ return retval;
+ }
+
+ hid_t attr = H5Aopen_name(obj, args(2).string_value().c_str());
+ if (attr==-1)
+ {
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: opening the given Attribute failed");
+ return retval;
+ }
+
+ hid_t type = H5Aget_type(attr);
+ if (type<0)
+ {
+ H5Aclose(attr);
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: dataset type error");
+ return retval;
+ }
+
+ if (H5Tget_class(type)!=H5T_FLOAT)
+ {
+ H5Aclose(attr);
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: attribute type not supported");
+ return retval;
+ }
+
+ size_t numVal = H5Aget_storage_size(attr)/H5Tget_size(type);
+ double value[numVal];
+ if (H5Tget_size(type)==sizeof(float))
+ {
+ float f_value[numVal];
+ if (H5Aread(attr, H5T_NATIVE_FLOAT, f_value)<0)
+ {
+ H5Aclose(attr);
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: reading the given Attribute failed");
+ return retval;
+ }
+ for (size_t n=0;n<numVal;++n)
+ value[n] = f_value[n];
+ }
+ else if (H5Tget_size(type)==sizeof(double))
+ {
+ if (H5Aread(attr, H5T_NATIVE_DOUBLE, value)<0)
+ {
+ H5Aclose(attr);
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: reading the given Attribute failed");
+ return retval;
+ }
+ }
+ else
+ {
+ H5Aclose(attr);
+ CloseH5Object(obj);
+ H5Fclose(file);
+ error("h5readatt_octave: reading the given Attribute failed: unknown type");
+ return retval;
+ }
+
+ H5Aclose(attr);
+ CloseH5Object(obj);
+ H5Fclose(file);
+ Matrix mat(numVal,1);
+ for (size_t n=0;n<numVal;++n)
+ mat(n)=value[n];
+ retval = octave_value(mat);
+ return retval;
+}
+
diff --git a/openEMS/matlab/harminv.m b/openEMS/matlab/harminv.m
new file mode 100644
index 0000000..a5d0c77
--- /dev/null
+++ b/openEMS/matlab/harminv.m
@@ -0,0 +1,77 @@
+function [f,decay,Q,amp,phase,err]=harminv( timeseries, timestep, start_freq, stop_freq )
+% [f,decay,Q,amp,phase,err]=harminv( timeseries, timestep, start_freq, stop_freq )
+%
+% reconstruct time signal with:
+% real(amp(n) * exp(-1i*(2*pi*freq(n)*t-phase(n))-decay(n)*t)));
+%
+% example:
+% t = linspace(0,(1/0.3e9)*5,1000);
+% u = 0.8 * sin(2*pi*0.7e9 * t + 0/180*pi);
+% u = u + 0.3 * sin(2*pi*0.3e9 * t + 0/180*pi);
+% [freq,decay,Q,amp,phase,err]=harminv( u, t(2)-t(1), 0, 1e9 );
+%
+% -----------------------
+% Sebastian Held <sebastian.held@gmx.de>
+
+if isunix
+ harminv_exe = 'export LD_LIBRARY_PATH=; harminv';
+elseif ispc
+ m_filename = mfilename('fullpath');
+ dir = fileparts( m_filename );
+ harminv_exe = [ '"' dir '\..\harminv.exe"'];
+else
+ error('openEMS:harminv','unknown/unsupported operating system...');
+end
+
+options = ['-t ' num2str(timestep)];
+tmpfile = tempname;
+
+% convert to column vector
+if size(timeseries,2) > size(timeseries,1)
+ timeseries = timeseries.';
+end
+
+% harminv hangs if timeseries is zero only
+if all(timeseries == 0)
+ disp( 'timeseries is 0' );
+ return
+end
+
+% write timeseries to temporary file
+dlmwrite( tmpfile, timeseries );
+
+command = [harminv_exe ' ' options ' '...
+ num2str(start_freq) '-' num2str(stop_freq) ' < "' tmpfile '"'];
+[status,result] = system( command );
+if status ~= 0
+ disp( 'error executing harminv:' );
+ disp( command );
+ disp( ['exit status: ' num2str(status)] );
+ disp( ['output: ' result] );
+ return
+end
+
+%disp( command )
+%disp( result )
+
+f = [];
+decay = [];
+Q = [];
+amp = [];
+phase = [];
+err = [];
+
+lines = textscan( result, '%s', 'Delimiter', '\n');
+
+for n=2:numel(lines{1})
+ [C] = textscan( lines{1}{n}, '%f', 6, 'Delimiter', ',');
+ if isempty(C{1}), break; end
+ if C{1}(1) >= 0
+ f = [f C{1}(1)];
+ decay = [decay C{1}(2)];
+ Q = [Q C{1}(3)];
+ amp = [amp 2*C{1}(4)]; % neglecting negative frequencies => amplitude doubles
+ phase = [phase C{1}(5)];
+ err = [err C{1}(6)];
+ end
+end
diff --git a/openEMS/matlab/optimize.m b/openEMS/matlab/optimize.m
new file mode 100644
index 0000000..78ef497
--- /dev/null
+++ b/openEMS/matlab/optimize.m
@@ -0,0 +1,203 @@
+function [params,result] = optimize( optimdir, params, options, algorithm )
+%params = optimize( optimdir, params, options, algorithm )
+%
+% input:
+% optimdir: folder where to optimize
+% params: array of structures with parameters to optimize
+% .name char string parameter name (e.g. 'length1')
+% .value number
+% .step number discretization of .value
+% .range row vector range of .value (e.g. [1 10])
+% .active (0/1) 1=optimize this parameter
+% options: structure
+% .folder_matlabstart set the startup folder for matlab or octave
+% .simfun char string with the simulation function name
+% .octave_exe if this field is present, octave is used
+% .clean clean the optimization folder before optimization start
+% algorithm: 'asco' or 'simplex-downhill'
+%
+% output:
+% params: optimal values
+% result: optimization criterion for optimal values
+%
+% example:
+% see openEMS/matlab/examples/optimizer
+%
+% notes:
+% Create a file named 'STOP_OPTIMIZATION' in the optimdir folder to stop
+% the optimization process (or press Ctrl+C).
+%
+% (C) 2010 Sebastian Held <sebastian.held@gmx.de>
+
+error( nargchk(3,4,nargin) );
+
+% default to simplex-downhill
+if nargin < 4
+ algorithm = 'simplex-downhill';
+end
+if ~strcmp( algorithm, 'asco' )
+ algorithm = 'simplex-downhill';
+end
+
+optimdir = absolutepath( optimdir );
+if isfield(options,'clean') && (options.clean == 1)
+ [a,a,a] = rmdir( optimdir, 's' );
+end
+[a,a,a] = mkdir( optimdir );
+oldfolder = cd( optimdir );
+
+if strcmp( algorithm, 'asco' )
+ % ---------------------------------------------------------------------
+ % selected algorithm: ASCO
+ % http://asco.sourceforge.net/
+
+% if ~exist( 'asco', 'file' ) && ~exist( 'asco.exe', 'file' )
+% error 'asco was not found in PATH. Download from http://asco.sf.net/'
+% end
+
+ % create asco config file
+ fid = fopen( 'asco.cfg', 'wt' );
+ fprintf( fid, '* asco configuration file\n' );
+ fprintf( fid, '* http://asco.sourceforge.net/\n' );
+ fprintf( fid, '* \n' );
+ fprintf( fid, '* Optimization for openEMS\n\n' );
+ fprintf( fid, '#Optimization Flow#\n' );
+ fprintf( fid, 'Alter:no $do we want to do corner analysis?\n' );
+ fprintf( fid, 'MonteCarlo:no $do we want to do MonteCarlo analysis?\n' );
+ fprintf( fid, 'AlterMC cost:0.00 $point below which ALTER and/or MONTECARLO can start\n' );
+ fprintf( fid, 'ExecuteRF:no $Execute or no the RF module to add RF parasitics?\n' );
+ fprintf( fid, '#\n\n' );
+ fprintf( fid, '#DE#\n' );
+ fprintf( fid, 'choice of method:3\n' );
+ fprintf( fid, 'maximum no. of iterations:50\n' );
+ fprintf( fid, 'Output refresh cycle:2\n' );
+ fprintf( fid, 'No. of parents NP:10\n' );
+ fprintf( fid, 'Constant F:0.85\n' );
+ fprintf( fid, 'Crossing Over factor CR:1\n' );
+ fprintf( fid, 'Seed for pseudo random number generator:3\n' );
+ fprintf( fid, 'Minimum Cost Variance:1e-6\n' );
+ fprintf( fid, 'Cost objectives:10\n' );
+ fprintf( fid, 'Cost constraints:100\n' );
+ fprintf( fid, '#\n\n' );
+
+ fprintf( fid, '# Parameters #\n' );
+ for n=1:numel(params)
+ if params(n).active == 1
+ active = 'OPT';
+ else
+ active = '---';
+ end
+ value = params(n).value / params(n).step;
+ range = params(n).range / params(n).step;
+ fprintf( fid, 'description:#%s#:%i:%i:%i:LIN_INT:%s\n', params(n).name, value, range(1), range(2), active );
+ end
+ fprintf( fid, '#\n\n' );
+
+ fprintf( fid, '# Measurements #\n' );
+ fprintf( fid, 'value:---:MIN:0\n' );
+ fprintf( fid, '#\n\n' );
+ fclose(fid);
+
+ % create extract file
+ [a,a,a]=mkdir( 'extract' );
+ fid = fopen( 'extract/value', 'wt' );
+ fprintf( fid, '# Info #\n' );
+ fprintf( fid, 'Name:value\n' );
+ fprintf( fid, 'Symbol:value\n' );
+ fprintf( fid, '#\n\n' );
+ fprintf( fid, '# Commands #\n' );
+ fprintf( fid, '#\n\n' );
+ fprintf( fid, '# Post Processing #\n' );
+ fprintf( fid, 'MEASURE_VAR: #SYMBOL#: SEARCH_FOR:''value=''\n' );
+ fprintf( fid, '#\n' );
+ fclose(fid);
+
+ % create matlab parameter file
+ fid = fopen( 'asco.txt', 'wt' );
+ fprintf( fid, '%% this file is processed by asco and variables enclosed in ## are substituted\n' );
+ fprintf( fid, 'params = [];\n' );
+ for n=1:numel(params)
+ fprintf( fid, 'params.%s = #%s# * %i;\n', params(n).name, params(n).name, params(n).step );
+ end
+ fclose(fid);
+
+ % create shell script
+ folder_asco_helper = fileparts( mfilename('fullpath') );
+ asco_sim_helper = 'optimizer_asco_sim';
+ fid = fopen( 'general.sh', 'wt' );
+ fprintf( fid, '#!/bin/sh\n' );
+ fprintf( fid, 'rm "$2.out" 2> /dev/null\n' );
+ fprintf( fid, 'mv "$1.txt" "$1.m"\n' );
+ fprintf( fid, 'if [ -f STOP_OPTIMIZATION ]; then\n' );
+ fprintf( fid, ' exit\n' );
+ fprintf( fid, 'fi\n' );
+ fprintf( fid, 'oldpwd=$PWD\n' );
+ if isfield(options,'folder_matlabstart')
+ % this allows to start the new matlab process in a specific folder
+ % => startup.m is picked up here
+ fprintf( fid, 'cd "%s"\n', functions.folder_matlabstart );
+ end
+ if ~isfield(options,'octave_exe')
+ % matlab
+ fprintf( fid, '%s/bin/matlab -nodesktop -nosplash -r "cd ''%s''; %s(''%s'',''$1'',''$2.out'',''%s''); exit"\n', matlabroot, folder_asco_helper, asco_sim_helper, optimdir, options.simfun );
+ else
+ % octave
+ fprintf( fid, 'export LD_LIBRARY_PATH=\n' );
+ fprintf( fid, '%s --silent --eval "cd ''%s''; %s(''%s'',''$1'',''$2.out'',''%s'');"\n', options.octave_exe, folder_asco_helper, asco_sim_helper, optimdir, options.simfun );
+ end
+ fprintf( fid, 'cd "$oldpwd"\n' );
+ fclose(fid);
+ fileattrib( 'general.sh', '+x' ); % make it executable
+
+ % clean up old data
+ if exist( './best_result.mat', 'file' ), delete( 'best_result.mat' ); end
+ if exist( './STOP_OPTIMIZATION', 'file' ), delete( 'STOP_OPTIMIZATION' ); end
+
+ % start asco
+ [status,result] = unix( 'asco -general asco.txt', '-echo' );
+
+ % get best result
+ best = load( 'best_result.mat' );
+ best = best.best;
+ result = best.result;
+ for n=1:numel(params)
+ name = params(n).name;
+ if isfield(best.params,name)
+ params(n).value = best.params.(name);
+ end
+ end
+
+elseif strcmp( algorithm, 'simplex-downhill' )
+ % ---------------------------------------------------------------------
+ % selected algorithm: simplex-downhill
+ % Thorsten Liebig <thorsten.liebig@uni-due.de>
+
+ error( 'not implemented yet' );
+end
+
+cd( oldfolder );
+
+
+
+
+
+function folder = absolutepath( folder )
+%folder = absolutepath( folder )
+% make the path absolute
+if isunix
+ % Unix
+ if folder(1) == '/'
+ return
+ end
+ folder = fullfile( pwd, folder );
+else
+ % Windows
+ folder = strrep( folder, '\', '/' );
+ if strcmp( folder(2:3), ':/' ) || strcmp( folder(1:2), '//' ) || (folder(1) == '/')
+ return
+ end
+ if (folder(2) == ':') && (folder(3) ~= '/')
+ error( 'relative paths with drive specifier are not supported' );
+ end
+ folder = fullfile( pwd, folder );
+end
diff --git a/openEMS/matlab/optimizer_asco_sim.m b/openEMS/matlab/optimizer_asco_sim.m
new file mode 100644
index 0000000..6f62ebf
--- /dev/null
+++ b/openEMS/matlab/optimizer_asco_sim.m
@@ -0,0 +1,88 @@
+function optimizer_asco_sim( optimdir, inputfile, outputfile, simfun )
+%optimizer_asco_sim( optimdir, inputfile, outputfile, simfun )
+%
+% This function is called from general.sh. Do not call it yourself.
+%
+% tasks:
+% - set correct matlab path
+% - evaluate inputfile
+% - start simulation or get result from cache
+% - postprocess simulation results
+% - create output file (important: needs single \n at the first line and double \n at the last line!)
+
+error( nargchk(4,4,nargin) );
+
+% add CSXCAD and openEMS to the matlab path
+folder = fileparts( mfilename('fullpath') );
+addpath( folder );
+addpath( [folder '/../../CSXCAD/matlab'] );
+
+% change to optimdir
+olddir = pwd;
+cd( optimdir );
+
+% read parameters set by asco
+if ~isempty( strfind(inputfile,'-') )
+ % matlab cannot execute a file with dashes...
+ inputfile2 = strrep( inputfile,'-','_' );
+ movefile( [inputfile '.m'], [inputfile2 '.m'] );
+ run( inputfile2 );
+ movefile( [inputfile2 '.m'], [inputfile '.m'] );
+end
+% now a structure named 'params' is available
+
+% check cache
+folder = create_folder_name( params );
+if exist( ['./' folder], 'dir' ) && exist( ['./' folder '/result.mat'], 'file' )
+ % read cache
+ disp( 'CACHE HIT' );
+ result = load( [folder '/result.mat'], 'result' );
+ result = result.result;
+else
+ % start simulation in folder <folder>
+ disp( ['starting simulation function ' simfun] );
+ disp( [' simulation folder ' folder] );
+ [simfun_folder,simfun] = fileparts(simfun);
+ oldpath = path;
+ addpath( simfun_folder );
+ fhandle = str2func(simfun); % does not work for octave-3.2.4!
+ path( oldpath );
+ mkdir( folder );
+ result = fhandle(folder,params);
+ save( [folder '/result.mat'], 'result', '-mat' );
+end
+
+% write results for asco
+fid = fopen( outputfile, 'wt' );
+fprintf( fid, '\nvalue= %e\n\n', result );
+fclose( fid );
+
+% update best result
+best = [];
+best.result = result;
+best.params = params;
+if exist( [pwd '/best_result.mat'], 'file' )
+ old = load( 'best_result.mat', 'best' );
+ if old.best.result > best.result
+ save( 'best_result.mat', 'best', '-mat' );
+ end
+else
+ save( 'best_result.mat', 'best', '-mat' );
+end
+
+% restore old folder
+cd( olddir );
+
+
+
+
+
+
+
+function folder = create_folder_name( params )
+params = orderfields( params );
+folder = 'opt';
+fnames = fieldnames(params);
+for n=1:numel(fnames)
+ folder = [folder '_' fnames{n} '=' num2str(params.(fnames{n}))];
+end
diff --git a/openEMS/matlab/physical_constants.m b/openEMS/matlab/physical_constants.m
new file mode 100644
index 0000000..cbb333e
--- /dev/null
+++ b/openEMS/matlab/physical_constants.m
@@ -0,0 +1,12 @@
+%
+% physical constants
+%
+
+% Bronstein 3rd ed., 1997, pp. 945-946
+C0 = 299792458; % m/s
+c0 = C0; %constans in capital letters, c0 for legacy support
+MUE0 = 4e-7*pi; % N/A^2
+EPS0 = 1/(MUE0*C0^2); % F/m
+
+% free space wave impedance
+Z0 = sqrt(MUE0/EPS0); % Ohm
diff --git a/openEMS/matlab/plotFF3D.m b/openEMS/matlab/plotFF3D.m
new file mode 100644
index 0000000..45950c8
--- /dev/null
+++ b/openEMS/matlab/plotFF3D.m
@@ -0,0 +1,91 @@
+function h = plotFF3D(nf2ff,varargin)
+% h = plotFF3D(nf2ff,varargin)
+%
+% plot normalized 3D far field pattern
+%
+% input:
+% nf2ff: output of CalcNF2FF
+%
+% variable input:
+% 'freq_index': - use the given frequency index, see nf2ff.freq
+% - default is 1
+% 'logscale': - if set, show farfield with logarithmic scale
+% - set the dB value for point of origin
+% - values below will be clamped
+% 'normalize': - true/false, normalize linear plot
+% - default is false, log-plot is always normalized!
+%
+% example:
+% plotFF3D(nf2ff, 'freq_index', 2, 'logscale', -20)
+%
+% see examples/antennas/infDipol.m
+%
+% See also CalcNF2FF, plotFFdB, polarFF
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig, Stefan Mahr
+
+% defaults
+logscale = [];
+freq_index = 1;
+normalize = 0;
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'logscale')==1);
+ logscale = varargin{n+1};
+ elseif (strcmp(varargin{n},'freq_index')==1);
+ freq_index = varargin{n+1};
+ elseif (strcmp(varargin{n},'normalize')==1);
+ normalize = varargin{n+1};
+ else
+ warning('openEMS:plotFF3D',['unknown argument key: ''' varargin{n} '''']);
+ end
+end
+
+if ((normalize~=0) || ~isempty(logscale))
+ E_far = nf2ff.E_norm{freq_index} / max(nf2ff.E_norm{freq_index}(:));
+else
+ E_far = nf2ff.E_norm{freq_index};
+end;
+
+if ~isempty(logscale)
+ E_far = 20*log10(E_far)/-logscale + 1;
+ E_far = E_far .* ( E_far > 0 );
+ titletext = sprintf('electrical far field [dB] @ f = %e Hz',nf2ff.freq(freq_index));
+elseif (normalize==0)
+ titletext = sprintf('electrical far field [V/m] @ f = %e Hz',nf2ff.freq(freq_index));
+else
+ titletext = sprintf('normalized electrical far field @ f = %e Hz',nf2ff.freq(freq_index));
+end
+
+[theta,phi] = ndgrid(nf2ff.theta,nf2ff.phi);
+x = E_far .* sin(theta) .* cos(phi);
+y = E_far .* sin(theta) .* sin(phi);
+z = E_far .* cos(theta);
+%figure
+h = surf( x,y,z, E_far );
+set(h,'EdgeColor','none');
+axis equal
+axis off
+
+try
+ if (isOctave && (strcmp(graphics_toolkit,'gnuplot')==1))
+ warning('openEMS:plotFF3D','Colorbar doesn''t work properly with octave and gnuplot. On problems, try ''colorbar off''');
+ end
+end
+
+if ~isempty(logscale)
+ colorbar('YTick', linspace(0,max(E_far(:)),9), ...
+ 'YTickLabel',num2str(linspace(logscale, 10*log10(nf2ff.Dmax(freq_index)),9)'));
+else
+ colorbar;
+end
+
+title( titletext );
+
+if (nargout == 0)
+ clear h;
+end
+
+end
diff --git a/openEMS/matlab/plotFFdB.m b/openEMS/matlab/plotFFdB.m
new file mode 100644
index 0000000..07e96e3
--- /dev/null
+++ b/openEMS/matlab/plotFFdB.m
@@ -0,0 +1,78 @@
+function h = plotFFdB(nf2ff,varargin)
+% h = plotFFdB(nf2ff,varargin)
+%
+% plot far field pattern in dBi
+%
+% input:
+% nf2ff: output of CalcNF2FF
+%
+% variable input:
+% 'freq_index': - use the given frequency index, see nf2ff.freq
+% - default is 1
+% 'xaxis': - 'phi' (default) or 'theta'
+% 'param': - array positions of parametric plot
+% - if xaxis='phi', theta is parameter, and vice versa
+% - default is 1
+%
+% example:
+% plotFFdB(nf2ff, 'freq_index', 2, ...
+% 'xaxis', 'phi', 'param', [1 46 91])
+%
+% see examples/NF2FF/infDipol.m
+%
+% See also CalcNF2FF, plotFF3D, polarFF
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig, Stefan Mahr
+
+% defaults
+freq_index = 1;
+xaxis = 'phi';
+param = 1;
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'freq_index')==1);
+ freq_index = varargin{n+1};
+ elseif (strcmp(varargin{n},'xaxis')==1);
+ xaxis = varargin{n+1};
+ elseif (strcmp(varargin{n},'param')==1);
+ param = varargin{n+1};
+ else
+ warning('openEMS:plotFFdB',['unknown argument key: ''' varargin{n} '''']);
+ end
+end
+
+D_log = nf2ff.E_norm{freq_index} / max(nf2ff.E_norm{freq_index}(:));
+D_log = 20*log10(D_log) + 10*log10(nf2ff.Dmax(freq_index));
+
+if (strcmp(xaxis,'theta')==1);
+ xax = nf2ff.theta;
+ yax = D_log(:,param);
+ parval = nf2ff.phi(param);
+ param = 'phi';
+elseif (strcmp(xaxis,'phi')==1);
+ xax = nf2ff.phi;
+ yax = D_log(param,:);
+ parval = nf2ff.theta(param);
+ param = 'theta';
+else
+ error('openEMS:plotFFdB','unknown parameter to ''xaxis''');
+end
+
+%figure
+h = plot( xax / pi * 180 , yax );
+xlabel( sprintf('%s (deg)',xaxis ));
+ylabel( 'directivity (dBi)');
+
+createlegend = @(d)sprintf('%s = %3.1f',param,d / pi * 180);
+legendtext = arrayfun(createlegend,parval,'UniformOutput',0);
+legend( legendtext );
+title( sprintf('far field pattern @ f = %e Hz',nf2ff.freq(freq_index)) );
+grid on;
+
+if (nargout == 0)
+ clear h;
+end
+
+end
diff --git a/openEMS/matlab/polarFF.m b/openEMS/matlab/polarFF.m
new file mode 100644
index 0000000..96b97da
--- /dev/null
+++ b/openEMS/matlab/polarFF.m
@@ -0,0 +1,172 @@
+function h = polarFF(nf2ff,varargin)
+% h = polarFF(nf2ff,varargin)
+%
+% plot polar far field pattern
+%
+% input:
+% nf2ff: output of CalcNF2FF
+%
+% variable input:
+% 'freq_index': - use the given frequency index, see nf2ff.freq
+% - default is 1
+% 'xaxis': - 'phi' (default) or 'theta'
+% 'param': - array positions of parametric plot
+% - if xaxis='phi', theta is parameter, and vice versa
+% - default is 1
+% 'normalize': - true/false, normalize linear plot
+% - default is false, log-plot is always normalized!
+% 'logscale': - if set, plot logarithmic polar
+% - set the dB value for point of origin if scalar
+% - set point of origin and maximum if 2-element array
+% - values below minimum will be clamped
+% - default is -20
+% 'xtics': - set the number of tics for polar grid
+% - default is 5
+%
+% example:
+% polarFF(nf2ff, 'freq_index', 2, ...
+% 'xaxis', 'phi', 'param', [1 46 91] );
+%
+% polarFF(..., 'normalize', true );
+% polarFF(..., 'logscale', -30 );
+% polarFF(..., 'logscale', [-30 10]);
+%
+% polarFF(..., 'xtics', 10);
+%
+% see examples/antenna/infDipol.m
+%
+% See also CalcNF2FF, plotFFdB, plotFF3D
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig, Stefan Mahr
+
+% defaults
+freq_index = 1;
+xaxis = 'phi';
+param = 1;
+logscale = [];
+xtics = 5;
+normalize = 0;
+
+for n=1:2:numel(varargin)
+ if (strcmp(varargin{n},'freq_index')==1);
+ freq_index = varargin{n+1};
+ elseif (strcmp(varargin{n},'xaxis')==1);
+ xaxis = varargin{n+1};
+ elseif (strcmp(varargin{n},'param')==1);
+ param = varargin{n+1};
+ elseif (strcmp(varargin{n},'normalize')==1);
+ normalize = varargin{n+1};
+ elseif (strcmp(varargin{n},'logscale')==1);
+ logscale = varargin{n+1};
+ elseif (strcmp(varargin{n},'xtics')==1);
+ xtics = varargin{n+1};
+ else
+ warning('openEMS:polarFF',['unknown argument key: ''' varargin{n} '''']);
+ end
+end
+
+E_far_max = max(nf2ff.E_norm{freq_index}(:));
+if ~isempty(logscale)
+ gridmin = logscale(1);
+
+ Dmax = 10*log10(nf2ff.Dmax(freq_index));
+ E_far_scale = Dmax - gridmin;
+ E_far = 20*log10(nf2ff.E_norm{freq_index}) - 20*log10(E_far_max) + E_far_scale;
+ E_far = E_far .* ( E_far > 0 );
+ E_far = E_far ./ E_far_scale;
+
+ titletext = sprintf('electrical far field [dBi] @ f = %e Hz',nf2ff.freq(freq_index));
+
+ if numel(logscale) == 2 % normalize to maximum grid
+ gridmax = logscale(2);
+ E_far = E_far .* E_far_scale/(gridmax-gridmin);
+ else
+ gridmax = Dmax;
+ end
+elseif (normalize==0)
+ E_far = nf2ff.E_norm{freq_index};
+
+ titletext = sprintf('electrical far field [V/m] @ f = %e Hz',nf2ff.freq(freq_index));
+
+ gridmin = 0;
+ gridmax = E_far_max;
+else % normalize == 1
+ E_far = nf2ff.E_norm{freq_index} / E_far_max;
+
+ titletext = sprintf('normalized electrical far field @ f = %e Hz',nf2ff.freq(freq_index));
+
+ gridmin = 0;
+ gridmax = 1;
+end
+
+
+if (strcmp(xaxis,'theta')==1);
+ xax = nf2ff.theta(:);
+ yax = E_far(:,param);
+ parval = nf2ff.phi(param);
+ param = 'phi';
+elseif (strcmp(xaxis,'phi')==1);
+ xax = nf2ff.phi(:);
+ yax = E_far(param,:)';
+ parval = nf2ff.theta(param);
+ param = 'theta';
+else
+ error('openEMS:polarFF','unknown parameter to ''xaxis''');
+end
+
+if ~isempty(logscale)
+ scalegrid = 1;
+else
+ scalegrid = gridmax;
+end
+
+% workaround for polar plot
+gridcolor = [0.85 0.85 0.85];
+% plot xtics circles
+a=linspace(0,2*pi,60);
+b=linspace(0,scalegrid,xtics+1);
+b=repmat(b(2:end),numel(a),1)';
+a=repmat(a,size(b,1),1);
+[x,y] = pol2cart(a,b);
+h = plot(x',y');
+%h=polar(a,b,'-k');
+set(h,'Color',gridcolor);
+set(h(end),'Color',gridcolor*0.8);
+hold on;
+% plot degree lines
+a=bsxfun(@plus,[0:pi/6:pi-pi/6],[0 pi]');
+b=scalegrid.*ones(size(a));
+h=polar(a,b,'-k');
+set(h,'Color',gridcolor);
+set(h([1 4]),'Color',gridcolor*0.8);
+text(scalegrid*0.05,scalegrid*0.05,num2str(gridmin))
+text(scalegrid*1.05,scalegrid*0.05,num2str(gridmax))
+
+
+% draw far field
+xax = repmat(xax,1,size(yax,2));
+[x,y] = pol2cart(xax,yax);
+h = plot(x,y);
+%h = polar( xax, yax );
+
+% legend
+ylabel( sprintf('%s / deg', xaxis) );
+title( titletext );
+createlegend = @(d)sprintf('%s = %3.1f',param,d / pi * 180);
+legendtext = arrayfun(createlegend,parval,'UniformOutput',0);
+legend( h, legendtext ,'location','southeast');
+
+% workaround for polar plot
+axis equal tight
+axis ([-scalegrid scalegrid -scalegrid scalegrid]);
+axis off
+hold off
+set(gcf,'Color','white');
+
+if (nargout == 0)
+ clear h;
+end
+
+end
diff --git a/openEMS/matlab/private/ReadNF2FF.m b/openEMS/matlab/private/ReadNF2FF.m
new file mode 100644
index 0000000..55f67f9
--- /dev/null
+++ b/openEMS/matlab/private/ReadNF2FF.m
@@ -0,0 +1,82 @@
+function nf2ff = ReadNF2FF(nf2ff)
+% function nf2ff = ReadNF2FF(nf2ff)
+%
+% internal function to read calculated nf2ff data, use CalcNF2FF to read
+% existing nf2ff data
+%
+% See also: CalcNF2FF, CreateNF2FFBox
+%
+% openEMS matlab interface
+% -----------------------
+% author: Thorsten Liebig, 2012
+
+file = nf2ff.hdf5;
+
+hdf_mesh = ReadHDF5Mesh(file);
+
+nf2ff.r = double(hdf_mesh.lines{1});
+nf2ff.theta = double(hdf_mesh.lines{2});
+nf2ff.phi = double(hdf_mesh.lines{3});
+
+% read attributes
+nf2ff.freq = ReadHDF5Attribute(file,'/nf2ff','Frequency');
+nf2ff.Prad = ReadHDF5Attribute(file,'/nf2ff','Prad');
+nf2ff.Dmax = ReadHDF5Attribute(file,'/nf2ff','Dmax');
+
+try
+ nf2ff.Eps_r = ReadHDF5Attribute(file,'/nf2ff','Eps_r');
+catch
+ nf2ff.Eps_r = ones(size(nf2ff.freq));
+end
+try
+ nf2ff.Mue_r = ReadHDF5Attribute(file,'/nf2ff','Mue_r');
+catch
+ nf2ff.Mue_r = ones(size(nf2ff.freq));
+end
+
+if isOctave
+ hdf = load( '-hdf5', file );
+ for n=1:numel(nf2ff.freq)
+ nf2ff.E_theta{n} = double(hdf.nf2ff.E_theta.FD.(['f' int2str(n-1) '_real']) +1i*hdf.nf2ff.E_theta.FD.(['f' int2str(n-1) '_imag']) );
+ nf2ff.E_phi{n} = double(hdf.nf2ff.E_phi.FD.(['f' int2str(n-1) '_real']) +1i*hdf.nf2ff.E_phi.FD.(['f' int2str(n-1) '_imag']) );
+ nf2ff.E_norm{n} = double(sqrt(abs(nf2ff.E_theta{n}).^2+abs(nf2ff.E_phi{n}).^2));
+ nf2ff.P_rad{n} = double(hdf.nf2ff.P_rad.FD.(['f' int2str(n-1)]));
+ end
+else
+ % matlab compatibility to older versions
+ if verLessThan('matlab','7.12')
+ % read data
+ for n=1:numel(nf2ff.freq)
+ nf2ff.E_theta{n} = double(hdf5read(file,['/nf2ff/E_theta/FD/f' int2str(n-1) '_real']) + 1i*hdf5read(file,['/nf2ff/E_theta/FD/f' int2str(n-1) '_imag']));
+ nf2ff.E_phi{n} = double(hdf5read(file,['/nf2ff/E_phi/FD/f' int2str(n-1) '_real']) + 1i*hdf5read(file,['/nf2ff/E_phi/FD/f' int2str(n-1) '_imag']));
+ nf2ff.E_norm{n} = double(sqrt(abs(nf2ff.E_theta{n}).^2+abs(nf2ff.E_phi{n}).^2));
+ nf2ff.P_rad{n} = double(hdf5read(file,['/nf2ff/P_rad/FD/f' int2str(n-1)]));
+ end
+ else
+ % read data
+ for n=1:numel(nf2ff.freq)
+ nf2ff.E_theta{n} = double(h5read(file,['/nf2ff/E_theta/FD/f' int2str(n-1) '_real']) + 1i*h5read(file,['/nf2ff/E_theta/FD/f' int2str(n-1) '_imag']));
+ nf2ff.E_phi{n} = double(h5read(file,['/nf2ff/E_phi/FD/f' int2str(n-1) '_real']) + 1i*h5read(file,['/nf2ff/E_phi/FD/f' int2str(n-1) '_imag']));
+ nf2ff.E_norm{n} = double(sqrt(abs(nf2ff.E_theta{n}).^2+abs(nf2ff.E_phi{n}).^2));
+ nf2ff.P_rad{n} = double(h5read(file,['/nf2ff/P_rad/FD/f' int2str(n-1)]));
+ end
+ end
+end
+
+% Calculation of right- and left-handed circular polarization
+% adopted from
+% 2012, Tim Pegg <teepegg@gmail.com>
+
+% cleanup (if exist)
+nf2ff.E_cprh = [];
+nf2ff.E_cplh = [];
+
+% Setup vectors for converting to LHCP and RHCP polarization senses
+[THETHA PHI] = ndgrid(nf2ff.theta,nf2ff.phi);
+cosphi = cos(PHI);
+sinphi = sin(PHI);
+
+for f=1:numel(nf2ff.freq)
+ nf2ff.E_cprh{f} = (cosphi+1i*sinphi) .* (nf2ff.E_theta{f}+1i*nf2ff.E_phi{f})/sqrt(2);
+ nf2ff.E_cplh{f} = (cosphi-1i*sinphi) .* (nf2ff.E_theta{f}-1i*nf2ff.E_phi{f})/sqrt(2);
+end
diff --git a/openEMS/matlab/private/invoke_openEMS.m b/openEMS/matlab/private/invoke_openEMS.m
new file mode 100644
index 0000000..afb2b46
--- /dev/null
+++ b/openEMS/matlab/private/invoke_openEMS.m
@@ -0,0 +1,47 @@
+function invoke_openEMS( opts, logfile, silent )
+% function invoke_openEMS( opts, logfile, silent )
+%
+% internal method to invoke openEMS, use RunOpenEMS instead
+%
+% See also RunOpenEMS
+%
+% openEMS matlab interface
+% -----------------------
+% author: Sebastian Held, Thorsten Liebig
+
+if nargin < 1
+ error 'specify the xml file to simulate'
+end
+if nargin < 3
+ silent = 0;
+end
+if (nargin < 2) || isempty(logfile)
+ if isunix
+ logfile = '/dev/null';
+ else
+ logfile = 'nul:';
+ end
+end
+
+filename = mfilename('fullpath');
+dir = fileparts( filename );
+
+if isunix
+ openEMS_bin = searchBinary('openEMS.sh', ...
+ {[dir filesep '..' filesep '..' filesep], ... % try devel path
+ [dir filesep '..' filesep '..' filesep '..' filesep '..' filesep 'bin' filesep]}); % try (default) install path
+else % assume windows
+ openEMS_bin = searchBinary('openEMS.exe', [dir filesep '..' filesep '..' filesep]);
+end
+
+command = [openEMS_bin ' ' opts];
+
+if ~silent
+ if (isunix && nargin>1)
+ command = [command ' 2>&1 | tee ' logfile];
+ end
+else
+ command = [command ' > ' logfile ' 2>&1'];
+end
+
+system(command);
diff --git a/openEMS/matlab/queue_addProcess.m b/openEMS/matlab/queue_addProcess.m
new file mode 100644
index 0000000..73d4e14
--- /dev/null
+++ b/openEMS/matlab/queue_addProcess.m
@@ -0,0 +1,22 @@
+function [pid,filenames] = queue_addProcess( command )
+% [pid,filenames] = queue_addProcess( command )
+%
+% Sebastian Held <sebastian.held@uni-due.de>
+% 12.5.2010
+
+if ~isunix
+ error 'your OS is not supported (Unix only)'
+end
+
+if nargout > 1
+ filenames.stdout = tempname;
+ filenames.stderr = tempname;
+else
+ filenames.stdout = '/dev/null';
+ filenames.stderr = '/dev/null';
+end
+
+cmd = ['(' command ') >' filenames.stdout ' 2>' filenames.stderr ' & echo $!' ];
+[~,result] = unix( cmd );
+
+pid = str2double(result);
diff --git a/openEMS/matlab/queue_checkProcess.m b/openEMS/matlab/queue_checkProcess.m
new file mode 100644
index 0000000..878165a
--- /dev/null
+++ b/openEMS/matlab/queue_checkProcess.m
@@ -0,0 +1,25 @@
+function [alive,stdout,stderr] = queue_checkProcess( pid, filenames )
+% [alive,stdout,stderr] = queue_checkProcess( pid )
+%
+% Sebastian Held <sebastian.held@uni-due.de>
+% 12.5.2010
+
+if ~isunix
+ error 'your OS is not supported (Unix only)'
+end
+
+if nargout > 1
+ fid = fopen( filenames.stdout );
+ stdout = fread(fid, '*char')';
+ fclose(fid);
+end
+if nargout > 2
+ fid = fopen( filenames.stderr );
+ stderr = fread(fid, '*char')';
+ fclose(fid);
+end
+
+cmd = ['ps --no-headers -p' num2str(pid) ];
+[status,~] = unix( cmd );
+
+alive = (status == 0);
diff --git a/openEMS/matlab/queue_delProcess.m b/openEMS/matlab/queue_delProcess.m
new file mode 100644
index 0000000..39ab45c
--- /dev/null
+++ b/openEMS/matlab/queue_delProcess.m
@@ -0,0 +1,40 @@
+function [stdout,stderr] = queue_delProcess( pid, filenames )
+% [stdout,stderr] = queue_delProcess( pid, filenames )
+%
+% if pid == 0, do not kill a process, but clean up files
+%
+% Sebastian Held <sebastian.held@uni-due.de>
+% 12.5.2010
+
+if ~isunix
+ error 'your OS is not supported (Unix only)'
+end
+
+if pid ~= 0
+ alive = queue_checkProcess( pid );
+
+ if alive
+ unix( ['kill ' num2str(pid)] );
+ alive = queue_checkProcess( pid );
+ end
+ if alive
+ pause(1)
+ unix( ['kill ' num2str(pid)] );
+ alive = queue_checkProcess( pid );
+ end
+ if alive
+ unix( ['kill -KILL ' num2str(pid)] );
+ end
+end
+
+if nargin > 1
+ if nargout == 1
+ [~,stdout] = queue_checkProcess( pid, filenames );
+ end
+ if nargout == 2
+ [~,stdout,stderr] = queue_checkProcess( pid, filenames );
+ end
+
+ delete( filenames.stdout );
+ delete( filenames.stderr );
+end
diff --git a/openEMS/matlab/setup.m b/openEMS/matlab/setup.m
new file mode 100644
index 0000000..df56b25
--- /dev/null
+++ b/openEMS/matlab/setup.m
@@ -0,0 +1,36 @@
+function setup()
+% function setup()
+%
+% setup openEMS Matlab/octave interface
+%
+% openEMS matlab/octave interface
+% -----------------------
+% author: Thorsten Liebig (2011)
+
+disp('setting up openEMS matlab/octave interface')
+
+% cd to directory of this file and restore current path at the end
+current_path = pwd;
+dir = fileparts( mfilename('fullpath') );
+cd(dir);
+
+if isOctave()
+ disp('compiling oct files')
+ fflush(stdout)
+ if isunix
+ [res, fn] = unix('find /usr/lib -name libhdf5.so');
+ if length(fn)>0
+ [hdf5lib_dir, hdf5lib_fn] = fileparts(fn);
+ disp(["HDF5 library path found at: " hdf5lib_dir])
+ mkoctfile(["-L" hdf5lib_dir ],"-lhdf5 -DH5_USE_16_API", "h5readatt_octave.cc")
+ else
+ mkoctfile -lhdf5 -DH5_USE_16_API h5readatt_octave.cc
+ end
+ else
+ mkoctfile -lhdf5 -DH5_USE_16_API h5readatt_octave.cc
+ end
+else
+ disp('Matlab does not need this function. It is Octave only.')
+end
+
+cd(current_path);
diff --git a/openEMS/nf2ff/CMakeLists.txt b/openEMS/nf2ff/CMakeLists.txt
new file mode 100644
index 0000000..d43d519
--- /dev/null
+++ b/openEMS/nf2ff/CMakeLists.txt
@@ -0,0 +1,51 @@
+
+# define build type
+IF( DEFINED CMAKE_BUILD_TYPE )
+ SET( CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Set to either \"Release\" or \"Debug\"" )
+ELSE()
+ SET( CMAKE_BUILD_TYPE Release CACHE STRING "Set to either \"Release\" or \"Debug\"" )
+ENDIF()
+
+PROJECT(nf2ff CXX)
+cmake_minimum_required(VERSION 2.8)
+
+set(LIB_VERSION_MAJOR 0)
+set(LIB_VERSION_MINOR 1)
+set(LIB_VERSION_PATCH 0)
+set(LIB_VERSION_STRING ${LIB_VERSION_MAJOR}.${LIB_VERSION_MINOR}.${LIB_VERSION_PATCH})
+
+set(VERSION "v${LIB_VERSION_STRING}")
+
+set(SOURCES
+ nf2ff.cpp
+ nf2ff_calc.cpp
+ ../tools/array_ops.cpp
+ ../tools/useful.cpp
+ ../tools/hdf5_file_reader.cpp
+ ../tools/hdf5_file_writer.cpp
+)
+
+#ADD_SUBDIRECTORY( ../tools )
+set(HEADERS
+ nf2ff.h
+ nf2ff_calc.h
+)
+
+add_library( nf2ff SHARED ${SOURCES})
+set_target_properties(nf2ff PROPERTIES VERSION ${LIB_VERSION_STRING} SOVERSION ${LIB_VERSION_MAJOR})
+
+TARGET_LINK_LIBRARIES( nf2ff
+ tinyxml
+ ${HDF5_LIBRARIES}
+ ${Boost_LIBRARIES}
+)
+
+ADD_EXECUTABLE( nf2ff_bin main.cpp )
+SET_TARGET_PROPERTIES(nf2ff_bin PROPERTIES OUTPUT_NAME nf2ff)
+TARGET_LINK_LIBRARIES(nf2ff_bin nf2ff)
+
+INSTALL(TARGETS nf2ff_bin DESTINATION bin)
+INSTALL(TARGETS nf2ff DESTINATION lib${LIB_SUFFIX})
+
+
+#TODO tarball, debug, release
diff --git a/openEMS/nf2ff/main.cpp b/openEMS/nf2ff/main.cpp
new file mode 100644
index 0000000..c8784f3
--- /dev/null
+++ b/openEMS/nf2ff/main.cpp
@@ -0,0 +1,44 @@
+/*
+* Copyright (C) 2012-2014 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <iostream>
+
+#include "nf2ff.h"
+
+using namespace std;
+
+int main(int argc, char *argv[])
+{
+ cout << " ---------------------------------------------------------------------- " << endl;
+ cout << " | nf2ff, near-field to far-field transformation for openEMS " << endl;
+ cout << " | (C) 2012-2014 Thorsten Liebig <thorsten.liebig@gmx.de> GPL license" << endl;
+ cout << " ---------------------------------------------------------------------- " << endl;
+
+ if (argc<=1)
+ {
+ cout << " Usage: nf2ff <nf2ff-xml-file>" << endl << endl;
+ cout << endl;
+ exit(-1);
+ }
+
+ if (argc>=2)
+ {
+ return !nf2ff::AnalyseXMLFile(argv[argc-1]);
+ }
+
+ return 0;
+}
diff --git a/openEMS/nf2ff/nf2ff.cpp b/openEMS/nf2ff/nf2ff.cpp
new file mode 100644
index 0000000..62c9238
--- /dev/null
+++ b/openEMS/nf2ff/nf2ff.cpp
@@ -0,0 +1,661 @@
+/*
+* Copyright (C) 2012-2014 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "nf2ff.h"
+#include "nf2ff_calc.h"
+#include "../tools/array_ops.h"
+#include "../tools/useful.h"
+#include "../tools/hdf5_file_reader.h"
+#include "../tools/hdf5_file_writer.h"
+#include <hdf5.h>
+#include <boost/algorithm/string.hpp>
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+#include <cmath>
+#include <complex>
+#include <iostream>
+#include <sstream>
+
+//external libs
+#include "tinyxml.h"
+
+using namespace std;
+
+nf2ff::nf2ff(vector<float> freq, vector<float> theta, vector<float> phi, vector<float> center, unsigned int numThreads)
+{
+ m_freq = freq;
+
+ m_numTheta = theta.size();
+ m_theta = new float[m_numTheta];
+ for (size_t n=0;n<m_numTheta;++n)
+ m_theta[n]=theta.at(n);
+
+ m_numPhi = phi.size();
+ m_phi = new float[m_numPhi];
+ for (size_t n=0;n<m_numPhi;++n)
+ m_phi[n]=phi.at(n);
+
+ m_nf2ff.resize(freq.size(),NULL);
+ for (size_t fn=0;fn<freq.size();++fn)
+ {
+ m_nf2ff.at(fn) = new nf2ff_calc(freq.at(fn),theta, phi, center);
+ if (numThreads)
+ m_nf2ff.at(fn)->SetNumThreads(numThreads);
+ }
+ m_radius = 1;
+ m_Verbose = 0;
+}
+
+nf2ff::~nf2ff()
+{
+ m_freq.clear();
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ delete m_nf2ff.at(fn);
+ m_nf2ff.clear();
+
+ delete[] m_phi;
+ m_phi = NULL;
+ delete[] m_theta;
+ m_theta = NULL;
+}
+
+void nf2ff::SetRadius(float radius)
+{
+ m_radius = radius;
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ m_nf2ff.at(fn)->SetRadius(radius);
+}
+
+void nf2ff::SetPermittivity(vector<float> permittivity)
+{
+ if (permittivity.size()==0)
+ return;
+
+ m_permittivity = permittivity;
+ if (permittivity.size()==1)
+ {
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ m_nf2ff.at(fn)->SetPermittivity(permittivity.at(0));
+ return;
+ }
+
+ if (permittivity.size()!=m_freq.size())
+ {
+ cerr << __func__ << ": Error, permittivity vector size must match number of set frequencies! skipping!" << endl;
+ return;
+ }
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ m_nf2ff.at(fn)->SetPermittivity(permittivity.at(fn));
+}
+
+void nf2ff::SetPermeability(vector<float> permeability)
+{
+ if (permeability.size()==0)
+ return;
+
+ m_permeability = permeability;
+ if (permeability.size()==1)
+ {
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ m_nf2ff.at(fn)->SetPermeability(permeability.at(0));
+ return;
+ }
+
+ if (permeability.size()!=m_freq.size())
+ {
+ cerr << __func__ << ": Error, permeability vector size must match number of set frequencies! skipping!" << endl;
+ return;
+ }
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ m_nf2ff.at(fn)->SetPermeability(permeability.at(fn));
+}
+
+void nf2ff::SetMirror(int type, int dir, float pos)
+{
+ if (m_Verbose>0)
+ cerr << "Enable mirror of type: "<< type << " in direction: " << dir << " at: " << pos << endl;
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ m_nf2ff.at(fn)->SetMirror(type, dir, pos);
+}
+
+bool nf2ff::AnalyseXMLNode(TiXmlElement* ti_nf2ff)
+{
+ if (ti_nf2ff==NULL)
+ return false;
+
+ unsigned int numThreads=0;
+ int ihelp=0;
+ if (ti_nf2ff->QueryIntAttribute("NumThreads",&ihelp) == TIXML_SUCCESS)
+ {
+ numThreads = ihelp;
+ cerr << "nf2ff: Set number of threads to: " << numThreads << endl;
+ }
+ int Verbose=0;
+ if (ti_nf2ff->QueryIntAttribute("Verbose",&Verbose) == TIXML_SUCCESS)
+ cerr << "nf2ff: Set verbose level to " << Verbose << endl;
+ else
+ Verbose = 0;
+
+ const char* attr = NULL;
+ attr = ti_nf2ff->Attribute("freq");
+ if (attr==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read frequency inforamtions ... " << endl;
+ return false;
+ }
+ vector<float> freq = SplitString2Float(attr);
+
+ vector<float> center;
+ attr = ti_nf2ff->Attribute("Center");
+ if (attr!=NULL)
+ center = SplitString2Float(attr);
+
+ attr = ti_nf2ff->Attribute("Outfile");
+ if (attr==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read frequency inforamtions ... " << endl;
+ return false;
+ }
+ string outfile = string(attr);
+ if (outfile.empty())
+ {
+ cerr << "nf2ff::AnalyseXMLNode: outfile is empty, skipping nf2ff... " << endl;
+ return false;
+ }
+
+ TiXmlElement* ti_theta = ti_nf2ff->FirstChildElement("theta");
+ if (ti_theta==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read theta values ... " << endl;
+ return false;
+ }
+ TiXmlNode* ti_theta_node = ti_theta->FirstChild();
+ if (ti_theta_node==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read theta text child ... " << endl;
+ return false;
+ }
+ TiXmlText* ti_theta_text = ti_theta_node->ToText();
+ if (ti_theta_text==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read theta text values ... " << endl;
+ return false;
+ }
+ vector<float> theta = SplitString2Float(ti_theta_text->Value());
+
+ TiXmlElement* ti_phi = ti_nf2ff->FirstChildElement("phi");
+ if (ti_phi==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read phi values ... " << endl;
+ return false;
+ }
+ TiXmlNode* ti_phi_node = ti_phi->FirstChild();
+ if (ti_phi_node==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read phi text child ... " << endl;
+ return false;
+ }
+ TiXmlText* ti_phi_text = ti_phi_node->ToText();
+ if (ti_phi_text==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Can't read phi text values ... " << endl;
+ return false;
+ }
+ vector<float> phi = SplitString2Float(ti_phi_text->Value());
+
+ nf2ff* l_nf2ff = new nf2ff(freq,theta,phi,center,numThreads);
+ l_nf2ff->SetVerboseLevel(Verbose);
+
+ attr = ti_nf2ff->Attribute("Eps_r");
+ if (attr!=NULL)
+ l_nf2ff->SetPermittivity(SplitString2Float(attr));
+
+ attr = ti_nf2ff->Attribute("Mue_r");
+ if (attr!=NULL)
+ l_nf2ff->SetPermeability(SplitString2Float(attr));
+
+ float radius = 1;
+ if (ti_nf2ff->QueryFloatAttribute("Radius",&radius) == TIXML_SUCCESS)
+ l_nf2ff->SetRadius(radius);
+
+ // read mirrors
+ TiXmlElement* ti_Mirros = ti_nf2ff->FirstChildElement("Mirror");
+ int dir=-1;
+ string type;
+ float pos=0.0;
+ while (ti_Mirros!=NULL)
+ {
+ type = string(ti_Mirros->Attribute("Type"));
+ if (ti_Mirros->QueryIntAttribute("Dir",&dir) != TIXML_SUCCESS)
+ dir = -1;
+ if (ti_Mirros->QueryFloatAttribute("Pos",&pos) != TIXML_SUCCESS)
+ dir = -1;
+ if ((dir>=0) && (strcmp(type.c_str(),"PEC")==0))
+ l_nf2ff->SetMirror(MIRROR_PEC, dir, pos);
+ else if ((dir>=0) && (strcmp(type.c_str(),"PMC")==0))
+ l_nf2ff->SetMirror(MIRROR_PMC, dir, pos);
+ ti_Mirros = ti_Mirros->NextSiblingElement("Mirror");
+ }
+
+ TiXmlElement* ti_Planes = ti_nf2ff->FirstChildElement("Planes");
+ string E_name;
+ string H_name;
+ while (ti_Planes!=NULL)
+ {
+ E_name = string(ti_Planes->Attribute("E_Field"));
+ H_name = string(ti_Planes->Attribute("H_Field"));
+ if ((!E_name.empty()) && (!H_name.empty()))
+ {
+ if (l_nf2ff->AnalyseFile(E_name,H_name)==false)
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Error, analysing Plane ... " << endl;
+ return false;
+ }
+ }
+ else
+ {
+ cerr << "nf2ff::AnalyseXMLNode: Error, invalid plane entry ... " << endl;
+ return false;
+ }
+ ti_Planes = ti_Planes->NextSiblingElement("Planes");
+ }
+ l_nf2ff->Write2HDF5(outfile);
+ delete l_nf2ff;
+ return true;
+}
+
+bool nf2ff::AnalyseXMLFile(string filename)
+{
+ TiXmlDocument doc(filename.c_str());
+ if (!doc.LoadFile())
+ {
+ cerr << "nf2ff::AnalyseXMLFile: Error loading xml-file failed!!! File: " << filename << endl;
+ return false;
+ }
+ TiXmlElement* ti_nf2ff = doc.FirstChildElement("nf2ff");
+ if (ti_nf2ff==NULL)
+ {
+ cerr << "nf2ff::AnalyseXMLFile: Can't read nf2ff ... " << endl;
+ return false;
+ }
+
+ return AnalyseXMLNode(ti_nf2ff);
+}
+
+bool nf2ff::AnalyseFile(string E_Field_file, string H_Field_file)
+{
+ HDF5_File_Reader E_file(E_Field_file);
+ HDF5_File_Reader H_file(H_Field_file);
+
+ if (m_Verbose>0)
+ cerr << "nf2ff: Reading planes: " << E_Field_file << " & " << H_Field_file << endl;
+
+ // read E-mesh
+ float* E_lines[3]={NULL,NULL,NULL};
+ unsigned int E_numLines[3];
+ int E_meshType;
+ if (E_file.ReadMesh(E_lines, E_numLines, E_meshType) == false)
+ {
+ cerr << "nf2ff::AnalyseFile: Error reading E-field mesh..." << endl;
+ return false;
+ }
+
+ // read H-mesh
+ float* H_lines[3]={NULL,NULL,NULL};
+ unsigned int H_numLines[3];
+ int H_meshType;
+ if (H_file.ReadMesh(H_lines, H_numLines, H_meshType) == false)
+ {
+ cerr << "nf2ff::AnalyseFile: Error reading H-Field mesh..." << endl;
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+
+ // compare E/H meshs
+ if (E_meshType!=H_meshType)
+ {
+ cerr << "nf2ff::AnalyseFile: Error mesh types don't agree" << endl;
+ for (int n=0;n<3;++n)
+ {
+ delete[] H_lines[n];
+ delete[] E_lines[n];
+ }
+ return false;
+ }
+ if ((E_numLines[0]!=H_numLines[0]) || (E_numLines[1]!=H_numLines[1]) || (E_numLines[2]!=H_numLines[2]))
+ {
+ cerr << "nf2ff::AnalyseFile: Error mesh dimensions don't agree" << endl;
+ for (int n=0;n<3;++n)
+ {
+ delete[] H_lines[n];
+ delete[] E_lines[n];
+ }
+ return false;
+ }
+ for (int n=0;n<3;++n)
+ for (unsigned int m=0;m<E_numLines[n];++m)
+ if (E_lines[n][m]!=H_lines[n][m])
+ {
+ cerr << "nf2ff::AnalyseFile: Error mesh lines don't agree" << endl;
+ for (int n=0;n<3;++n)
+ {
+ delete[] H_lines[n];
+ delete[] E_lines[n];
+ }
+ return false;
+ }
+
+ for (int n=0;n<3;++n)
+ delete[] H_lines[n];
+
+ if (m_Verbose>0)
+ cerr << "nf2ff: Data-Size: " << E_numLines[0] << "x" << E_numLines[1] << "x" << E_numLines[2] << endl;
+
+ // test if FD data available or fallback to TD is necessary
+ bool fallBack_TD=false;
+ vector<float> FD_freq;
+ if (E_file.ReadFrequencies(FD_freq)==false)
+ fallBack_TD = true;
+ if (FD_freq.size()>0)
+ {
+ vector<float> H_freq;
+ if (H_file.ReadFrequencies(H_freq)==false)
+ {
+ cerr << "nf2ff::AnalyseFile: Error, number of FD data mismatch, fallback to TD data..." << endl;
+ fallBack_TD = true;
+ }
+ else
+ {
+ for (size_t nf=0;nf<FD_freq.size();++nf)
+ if (FD_freq.at(nf)!=H_freq.at(nf))
+ {
+ cerr << "nf2ff::AnalyseFile: Error, frequency data mismatch, fallback to TD data..." << endl;
+ fallBack_TD = true;
+ break;
+ }
+ }
+ }
+ else
+ fallBack_TD = true;
+
+ // search FD-data frequency index that matches requested nf2ff frequencies
+ vector<size_t> FD_index;
+ if (fallBack_TD==false)
+ {
+ FD_index.resize(FD_freq.size(),-1);
+
+ for (size_t n=0;n<m_freq.size();++n)
+ {
+ bool found=false;
+ for (size_t nf=0;nf<FD_freq.size();++nf)
+ {
+ if (FD_freq.at(nf)==m_freq.at(n))
+ {
+ FD_index.at(n)=nf;
+ found = true;
+ break;
+ }
+ }
+ if (found==false)
+ {
+ fallBack_TD=true;
+ cerr << "nf2ff::AnalyseFile: Frequency " << m_freq.at(n) << " not found in FD data, general fallback to TD data..." << endl;
+ break;
+ }
+ }
+ }
+
+ if (fallBack_TD)
+ {
+ vector<complex<float>****> E_fd_data;
+ vector<complex<float>****> H_fd_data;
+
+ if (m_Verbose>1)
+ cerr << "nf2ff: calculate dft..." << endl;
+
+ unsigned int data_size[4];
+ if (E_file.CalcFDVectorData(m_freq,E_fd_data,data_size)==false)
+ {
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+ if ((data_size[0]!=E_numLines[0]) || (data_size[1]!=E_numLines[1]) || (data_size[2]!=E_numLines[2]) )
+ {
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ {
+ Delete_N_3DArray<complex<float> >(E_fd_data.at(fn),data_size);
+ }
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+
+ if (H_file.CalcFDVectorData(m_freq,H_fd_data,data_size)==false)
+ {
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ Delete_N_3DArray<complex<float> >(E_fd_data.at(fn),data_size);
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+ if ((data_size[0]!=E_numLines[0]) || (data_size[1]!=E_numLines[1]) || (data_size[2]!=E_numLines[2]) )
+ {
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ {
+ Delete_N_3DArray<complex<float> >(E_fd_data.at(fn),data_size);
+ Delete_N_3DArray<complex<float> >(H_fd_data.at(fn),data_size);
+ }
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+
+ if (m_Verbose>0)
+ cerr << "nf2ff: Analysing far-field for " << m_nf2ff.size() << " frequencies. " << endl;
+
+ for (size_t fn=0;fn<m_nf2ff.size();++fn)
+ {
+ if (m_Verbose>1)
+ cerr << "nf2ff: f = " << m_freq.at(fn) << "Hz (" << fn+1 << "/" << m_freq.size() << ") ...";
+ m_nf2ff.at(fn)->AddPlane(E_lines, E_numLines, E_fd_data.at(fn), H_fd_data.at(fn),E_meshType);
+ if (m_Verbose>1)
+ cerr << " done." << endl;
+ }
+
+ }
+ else
+ {
+ complex<float>**** E_fd_data;
+ complex<float>**** H_fd_data;
+ unsigned int data_size[4];
+ for (size_t n=0;n<m_freq.size();++n)
+ {
+ E_fd_data = E_file.GetFDVectorData(FD_index.at(n),data_size);
+ if ((data_size[0]!=E_numLines[0]) || (data_size[1]!=E_numLines[1]) || (data_size[2]!=E_numLines[2]) )
+ {
+ cerr << data_size[0] << "," << data_size[1] << "," << data_size[2] << endl;
+ cerr << "nf2ff::AnalyseFile: FD data size mismatch... " << endl;
+ Delete_N_3DArray<complex<float> >(E_fd_data,data_size);
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+
+ H_fd_data = H_file.GetFDVectorData(FD_index.at(n),data_size);
+ if ((data_size[0]!=E_numLines[0]) || (data_size[1]!=E_numLines[1]) || (data_size[2]!=E_numLines[2]) )
+ {
+ cerr << data_size[0] << "," << data_size[1] << "," << data_size[2] << endl;
+ cerr << "nf2ff::AnalyseFile: FD data size mismatch... " << endl;
+ Delete_N_3DArray<complex<float> >(H_fd_data,data_size);
+ Delete_N_3DArray<complex<float> >(E_fd_data,data_size);
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+
+ if ((E_fd_data==NULL) || (H_fd_data==NULL))
+ {
+ cerr << "nf2ff::AnalyseFile: Reaing FD data failed... " << endl;
+ Delete_N_3DArray<complex<float> >(E_fd_data,data_size);
+ Delete_N_3DArray<complex<float> >(H_fd_data,data_size);
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+ return false;
+ }
+ if (m_Verbose>1)
+ cerr << "nf2ff: f = " << m_freq.at(n) << "Hz (" << n+1 << "/" << m_freq.size() << ") ...";
+ m_nf2ff.at(n)->AddPlane(E_lines, E_numLines, E_fd_data, H_fd_data,E_meshType);
+ if (m_Verbose>1)
+ cerr << " done." << endl;
+ }
+ }
+
+ for (int n=0;n<3;++n)
+ delete[] E_lines[n];
+
+ return true;
+}
+
+bool nf2ff::Write2HDF5(string filename)
+{
+ HDF5_File_Writer hdf_file(filename);
+
+ //write mesh information
+ hdf_file.SetCurrentGroup("/Mesh");
+ size_t meshsize[1]={m_numTheta};
+ if (hdf_file.WriteData(string("theta"),m_theta,1,meshsize)==false)
+ return false;
+ meshsize[0]=m_numPhi;
+ if (hdf_file.WriteData(string("phi"),m_phi,1,meshsize)==false)
+ return false;
+ meshsize[0]=1;
+ float rad[1]={m_radius};
+ if (hdf_file.WriteData(string("r"),rad,1,meshsize)==false)
+ return false;
+
+ float attr_value = 2;
+ hdf_file.WriteAtrribute("/Mesh", "MeshType", &attr_value, 1);
+
+ //write field data
+ size_t dim = 2;
+ size_t pos = 0;
+ size_t datasize[2]={m_numPhi,m_numTheta};
+ size_t size = datasize[0]*datasize[1];
+ double* buffer = new double[size];
+ complex<double>** field_data;
+ string field_names[2]={"E_theta", "E_phi"};
+ for (int n=0;n<2;++n)
+ {
+ hdf_file.SetCurrentGroup("/nf2ff/" + field_names[n] + "/FD");
+ for (size_t fn=0;fn<m_freq.size();++fn)
+ {
+ stringstream ss;
+ ss << "f" << fn;
+ pos = 0;
+ if (n==0)
+ field_data = GetETheta(fn);
+ else
+ field_data = GetEPhi(fn);
+ for (size_t j=0;j<m_numPhi;++j)
+ for (size_t i=0;i<m_numTheta;++i)
+ {
+ buffer[pos++]=real(field_data[i][j]);
+ }
+ if (hdf_file.WriteData(ss.str() + "_real",buffer,dim,datasize)==false)
+ {
+ delete[] buffer;
+ cerr << "nf2ff::Write2HDF5: Error writing field data" << endl;
+ return false;
+ }
+
+ pos = 0;
+ for (size_t j=0;j<m_numPhi;++j)
+ for (size_t i=0;i<m_numTheta;++i)
+ {
+ buffer[pos++]=imag(field_data[i][j]);
+ }
+ if (hdf_file.WriteData(ss.str() + "_imag",buffer,dim,datasize)==false)
+ {
+ delete[] buffer;
+ cerr << "nf2ff::Write2HDF5: Error writing field data" << endl;
+ return false;
+ }
+ }
+ }
+
+ //dump radiated power
+ hdf_file.SetCurrentGroup("/nf2ff/P_rad/FD");
+ for (size_t fn=0;fn<m_freq.size();++fn)
+ {
+ stringstream ss;
+ ss << "f" << fn;
+ pos = 0;
+ double** field_data = GetRadPower(fn);
+ for (size_t j=0;j<m_numPhi;++j)
+ for (size_t i=0;i<m_numTheta;++i)
+ {
+ buffer[pos++]=field_data[i][j];
+ }
+ if (hdf_file.WriteData(ss.str(),buffer,dim,datasize)==false)
+ {
+ delete[] buffer;
+ cerr << "nf2ff::Write2HDF5: Error writing field data" << endl;
+ return false;
+ }
+ }
+ delete[] buffer;
+
+ //write frequency attribute
+ hdf_file.WriteAtrribute("/nf2ff", "Frequency",m_freq);
+
+ buffer = new double[m_freq.size()];
+ //write radiated power attribute
+ for (size_t fn=0;fn<m_freq.size();++fn)
+ buffer[fn] = GetTotalRadPower(fn);
+ hdf_file.WriteAtrribute("/nf2ff", "Prad",buffer,m_freq.size());
+ delete[] buffer;
+
+ //write max directivity attribute
+ buffer = new double[m_freq.size()];
+ for (size_t fn=0;fn<m_freq.size();++fn)
+ buffer[fn] = GetMaxDirectivity(fn);
+ hdf_file.WriteAtrribute("/nf2ff", "Dmax",buffer,m_freq.size());
+ delete[] buffer;
+
+ if (m_permittivity.size()>0)
+ {
+ buffer = new double[m_permittivity.size()];
+ for (size_t n=0;n<m_permittivity.size();++n)
+ buffer[n] = m_permittivity.at(n);
+ hdf_file.WriteAtrribute("/nf2ff", "Eps_r",buffer,m_permittivity.size());
+ delete[] buffer;
+ }
+
+ if (m_permeability.size()>0)
+ {
+ buffer = new double[m_permeability.size()];
+ for (size_t n=0;n<m_permeability.size();++n)
+ buffer[n] = m_permeability.at(n);
+ hdf_file.WriteAtrribute("/nf2ff", "Mue_r",buffer,m_permeability.size());
+ delete[] buffer;
+ }
+
+ return true;
+}
diff --git a/openEMS/nf2ff/nf2ff.h b/openEMS/nf2ff/nf2ff.h
new file mode 100644
index 0000000..06823af
--- /dev/null
+++ b/openEMS/nf2ff/nf2ff.h
@@ -0,0 +1,74 @@
+/*
+* Copyright (C) 2012-2014 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef NF2FF_H
+#define NF2FF_H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+#include <cmath>
+#include <complex>
+#include "nf2ff_calc.h"
+
+using namespace std;
+
+class TiXmlElement;
+
+class nf2ff
+{
+public:
+ nf2ff(vector<float> freq, vector<float> theta, vector<float> phi, vector<float> center, unsigned int numThreads=0);
+ ~nf2ff();
+
+ bool AnalyseFile(string E_Field_file, string H_Field_file);
+
+ void SetRadius(float radius);
+ void SetPermittivity(vector<float> permittivity);
+ void SetPermeability(vector<float> permeability);
+
+ void SetMirror(int type, int dir, float pos);
+
+ double GetTotalRadPower(size_t f_idx) const {return m_nf2ff.at(f_idx)->GetTotalRadPower();}
+ double GetMaxDirectivity(size_t f_idx) const {return m_nf2ff.at(f_idx)->GetMaxDirectivity();}
+
+ complex<double>** GetETheta(size_t f_idx) const {return m_nf2ff.at(f_idx)->GetETheta();}
+ complex<double>** GetEPhi(size_t f_idx) const {return m_nf2ff.at(f_idx)->GetEPhi();}
+ double** GetRadPower(size_t f_idx) const {return m_nf2ff.at(f_idx)->GetRadPower();}
+
+ //! Write results to a hdf5 file
+ bool Write2HDF5(string filename);
+
+ void SetVerboseLevel(int level) {m_Verbose=level;}
+
+ static bool AnalyseXMLNode(TiXmlElement* ti_nf2ff);
+ static bool AnalyseXMLFile(string filename);
+
+protected:
+ vector<float> m_freq;
+ vector<float> m_permittivity;
+ vector<float> m_permeability;
+ unsigned int m_numTheta;
+ unsigned int m_numPhi;
+ float* m_theta;
+ float* m_phi;
+ float m_radius;
+ int m_Verbose;
+ vector<nf2ff_calc*> m_nf2ff;
+};
+
+#endif // NF2FF_H
diff --git a/openEMS/nf2ff/nf2ff_calc.cpp b/openEMS/nf2ff/nf2ff_calc.cpp
new file mode 100644
index 0000000..335dd9a
--- /dev/null
+++ b/openEMS/nf2ff/nf2ff_calc.cpp
@@ -0,0 +1,513 @@
+/*
+* Copyright (C) 2012-2014 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "nf2ff_calc.h"
+#include "../tools/array_ops.h"
+#include "../tools/useful.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+#include <cmath>
+#include <complex>
+#include <iostream>
+#include <sstream>
+
+using namespace std;
+
+nf2ff_calc_thread::nf2ff_calc_thread(nf2ff_calc* nfc, unsigned int start, unsigned int stop, unsigned int threadID, nf2ff_data &data)
+{
+ m_nf_calc = nfc;
+ m_start = start;
+ m_stop = stop;
+ m_threadID = threadID;
+ m_data = data;
+}
+
+void nf2ff_calc_thread::operator()()
+{
+ m_nf_calc->m_Barrier->wait(); // start
+
+ int ny = m_data.ny;
+ int nP = (ny+1)%3;
+ int nPP = (ny+2)%3;
+
+ unsigned int* numLines = m_data.numLines;
+ float* normDir = m_data.normDir;
+ float **lines = m_data.lines;
+ float* edge_length_P = m_data.edge_length_P;
+ float* edge_length_PP = m_data.edge_length_PP;
+
+ unsigned int pos[3];
+ unsigned int pos_t=0;
+ unsigned int num_t=m_stop-m_start+1;
+
+
+ complex<float>**** Js=m_data.Js;
+ complex<float>**** Ms=m_data.Ms;
+ complex<float>**** E_field=m_data.E_field;
+ complex<float>**** H_field=m_data.H_field;
+
+ int mesh_type = m_data.mesh_type;
+
+ // calc Js and Ms (eq. 8.15a/b)
+ pos[ny]=0;
+ for (pos_t=0; pos_t<num_t; ++pos_t)
+ {
+ pos[nP] = m_start+pos_t;
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ // Js = n x H
+ Js[0][pos[0]][pos[1]][pos[2]] = normDir[1]*H_field[2][pos[0]][pos[1]][pos[2]] - normDir[2]*H_field[1][pos[0]][pos[1]][pos[2]];
+ Js[1][pos[0]][pos[1]][pos[2]] = normDir[2]*H_field[0][pos[0]][pos[1]][pos[2]] - normDir[0]*H_field[2][pos[0]][pos[1]][pos[2]];
+ Js[2][pos[0]][pos[1]][pos[2]] = normDir[0]*H_field[1][pos[0]][pos[1]][pos[2]] - normDir[1]*H_field[0][pos[0]][pos[1]][pos[2]];
+
+ // Ms = -n x E
+ Ms[0][pos[0]][pos[1]][pos[2]] = normDir[2]*E_field[1][pos[0]][pos[1]][pos[2]] - normDir[1]*E_field[2][pos[0]][pos[1]][pos[2]];
+ Ms[1][pos[0]][pos[1]][pos[2]] = normDir[0]*E_field[2][pos[0]][pos[1]][pos[2]] - normDir[2]*E_field[0][pos[0]][pos[1]][pos[2]];
+ Ms[2][pos[0]][pos[1]][pos[2]] = normDir[1]*E_field[0][pos[0]][pos[1]][pos[2]] - normDir[0]*E_field[1][pos[0]][pos[1]][pos[2]];
+
+ //transform to cartesian coordinates
+ if (mesh_type==1)
+ {
+ Js[0][pos[0]][pos[1]][pos[2]] = (normDir[1]*H_field[2][pos[0]][pos[1]][pos[2]] - normDir[2]*H_field[1][pos[0]][pos[1]][pos[2]])*cos(lines[1][pos[1]]) \
+ - (normDir[2]*H_field[0][pos[0]][pos[1]][pos[2]] - normDir[0]*H_field[2][pos[0]][pos[1]][pos[2]])*sin(lines[1][pos[1]]);
+ Js[1][pos[0]][pos[1]][pos[2]] = (normDir[1]*H_field[2][pos[0]][pos[1]][pos[2]] - normDir[2]*H_field[1][pos[0]][pos[1]][pos[2]])*sin(lines[1][pos[1]]) \
+ + (normDir[2]*H_field[0][pos[0]][pos[1]][pos[2]] - normDir[0]*H_field[2][pos[0]][pos[1]][pos[2]])*cos(lines[1][pos[1]]);
+
+ Ms[0][pos[0]][pos[1]][pos[2]] = (normDir[2]*E_field[1][pos[0]][pos[1]][pos[2]] - normDir[1]*E_field[2][pos[0]][pos[1]][pos[2]])*cos(lines[1][pos[1]]) \
+ - (normDir[0]*E_field[2][pos[0]][pos[1]][pos[2]] - normDir[2]*E_field[0][pos[0]][pos[1]][pos[2]])*sin(lines[1][pos[1]]);
+ Ms[1][pos[0]][pos[1]][pos[2]] = (normDir[2]*E_field[1][pos[0]][pos[1]][pos[2]] - normDir[1]*E_field[2][pos[0]][pos[1]][pos[2]])*sin(lines[1][pos[1]]) \
+ + (normDir[0]*E_field[2][pos[0]][pos[1]][pos[2]] - normDir[2]*E_field[0][pos[0]][pos[1]][pos[2]])*cos(lines[1][pos[1]]);
+ }
+ }
+ }
+
+ complex<double>** m_Nt=m_data.m_Nt;
+ complex<double>** m_Np=m_data.m_Np;
+ complex<double>** m_Lt=m_data.m_Lt;
+ complex<double>** m_Lp=m_data.m_Lp;
+
+ float center[3] = {m_nf_calc->m_centerCoord[0],m_nf_calc->m_centerCoord[1],m_nf_calc->m_centerCoord[2]};
+ if (mesh_type==1)
+ {
+ center[0] = m_nf_calc->m_centerCoord[0]*cos(m_nf_calc->m_centerCoord[1]);
+ center[1] = m_nf_calc->m_centerCoord[0]*sin(m_nf_calc->m_centerCoord[1]);
+ }
+ // calc local Nt,Np,Lt and Lp
+ float area;
+ float cosT_cosP,cosP_sinT;
+ float cosT_sinP,sinT_sinP;
+ float sinT,sinP;
+ float cosP,cosT;
+ float r_cos_psi;
+ float k = 2*M_PI*m_nf_calc->m_freq/__C0__*sqrt(m_nf_calc->m_permittivity*m_nf_calc->m_permeability);
+ complex<float> exp_jkr;
+ complex<float> _I_(0,1);
+ for (unsigned int tn=0;tn<m_nf_calc->m_numTheta;++tn)
+ for (unsigned int pn=0;pn<m_nf_calc->m_numPhi;++pn)
+ {
+ sinT = sin(m_nf_calc->m_theta[tn]);
+ sinP = sin(m_nf_calc->m_phi[pn]);
+ cosT = cos(m_nf_calc->m_theta[tn]);
+ cosP = cos(m_nf_calc->m_phi[pn]);
+ cosT_cosP = cosT*cosP;
+ cosT_sinP = cosT*sinP;
+ cosP_sinT = cosP*sinT;
+ sinT_sinP = sinP*sinT;
+
+ for (pos_t=0; pos_t<num_t; ++pos_t)
+ {
+ pos[nP] = m_start+pos_t;
+ for (pos[nPP]=0; pos[nPP]<numLines[nPP]; ++pos[nPP])
+ {
+ if (mesh_type==0)
+ r_cos_psi = (lines[0][pos[0]]-center[0])*cosP_sinT + (lines[1][pos[1]]-center[1])*sinT_sinP + (lines[2][pos[2]]-center[2])*cosT;
+ else
+ r_cos_psi = ((lines[0][pos[0]]*cos(lines[1][pos[1]]))-center[0])*cosP_sinT + ((lines[0][pos[0]]*sin(lines[1][pos[1]]))-center[1])*sinT_sinP + (lines[2][pos[2]]-center[2])*cosT;
+ exp_jkr = exp(_I_*k*r_cos_psi);
+ area = edge_length_P[pos[nP]]*edge_length_PP[pos[nPP]];
+ m_Nt[tn][pn] += area*exp_jkr*(Js[0][pos[0]][pos[1]][pos[2]]*cosT_cosP + Js[1][pos[0]][pos[1]][pos[2]]*cosT_sinP \
+ - Js[2][pos[0]][pos[1]][pos[2]]*sinT);
+ m_Np[tn][pn] += area*exp_jkr*(Js[1][pos[0]][pos[1]][pos[2]]*cosP - Js[0][pos[0]][pos[1]][pos[2]]*sinP);
+
+ m_Lt[tn][pn] += area*exp_jkr*(Ms[0][pos[0]][pos[1]][pos[2]]*cosT_cosP + Ms[1][pos[0]][pos[1]][pos[2]]*cosT_sinP \
+ - Ms[2][pos[0]][pos[1]][pos[2]]*sinT);
+ m_Lp[tn][pn] += area*exp_jkr*(Ms[1][pos[0]][pos[1]][pos[2]]*cosP - Ms[0][pos[0]][pos[1]][pos[2]]*sinP);
+ }
+ }
+ }
+
+ m_nf_calc->m_Barrier->wait(); //combine all thread local Nt,Np,Lt and Lp
+
+ m_nf_calc->m_Barrier->wait(); //wait for termination
+}
+
+
+/***********************************************************************/
+
+
+nf2ff_calc::nf2ff_calc(float freq, vector<float> theta, vector<float> phi, vector<float> center)
+{
+ m_freq = freq;
+ m_permittivity = 1;
+ m_permeability = 1;
+
+ m_numTheta = theta.size();
+ m_theta = new float[m_numTheta];
+ for (size_t n=0;n<m_numTheta;++n)
+ m_theta[n]=theta.at(n);
+
+ m_numPhi = phi.size();
+ m_phi = new float[m_numPhi];
+ for (size_t n=0;n<m_numPhi;++n)
+ m_phi[n]=phi.at(n);
+
+ unsigned int numLines[2] = {m_numTheta, m_numPhi};
+ m_E_theta = Create2DArray<std::complex<double> >(numLines);
+ m_E_phi = Create2DArray<std::complex<double> >(numLines);
+ m_H_theta = Create2DArray<std::complex<double> >(numLines);
+ m_H_phi = Create2DArray<std::complex<double> >(numLines);
+ m_P_rad = Create2DArray<double>(numLines);
+
+ if (center.size()==3)
+ {
+ m_centerCoord[0]=center.at(0);
+ m_centerCoord[1]=center.at(1);
+ m_centerCoord[2]=center.at(2);
+ }
+ else if (center.size()>0)
+ {
+ cerr << "nf2ff_calc::nf2ff_calc: Warning: Center coordinates error, ignoring!" << endl;
+ m_centerCoord[0]=m_centerCoord[1]=m_centerCoord[2]=0.0;
+ }
+ else
+ m_centerCoord[0]=m_centerCoord[1]=m_centerCoord[2]=0.0;
+
+ m_radPower = 0;
+ m_maxDir = 0;
+ m_radius = 1;
+
+ for (int n=0;n<3;++n)
+ {
+ m_MirrorType[n] = MIRROR_OFF;
+ m_MirrorPos[n] = 0.0;
+ }
+
+ m_Barrier = NULL;
+ m_numThreads = boost::thread::hardware_concurrency();
+}
+
+nf2ff_calc::~nf2ff_calc()
+{
+ delete[] m_phi;
+ m_phi = NULL;
+ delete[] m_theta;
+ m_theta = NULL;
+
+ unsigned int numLines[2] = {m_numTheta, m_numPhi};
+ Delete2DArray(m_E_theta,numLines);
+ m_E_theta = NULL;
+ Delete2DArray(m_E_phi,numLines);
+ m_E_phi = NULL;
+ Delete2DArray(m_H_theta,numLines);
+ m_H_theta = NULL;
+ Delete2DArray(m_H_phi,numLines);
+ m_H_phi = NULL;
+ Delete2DArray(m_P_rad,numLines);
+ m_P_rad = NULL;
+
+ delete m_Barrier;
+ m_Barrier = NULL;
+}
+
+int nf2ff_calc::GetNormalDir(unsigned int* numLines)
+{
+ int ny = -1;
+ int nP,nPP;
+ for (int n=0;n<3;++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ if ((numLines[n]==1) && (numLines[nP]>2) && (numLines[nPP]>2))
+ ny=n;
+ }
+ return ny;
+}
+
+void nf2ff_calc::SetMirror(int type, int dir, float pos)
+{
+ if ((dir<0) || (dir>3))
+ {
+ cerr << "nf2ff_calc::SetMirror: Error, invalid direction!" << endl;
+ return;
+ }
+ if ((type!=MIRROR_PEC) && (type!=MIRROR_PMC))
+ {
+ cerr << "nf2ff_calc::SetMirror: Error, invalid type!" << endl;
+ return;
+ }
+ m_MirrorType[dir] = type;
+ m_MirrorPos[dir] = pos;
+}
+
+bool nf2ff_calc::AddMirrorPlane(int n, float **lines, unsigned int* numLines, complex<float>**** E_field, complex<float>**** H_field, int MeshType)
+{
+ float E_factor[3] = {1,1,1};
+ float H_factor[3] = {1,1,1};
+
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+
+ // mirror in ny direction
+ for (unsigned int i=0;i<numLines[n];++i)
+ lines[n][i] = 2.0*m_MirrorPos[n] - lines[n][i];
+ if (m_MirrorType[n]==MIRROR_PEC)
+ {
+ H_factor[n] =-1.0;
+ E_factor[nP] =-1.0;
+ E_factor[nPP]=-1.0;
+ }
+ else if (m_MirrorType[n]==MIRROR_PMC)
+ {
+ E_factor[n] = -1.0;
+ H_factor[nP] = -1.0;
+ H_factor[nPP]= -1.0;
+ }
+
+ for (int d=0;d<3;++d)
+ for (unsigned int i=0;i<numLines[0];++i)
+ for (unsigned int j=0;j<numLines[1];++j)
+ for (unsigned int k=0;k<numLines[2];++k)
+ {
+ E_field[d][i][j][k] *= E_factor[d];
+ H_field[d][i][j][k] *= H_factor[d];
+ }
+
+ return this->AddSinglePlane(lines, numLines, E_field, H_field, MeshType);
+}
+
+bool nf2ff_calc::AddPlane(float **lines, unsigned int* numLines, complex<float>**** E_field, complex<float>**** H_field, int MeshType)
+{
+ this->AddSinglePlane(lines, numLines, E_field, H_field, MeshType);
+
+ for (int n=0;n<3;++n)
+ {
+ int nP = (n+1)%3;
+ int nPP = (n+2)%3;
+ // check if a single mirror plane is on
+ if ((m_MirrorType[n]!=MIRROR_OFF) && (m_MirrorType[nP]==MIRROR_OFF) && (m_MirrorType[nPP]==MIRROR_OFF))
+ {
+ this->AddMirrorPlane(n, lines, numLines, E_field, H_field, MeshType);
+ break;
+ }
+ //check if two planes are on
+ else if ((m_MirrorType[n]==MIRROR_OFF) && (m_MirrorType[nP]!=MIRROR_OFF) && (m_MirrorType[nPP]!=MIRROR_OFF))
+ {
+ this->AddMirrorPlane(nP, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(nPP, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(nP, lines, numLines, E_field, H_field, MeshType);
+ break;
+ }
+ }
+ // check if all planes are on
+ if ((m_MirrorType[0]!=MIRROR_OFF) && (m_MirrorType[1]!=MIRROR_OFF) && (m_MirrorType[2]!=MIRROR_OFF))
+ {
+ this->AddMirrorPlane(0, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(1, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(0, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(2, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(0, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(1, lines, numLines, E_field, H_field, MeshType);
+ this->AddMirrorPlane(0, lines, numLines, E_field, H_field, MeshType);
+ }
+
+ //cleanup E- & H-Fields
+ Delete_N_3DArray(E_field,numLines);
+ Delete_N_3DArray(H_field,numLines);
+ return true;
+}
+
+bool nf2ff_calc::AddSinglePlane(float **lines, unsigned int* numLines, complex<float>**** E_field, complex<float>**** H_field, int MeshType)
+{
+ //find normal direction
+ int ny = this->GetNormalDir(numLines);
+ if (ny<0)
+ {
+ cerr << "nf2ff_calc::AddPlane: Error can't determine normal direction..." << endl;
+ return false;
+ }
+ int nP = (ny+1)%3;
+ int nPP = (ny+2)%3;
+
+ complex<float>**** Js = Create_N_3DArray<complex<float> >(numLines);
+ complex<float>**** Ms = Create_N_3DArray<complex<float> >(numLines);
+
+ float normDir[3]= {0,0,0};
+ if (lines[ny][0]>=m_centerCoord[ny])
+ normDir[ny]=1;
+ else
+ normDir[ny]=-1;
+ unsigned int pos[3];
+
+ float edge_length_P[numLines[nP]];
+ for (unsigned int n=1;n<numLines[nP]-1;++n)
+ edge_length_P[n]=0.5*fabs(lines[nP][n+1]-lines[nP][n-1]);
+ edge_length_P[0]=0.5*fabs(lines[nP][1]-lines[nP][0]);
+ edge_length_P[numLines[nP]-1]=0.5*fabs(lines[nP][numLines[nP]-1]-lines[nP][numLines[nP]-2]);
+
+ float edge_length_PP[numLines[nPP]];
+ for (unsigned int n=1;n<numLines[nPP]-1;++n)
+ edge_length_PP[n]=0.5*fabs(lines[nPP][n+1]-lines[nPP][n-1]);
+ edge_length_PP[0]=0.5*fabs(lines[nPP][1]-lines[nPP][0]);
+ edge_length_PP[numLines[nPP]-1]=0.5*fabs(lines[nPP][numLines[nPP]-1]-lines[nPP][numLines[nPP]-2]);
+
+ //check for cylindrical mesh
+ if (MeshType==1)
+ {
+ if (ny==0) //surface a-z
+ {
+ for (unsigned int n=0;n<numLines[nP];++n)
+ edge_length_P[n]*=lines[0][0]; //angle-width * radius
+ }
+ else if (ny==2) //surface r-a
+ {
+ //calculate: area = delta_angle * delta_radius * center_radius
+ for (unsigned int n=1;n<numLines[nP]-1;++n)
+ edge_length_P[n]*=lines[nP][n]; //radius-width * center-radius
+ edge_length_P[0]*=(lines[nP][0]+0.5*edge_length_P[0]);
+ edge_length_P[numLines[nP]-1]*=(lines[nP][numLines[nP]-1]-0.5*edge_length_P[numLines[nP]-1]);
+ }
+ }
+
+ complex<double> power = 0;
+ double area;
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ area = edge_length_P[pos[nP]]*edge_length_PP[pos[nPP]];
+ power = (E_field[nP][pos[0]][pos[1]][pos[2]]*conj(H_field[nPP][pos[0]][pos[1]][pos[2]]) \
+ - E_field[nPP][pos[0]][pos[1]][pos[2]]*conj(H_field[nP][pos[0]][pos[1]][pos[2]]));
+ m_radPower += 0.5*area*real(power)*normDir[ny];
+ }
+ unsigned int numAngles[2] = {m_numTheta, m_numPhi};
+
+ // setup multi-threading jobs
+ vector<unsigned int> jpt = AssignJobs2Threads(numLines[nP], m_numThreads, true);
+ m_numThreads = jpt.size();
+ nf2ff_data thread_data[m_numThreads];
+ m_Barrier = new boost::barrier(m_numThreads+1); // numThread workers + 1 controller
+ unsigned int start=0;
+ unsigned int stop=jpt.at(0)-1;
+ for (unsigned int n=0; n<m_numThreads; n++)
+ {
+ thread_data[n].ny=ny;
+ thread_data[n].mesh_type = MeshType;
+ thread_data[n].normDir=normDir;
+ thread_data[n].numLines=numLines;
+ thread_data[n].lines=lines;
+ thread_data[n].edge_length_P=edge_length_P;
+ thread_data[n].edge_length_PP=edge_length_PP;
+ thread_data[n].E_field=E_field;
+ thread_data[n].H_field=H_field;
+ thread_data[n].Js=Js;
+ thread_data[n].Ms=Ms;
+ thread_data[n].m_Nt=Create2DArray<complex<double> >(numAngles);
+ thread_data[n].m_Np=Create2DArray<complex<double> >(numAngles);
+ thread_data[n].m_Lt=Create2DArray<complex<double> >(numAngles);
+ thread_data[n].m_Lp=Create2DArray<complex<double> >(numAngles);
+
+ boost::thread *t = new boost::thread( nf2ff_calc_thread(this,start,stop,n,thread_data[n]) );
+
+ m_thread_group.add_thread( t );
+
+ start = stop+1;
+ if (n<m_numThreads-1)
+ stop = start + jpt.at(n+1)-1;
+ }
+ //all threads a running and waiting for the barrier
+
+ m_Barrier->wait(); //start
+
+ // threads: calc Js and Ms (eq. 8.15a/b)
+ // threads calc their local Nt,Np,Lt and Lp
+
+ m_Barrier->wait(); //combine all thread local Nt,Np,Lt and Lp
+
+ complex<float>** Nt = Create2DArray<complex<float> >(numAngles);
+ complex<float>** Np = Create2DArray<complex<float> >(numAngles);
+ complex<float>** Lt = Create2DArray<complex<float> >(numAngles);
+ complex<float>** Lp = Create2DArray<complex<float> >(numAngles);
+
+ for (unsigned int n=0; n<m_numThreads; n++)
+ {
+ for (unsigned int tn=0;tn<m_numTheta;++tn)
+ for (unsigned int pn=0;pn<m_numPhi;++pn)
+ {
+ Nt[tn][pn] += thread_data[n].m_Nt[tn][pn];
+ Np[tn][pn] += thread_data[n].m_Np[tn][pn];
+ Lt[tn][pn] += thread_data[n].m_Lt[tn][pn];
+ Lp[tn][pn] += thread_data[n].m_Lp[tn][pn];
+ }
+ Delete2DArray(thread_data[n].m_Nt,numAngles);
+ Delete2DArray(thread_data[n].m_Np,numAngles);
+ Delete2DArray(thread_data[n].m_Lt,numAngles);
+ Delete2DArray(thread_data[n].m_Lp,numAngles);
+ }
+
+ m_Barrier->wait(); //wait for termination
+ m_thread_group.join_all(); // wait for termination
+ delete m_Barrier;
+ m_Barrier = NULL;
+
+ //cleanup Js & Ms
+ Delete_N_3DArray(Js,numLines);
+ Delete_N_3DArray(Ms,numLines);
+
+ // calc equations 8.23a/b and 8.24a/b
+ float k = 2*M_PI*m_freq/__C0__*sqrt(m_permittivity*m_permeability);
+ complex<float> factor(0,k/4.0/M_PI/m_radius);
+ complex<float> f_exp(0,-1*k*m_radius);
+ factor *= exp(f_exp);
+ float fZ0 = __Z0__ * sqrt(m_permeability/m_permittivity);
+ complex<float> Z0 = fZ0;
+ float P_max = 0;
+ for (unsigned int tn=0;tn<m_numTheta;++tn)
+ for (unsigned int pn=0;pn<m_numPhi;++pn)
+ {
+ m_E_theta[tn][pn] -= factor*(Lp[tn][pn] + Z0*Nt[tn][pn]);
+ m_E_phi[tn][pn] += factor*(Lt[tn][pn] - Z0*Np[tn][pn]);
+
+ m_H_theta[tn][pn] += factor*(Np[tn][pn] - Lt[tn][pn]/Z0);
+ m_H_phi[tn][pn] -= factor*(Nt[tn][pn] + Lp[tn][pn]/Z0);
+
+ m_P_rad[tn][pn] = m_radius*m_radius/(2*fZ0) * abs((m_E_theta[tn][pn]*conj(m_E_theta[tn][pn])+m_E_phi[tn][pn]*conj(m_E_phi[tn][pn])));
+ if (m_P_rad[tn][pn]>P_max)
+ P_max = m_P_rad[tn][pn];
+ }
+
+ //cleanup Nx and Lx
+ Delete2DArray(Nt,numAngles);
+ Delete2DArray(Np,numAngles);
+ Delete2DArray(Lt,numAngles);
+ Delete2DArray(Lp,numAngles);
+
+ m_maxDir = 4*M_PI*P_max / m_radPower;
+
+ return true;
+}
diff --git a/openEMS/nf2ff/nf2ff_calc.h b/openEMS/nf2ff/nf2ff_calc.h
new file mode 100644
index 0000000..ab46e5e
--- /dev/null
+++ b/openEMS/nf2ff/nf2ff_calc.h
@@ -0,0 +1,136 @@
+/*
+* Copyright (C) 2012-2014 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef NF2FF_CALC_H
+#define NF2FF_CALC_H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+#include <cmath>
+#include <complex>
+#include <boost/thread.hpp>
+
+class nf2ff_calc;
+
+#define MIRROR_OFF 0
+#define MIRROR_PEC 1
+#define MIRROR_PMC 2
+
+// data structure to exchange data between thread-controller and worker-threads
+typedef struct
+{
+ //local working data IN
+ int ny;
+ int mesh_type;
+ float* normDir;
+ unsigned int* numLines;
+ float **lines;
+ float* edge_length_P;
+ float* edge_length_PP;
+
+ std::complex<float>**** E_field;
+ std::complex<float>**** H_field;
+ std::complex<float>**** Js;
+ std::complex<float>**** Ms;
+
+ //local working data OUT
+ std::complex<double>** m_Nt;
+ std::complex<double>** m_Np;
+ std::complex<double>** m_Lt;
+ std::complex<double>** m_Lp;
+
+} nf2ff_data;
+
+class nf2ff_calc_thread
+{
+public:
+ nf2ff_calc_thread(nf2ff_calc* nfc, unsigned int start, unsigned int stop, unsigned int threadID, nf2ff_data &data);
+ void operator()();
+
+protected:
+ unsigned int m_start, m_stop, m_threadID;
+ nf2ff_calc *m_nf_calc;
+
+ nf2ff_data m_data;
+};
+
+class nf2ff_calc
+{
+ // allow full data access to nf2ff_calc_thread class
+ friend class nf2ff_calc_thread;
+public:
+ nf2ff_calc(float freq, std::vector<float> theta, std::vector<float> phi, std::vector<float> center);
+ ~nf2ff_calc();
+
+ void SetRadius(float radius) {m_radius=radius;}
+ void SetPermittivity(float permittivity) {m_permittivity=permittivity;}
+ void SetPermeability(float permeability) {m_permeability=permeability;}
+
+ double GetTotalRadPower() const {return m_radPower;}
+ double GetMaxDirectivity() const {return m_maxDir;}
+
+ std::complex<double>** GetETheta() const {return m_E_theta;}
+ std::complex<double>** GetEPhi() const {return m_E_phi;}
+ double** GetRadPower() const {return m_P_rad;}
+
+ unsigned int GetNumThreads() const {return m_numThreads;}
+ void SetNumThreads(unsigned int n) {m_numThreads=n;}
+
+ void SetMirror(int type, int dir, float pos);
+
+ bool AddPlane(float **lines, unsigned int* numLines, std::complex<float>**** E_field, std::complex<float>**** H_field, int MeshType=0);
+
+protected:
+ float m_freq;
+ float m_radius;
+
+ float m_permittivity; //relative electric permittivity
+ float m_permeability; //relative magnetic permeability
+
+ double m_radPower;
+ double m_maxDir;
+
+ std::complex<double>** m_E_theta;
+ std::complex<double>** m_E_phi;
+ std::complex<double>** m_H_theta;
+ std::complex<double>** m_H_phi;
+ double** m_P_rad;
+
+ float m_centerCoord[3];
+ unsigned int m_numTheta;
+ unsigned int m_numPhi;
+ float* m_theta;
+ float* m_phi;
+
+ //mirror settings
+ bool m_EnableMirror;
+ int m_MirrorType[3];
+ float m_MirrorPos[3];
+
+ int GetNormalDir(unsigned int* numLines);
+ bool AddSinglePlane(float **lines, unsigned int* numLines, std::complex<float>**** E_field, std::complex<float>**** H_field, int MeshType=0);
+ bool AddMirrorPlane(int n, float **lines, unsigned int* numLines, std::complex<float>**** E_field, std::complex<float>**** H_field, int MeshType=0);
+
+ //boost multi-threading
+ unsigned int m_numThreads;
+ boost::thread_group m_thread_group;
+ boost::barrier *m_Barrier;
+};
+
+
+#endif // NF2FF_CALC_H
diff --git a/openEMS/openEMS.sh b/openEMS/openEMS.sh
new file mode 100755
index 0000000..fe5e5e1
--- /dev/null
+++ b/openEMS/openEMS.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+#clear LD_LIBRARY_PATH
+export LD_LIBRARY_PATH=
+
+#get path to openEMS
+openEMS_PATH=`dirname $0`
+
+#execute openEMS
+exec $openEMS_PATH/openEMS $@
+
diff --git a/openEMS/openEMS_MPI.pro b/openEMS/openEMS_MPI.pro
new file mode 100644
index 0000000..d564c2b
--- /dev/null
+++ b/openEMS/openEMS_MPI.pro
@@ -0,0 +1,5 @@
+# enable MPI support
+!win32:CONFIG += MPI_SUPPORT
+
+include(openEMS.pro)
+
diff --git a/openEMS/openEMS_MPI.sh b/openEMS/openEMS_MPI.sh
new file mode 100755
index 0000000..c46f0fa
--- /dev/null
+++ b/openEMS/openEMS_MPI.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+#clear LD_LIBRARY_PATH
+export LD_LIBRARY_PATH=
+
+#get path to openEMS
+openEMS_PATH=`dirname $0`
+
+#execute openEMS
+exec mpirun -l -n 2 $openEMS_PATH/openEMS $@
+
diff --git a/openEMS/openems.cpp b/openEMS/openems.cpp
new file mode 100644
index 0000000..72476d3
--- /dev/null
+++ b/openEMS/openems.cpp
@@ -0,0 +1,1231 @@
+/*
+* Copyright (C) 2010-2015 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "openems.h"
+#include <iomanip>
+#include <iostream>
+#include <fstream>
+#include "tools/array_ops.h"
+#include "tools/useful.h"
+#include "FDTD/operator_cylinder.h"
+#include "FDTD/operator_cylindermultigrid.h"
+#include "FDTD/engine_multithread.h"
+#include "FDTD/operator_multithread.h"
+#include "FDTD/extensions/operator_ext_excitation.h"
+#include "FDTD/extensions/operator_ext_tfsf.h"
+#include "FDTD/extensions/operator_ext_mur_abc.h"
+#include "FDTD/extensions/operator_ext_upml.h"
+#include "FDTD/extensions/operator_ext_lorentzmaterial.h"
+#include "FDTD/extensions/operator_ext_conductingsheet.h"
+#include "FDTD/extensions/operator_ext_steadystate.h"
+#include "FDTD/extensions/engine_ext_steadystate.h"
+#include "FDTD/engine_interface_fdtd.h"
+#include "FDTD/engine_interface_cylindrical_fdtd.h"
+#include "Common/processvoltage.h"
+#include "Common/processcurrent.h"
+#include "Common/processfieldprobe.h"
+#include "Common/processmodematch.h"
+#include "Common/processfields_td.h"
+#include "Common/processfields_fd.h"
+#include "Common/processfields_sar.h"
+#include <hdf5.h> // only for H5get_libversion()
+#include <boost/version.hpp> // only for BOOST_LIB_VERSION
+#include <vtkVersion.h>
+
+//external libs
+#include "tinyxml.h"
+#include "ContinuousStructure.h"
+#include "CSPropProbeBox.h"
+#include "CSPropDumpBox.h"
+
+using namespace std;
+
+double CalcDiffTime(timeval t1, timeval t2)
+{
+ double s_diff = t1.tv_sec - t2.tv_sec;
+ s_diff += (t1.tv_usec-t2.tv_usec)*1e-6;
+ return s_diff;
+}
+
+openEMS::openEMS()
+{
+ FDTD_Op=NULL;
+ FDTD_Eng=NULL;
+ Eng_Ext_SSD=NULL;
+ m_CSX=NULL;
+ PA=NULL;
+ CylinderCoords = false;
+ Enable_Dumps = true;
+ DebugMat = false;
+ DebugOp = false;
+ m_debugCSX = false;
+ m_debugBox = m_debugPEC = m_no_simulation = false;
+ m_DumpStats = false;
+ endCrit = 1e-6;
+ m_OverSampling = 4;
+ m_CellConstantMaterial=false;
+
+ m_engine = EngineType_Multithreaded; //default engine type
+ m_engine_numThreads = 0;
+
+ m_Abort = false;
+ m_Exc = 0;
+
+ m_TS_method=3;
+ m_TS=0;
+ m_TS_fac=1.0;
+ m_maxTime=0.0;
+
+ for (int n=0;n<6;++n)
+ {
+ m_BC_type[n] = 0;
+ m_PML_size[n] = 8;
+ m_Mur_v_ph[n] = 0;
+ }
+}
+
+openEMS::~openEMS()
+{
+ Reset();
+}
+
+void openEMS::Reset()
+{
+ if (PA) PA->DeleteAll();
+ delete PA;
+ PA=0;
+ delete FDTD_Eng;
+ FDTD_Eng=0;
+ delete FDTD_Op;
+ FDTD_Op=0;
+ delete m_CSX;
+ m_CSX=0;
+ delete m_Exc;
+ m_Exc=0;
+}
+
+void openEMS::showUsage()
+{
+ cout << " Usage: openEMS <FDTD_XML_FILE> [<options>...]" << endl << endl;
+ cout << " <options>" << endl;
+ cout << "\t--disable-dumps\t\tDisable all field dumps for faster simulation" << endl;
+ cout << "\t--debug-material\tDump material distribution to a vtk file for debugging" << endl;
+ cout << "\t--debug-PEC\t\tDump metal distribution to a vtk file for debugging" << endl;
+ cout << "\t--debug-operator\tDump operator to vtk file for debugging" << endl;
+ cout << "\t--debug-boxes\t\tDump e.g. probe boxes to vtk file for debugging" << endl;
+ cout << "\t--debug-CSX\t\tWrite CSX geometry file to debugCSX.xml" << endl;
+ cout << "\t--engine=<type>\t\tChoose engine type" << endl;
+ cout << "\t\t--engine=fastest\t\tfastest available engine (default)" << endl;
+ cout << "\t\t--engine=basic\t\t\tbasic FDTD engine" << endl;
+ cout << "\t\t--engine=sse\t\t\tengine using sse vector extensions" << endl;
+ cout << "\t\t--engine=sse-compressed\t\tengine using compressed operator + sse vector extensions" << endl;
+#ifdef MPI_SUPPORT
+ cout << "\t\t--engine=MPI\t\t\tengine using compressed operator + sse vector extensions + MPI parallel processing" << endl;
+ cout << "\t\t--engine=multithreaded\t\tengine using compressed operator + sse vector extensions + MPI + multithreading" << endl;
+#else
+ cout << "\t\t--engine=multithreaded\t\tengine using compressed operator + sse vector extensions + multithreading" << endl;
+#endif
+ cout << "\t--numThreads=<n>\tForce use n threads for multithreaded engine (needs: --engine=multithreaded)" << endl;
+ cout << "\t--no-simulation\t\tonly run preprocessing; do not simulate" << endl;
+ cout << "\t--dump-statistics\tdump simulation statistics to '" << __OPENEMS_RUN_STAT_FILE__ << "' and '" << __OPENEMS_STAT_FILE__ << "'" << endl;
+ cout << "\n\t Additional global arguments " << endl;
+ g_settings.ShowArguments(cout,"\t");
+ cout << endl;
+}
+
+//! \brief processes a command line argument
+//! \return true if argument is known
+//! \return false if argument is unknown
+bool openEMS::parseCommandLineArgument( const char *argv )
+{
+ if (!argv)
+ return false;
+
+ if (strcmp(argv,"--disable-dumps")==0)
+ {
+ cout << "openEMS - disabling all field dumps" << endl;
+ SetEnableDumps(false);
+ return true;
+ }
+ else if (strcmp(argv,"--debug-material")==0)
+ {
+ cout << "openEMS - dumping material to 'material_dump.vtk'" << endl;
+ DebugMaterial();
+ return true;
+ }
+ else if (strcmp(argv,"--debug-operator")==0)
+ {
+ cout << "openEMS - dumping operator to 'operator_dump.vtk'" << endl;
+ DebugOperator();
+ return true;
+ }
+ else if (strcmp(argv,"--debug-boxes")==0)
+ {
+ cout << "openEMS - dumping boxes to 'box_dump*.vtk'" << endl;
+ DebugBox();
+ return true;
+ }
+ else if (strcmp(argv,"--debug-PEC")==0)
+ {
+ cout << "openEMS - dumping PEC info to 'PEC_dump.vtk'" << endl;
+ m_debugPEC = true;
+ return true;
+ }
+ else if (strcmp(argv,"--debug-CSX")==0)
+ {
+ cout << "openEMS - dumping CSX geometry to 'debugCSX.xml'" << endl;
+ m_debugCSX = true;
+ return true;
+ }
+ else if (strcmp(argv,"--engine=basic")==0)
+ {
+ cout << "openEMS - enabled basic engine" << endl;
+ m_engine = EngineType_Basic;
+ return true;
+ }
+ else if (strcmp(argv,"--engine=sse")==0)
+ {
+ cout << "openEMS - enabled sse engine" << endl;
+ m_engine = EngineType_SSE;
+ return true;
+ }
+ else if (strcmp(argv,"--engine=sse-compressed")==0)
+ {
+ cout << "openEMS - enabled compressed sse engine" << endl;
+ m_engine = EngineType_SSE_Compressed;
+ return true;
+ }
+ else if (strcmp(argv,"--engine=multithreaded")==0)
+ {
+ cout << "openEMS - enabled multithreading" << endl;
+ m_engine = EngineType_Multithreaded;
+ return true;
+ }
+ else if (strncmp(argv,"--numThreads=",13)==0)
+ {
+ m_engine_numThreads = atoi(argv+13);
+ cout << "openEMS - fixed number of threads: " << m_engine_numThreads << endl;
+ return true;
+ }
+ else if (strcmp(argv,"--engine=fastest")==0)
+ {
+ cout << "openEMS - enabled multithreading engine" << endl;
+ m_engine = EngineType_Multithreaded;
+ return true;
+ }
+ else if (strcmp(argv,"--no-simulation")==0)
+ {
+ cout << "openEMS - disabling simulation => preprocessing only" << endl;
+ m_no_simulation = true;
+ return true;
+ }
+ else if (strcmp(argv,"--dump-statistics")==0)
+ {
+ cout << "openEMS - dump simulation statistics to '" << __OPENEMS_RUN_STAT_FILE__ << "' and '" << __OPENEMS_STAT_FILE__ << "'" << endl;
+ m_DumpStats = true;
+ return true;
+ }
+
+ return false;
+}
+
+string openEMS::GetExtLibsInfo(string prefix)
+{
+ stringstream str;
+
+ str << prefix << "Used external libraries:" << endl;
+ str << prefix << "\t" << ContinuousStructure::GetInfoLine(true) << endl;
+
+ // libhdf5
+ unsigned int major, minor, release;
+ if (H5get_libversion( &major, &minor, &release ) >= 0)
+ {
+ str << prefix << "\t" << "hdf5 -- Version: " << major << '.' << minor << '.' << release << endl;
+ str << prefix << "\t" << " compiled against: " H5_VERS_INFO << endl;
+ }
+
+ // tinyxml
+ str << prefix << "\t" << "tinyxml -- compiled against: " << TIXML_MAJOR_VERSION << '.' << TIXML_MINOR_VERSION << '.' << TIXML_PATCH_VERSION << endl;
+
+ // fparser
+ str << prefix << "\t" << "fparser" << endl;
+
+ // boost
+ str << prefix << "\t" << "boost -- compiled against: " << BOOST_LIB_VERSION << endl;
+
+ //vtk
+ str << prefix << "\t" << "vtk -- Version: " << vtkVersion::GetVTKMajorVersion() << "." << vtkVersion::GetVTKMinorVersion() << "." << vtkVersion::GetVTKBuildVersion() << endl;
+ str << prefix << "\t" << " compiled against: " << VTK_VERSION << endl;
+
+ return str.str();
+}
+
+void openEMS::WelcomeScreen()
+{
+#if defined(_LP64) || defined(_WIN64)
+ string bits = "64bit";
+#else
+ string bits = "32bit";
+#endif
+
+ cout << " ---------------------------------------------------------------------- " << endl;
+ cout << " | openEMS " << bits << " -- version " GIT_VERSION << endl;
+ cout << " | (C) 2010-2016 Thorsten Liebig <thorsten.liebig@gmx.de> GPL license" << endl;
+ cout << " ---------------------------------------------------------------------- " << endl;
+ cout << openEMS::GetExtLibsInfo("\t") << endl;
+}
+
+bool openEMS::SetupBoundaryConditions()
+{
+ FDTD_Op->SetBoundaryCondition(m_BC_type); //operator only knows about PEC and PMC, everything else is defined by extensions (see below)
+
+ /**************************** create all operator/engine extensions here !!!! **********************************/
+ for (int n=0; n<6; ++n)
+ {
+ FDTD_Op->SetBCSize(n, 0);
+ if (m_BC_type[n]==2) //Mur-ABC
+ {
+ FDTD_Op->SetBCSize(n, 1);
+ Operator_Ext_Mur_ABC* op_ext_mur = new Operator_Ext_Mur_ABC(FDTD_Op);
+ op_ext_mur->SetDirection(n/2,n%2);
+ if (m_Mur_v_ph[n]>0)
+ op_ext_mur->SetPhaseVelocity(m_Mur_v_ph[n]);
+ FDTD_Op->AddExtension(op_ext_mur);
+ }
+ if (m_BC_type[n]==3)
+ FDTD_Op->SetBCSize(n, m_PML_size[n]);
+ }
+
+
+ //create the upml
+ Operator_Ext_UPML::Create_UPML(FDTD_Op, m_BC_type, m_PML_size, string());
+
+ return true;
+}
+
+Engine_Interface_FDTD* openEMS::NewEngineInterface(int multigridlevel)
+{
+ Operator_CylinderMultiGrid* op_cyl_mg = dynamic_cast<Operator_CylinderMultiGrid*>(FDTD_Op);
+ while (op_cyl_mg && multigridlevel>0)
+ {
+ int mgl = op_cyl_mg->GetMultiGridLevel();
+ if (mgl==multigridlevel)
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cout << __func__ << ": Operator with requested multi-grid level found." << endl;
+ return new Engine_Interface_Cylindrical_FDTD(op_cyl_mg);
+ }
+ Operator_Cylinder* op_cyl_inner = op_cyl_mg->GetInnerOperator();
+ op_cyl_mg = dynamic_cast<Operator_CylinderMultiGrid*>(op_cyl_inner);
+ if (op_cyl_mg==NULL) //inner most operator reached
+ {
+ if (g_settings.GetVerboseLevel()>0)
+ cout << __func__ << ": Operator with highest multi-grid level chosen." << endl;
+ return new Engine_Interface_Cylindrical_FDTD(op_cyl_inner);
+ }
+ // try next level
+ }
+ Operator_Cylinder* op_cyl = dynamic_cast<Operator_Cylinder*>(FDTD_Op);
+ if (op_cyl)
+ return new Engine_Interface_Cylindrical_FDTD(op_cyl);
+ Operator_sse* op_sse = dynamic_cast<Operator_sse*>(FDTD_Op);
+ if (op_sse)
+ return new Engine_Interface_SSE_FDTD(op_sse);
+ return new Engine_Interface_FDTD(FDTD_Op);
+}
+
+void openEMS::SetVerboseLevel(int level)
+{
+ g_settings.SetVerboseLevel(level);
+}
+
+bool openEMS::SetupProcessing()
+{
+ //*************** setup processing ************//
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Setting up processing..." << endl;
+
+ unsigned int Nyquist = FDTD_Op->GetExcitationSignal()->GetNyquistNum();
+ PA = new ProcessingArray(Nyquist);
+
+ double start[3];
+ double stop[3];
+ bool l_MultiBox = false;
+ vector<CSProperties*> Probes = m_CSX->GetPropertyByType(CSProperties::PROBEBOX);
+ for (size_t i=0; i<Probes.size(); ++i)
+ {
+ //check whether one or more probe boxes are defined
+ l_MultiBox = (Probes.at(i)->GetQtyPrimitives()>1);
+
+ for (size_t nb=0; nb<Probes.at(i)->GetQtyPrimitives(); ++nb)
+ {
+ CSPrimitives* prim = Probes.at(i)->GetPrimitive(nb);
+ if (prim!=NULL)
+ {
+ double bnd[6] = {0,0,0,0,0,0};
+ prim->GetBoundBox(bnd,true);
+ start[0]= bnd[0];
+ start[1]=bnd[2];
+ start[2]=bnd[4];
+ stop[0] = bnd[1];
+ stop[1] =bnd[3];
+ stop[2] =bnd[5];
+ CSPropProbeBox* pb = Probes.at(i)->ToProbeBox();
+ ProcessIntegral* proc = NULL;
+ if (pb)
+ {
+ if (pb->GetProbeType()==0)
+ {
+ ProcessVoltage* procVolt = new ProcessVoltage(NewEngineInterface());
+ proc=procVolt;
+ }
+ else if (pb->GetProbeType()==1)
+ {
+ ProcessCurrent* procCurr = new ProcessCurrent(NewEngineInterface());
+ proc=procCurr;
+ }
+ else if (pb->GetProbeType()==2)
+ proc = new ProcessFieldProbe(NewEngineInterface(),0);
+ else if (pb->GetProbeType()==3)
+ proc = new ProcessFieldProbe(NewEngineInterface(),1);
+ else if ((pb->GetProbeType()==10) || (pb->GetProbeType()==11))
+ {
+ ProcessModeMatch* pmm = new ProcessModeMatch(NewEngineInterface());
+ pmm->SetFieldType(pb->GetProbeType()-10);
+ pmm->SetModeFunction(0,pb->GetAttributeValue("ModeFunctionX"));
+ pmm->SetModeFunction(1,pb->GetAttributeValue("ModeFunctionY"));
+ pmm->SetModeFunction(2,pb->GetAttributeValue("ModeFunctionZ"));
+ proc = pmm;
+ }
+ else
+ {
+ cerr << "openEMS::SetupFDTD: Warning: Probe type " << pb->GetProbeType() << " of property '" << pb->GetName() << "' is unknown..." << endl;
+ continue;
+ }
+ if (CylinderCoords)
+ proc->SetMeshType(Processing::CYLINDRICAL_MESH);
+ if ((pb->GetProbeType()==1) || (pb->GetProbeType()==3) || (pb->GetProbeType()==11))
+ {
+ proc->SetDualTime(true);
+ proc->SetDualMesh(true);
+ }
+ proc->SetProcessInterval(Nyquist/m_OverSampling);
+ if (pb->GetStartTime()>0 || pb->GetStopTime()>0)
+ proc->SetProcessStartStopTime(pb->GetStartTime(), pb->GetStopTime());
+ proc->AddFrequency(pb->GetFDSamples());
+ proc->GetNormalDir(pb->GetNormalDir());
+ if (l_MultiBox==false)
+ proc->SetName(pb->GetName());
+ else
+ proc->SetName(pb->GetName(),nb);
+ proc->DefineStartStopCoord(start,stop);
+ if (g_settings.showProbeDiscretization())
+ proc->ShowSnappedCoords();
+ proc->SetWeight(pb->GetWeighting());
+ PA->AddProcessing(proc);
+ prim->SetPrimitiveUsed(true);
+ }
+ else
+ delete proc;
+ }
+ }
+ }
+
+ vector<CSProperties*> DumpProps = m_CSX->GetPropertyByType(CSProperties::DUMPBOX);
+ for (size_t i=0; i<DumpProps.size(); ++i)
+ {
+ ProcessFields* ProcField=NULL;
+
+ //check whether one or more probe boxes are defined
+ l_MultiBox = (DumpProps.at(i)->GetQtyPrimitives()>1);
+
+ for (size_t nb=0; nb<DumpProps.at(i)->GetQtyPrimitives(); ++nb)
+ {
+
+ CSPrimitives* prim = DumpProps.at(i)->GetPrimitive(nb);
+ if (prim!=NULL)
+ {
+ double bnd[6] = {0,0,0,0,0,0};
+ prim->GetBoundBox(bnd,true);
+ start[0]= bnd[0];
+ start[1]=bnd[2];
+ start[2]=bnd[4];
+ stop[0] = bnd[1];
+ stop[1] =bnd[3];
+ stop[2] =bnd[5];
+ CSPropDumpBox* db = DumpProps.at(i)->ToDumpBox();
+ if (db)
+ {
+ if ((db->GetDumpType()>=0) && (db->GetDumpType()<=3))
+ ProcField = new ProcessFieldsTD(NewEngineInterface(db->GetMultiGridLevel()));
+ else if ((db->GetDumpType()>=10) && (db->GetDumpType()<=13))
+ ProcField = new ProcessFieldsFD(NewEngineInterface(db->GetMultiGridLevel()));
+ else if ( ((db->GetDumpType()>=20) && (db->GetDumpType()<=22)) || (db->GetDumpType()==29) )
+ {
+ ProcessFieldsSAR* procSAR = new ProcessFieldsSAR(NewEngineInterface(db->GetMultiGridLevel()));
+ ProcField = procSAR;
+ string method = db->GetAttributeValue("SAR_Method");
+ if (!method.empty())
+ procSAR->SetSARAveragingMethod(method);
+ // use (center)-cell based conductivity only
+ procSAR->SetUseCellConductivity(true);
+ }
+ else
+ cerr << "openEMS::SetupFDTD: unknown dump box type... skipping!" << endl;
+ if (ProcField)
+ {
+ ProcField->SetEnable(Enable_Dumps);
+ ProcField->SetProcessInterval(Nyquist/m_OverSampling);
+ if (db->GetStopTime()>0 || db->GetStartTime()>0)
+ ProcField->SetProcessStartStopTime(db->GetStartTime(), db->GetStopTime());
+ if ((db->GetDumpType()==1) || (db->GetDumpType()==11))
+ {
+ ProcField->SetDualTime(true);
+ //make dualMesh the default mesh for h-field dumps, maybe overwritten by interpolation type (node-interpolation)
+ ProcField->SetDualMesh(true);
+ }
+ if (db->GetDumpType()>=10)
+ {
+ ProcField->AddFrequency(db->GetFDSamples());
+ ProcField->SetDumpType((ProcessFields::DumpType)(db->GetDumpType()-10));
+ }
+ else
+ ProcField->SetDumpType((ProcessFields::DumpType)db->GetDumpType());
+
+ if (db->GetDumpType()==20)
+ ProcField->SetDumpType(ProcessFields::SAR_LOCAL_DUMP);
+ if (db->GetDumpType()==21)
+ ProcField->SetDumpType(ProcessFields::SAR_1G_DUMP);
+ if (db->GetDumpType()==22)
+ ProcField->SetDumpType(ProcessFields::SAR_10G_DUMP);
+ if (db->GetDumpType()==29)
+ ProcField->SetDumpType(ProcessFields::SAR_RAW_DATA);
+
+ //SetupMaterialStorages() has previewed storage needs... refresh here to prevent cleanup!!!
+ if ( ProcField->NeedConductivity() && Enable_Dumps )
+ FDTD_Op->SetMaterialStoreFlags(1,true);
+
+ ProcField->SetDumpMode((Engine_Interface_Base::InterpolationType)db->GetDumpMode());
+ ProcField->SetFileType((ProcessFields::FileType)db->GetFileType());
+ if (CylinderCoords)
+ ProcField->SetMeshType(Processing::CYLINDRICAL_MESH);
+ if (db->GetSubSampling())
+ for (int n=0; n<3; ++n)
+ ProcField->SetSubSampling(db->GetSubSampling(n),n);
+ if (db->GetOptResolution())
+ for (int n=0; n<3; ++n)
+ ProcField->SetOptResolution(db->GetOptResolution(n),n);
+
+ if (l_MultiBox==false)
+ ProcField->SetName(db->GetName());
+ else
+ ProcField->SetName(db->GetName(),nb);
+
+ ProcField->SetFileName(ProcField->GetName());
+ ProcField->DefineStartStopCoord(start,stop);
+ if (g_settings.showProbeDiscretization())
+ ProcField->ShowSnappedCoords();
+ PA->AddProcessing(ProcField);
+ prim->SetPrimitiveUsed(true);
+ }
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool openEMS::SetupMaterialStorages()
+{
+ vector<CSProperties*> DumpProps = m_CSX->GetPropertyByType(CSProperties::DUMPBOX);
+ for (size_t i=0; i<DumpProps.size(); ++i)
+ {
+ CSPropDumpBox* db = DumpProps.at(i)->ToDumpBox();
+ if (!db)
+ continue;
+ if (db->GetQtyPrimitives()==0)
+ continue;
+ //check for current density dump types
+ if ( ((db->GetDumpType()==2) || (db->GetDumpType()==12) || // current density storage
+ (db->GetDumpType()==20) || (db->GetDumpType()==21) || (db->GetDumpType()==22)) && // SAR dump types
+ Enable_Dumps )
+ FDTD_Op->SetMaterialStoreFlags(1,true); //tell operator to store kappa material data
+ }
+ return true;
+}
+
+void openEMS::SetupCylinderMultiGrid(std::string val)
+{
+ m_CC_MultiGrid.clear();
+ m_CC_MultiGrid = SplitString2Double(val,',');
+}
+
+bool openEMS::SetupOperator()
+{
+ if (CylinderCoords)
+ {
+ if (m_CC_MultiGrid.size()>0)
+ {
+ FDTD_Op = Operator_CylinderMultiGrid::New(m_CC_MultiGrid, m_engine_numThreads);
+ if (FDTD_Op==NULL)
+ FDTD_Op = Operator_Cylinder::New(m_engine_numThreads);
+ }
+ else
+ FDTD_Op = Operator_Cylinder::New(m_engine_numThreads);
+ }
+ else if (m_engine == EngineType_SSE)
+ {
+ FDTD_Op = Operator_sse::New();
+ }
+ else if (m_engine == EngineType_SSE_Compressed)
+ {
+ FDTD_Op = Operator_SSE_Compressed::New();
+ }
+ else if (m_engine == EngineType_Multithreaded)
+ {
+ FDTD_Op = Operator_Multithread::New(m_engine_numThreads);
+ }
+ else
+ {
+ FDTD_Op = Operator::New();
+ }
+ return true;
+}
+
+void openEMS::Set_BC_Type(int idx, int type)
+{
+ if ((idx<0) || (idx>5))
+ return;
+ m_BC_type[idx] = type;
+}
+
+int openEMS::Get_BC_Type(int idx)
+{
+ if ((idx<0) || (idx>5))
+ return -1;
+ return m_BC_type[idx];
+}
+
+void openEMS::Set_BC_PML(int idx, unsigned int size)
+{
+ if ((idx<0) || (idx>5))
+ return;
+ m_BC_type[idx] = 3;
+ m_PML_size[idx] = size;
+}
+
+int openEMS::Get_PML_Size(int idx)
+{
+ if ((idx<0) || (idx>5))
+ return -1;
+ if (m_BC_type[idx]!=3)
+ return -1; // return -1 if BC was *not* a PML
+ return m_PML_size[idx];
+}
+
+void openEMS::Set_Mur_PhaseVel(int idx, double val)
+{
+ if ((idx<0) || (idx>5))
+ return;
+ m_Mur_v_ph[idx] = val;
+}
+
+bool openEMS::ParseFDTDSetup(std::string file)
+{
+ Reset();
+
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Read openEMS xml file: " << file << " ..." << endl;
+
+ TiXmlDocument doc(file);
+ if (!doc.LoadFile())
+ {
+ cerr << "openEMS: Error File-Loading failed!!! File: " << file << endl;
+ exit(-1);
+ }
+
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Read openEMS Settings..." << endl;
+ TiXmlElement* openEMSxml = doc.FirstChildElement("openEMS");
+ if (openEMSxml==NULL)
+ {
+ cerr << "Can't read openEMS ... " << endl;
+ exit(-1);
+ }
+ TiXmlElement* FDTD_Opts = openEMSxml->FirstChildElement("FDTD");
+
+ if (FDTD_Opts==NULL)
+ {
+ cerr << "Can't read openEMS FDTD Settings... " << endl;
+ exit(-1);
+ }
+
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Read Geometry..." << endl;
+ ContinuousStructure* csx = new ContinuousStructure();
+ string EC(csx->ReadFromXML(openEMSxml));
+ if (EC.empty()==false)
+ cerr << EC << endl;
+ this->SetCSX(csx);
+
+
+ return this->Parse_XML_FDTDSetup(FDTD_Opts);
+}
+
+bool openEMS::Parse_XML_FDTDSetup(TiXmlElement* FDTD_Opts)
+{
+ double dhelp=0;
+ FDTD_Opts->QueryDoubleAttribute("NumberOfTimesteps",&dhelp);
+ if (dhelp<0)
+ this->SetNumberOfTimeSteps(0);
+ else
+ this->SetNumberOfTimeSteps((unsigned int)dhelp);
+
+ int ihelp = 0;
+ FDTD_Opts->QueryIntAttribute("CylinderCoords",&ihelp);
+ if (ihelp==1)
+ {
+ this->SetCylinderCoords(true);
+ const char* cchelp = FDTD_Opts->Attribute("MultiGrid");
+ if (cchelp!=NULL)
+ this->SetupCylinderMultiGrid(string(cchelp));
+ }
+
+ dhelp = 0;
+ FDTD_Opts->QueryDoubleAttribute("endCriteria",&dhelp);
+ if (dhelp==0)
+ this->SetEndCriteria(1e-6);
+ else
+ this->SetEndCriteria(dhelp);
+
+ ihelp = 0;
+ FDTD_Opts->QueryIntAttribute("OverSampling",&ihelp);
+ if (ihelp<2)
+ this->SetOverSampling(2);
+ else
+ this->SetOverSampling(ihelp);
+
+ // check for cell constant material averaging
+ if (FDTD_Opts->QueryIntAttribute("CellConstantMaterial",&ihelp)==TIXML_SUCCESS)
+ this->SetCellConstantMaterial(ihelp==1);
+
+ TiXmlElement* BC = FDTD_Opts->FirstChildElement("BoundaryCond");
+ if (BC==NULL)
+ {
+ cerr << "Can't read openEMS boundary cond Settings... " << endl;
+ exit(-3);
+ }
+
+// const char* tmp = BC->Attribute("PML_Grading");
+// string pml_gradFunc;
+// if (tmp)
+// pml_gradFunc = string(tmp);
+
+ string bound_names[] = {"xmin","xmax","ymin","ymax","zmin","zmax"};
+ string s_bc;
+ for (int n=0; n<6; ++n)
+ {
+ int EC = BC->QueryIntAttribute(bound_names[n].c_str(),&ihelp);
+ if (EC==TIXML_SUCCESS)
+ {
+ this->Set_BC_Type(n, ihelp);
+ continue;
+ }
+ if (EC==TIXML_WRONG_TYPE)
+ {
+ const char* tmp = BC->Attribute(bound_names[n].c_str());
+ if (tmp)
+ s_bc = string(tmp);
+ else
+ cerr << "openEMS::SetupBoundaryConditions: Warning, boundary condition for \"" << bound_names[n] << "\" unknown... set to PEC " << endl;
+ if (s_bc=="PEC")
+ this->Set_BC_Type(n, 0);
+ else if (s_bc=="PMC")
+ this->Set_BC_Type(n, 1);
+ else if (s_bc=="MUR")
+ this->Set_BC_Type(n, 2);
+ else if (strncmp(s_bc.c_str(),"PML_=",4)==0)
+ this->Set_BC_PML(n, atoi(s_bc.c_str()+4));
+ else
+ cerr << "openEMS::SetupBoundaryConditions: Warning, boundary condition for \"" << bound_names[n] << "\" unknown... set to PEC " << endl;
+ }
+ else
+ cerr << "openEMS::SetupBoundaryConditions: Warning, boundary condition for \"" << bound_names[n] << "\" not found... set to PEC " << endl;
+ }
+
+ //read general mur phase velocity
+ if (BC->QueryDoubleAttribute("MUR_PhaseVelocity",&dhelp) == TIXML_SUCCESS)
+ for (int n=0;n<6;++n)
+ this->Set_Mur_PhaseVel(n, dhelp);
+
+ string mur_v_ph_names[6] = {"MUR_PhaseVelocity_xmin", "MUR_PhaseVelocity_xmax", "MUR_PhaseVelocity_ymin", "MUR_PhaseVelocity_ymax", "MUR_PhaseVelocity_zmin", "MUR_PhaseVelocity_zmax"};
+ for (int n=0; n<6; ++n)
+ if (BC->QueryDoubleAttribute(mur_v_ph_names[n].c_str(),&dhelp) == TIXML_SUCCESS)
+ this->Set_Mur_PhaseVel(n, dhelp);
+
+ TiXmlElement* m_Excite_Elem = FDTD_Opts->FirstChildElement("Excitation");
+ if (!m_Excite_Elem)
+ {
+ cerr << "Excitation::setupExcitation: Error, can't read openEMS excitation settings... " << endl;
+ return false;
+ }
+
+ Excitation* exc = this->InitExcitation();
+ double f0=0, fc=0, f_max=0;
+ ihelp = -1;
+ m_Excite_Elem->QueryIntAttribute("Type",&ihelp);
+ switch (ihelp)
+ {
+ case Excitation::GaissianPulse:
+ m_Excite_Elem->QueryDoubleAttribute("f0",&f0);
+ m_Excite_Elem->QueryDoubleAttribute("fc",&fc);
+ exc->SetupGaussianPulse(f0, fc);
+ break;
+ case Excitation::Sinusoidal: // sinusoidal excite
+ m_Excite_Elem->QueryDoubleAttribute("f0",&f0);
+ exc->SetupSinusoidal(f0);
+ break;
+ case Excitation::DiracPulse:
+ FDTD_Opts->QueryDoubleAttribute("f_max",&f_max);
+ exc->SetupDiracPulse(f_max);
+ break;
+ case Excitation::Step:
+ FDTD_Opts->QueryDoubleAttribute("f_max",&f_max);
+ exc->SetupStepExcite(f_max);
+ break;
+ case Excitation::CustomExcite:
+ m_Excite_Elem->QueryDoubleAttribute("f0",&f0);
+ FDTD_Opts->QueryDoubleAttribute("f_max",&f_max);
+ exc->SetupCustomExcite(m_Excite_Elem->Attribute("Function"), f0, f_max);
+ break;
+ }
+
+ if (FDTD_Opts->QueryIntAttribute("TimeStepMethod",&ihelp)==TIXML_SUCCESS)
+ this->SetTimeStepMethod(ihelp);
+ if (FDTD_Opts->QueryDoubleAttribute("TimeStep",&dhelp)==TIXML_SUCCESS)
+ this->SetTimeStep(dhelp);
+ if (FDTD_Opts->QueryDoubleAttribute("TimeStepFactor",&dhelp)==TIXML_SUCCESS)
+ this->SetTimeStepFactor(dhelp);
+}
+
+void openEMS::SetGaussExcite(double f0, double fc)
+{
+ this->InitExcitation();
+ m_Exc->SetupGaussianPulse(f0, fc);
+}
+
+Excitation* openEMS::InitExcitation()
+{
+ delete m_Exc;
+ m_Exc = new Excitation();
+ return m_Exc;
+}
+
+void openEMS::SetCSX(ContinuousStructure* csx)
+{
+ delete m_CSX;
+ m_CSX = csx;
+}
+
+int openEMS::SetupFDTD()
+{
+ timeval startTime;
+ gettimeofday(&startTime,NULL);
+
+ if (m_CSX==NULL)
+ {
+ cerr << "openEMS::SetupFDTD: Error: CSXCAD is not set!" << endl;
+ return 3;
+ }
+ if (m_CSX==NULL)
+ {
+ cerr << "openEMS::SetupFDTD: Error: CSXCAD is not set!" << endl;
+ return 3;
+ }
+ std::string ec = m_CSX->Update();
+ if (!ec.empty())
+ cerr << ec << endl;
+ if (g_settings.GetVerboseLevel()>2)
+ m_CSX->ShowPropertyStatus(cerr);
+
+ if (CylinderCoords)
+ if (m_CSX->GetCoordInputType()!=CYLINDRICAL)
+ {
+ cerr << "openEMS::SetupFDTD: Warning: Coordinate system found in the CSX file is not a cylindrical. Forcing to cylindrical coordinate system!" << endl;
+ m_CSX->SetCoordInputType(CYLINDRICAL); //tell CSX to use cylinder-coords
+ }
+
+ if (m_debugCSX)
+ m_CSX->Write2XML("debugCSX.xml");
+
+ //*************** setup operator ************//
+ if (SetupOperator()==false)
+ return 2;
+
+ // default material averaging is quarter cell averaging
+ FDTD_Op->SetQuarterCellMaterialAvg();
+
+ if (m_CellConstantMaterial)
+ {
+ FDTD_Op->SetCellConstantMaterial();
+ if (g_settings.GetVerboseLevel()>0)
+ cout << "Enabling constant cell material assumption." << endl;
+ }
+
+ if (m_Exc==NULL)
+ {
+ cerr << "openEMS::SetupFDTD: Error, excitation is not defined! Abort!" << endl;
+ return 3;
+ }
+
+ FDTD_Op->SetExcitationSignal(m_Exc);
+ FDTD_Op->AddExtension(new Operator_Ext_Excitation(FDTD_Op));
+ if (!CylinderCoords)
+ FDTD_Op->AddExtension(new Operator_Ext_TFSF(FDTD_Op));
+
+ if (FDTD_Op->SetGeometryCSX(m_CSX)==false) return(2);
+
+ SetupBoundaryConditions();
+
+ FDTD_Op->SetTimeStepMethod(m_TS_method);
+
+ if (m_TS>0)
+ FDTD_Op->SetTimestep(m_TS);
+ if (m_TS_fac<1)
+ FDTD_Op->SetTimestepFactor(m_TS_fac);
+
+ // Is a steady state detection requested
+ Operator_Ext_SteadyState* Op_Ext_SSD = NULL;
+ if (m_Exc->GetSignalPeriod()>0)
+ {
+ cout << "Create a steady state detection using a period of " << m_Exc->GetSignalPeriod() << " s" << endl;
+ Op_Ext_SSD = new Operator_Ext_SteadyState(FDTD_Op, m_Exc->GetSignalPeriod());
+ unsigned int pos[3];
+ for (int p=0;p<3;++p)
+ pos[p] = FDTD_Op->GetNumberOfLines(p)/2;
+ Op_Ext_SSD->Add_E_Probe(pos, 0);
+ Op_Ext_SSD->Add_E_Probe(pos, 1);
+ Op_Ext_SSD->Add_E_Probe(pos, 2);
+
+ for (int n=0;n<3;++n)
+ {
+ for (int p=0;p<3;++p)
+ pos[p] = FDTD_Op->GetNumberOfLines(p)/2;
+
+ pos[n] *= 1/4;
+ Op_Ext_SSD->Add_E_Probe(pos, 0);
+ Op_Ext_SSD->Add_E_Probe(pos, 1);
+ Op_Ext_SSD->Add_E_Probe(pos, 2);
+
+ pos[n] *= 3/4;
+ Op_Ext_SSD->Add_E_Probe(pos, 0);
+ Op_Ext_SSD->Add_E_Probe(pos, 1);
+ Op_Ext_SSD->Add_E_Probe(pos, 2);
+ }
+ FDTD_Op->AddExtension(Op_Ext_SSD);
+ }
+
+ if ((m_CSX->GetQtyPropertyType(CSProperties::LORENTZMATERIAL)>0) || (m_CSX->GetQtyPropertyType(CSProperties::DEBYEMATERIAL)>0))
+ FDTD_Op->AddExtension(new Operator_Ext_LorentzMaterial(FDTD_Op));
+ if (m_CSX->GetQtyPropertyType(CSProperties::CONDUCTINGSHEET)>0)
+ FDTD_Op->AddExtension(new Operator_Ext_ConductingSheet(FDTD_Op, m_Exc->GetMaxFreq()));
+
+ //check all properties to request material storage during operator creation...
+ SetupMaterialStorages();
+
+ /******************* create the EC-FDTD operator *****************************/
+ Operator::DebugFlags debugFlags = Operator::None;
+ if (DebugMat)
+ debugFlags |= Operator::debugMaterial;
+ if (DebugOp)
+ debugFlags |= Operator::debugOperator;
+ if (m_debugPEC)
+ debugFlags |= Operator::debugPEC;
+
+ FDTD_Op->CalcECOperator( debugFlags );
+ /*******************************************************************************/
+
+ //reset flags for material storage, if no dump-box resets it to true, it will be cleaned up...
+ FDTD_Op->SetMaterialStoreFlags(0,false);
+ FDTD_Op->SetMaterialStoreFlags(1,false);
+ FDTD_Op->SetMaterialStoreFlags(2,false);
+ FDTD_Op->SetMaterialStoreFlags(3,false);
+
+ unsigned int maxTime_TS = (unsigned int)(m_maxTime/FDTD_Op->GetTimestep());
+ if ((m_maxTime>0) && (maxTime_TS<NrTS))
+ NrTS = maxTime_TS;
+
+ if (!m_Exc->buildExcitationSignal(NrTS))
+ exit(2);
+ m_Exc->DumpVoltageExcite("et");
+ m_Exc->DumpCurrentExcite("ht");
+
+ timeval OpDoneTime;
+ gettimeofday(&OpDoneTime,NULL);
+
+ if (g_settings.GetVerboseLevel()>0)
+ {
+ FDTD_Op->ShowStat();
+ FDTD_Op->ShowExtStat();
+ cout << "Creation time for operator: " << CalcDiffTime(OpDoneTime,startTime) << " s" << endl;
+ }
+ cout << "FDTD simulation size: " << FDTD_Op->GetNumberOfLines(0) << "x" << FDTD_Op->GetNumberOfLines(1) << "x" << FDTD_Op->GetNumberOfLines(2) << " --> " << FDTD_Op->GetNumberCells() << " FDTD cells " << endl;
+ cout << "FDTD timestep is: " <<FDTD_Op->GetTimestep() << " s; Nyquist rate: " << m_Exc->GetNyquistNum() << " timesteps @" << CalcNyquistFrequency(m_Exc->GetNyquistNum(),FDTD_Op->GetTimestep()) << " Hz" << endl;
+ if (m_Exc->GetNyquistNum()>1000)
+ cerr << "openEMS::SetupFDTD: Warning, the timestep seems to be very small --> long simulation. Check your mesh!?" << endl;
+
+ if (m_Exc->GetSignalPeriod()==0)
+ {
+ cout << "Excitation signal length is: " << m_Exc->GetLength() << " timesteps (" << m_Exc->GetLength()*FDTD_Op->GetTimestep() << "s)" << endl;
+ cout << "Max. number of timesteps: " << NrTS << " ( --> " << (double)NrTS/(double)(m_Exc->GetLength()) << " * Excitation signal length)" << endl;
+ if ( ((double)NrTS/(double)m_Exc->GetLength() < 3) && (m_Exc->GetExciteType()==0))
+ cerr << "openEMS::SetupFDTD: Warning, max. number of timesteps is smaller than three times the excitation. " << endl << \
+ "\tYou may want to choose a higher number of max. timesteps... " << endl;
+ }
+ else
+ {
+ int p = int(m_Exc->GetSignalPeriod()/FDTD_Op->GetTimestep());
+ cout << "Excitation signal period is: " << p << " timesteps (" << m_Exc->GetSignalPeriod() << "s)" << endl;
+ cout << "Max. number of timesteps: " << NrTS << " ( --> " << (double)NrTS/(double)(m_Exc->GetLength()) << " * Excitation signal period)" << endl;
+ if (NrTS/p < 3)
+ cerr << "openEMS::SetupFDTD: Warning, max. number of timesteps is smaller than three times the excitation signal period. " << endl << \
+ "\tYou may want to choose a higher number of max. timesteps... " << endl;
+ }
+
+ if (m_no_simulation)
+ {
+ // simulation was disabled (to generate debug output only)
+ return 1;
+ }
+
+ //create FDTD engine
+ FDTD_Eng = FDTD_Op->CreateEngine();
+
+ if (Op_Ext_SSD)
+ {
+ Eng_Ext_SSD = dynamic_cast<Engine_Ext_SteadyState*>(Op_Ext_SSD->GetEngineExtention());
+ Eng_Ext_SSD->SetEngineInterface(this->NewEngineInterface());
+ }
+
+ //setup all processing classes
+ if (SetupProcessing()==false)
+ return 2;
+
+ // Cleanup all unused material storages...
+ FDTD_Op->CleanupMaterialStorage();
+
+ //check and warn for unused properties and primitives
+ m_CSX->WarnUnusedPrimitves(cerr);
+
+ // dump all boxes (voltage, current, fields, ...)
+ if (m_debugBox)
+ {
+ PA->DumpBoxes2File("box_dump_");
+ }
+
+ return 0;
+}
+
+string FormatTime(int sec)
+{
+ stringstream ss;
+ if (sec<60)
+ {
+ ss << setw(9) << sec << "s";
+ return ss.str();
+ }
+ if (sec<3600)
+ {
+ ss << setw(6) << sec/60 << "m" << setw(2) << setfill('0') << sec%60 << "s";
+ return ss.str();
+ }
+ ss << setw(3) << sec/3600 << "h" << setw(2) << setfill('0') << (sec%3600)/60 << "m" << setw(2) << setfill('0') << sec%60 << "s";
+ return ss.str();
+}
+
+bool openEMS::CheckAbortCond()
+{
+ if (m_Abort) //abort was set externally
+ return true;
+
+ //check whether the file "ABORT" exist in current working directory
+ ifstream ifile("ABORT");
+ if (ifile)
+ {
+ ifile.close();
+ cerr << "openEMS::CheckAbortCond(): Found file \"ABORT\", aborting simulation..." << endl;
+ return true;
+ }
+
+ return false;
+}
+
+void openEMS::RunFDTD()
+{
+ cout << "Running FDTD engine... this may take a while... grab a cup of coffee?!?" << endl;
+
+ //special handling of a field processing, needed to realize the end criteria...
+ ProcessFields* ProcField = new ProcessFields(NewEngineInterface());
+ PA->AddProcessing(ProcField);
+ double maxE=0,currE=0;
+
+ //init processings
+ PA->InitAll();
+
+ //add all timesteps to end-crit field processing with max excite amplitude
+ unsigned int maxExcite = FDTD_Op->GetExcitationSignal()->GetMaxExcitationTimestep();
+// for (unsigned int n=0; n<FDTD_Op->Exc->Volt_Count; ++n)
+// ProcField->AddStep(FDTD_Op->Exc->Volt_delay[n]+maxExcite);
+ ProcField->AddStep(maxExcite);
+
+ double change=1;
+ int prevTS=0,currTS=0;
+ double numCells = FDTD_Op->GetNumberCells();
+ double speed = 0;
+ double t_diff;
+ double t_run;
+
+ timeval currTime;
+ gettimeofday(&currTime,NULL);
+ timeval startTime = currTime;
+ timeval prevTime= currTime;
+
+ if (m_DumpStats)
+ InitRunStatistics(__OPENEMS_RUN_STAT_FILE__);
+ //*************** simulate ************//
+
+ PA->PreProcess();
+ int step=PA->Process();
+ if ((step<0) || (step>(int)NrTS)) step=NrTS;
+ while ((FDTD_Eng->GetNumberOfTimesteps()<NrTS) && (change>endCrit) && !CheckAbortCond())
+ {
+ FDTD_Eng->IterateTS(step);
+ step=PA->Process();
+
+ if ((Eng_Ext_SSD==NULL) && ProcField->CheckTimestep())
+ {
+ currE = ProcField->CalcTotalEnergyEstimate();
+ if (currE>maxE)
+ maxE=currE;
+ }
+
+// cout << " do " << step << " steps; current: " << eng.GetNumberOfTimesteps() << endl;
+ currTS = FDTD_Eng->GetNumberOfTimesteps();
+ if ((step<0) || (step>(int)(NrTS - currTS))) step=NrTS - currTS;
+
+ gettimeofday(&currTime,NULL);
+
+ t_diff = CalcDiffTime(currTime,prevTime);
+
+ if (t_diff>4)
+ {
+ t_run = CalcDiffTime(currTime,startTime);
+ speed = numCells*(currTS-prevTS)/t_diff;
+ cout << "[@" << FormatTime(t_run) << "] Timestep: " << setw(12) << currTS ;
+ cout << " || Speed: " << setw(6) << setprecision(1) << std::fixed << speed*1e-6 << " MC/s (" << setw(4) << setprecision(3) << std::scientific << t_diff/(currTS-prevTS) << " s/TS)" ;
+ if (Eng_Ext_SSD==NULL)
+ {
+ currE = ProcField->CalcTotalEnergyEstimate();
+ if (currE>maxE)
+ maxE=currE;
+ if (maxE)
+ change = currE/maxE;
+ cout << " || Energy: ~" << setw(6) << setprecision(2) << std::scientific << currE << " (-" << setw(5) << setprecision(2) << std::fixed << fabs(10.0*log10(change)) << "dB)" << endl;
+ }
+ else
+ {
+ change = Eng_Ext_SSD->GetLastDiff();
+ cout << " || SteadyState: " << setw(6) << setprecision(2) << std::fixed << 10.0*log10(change) << " dB" << endl;
+ }
+ prevTime=currTime;
+ prevTS=currTS;
+
+ PA->FlushNext();
+
+ if (m_DumpStats)
+ DumpRunStatistics(__OPENEMS_RUN_STAT_FILE__, t_run, currTS, speed, currE);
+ }
+ }
+ if ((change>endCrit) && (FDTD_Op->GetExcitationSignal()->GetExciteType()==0))
+ cerr << "RunFDTD: Warning: Max. number of timesteps was reached before the end-criteria of -" << fabs(10.0*log10(endCrit)) << "dB was reached... " << endl << \
+ "\tYou may want to choose a higher number of max. timesteps... " << endl;
+
+ gettimeofday(&currTime,NULL);
+ t_diff = CalcDiffTime(currTime,startTime);
+
+ cout << "Time for " << FDTD_Eng->GetNumberOfTimesteps() << " iterations with " << FDTD_Op->GetNumberCells() << " cells : " << t_diff << " sec" << endl;
+ cout << "Speed: " << numCells*(double)FDTD_Eng->GetNumberOfTimesteps()/t_diff*1e-6 << " MCells/s " << endl;
+
+ if (m_DumpStats)
+ DumpStatistics(__OPENEMS_STAT_FILE__, t_diff);
+
+ //*************** postproc ************//
+ PA->PostProcess();
+}
+
+bool openEMS::DumpStatistics(const string& filename, double time)
+{
+ ofstream stat_file;
+ stat_file.open(filename.c_str());
+
+ if (!stat_file.is_open())
+ {
+ cerr << "openEMS::DumpStatistics: Error, opening file failed..." << endl;
+ return false;
+ }
+ stat_file << std::setprecision( 16 );
+ stat_file << FDTD_Op->GetNumberCells() << "\t% number of cells" << endl;
+ stat_file << FDTD_Op->GetTimestep() << "\t% timestep (s)" << endl;
+ stat_file << FDTD_Eng->GetNumberOfTimesteps() << "\t% number of iterations" << endl;
+ stat_file << FDTD_Eng->GetNumberOfTimesteps()*FDTD_Op->GetTimestep() << "\t% total numercial time (s)" << endl;
+ stat_file << time << "\t% simulation time (s)" << endl;
+ stat_file << (double)FDTD_Op->GetNumberCells()*(double)FDTD_Eng->GetNumberOfTimesteps()/time << "\t% speed (cells/s)" << endl;
+
+ stat_file.close();
+ return true;
+}
+
+bool openEMS::InitRunStatistics(const string& filename)
+{
+ ofstream stat_file;
+ stat_file.open(filename.c_str(), ios_base::out);
+
+ if (!stat_file.is_open())
+ {
+ cerr << "openEMS::InitRunStatistics: Error, opening file failed..." << endl;
+ return false;
+ }
+ stat_file << "%time\ttimestep\tspeed\tenergy" << endl;
+ stat_file.close();
+ return true;
+}
+
+bool openEMS::DumpRunStatistics(const string& filename, double time, unsigned int ts, double speed, double energy)
+{
+ ofstream stat_file;
+ stat_file.open(filename.c_str(), ios_base::app);
+
+ if (!stat_file.is_open())
+ {
+ cerr << "openEMS::DumpRunStatistics: Error, opening file failed..." << endl;
+ return false;
+ }
+ stat_file << time << "\t" << ts << "\t" << speed << "\t" << energy << endl;
+ stat_file.close();
+ return true;
+}
diff --git a/openEMS/openems.h b/openEMS/openems.h
new file mode 100644
index 0000000..d194050
--- /dev/null
+++ b/openEMS/openems.h
@@ -0,0 +1,167 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef OPENEMS_H
+#define OPENEMS_H
+
+#include <sstream>
+#include <sys/time.h>
+#include <time.h>
+#include <vector>
+
+#define __OPENEMS_STAT_FILE__ "openEMS_stats.txt"
+#define __OPENEMS_RUN_STAT_FILE__ "openEMS_run_stats.txt"
+
+class Operator;
+class Engine;
+class Engine_Interface_FDTD;
+class ProcessingArray;
+class TiXmlElement;
+class ContinuousStructure;
+class Engine_Interface_FDTD;
+class Excitation;
+class Engine_Ext_SteadyState;
+
+double CalcDiffTime(timeval t1, timeval t2);
+std::string FormatTime(int sec);
+
+class openEMS
+{
+public:
+ openEMS();
+ virtual ~openEMS();
+
+ virtual bool parseCommandLineArgument( const char *argv );
+ static void showUsage();
+
+ bool ParseFDTDSetup(std::string file);
+ virtual bool Parse_XML_FDTDSetup(TiXmlElement* openEMSxml);
+ virtual int SetupFDTD();
+ virtual void RunFDTD();
+
+ void Reset();
+
+ void SetNumberOfTimeSteps(unsigned int val) {NrTS=val;}
+ void SetEnableDumps(bool val) {Enable_Dumps=val;}
+ void SetEndCriteria(double val) {endCrit=val;}
+ void SetOverSampling(int val) {m_OverSampling=val;}
+ void SetCellConstantMaterial(bool val) {m_CellConstantMaterial=val;}
+
+ void SetCylinderCoords(bool val) {CylinderCoords=val;}
+ void SetupCylinderMultiGrid(std::vector<double> val) {m_CC_MultiGrid=val;}
+ void SetupCylinderMultiGrid(std::string val);
+
+ void SetTimeStepMethod(int val) {m_TS_method=val;}
+ void SetTimeStep(double val) {m_TS=val;}
+ void SetTimeStepFactor(double val) {m_TS_fac=val;}
+ void SetMaxTime(double val) {m_maxTime=val;}
+
+ void DebugMaterial() {DebugMat=true;}
+ void DebugOperator() {DebugOp=true;}
+ void DebugBox() {m_debugBox=true;}
+
+ void Set_BC_Type(int idx, int type);
+ int Get_BC_Type(int idx);
+ void Set_BC_PML(int idx, unsigned int size);
+ int Get_PML_Size(int idx);
+ void Set_Mur_PhaseVel(int idx, double val);
+
+ //! Get informations about external libs used by openEMS
+ static std::string GetExtLibsInfo(std::string prefix="\t");
+
+ //! Get welcome screen for openEMS
+ static void WelcomeScreen();
+
+ //! Set this to about FDTD iteration process
+ void SetAbort(bool val) {m_Abort=val;}
+ //! Check for abort conditions
+ bool CheckAbortCond();
+
+ void SetGaussExcite(double f0, double fc);
+ Excitation* InitExcitation();
+
+ void SetCSX(ContinuousStructure* csx);
+
+ Engine_Interface_FDTD* NewEngineInterface(int multigridlevel = 0);
+
+ void SetVerboseLevel(int level);
+
+protected:
+ bool CylinderCoords;
+ std::vector<double> m_CC_MultiGrid;
+
+ ContinuousStructure* m_CSX;
+
+ //! Number of Timesteps
+ unsigned int NrTS;
+ int m_TS_method;
+ double m_TS;
+ double m_TS_fac;
+ double m_maxTime;
+
+ // some command line flags
+ bool Enable_Dumps;
+ bool DebugMat;
+ bool DebugOp;
+ bool m_debugCSX;
+ bool m_DumpStats;
+ bool m_debugBox, m_debugPEC, m_no_simulation;
+
+ double endCrit;
+ int m_OverSampling;
+ bool m_CellConstantMaterial;
+ Operator* FDTD_Op;
+ Engine* FDTD_Eng;
+ Engine_Ext_SteadyState* Eng_Ext_SSD;
+ ProcessingArray* PA;
+
+ Excitation* m_Exc;
+
+ bool m_Abort;
+
+#ifdef MPI_SUPPORT
+ enum EngineType {EngineType_Basic, EngineType_SSE, EngineType_SSE_Compressed, EngineType_Multithreaded, EngineType_MPI};
+#else
+ enum EngineType {EngineType_Basic, EngineType_SSE, EngineType_SSE_Compressed, EngineType_Multithreaded};
+#endif
+ EngineType m_engine;
+ unsigned int m_engine_numThreads;
+
+ //! Setup an operator matching the requested engine
+ virtual bool SetupOperator();
+
+ //! Read boundary conditions from xml element and apply to FDTD operator
+ bool SetupBoundaryConditions();
+ int m_BC_type[6];
+ unsigned int m_PML_size[6];
+ double m_Mur_v_ph[6];
+
+ //! Check whether or not the FDTD-Operator has to store material data.
+ bool SetupMaterialStorages();
+
+ //! Setup all processings.
+ virtual bool SetupProcessing();
+
+ //! Dump statistics to file
+ virtual bool DumpStatistics(const std::string& filename, double time);
+
+ //! Dump run statistivs to file
+ virtual bool InitRunStatistics(const std::string& filename);
+ virtual bool DumpRunStatistics(const std::string& filename, double time, unsigned int ts, double speed, double energy);
+};
+
+#endif // OPENEMS_H
diff --git a/openEMS/tools/AdrOp.cpp b/openEMS/tools/AdrOp.cpp
new file mode 100644
index 0000000..228f8de
--- /dev/null
+++ b/openEMS/tools/AdrOp.cpp
@@ -0,0 +1,554 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "AdrOp.h"
+
+using namespace std;
+
+AdrOp::AdrOp(unsigned int muiImax, unsigned int muiJmax, unsigned int muiKmax, unsigned int muiLmax)
+{
+ //error-handling...
+ error = new ErrorMsg(9);
+ if (error==NULL)
+ {
+ fprintf(stderr,"Memory allocation failed!! exiting...");
+ exit(1);
+ }
+ error->SetMsg(1,"Adress Operator: Memory allocation failed!! exiting...");
+ error->SetMsg(2,"Adress Operator: Invalid Adress requested!! exiting...");
+ error->SetMsg(3,"Adress Operator: Invalid Position set!! exiting...");
+ error->SetMsg(4,"Adress Operator: Invalid jump or passing end of iteration!! exiting...");
+ error->SetMsg(5,"Adress Operator: 4D not yet implemented!! exiting...");
+ error->SetMsg(6,"Adress Operator: Position not set!! exiting...");
+ error->SetMsg(7,"Adress Operator: Cells not added to Adress Operator!! exiting...");
+ error->SetMsg(8,"Adress Operator: Invalid Node!! exiting...");
+ error->SetMsg(9,"Adress Operator: Grid invalid!! exiting...");
+
+ //if (muiImax<0) muiImax=0;
+ //if (muiJmax<0) muiJmax=0;
+ //if (muiKmax<0) muiKmax=0;
+ //if (muiLmax<0) muiLmax=0;
+
+ uiDimension=0;
+ if (muiImax>0) uiDimension++;
+ else exit(-1);
+ if (muiJmax>0) uiDimension++;
+ else exit(-2);
+ if (muiKmax>0) uiDimension++;
+ if ( (muiLmax>0) && (muiKmax>0) ) uiDimension++;
+// cout << "\n-----Adress Operator created: Dimension: " << uiDimension << "----" <<endl;
+ uiImax=muiImax;
+ uiJmax=muiJmax;
+ uiKmax=muiKmax;
+ uiLmax=muiLmax=0;
+ if (uiDimension==2) uiSize=uiImax*uiJmax;
+ else if (uiDimension==3) uiSize=uiImax*uiJmax*uiKmax;
+ else if (uiDimension==4) uiSize=uiImax*uiJmax*uiKmax*uiLmax;
+ else uiSize=0;
+ bPosSet=false;
+ if (uiDimension==4) error->Error(5);
+ iIshift=iJshift=iKshift=0;
+ reflect=false;
+ uiTypeOffset=0;
+ clCellAdr=NULL;
+ dGrid[0]=NULL;
+ dGrid[1]=NULL;
+ dGrid[2]=NULL;
+ dGrid[3]=NULL;
+ dDeltaUnit=1;
+ bDebug=false;
+}
+
+AdrOp::AdrOp(AdrOp* origOP)
+{
+ clCellAdr=NULL;
+ error=NULL; // has to be done!!!
+
+ uiDimension=origOP->uiDimension;
+ uiSize=origOP->uiSize;
+ uiImax=origOP->uiImax;
+ uiJmax=origOP->uiJmax;
+ uiKmax=origOP->uiKmax;
+ uiLmax=origOP->uiLmax;
+ uiIpos=origOP->uiIpos;
+ uiJpos=origOP->uiJpos;
+ uiKpos=origOP->uiKpos;
+ uiLpos=origOP->uiLpos;
+ for (int ii=0; ii<4; ++ii) dGrid[ii]=origOP->dGrid[ii];
+ dDeltaUnit=origOP->dDeltaUnit;
+ iIshift=origOP->iIshift;
+ iJshift=origOP->iJshift;
+ iKshift=origOP->iKshift;
+ for (int ii=0; ii<3; ++ii) iCellShift[ii]=origOP->iCellShift[ii];
+ i=origOP->i;
+ j=origOP->j;
+ k=origOP->k;
+ l=origOP->l;
+ reflect=origOP->reflect;
+ uiTypeOffset=origOP->uiTypeOffset;
+
+ bPosSet=origOP->bPosSet;
+ bDebug=origOP->bDebug;
+// return;
+ if (origOP->clCellAdr!=NULL) clCellAdr= new AdrOp(origOP->clCellAdr);
+}
+
+AdrOp::~AdrOp()
+{
+// cerr << "\n------Adress Operator deconstructed-----\n" << endl;
+ delete error;
+ error=NULL;
+ delete clCellAdr;
+ clCellAdr=NULL;
+}
+
+unsigned int AdrOp::SetPos(unsigned int muiIpos, unsigned int muiJpos, unsigned int muiKpos, unsigned int muiLpos)
+{
+ if (bDebug) fprintf(stderr,"AdrOp Debug:: SetPos(%d,%d,%d,%d) Max(%d,%d,%d,%d) \n",muiIpos,muiJpos,muiKpos,muiLpos,uiImax,uiJmax,uiKmax,uiLmax);
+ bPosSet=false;
+ if (muiIpos<uiImax) uiIpos=muiIpos;
+ else error->Error(3);
+ if (muiJpos<uiJmax) uiJpos=muiJpos;
+ else error->Error(3);
+ if ((muiKpos>=uiKmax) && (uiDimension>2)) error->Error(3);
+ else if (uiDimension>2) uiKpos=muiKpos;
+ if ((muiLpos>=uiLmax) && (uiDimension>3)) error->Error(3);
+ else if (uiDimension>3) uiLpos=muiLpos;
+ bPosSet=true;
+// cerr << "Position i:" << uiIpos << " j: " << uiJpos << " k: " << uiKpos << " l: " << 0 << " MAX: i:" << uiImax << " j: " << uiJmax << " k: " << uiKmax << endl; //debug
+ ADRESSEXPENSE(0,0,0,0,uiDimension+1,18)
+ return GetPos();
+}
+
+bool AdrOp::SetPosChecked(unsigned int muiIpos, unsigned int muiJpos, unsigned int muiKpos, unsigned int muiLpos)
+{
+ bPosSet=true;
+ if (muiIpos<uiImax) uiIpos=muiIpos;
+ else bPosSet=false;
+ if (muiJpos<uiJmax) uiJpos=muiJpos;
+ else bPosSet=false;
+ if ((muiKpos>=uiKmax) && (uiDimension>2)) bPosSet=false;
+ else if (uiDimension>2) uiKpos=muiKpos;
+ if ((muiLpos>=uiLmax) && (uiDimension>3)) bPosSet=false;
+ else if (uiDimension>3) uiLpos=muiLpos;
+ ADRESSEXPENSE(0,0,0,0,uiDimension+1,18)
+ return bPosSet;
+}
+
+void AdrOp::SetGrid(double *gridI,double *gridJ,double *gridK,double *gridL)
+{
+ dGrid[0]=gridI;
+ dGrid[1]=gridJ;
+ dGrid[2]=gridK;
+ dGrid[3]=gridL;
+ ADRESSEXPENSE(0,0,0,0,4,0)
+}
+
+bool AdrOp::CheckPos(unsigned int muiIpos, unsigned int muiJpos, unsigned int muiKpos, unsigned int muiLpos)
+{
+ bPosSet=true;
+ if ((muiIpos>=uiImax)) bPosSet=false;
+ if ((muiJpos>=uiJmax)) bPosSet=false;
+ if ((muiKpos>=uiKmax) && (uiDimension>2)) bPosSet=false;
+ if ((muiLpos>=uiLmax) && (uiDimension>3)) bPosSet=false;
+ ADRESSEXPENSE(0,0,0,0,uiDimension+1,18)
+ return bPosSet;
+}
+
+bool AdrOp::CheckRelativePos(int muiIrel,int muiJrel,int muiKrel, int muiLrel)
+{
+ bPosSet=true;
+ if ((muiIrel+(int)uiIpos<0) || (muiIrel+(int)uiIpos>=(int)uiImax)) bPosSet=false;
+ if ((muiJrel+(int)uiJpos<0) || (muiJrel+(int)uiJpos>=(int)uiJmax)) bPosSet=false;
+ if (((muiKrel+(int)uiKpos<0) || (muiKrel+(int)uiKpos>=(int)uiKmax)) && (uiDimension>2)) bPosSet=false;
+ if (((muiLrel+(int)uiLpos<0) || (muiLrel+(int)uiLpos>=(int)uiLmax)) && (uiDimension>3)) bPosSet=false;
+ ADRESSEXPENSE(2*uiDimension,0,0,0,uiDimension+1,18)
+ return bPosSet;
+}
+
+unsigned int AdrOp::GetPos(int muiIrel, int muiJrel, int muiKrel, int /*muiLrel*/)
+{
+ if (bPosSet==false) error->Error(6);
+ if (reflect)
+ {
+#if EXPENSE_LOG==1
+ if (muiIrel+(int)uiIpos<0) ADRESSEXPENSE(2,1,0,0,1,0)
+ if (muiIrel+(int)uiIpos>(int)uiImax-1) ADRESSEXPENSE(4,1,0,0,1,0)
+ if (muiJrel+(int)uiJpos<0) ADRESSEXPENSE(2,1,0,0,1,0)
+ if (muiJrel+(int)uiJpos>(int)uiJmax-1) ADRESSEXPENSE(4,1,0,0,1,0)
+ if (muiKrel+(int)uiKpos<0) ADRESSEXPENSE(2,1,0,0,1,0)
+ if (muiKrel+(int)uiKpos>(int)uiKmax-1) ADRESSEXPENSE(4,1,0,0,1,0)
+#endif
+
+ if (muiIrel+(int)uiIpos<0) muiIrel=-2*uiIpos-muiIrel-uiTypeOffset;
+ if (muiIrel+(int)uiIpos>(int)uiImax-1) muiIrel=2*(uiImax-1-uiIpos)-muiIrel+uiTypeOffset;
+ if (muiJrel+(int)uiJpos<0) muiJrel=-2*uiJpos-muiJrel-uiTypeOffset;
+ if (muiJrel+(int)uiJpos>(int)uiJmax-1) muiJrel=2*(uiJmax-1-uiJpos)-muiJrel+uiTypeOffset;
+ if (muiKrel+(int)uiKpos<0) muiKrel=-2*uiKpos-muiKrel-uiTypeOffset;
+ if (muiKrel+(int)uiKpos>(int)uiKmax-1) muiKrel=2*(uiKmax-1-uiKpos)-muiKrel+uiTypeOffset;
+ }
+ if (uiDimension==2)
+ {
+ ADRESSEXPENSE(7,1,0,0,0,7)
+ if ( (muiIrel+uiIpos<uiImax) && (muiJrel+uiJpos<uiJmax) )
+ return (muiIrel+uiIpos)+(muiJrel+uiJpos)*uiImax;
+ else error->Error(2);
+ return 0;
+ }
+ else if (uiDimension==3)
+ {
+ ADRESSEXPENSE(9,3,0,0,0,11)
+ if ( (muiIrel+uiIpos<uiImax) && (muiJrel+uiJpos<uiJmax) && (muiKrel+uiKpos<uiKmax) )
+ return (muiIrel+uiIpos) + (muiJrel+uiJpos)*uiImax + (muiKrel+uiKpos)*uiJmax*uiImax;
+ else error->Error(2);
+ return 0;
+ }
+ else return 0;
+}
+
+unsigned int AdrOp::GetPosFromNode(int ny, unsigned int uiNode)
+{
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ unsigned int help=uiNode,i=0,j=0,k=0,l=0;
+ i=help%uiImax;
+ help=help/uiImax;
+ j=help%uiJmax;
+ help=help/uiJmax;
+ if (uiKmax>0)
+ {
+ k=help%uiKmax;
+ help=help/uiKmax;
+ l=help;
+ }
+ if (!CheckPos(i,j,k,l)) error->Error(8);
+ ADRESSEXPENSE(0,7,0,0,13,4)
+ switch (ny)
+ {
+ case 0:
+ {
+ return i;
+ break;
+ }
+ case 1:
+ {
+ return j;
+ break;
+ }
+ case 2:
+ {
+ return k;
+ break;
+ }
+ case 3:
+ {
+ return l;
+ break;
+ }
+ }
+ return 0;
+}
+
+double AdrOp::GetNodeVolume(unsigned int uiNode)
+{
+ for (unsigned int n=0; n<uiDimension; n++) if (dGrid[n]==NULL) error->Error(9);
+ double dVol=1;
+ unsigned int uiMax[4]={uiImax,uiJmax,uiKmax,uiLmax};
+ unsigned int uiPos[4]={GetPosFromNode(0,uiNode),GetPosFromNode(1,uiNode),GetPosFromNode(2,uiNode),GetPosFromNode(3,uiNode)};
+ for (unsigned int n=0; n<uiDimension; n++)
+ {
+ if ((uiPos[n]>0) && (uiPos[n]<uiMax[n]-1))
+ {
+ dVol*=0.5*dDeltaUnit*(dGrid[n][uiPos[n]+1]-dGrid[n][uiPos[n]-1]);
+ ADRESSEXPENSE(4,0,1,3,0,4)
+ }
+ else if ((uiPos[n]==0) && (uiPos[n]<uiMax[n]-1))
+ {
+ dVol*=dDeltaUnit*(dGrid[n][uiPos[n]+1]-dGrid[n][uiPos[n]]);
+ ADRESSEXPENSE(3,0,1,2,0,4)
+ }
+ else if ((uiPos[n]>0) && (uiPos[n]==uiMax[n]-1))
+ {
+ dVol*=dDeltaUnit*(dGrid[n][uiPos[n]]-dGrid[n][uiPos[n]-1]);
+ ADRESSEXPENSE(3,0,1,2,0,4)
+ }
+ }
+ return dVol;
+}
+
+double AdrOp::GetIndexWidth(int ny, int index)
+{
+ for (unsigned int n=0; n<uiDimension; n++) if (dGrid[n]==NULL) error->Error(9);
+ double width=0;
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ unsigned int uiMax[4]={uiImax,uiJmax,uiKmax,uiLmax};
+ if ((index>0) && (index<(int)uiMax[ny]-1)) width= (dGrid[ny][index+1]-dGrid[ny][index-1])/2*dDeltaUnit;
+ else if ((index==0) && (index<(int)uiMax[ny]-1)) width=(dGrid[ny][index+1]-dGrid[ny][index])*dDeltaUnit;
+ else if ((index>0) && (index==(int)uiMax[ny]-1)) width=(dGrid[ny][index]-dGrid[ny][index-1])*dDeltaUnit;
+ else width= 0;
+ return width;
+}
+
+double AdrOp::GetIndexCoord(int ny, int index)
+{
+ for (unsigned int n=0; n<uiDimension; n++) if (dGrid[n]==NULL) error->Error(9);
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ unsigned int uiMax[4]={uiImax,uiJmax,uiKmax,uiLmax};
+ if (index<0) index=0;
+ if (index>=(int)uiMax[ny]) index=uiMax[ny]-1;
+ return dGrid[ny][index]*dDeltaUnit;
+}
+
+double AdrOp::GetIndexDelta(int ny, int index)
+{
+ if (index<0) return GetIndexCoord(ny, 0) - GetIndexCoord(ny, 1);
+ unsigned int uiMax[4]={uiImax,uiJmax,uiKmax,uiLmax};
+ if (index>=(int)uiMax[ny]-1) return GetIndexCoord(ny, (int)uiMax[ny]-2) - GetIndexCoord(ny, (int)uiMax[ny]-1);
+ return GetIndexCoord(ny, index+1) - GetIndexCoord(ny, index);
+}
+
+
+unsigned int AdrOp::Shift(int ny, int step)
+{
+ if (bPosSet==false) error->Error(6);
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ switch (ny)
+ {
+ case 0:
+ {
+ iIshift=step;
+// if ((int)uiIpos+step<0) iIshift=-2*uiIpos-iIshift;
+// else if ((int)uiIpos+step>=(int)uiImax) iIshift=-1*iIshift+2*(uiImax-1-uiIpos);
+ break;
+ }
+ case 1:
+ {
+ iJshift=step;
+// if ((int)uiJpos+iJshift<0) iJshift=-2*uiJpos-iJshift;
+// else if ((int)uiJpos+iJshift>=(int)uiJmax) iJshift=-1*iJshift+2*(uiJmax-1-uiJpos);
+ break;
+ }
+ case 2:
+ {
+ iKshift=step;
+// if ((int)uiKpos+iKshift<0) iKshift=-2*uiKpos-iKshift;
+// else if ((int)uiKpos+iKshift>=(int)uiKmax) iKshift=-1*iKshift+2*(uiKmax-1-uiKpos);
+ break;
+ }
+ }
+ ADRESSEXPENSE(1,1,0,0,2,3)
+ return GetPos(iIshift,iJshift,iKshift);
+}
+
+bool AdrOp::CheckShift(int ny, int step)
+{
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ int shift[3]={0,0,0};
+ shift[ny]=step;
+ if (this->CheckPos(uiIpos+shift[0],uiJpos+shift[1],uiKpos+shift[2]))
+ {
+ this->Shift(ny,step);
+ return true;
+ }
+ else return false;
+}
+
+unsigned int AdrOp::GetShiftedPos(int ny, int step)
+{
+ if ((ny<0) || (ny>2))
+ return GetPos(iIshift,iJshift,iKshift);
+ int pos[3] = {iIshift, iJshift, iKshift};
+ pos[ny]+=step;
+ return GetPos(pos[0],pos[1],pos[2]);
+}
+
+void AdrOp::ResetShift()
+{
+ iIshift=iJshift=iKshift=0;
+}
+
+unsigned int AdrOp::Iterate(int jump)
+{
+ if (abs(jump)>=(int)uiImax) error->Error(4);
+ i=uiIpos+jump;
+ if (i>=uiImax)
+ {
+ i=i-uiImax;
+ j=uiJpos+1;
+ if (j>=uiJmax)
+ {
+ j=0;
+ if (uiDimension==3)
+ {
+ k=uiKpos+1;
+ if (k>=uiKmax) k=0;
+ uiKpos=k;
+ }
+ }
+ uiIpos=i;
+ uiJpos=j;
+ return GetPos();
+ }
+ else
+ {
+ uiIpos=i;
+ return GetPos();
+ }
+}
+
+unsigned int AdrOp::GetSize()
+{
+ return uiSize;
+}
+
+
+void AdrOp::SetReflection2Node()
+{
+ reflect=true;
+ uiTypeOffset=0;
+}
+
+void AdrOp::SetReflection2Cell()
+{
+ reflect=true;
+ uiTypeOffset=1;
+}
+
+void AdrOp::SetReflectionOff()
+{
+ reflect=false;
+}
+
+AdrOp* AdrOp::AddCellAdrOp()
+{
+ if (clCellAdr!=NULL) return clCellAdr;
+ if (uiDimension==3) clCellAdr = new AdrOp(uiImax-1,uiJmax-1,uiKmax-1);
+ else if (uiDimension==2) clCellAdr = new AdrOp(uiImax-1,uiJmax-1);
+ else clCellAdr=NULL;
+ if (clCellAdr!=NULL)
+ {
+ clCellAdr->SetPos(0,0,0);
+ clCellAdr->SetReflection2Cell();
+ }
+ iCellShift[0]=iCellShift[1]=iCellShift[2]=0;
+ return clCellAdr;
+}
+
+AdrOp* AdrOp::DeleteCellAdrOp()
+{
+ delete clCellAdr;
+ clCellAdr=NULL;
+ return NULL;
+}
+
+unsigned int AdrOp::ShiftCell(int ny, int step)
+{
+ if (clCellAdr==NULL) error->Error(7);
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ iCellShift[ny]=step;
+ ADRESSEXPENSE(3,1,0,0,1,2)
+ return clCellAdr->GetPos(uiIpos+iCellShift[0],uiJpos+iCellShift[1],uiKpos+iCellShift[2]);
+}
+
+bool AdrOp::ShiftCellCheck(int ny, int step)
+{
+ return clCellAdr->CheckShift(ny,step);
+}
+
+void AdrOp::ResetCellShift()
+{
+ if (clCellAdr==NULL) error->Error(7);
+ iCellShift[0]=iCellShift[1]=iCellShift[2]=0;
+}
+
+unsigned int AdrOp::GetCellPos(bool incShift)
+{
+ if (bPosSet==false) error->Error(6);
+ if (clCellAdr==NULL) error->Error(7);
+#if EXPENSE_LOG==1
+ if (incShift) ADRESSEXPENSE(3,0,0,0,0,2)
+#endif
+ if (incShift) return clCellAdr->GetPos(uiIpos+iCellShift[0],uiJpos+iCellShift[1],uiKpos+iCellShift[2]);
+ else return clCellAdr->GetPos(uiIpos,uiJpos,uiKpos);
+}
+
+unsigned int AdrOp::GetCellPos(int i, int j, int k)
+{
+ if (bPosSet==false) error->Error(6);
+ return clCellAdr->GetPos(uiIpos+i,uiJpos+j,uiKpos+k);
+}
+
+
+double AdrOp::GetShiftCellVolume(int ny, int step)
+{
+ for (unsigned int n=0; n<uiDimension; n++) if (dGrid[n]==NULL) error->Error(9);
+ int uiMax[4]={(int)uiImax-1,(int)uiJmax-1,(int)uiKmax-1,(int)uiLmax-1};
+ while (ny<0) ny+=uiDimension;
+ ny=ny%uiDimension;
+ iCellShift[ny]=step;
+ int uiPos[4]={(int)uiIpos+iCellShift[0],(int)uiJpos+iCellShift[1],(int)uiKpos+iCellShift[2]};
+ double dVol=1;
+ for (unsigned int n=0; n<uiDimension; ++n)
+ {
+ if (uiMax[n]>0)
+ {
+ while ((uiPos[n]<0) || (uiPos[n]>=uiMax[n]))
+ {
+ if (uiPos[n]<0) uiPos[n]=-1*uiPos[n]-1;
+ else if (uiPos[n]>=uiMax[n]) uiPos[n]=uiMax[n]-(uiPos[n]-uiMax[n]+1);
+ }
+ dVol*=(dGrid[n][uiPos[n]+1]-dGrid[n][uiPos[n]])*dDeltaUnit;
+ }
+ }
+ return dVol;
+}
+
+
+deltaAdrOp::deltaAdrOp(unsigned int max)
+{
+ uiMax=max;
+}
+
+deltaAdrOp::~deltaAdrOp()
+{
+}
+
+void deltaAdrOp::SetMax(unsigned int max)
+{
+ uiMax=max;
+}
+
+unsigned int deltaAdrOp::GetAdr(int pos)
+{
+ if (uiMax==1) return 0;
+ if (pos<0) pos=pos*-1;
+ else if (pos>(int)uiMax-1) pos=2*(uiMax-1)-pos+1;
+ if ((pos<0) || (pos>(int)uiMax-1))
+ {
+ fprintf(stderr," Error exiting... ");
+ getchar();
+ exit(-1);
+ }
+ return pos;
+}
+
+
diff --git a/openEMS/tools/AdrOp.h b/openEMS/tools/AdrOp.h
new file mode 100644
index 0000000..e4a690b
--- /dev/null
+++ b/openEMS/tools/AdrOp.h
@@ -0,0 +1,149 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/*!
+\class AdrOp
+\author Thorsten Liebig
+\version $Revision: 1.10 $
+\date $Date: 2006/10/29 18:50:44 $
+*/
+
+#ifndef ADROP_H
+#define ADROP_H
+
+#include <iostream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+#include "ExpenseLog.h"
+#include "ErrorMsg.h"
+
+class AdrOp
+{
+public:
+ ///Constructor, define dimension/size here
+ AdrOp(unsigned int muiImax, unsigned int muiYmax, unsigned int muiKmax=0, unsigned int muiLmax=0);
+ ///Copy-Constructor
+ AdrOp(AdrOp* origOP);
+ ///Deconstructor
+ virtual ~AdrOp();
+ ///Set the current n-dim position, get 1-dim array position as return value
+ /*!A position has to be set or all other methodes will case error! \n The methode will exit with error message if invalid position is set! \sa ErrorMsg */
+ unsigned int SetPos(unsigned int muiIpos, unsigned int muiJpos, unsigned int muiKpos=0, unsigned int muiLpos=0);
+
+ bool SetPosChecked(unsigned int muiIpos, unsigned int muiJpos, unsigned int muiKpos=0, unsigned int muiLpos=0);
+
+ void SetGrid(double *gridI,double *gridJ,double *gridK=NULL,double *gridL=NULL);
+ void SetGridDelta(double delta) {this->dDeltaUnit=delta;};
+
+ bool CheckPos(unsigned int muiIpos, unsigned int muiJpos, unsigned int muiKpos=0, unsigned int muiLpos=0);
+ bool CheckRelativePos(int muiIrel=0,int muiJrel=0,int muiKrel=0, int muiLrel=0);
+ ///will return current 1-dim position, in addition to a relative n-dim shift
+ /*!In case of crossing the boundaries, activate reflection or an error will be invoked\sa SetReflection2Node \sa SetReflection2Cell \sa SetReflectionOff */
+ unsigned int GetPos(int muiIrel=0,int muiJrel=0,int muiKrel=0, int muiLrel=0);
+
+ double GetNodeVolume(unsigned int uiNode);
+
+ double GetIndexWidth(int ny, int index);
+ double GetIndexCoord(int ny, int index);
+ ///Get the gird delta at the given index of direction ny. (if index<0 return negative value as index=0 would give, if index>=max-1 returns negative value as index=max-2 would give)
+ double GetIndexDelta(int ny, int index);
+
+// double GetCellVolume(unsigned int uiCell);
+
+ unsigned int GetPosFromNode(int ny, unsigned int uiNode);
+ ///Set a shift in ny direction (e.g. 0 for i-direction)
+ /*!Shift set by this methode will be ignored by methode GetPos*/
+ unsigned int Shift(int ny, int step);
+ ///Set a checked shift in ny direction (e.g. 0 for i-direction)
+ /*!Shift set by this methode will be ignored by methode GetPos*/
+ bool CheckShift(int ny, int step);
+ ///Returns the current 1-dim position including shift by methode "Shift" + additional (transitory) shift
+ unsigned int GetShiftedPos(int ny=-1, int step=0);
+ ///Reset shift set by "Shift"-methode
+ void ResetShift();
+ ///Iterates through AdrOp; --- obsolete ---
+ unsigned int Iterate(int jump=1);
+ ///Retruns size of array
+ unsigned int GetSize();
+ ///Set mode to reflect by node
+ /*!1D-example (6 nodes): \image html node_reflect.PNG order: 0,1,2,3,4,5,4,3,...*/
+ void SetReflection2Node();
+ ///Set mode to reflect by cell
+ /*!1D-example (5 cells): \image html cell_reflect.PNG order: 0,1,2,3,4,4,3,...*/
+ void SetReflection2Cell();
+ ///Deactivate reflection (default)
+ void SetReflectionOff();
+ ///Add a cell adress operator (dimensions: i-1 j-1 k-1 l-1)
+ /*!\image html cells_nodes.png */
+ AdrOp* AddCellAdrOp();
+
+ AdrOp* GetCellAdrOp() {return clCellAdr;};
+
+ ///Deconstructed cell adress operator if no longer needed
+ AdrOp* DeleteCellAdrOp();
+ ///Shift cell in ny dircetion; cell reflection is active
+ unsigned int ShiftCell(int ny, int step);
+ ///Shift cell in ny dircetion; cell reflection is active; return check
+ bool ShiftCellCheck(int ny, int step);
+ ///Reset cell shift
+ void ResetCellShift();
+ ///Get current cell position from cell adress operator
+ unsigned int GetCellPos(bool incShift=true);
+ ///Get cell position from cell adress operator
+ unsigned int GetCellPos(int i, int j, int k=0);
+ //get volume of cell; incl shift
+ double GetShiftCellVolume(int ny, int step);
+
+
+ void SetDebugOn() {this->bDebug=true;};
+ void SetDebugOff() {this->bDebug=false;};
+
+protected:
+ AdrOp *clCellAdr;
+ unsigned int uiDimension;
+ unsigned int uiSize;
+ unsigned int uiImax,uiJmax,uiKmax,uiLmax;
+ unsigned int uiIpos, uiJpos, uiKpos, uiLpos;
+ double *dGrid[4];
+ double dDeltaUnit;
+ int iIshift, iJshift, iKshift;
+ int iCellShift[3];
+ unsigned int i,j,k,l;
+ bool reflect;
+ unsigned int uiTypeOffset;
+
+ bool bPosSet;
+ bool bDebug;
+ ErrorMsg *error;
+};
+
+
+class deltaAdrOp
+{
+public:
+ deltaAdrOp(unsigned int max=0);
+ virtual ~deltaAdrOp();
+ void SetMax(unsigned int max);
+ unsigned int GetAdr(int pos);
+
+protected:
+ unsigned int uiMax;
+};
+
+
+#endif // ADROP_H
diff --git a/openEMS/tools/CMakeLists.txt b/openEMS/tools/CMakeLists.txt
new file mode 100644
index 0000000..8b62b8a
--- /dev/null
+++ b/openEMS/tools/CMakeLists.txt
@@ -0,0 +1,28 @@
+
+set(SOURCES
+ ${SOURCES}
+ ${CMAKE_CURRENT_SOURCE_DIR}/AdrOp.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/ErrorMsg.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/array_ops.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/global.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/hdf5_file_reader.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/hdf5_file_writer.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/sar_calculation.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/useful.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/vtk_file_writer.cpp
+ PARENT_SCOPE
+)
+
+#set(HEADERS
+# constants.h
+# array_ops.h
+# global.h
+# useful.h
+# aligned_allocator.h
+# hdf5_file_reader.h
+# hdf5_file_writer.h
+#)
+
+# tools lib
+#add_library(tools STATIC ${SOURCES} )
+
diff --git a/openEMS/tools/ErrorMsg.cpp b/openEMS/tools/ErrorMsg.cpp
new file mode 100644
index 0000000..9a1974c
--- /dev/null
+++ b/openEMS/tools/ErrorMsg.cpp
@@ -0,0 +1,98 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "ErrorMsg.h"
+
+ErrorMsg::ErrorMsg(unsigned int NoMessage)
+{
+ NoMsg=NoMessage;
+ if (NoMsg>0) Msg = new char*[NoMsg];
+ if (Msg==NULL)
+ {
+ fprintf(stderr,"Memory allocation failed!! exiting...");
+ exit(1);
+ }
+ for (unsigned int i=0; i<NoMsg; i++) Msg[i]=NULL;
+}
+
+ErrorMsg::~ErrorMsg()
+{
+ for (unsigned int i=0; i<NoMsg; i++)
+ {
+ delete[] Msg[i];
+ Msg[i]=NULL;
+ };
+ delete[] Msg;
+ Msg=NULL;
+}
+
+void ErrorMsg::SetMsg(unsigned int nr, const char *Message)
+{
+ if ((nr<1) || (nr>NoMsg) || (Message==NULL)) ownError();
+ Msg[nr-1] = new char[strlen(Message)+1];
+ if (Msg[nr-1]==NULL)
+ {
+ fprintf(stderr,"Memory allocation failed!! exiting...");
+ exit(1);
+ }
+ Msg[nr-1]=strcpy(Msg[nr-1],Message);
+}
+
+void ErrorMsg::Error(unsigned int nr,char *chAddMsg)
+{
+ if ((nr>0) && (nr<=NoMsg))
+ {
+ if (Msg[nr-1]!=NULL) fprintf(stderr,"%s",Msg[nr-1]);
+ else fprintf(stderr,"unkown error occured!! Error code: %d exiting...",nr);
+ if (chAddMsg!=NULL) fprintf(stderr,"%s",chAddMsg);
+ getchar();
+ exit(nr);
+ }
+ else
+ {
+ fprintf(stderr,"unkown error occured!! Error code: %d exiting...",nr);
+ getchar();
+ exit(nr);
+ }
+}
+
+void ErrorMsg::Error(unsigned int nr,int addNr)
+{
+ if ((nr>0) && (nr<=NoMsg))
+ {
+ if (Msg[nr-1]!=NULL) fprintf(stderr,"%s",Msg[nr-1]);
+ else fprintf(stderr,"unkown error occured!! Error code: %d exiting...",nr);
+ fprintf(stderr,"%d",addNr);
+ getchar();
+ exit(nr);
+ }
+ else
+ {
+ fprintf(stderr,"unkown error occured!! Error code: %d exiting...",nr);
+ getchar();
+ exit(nr);
+ }
+}
+
+void ErrorMsg::ownError(void)
+{
+ fprintf(stdout," Error occured by using Error Message class!! ... exiting...");
+ exit(-1);
+}
diff --git a/openEMS/tools/ErrorMsg.h b/openEMS/tools/ErrorMsg.h
new file mode 100644
index 0000000..fa63c93
--- /dev/null
+++ b/openEMS/tools/ErrorMsg.h
@@ -0,0 +1,50 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/*!
+\class ErrorMsg
+\author Thorsten Liebig
+\version $Revision: 1.2 $
+\date $Date: 2006/01/25 11:47:07 $
+*/
+
+#ifndef _ERRORMSG_H_
+#define _ERRORMSG_H_
+
+class ErrorMsg
+{
+public:
+ ///Constructor defines number of error messages
+ ErrorMsg(unsigned int NoMessage=0);
+ ///Deconstructor
+ virtual ~ErrorMsg();
+ ///Methode for defining error messages
+ /*! \param nr Number of defining error message \param *Message Set error message string \sa Error */
+ void SetMsg(unsigned int nr, const char *Message);
+ ///Call an error message. Will exit the program!
+ /*! \param nr Number of called error message. default is 0 \sa SetMsg*/
+ void Error(unsigned int nr=0,char *chAddMsg=0);
+
+ void Error(unsigned int nr,int addNr);
+
+protected:
+ void ownError(void);
+ unsigned int NoMsg;
+ char **Msg;
+};
+
+#endif //_ERRORMSG_H_
diff --git a/openEMS/tools/ExpenseLog.cpp b/openEMS/tools/ExpenseLog.cpp
new file mode 100644
index 0000000..95a0d4c
--- /dev/null
+++ b/openEMS/tools/ExpenseLog.cpp
@@ -0,0 +1,145 @@
+#include "ExpenseLog.h"
+
+ExpenseModule::ExpenseModule(const char* moduleName)
+{
+ chModuleName=moduleName;
+ uiDoubleAdditions=uiDoubleMultiplications=uiIntAdditions=uiIntMultiplications=uiAssignments=uiBoolOp=0;
+ uiMrdDA=uiMrdDM=uiMrdIA=uiMrdIM=uiMrdAssign=uiMrdBO=0;
+}
+
+ExpenseModule::~ExpenseModule() {};
+
+void ExpenseModule::Clear()
+{
+ uiDoubleAdditions=uiDoubleMultiplications=uiIntAdditions=uiIntMultiplications=uiAssignments=uiBoolOp=0;
+ uiMrdDA=uiMrdDM=uiMrdIA=uiMrdIM=uiMrdAssign=uiMrdBO=0;
+}
+
+void ExpenseModule::AddDoubleAdditons(unsigned int number)
+{
+ uiDoubleAdditions+=number;
+ if (uiDoubleAdditions>=MRD)
+ {
+ uiDoubleAdditions-=MRD;
+ ++uiMrdDA;
+ }
+}
+
+void ExpenseModule::AddDoubleMultiplications(unsigned int number)
+{
+ uiDoubleMultiplications+=number;
+ if (uiDoubleMultiplications>=MRD)
+ {
+ uiDoubleMultiplications-=MRD;
+ ++uiMrdDM;
+ }
+}
+
+void ExpenseModule::AddIntAdditons(unsigned int number)
+{
+ uiIntAdditions+=number;
+ if (uiIntAdditions>=MRD)
+ {
+ uiIntAdditions-=MRD;
+ ++uiMrdIA;
+ }
+}
+
+void ExpenseModule::AddIntMultiplications(unsigned int number)
+{
+ uiIntMultiplications+=number;
+ if (uiIntMultiplications>=MRD)
+ {
+ uiIntMultiplications-=MRD;
+ ++uiMrdIM;
+ }
+}
+
+void ExpenseModule::AddAssignments(unsigned int number)
+{
+ uiAssignments+=number;
+ if (uiAssignments>=MRD)
+ {
+ uiAssignments-=MRD;
+ ++uiMrdAssign;
+ }
+}
+
+void ExpenseModule::AddBoolOperations(unsigned int number)
+{
+ uiBoolOp+=number;
+ if (uiBoolOp>=MRD)
+ {
+ uiBoolOp-=MRD;
+ ++uiMrdBO;
+ }
+}
+
+void ExpenseModule::AddOperations(unsigned int IntAdd, unsigned int IntMul, unsigned int DoubleAdd, unsigned int DoubleMul, unsigned int Assigns, unsigned int BoolOp)
+{
+ this->AddIntAdditons(IntAdd);
+ this->AddIntMultiplications(IntMul);
+ this->AddDoubleAdditons(DoubleAdd);
+ this->AddDoubleMultiplications(DoubleMul);
+ this->AddAssignments(Assigns);
+ this->AddBoolOperations(BoolOp);
+}
+
+void ExpenseModule::PrintfSelf(FILE* file)
+{
+ fprintf(file,"\n***********\n Module: %s\n Additions:\n Double: %3.0d%9d\tInteger: %3.0d%9d",chModuleName,uiMrdDA,uiDoubleAdditions,uiMrdIA,uiIntAdditions);
+ fprintf(file,"\n\n Multiplications:\n Double: %3.0d%9d\tInteger: %3.0d%9d\n",uiMrdDM,uiDoubleMultiplications,uiMrdIM,uiIntMultiplications);
+ fprintf(file,"\n Assignments: %3.0d%9d\tBool Operations: %3.0d%9d\n",uiMrdAssign,uiAssignments,uiMrdBO,uiBoolOp);
+ fprintf(file,"\n***********\n");
+}
+
+
+
+
+/***********************************************************************************************************************/
+
+ExpenseLog::ExpenseLog(void)
+{
+}
+
+ExpenseLog::~ExpenseLog(void)
+{
+ for (size_t i=0; i<vModules.size(); ++i)
+ {
+ delete vModules.at(i);
+ vModules.at(i)=NULL;
+ }
+ vModules.clear();
+}
+
+ExpenseModule* ExpenseLog::AddModule(const char* name)
+{
+ ExpenseModule* newModule = new ExpenseModule(name);
+ vModules.push_back(newModule);
+ return newModule;
+}
+
+void ExpenseLog::PrintAll(FILE *file)
+{
+ double totalAdd=0,totalMul=0,totalBool=0,totalAssign=0;
+ fprintf(stderr,"\n ----------------\n Expense Log PrintOut\n Nr of Modules: %d\n",vModules.size());
+ for (size_t i=0; i<vModules.size(); ++i)
+ {
+ totalAdd+=((double)vModules.at(i)->uiIntAdditions+(double)vModules.at(i)->uiDoubleAdditions) + 1e9*((double)vModules.at(i)->uiMrdIA+(double)vModules.at(i)->uiMrdIA);
+ totalMul+=((double)vModules.at(i)->uiIntMultiplications+(double)vModules.at(i)->uiDoubleMultiplications) + 1e9*(double)(vModules.at(i)->uiMrdIM+vModules.at(i)->uiMrdIM);
+ totalBool+=(double)vModules.at(i)->uiBoolOp + 1e9*(double)vModules.at(i)->uiMrdBO;
+ totalAssign+=(double)vModules.at(i)->uiAssignments + 1e9*(double)vModules.at(i)->uiMrdAssign;
+ vModules.at(i)->PrintfSelf(file);
+ }
+ fprintf(stderr," Total:\n Additions: %e Multiplications: %e\n Bool Operations: %e Assignments: %e\n",totalAdd,totalMul,totalBool,totalAssign);
+ fprintf(stderr,"\n ----------------\n");
+}
+
+void ExpenseLog::ClearAll()
+{
+ for (size_t i=0; i<vModules.size(); ++i)
+ {
+ vModules.at(i)->Clear();
+ }
+}
+
diff --git a/openEMS/tools/ExpenseLog.h b/openEMS/tools/ExpenseLog.h
new file mode 100644
index 0000000..f8cc1ba
--- /dev/null
+++ b/openEMS/tools/ExpenseLog.h
@@ -0,0 +1,92 @@
+#pragma once
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+
+using namespace std;
+
+#define EXPENSE_LOG 0
+#define MRD 1000000000
+
+#if EXPENSE_LOG==1
+
+#define EXPENSE_DEFINE \
+ExpenseLog EL; \
+ExpenseModule* EngineExpense=EL.AddModule("Static Engine Expenses"); \
+ExpenseModule* PPExpense=EL.AddModule("Static Post Processing"); \
+ExpenseModule* AdrOpExpense=EL.AddModule("Adress Operator");
+#define EXTERN_EXPENSE_DEFINE extern ExpenseLog EL;
+#define ENGINEEXPENSE_DEFINE extern ExpenseModule* EngineExpense;
+#define POSTPROCEXPENSE_DEFINE extern ExpenseModule* PPExpense;
+#define ADREXPENSE_DEFINE extern ExpenseModule* AdrOpExpense;
+#define ENGINEEXPENSE(IA,IM,DA,DM,AS,BO) EngineExpense->AddOperations((IA),(IM),(DA),(DM),(AS),(BO));
+#define POSTPROCEXPENSE(IA,IM,DA,DM,AS,BO) PPExpense->AddOperations((IA),(IM),(DA),(DM),(AS),(BO));
+#define ADRESSEXPENSE(IA,IM,DA,DM,AS,BO) AdrOpExpense->AddOperations((IA),(IM),(DA),(DM),(AS),(BO));
+#define EXPENSEPRINT EL.PrintAll(stderr);
+#define EXPENSECLEAR EL.ClearAll();
+#else
+
+#define EXPENSE_DEFINE
+#define EXTERN_EXPENSE_DEFINE
+#define ENGINEEXPENSE_DEFINE
+#define POSTPROCEXPENSE_DEFINE
+#define ADREXPENSE_DEFINE
+#define ENGINEEXPENSE(IA,IM,DA,DM,AS,BO)
+#define POSTPROCEXPENSE(IA,IM,DA,DM,AS,BO)
+#define ADRESSEXPENSE(IA,IM,DA,DM,AS,BO)
+#define EXPENSEPRINT
+#define EXPENSECLEAR
+#endif
+
+class ExpenseModule
+{
+ friend class ExpenseLog;
+public:
+ ExpenseModule(const char* moduleName);
+ ~ExpenseModule();
+
+ void Clear();
+
+ void AddDoubleAdditons(unsigned int number);
+ void AddDoubleMultiplications(unsigned int number);
+
+ void AddIntAdditons(unsigned int number);
+ void AddIntMultiplications(unsigned int number);
+
+ void AddAssignments(unsigned int number);
+ void AddBoolOperations(unsigned int number);
+
+ void AddOperations(unsigned int IntAdd, unsigned int IntMul, unsigned int DoubleAdd, unsigned int DoubleMul, unsigned int Assigns, unsigned int BoolOp);
+
+ void PrintfSelf(FILE* file=stdout);
+
+protected:
+ const char* chModuleName;
+ unsigned int uiDoubleAdditions;
+ unsigned int uiDoubleMultiplications;
+ unsigned int uiIntAdditions;
+ unsigned int uiIntMultiplications;
+ unsigned int uiAssignments;
+ unsigned int uiBoolOp;
+ unsigned int uiMrdDA;
+ unsigned int uiMrdDM;
+ unsigned int uiMrdIA;
+ unsigned int uiMrdIM;
+ unsigned int uiMrdAssign;
+ unsigned int uiMrdBO;
+};
+
+class ExpenseLog
+{
+public:
+ ExpenseLog(void);
+ ~ExpenseLog(void);
+
+ ExpenseModule* AddModule(const char* name);
+ void PrintAll(FILE *file=stdout);
+ void ClearAll();
+protected:
+ vector<ExpenseModule*> vModules;
+};
+
+
diff --git a/openEMS/tools/aligned_allocator.h b/openEMS/tools/aligned_allocator.h
new file mode 100644
index 0000000..efabe7d
--- /dev/null
+++ b/openEMS/tools/aligned_allocator.h
@@ -0,0 +1,173 @@
+/*
+* Copyright (C) 2010 Sebastian Held (sebastian.held@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// based on http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-aligned_allocator.aspx
+// from Stephan T. Lavavej
+
+
+// The following headers are required for all allocators.
+#include <stddef.h> // Required for size_t and ptrdiff_t and NULL
+#include <new> // Required for placement new and std::bad_alloc
+#include <stdexcept> // Required for std::length_error
+
+
+#ifdef WIN32
+#define __MSVCRT_VERSION__ 0x0700
+#include <malloc.h>
+#define MEMALIGN( array, alignment, size ) !(*array = _aligned_malloc( size, alignment ))
+#define FREE( array ) _aligned_free( array )
+#else
+#define MEMALIGN( array, alignment, size ) posix_memalign( array, alignment, size )
+#define FREE( array ) free( array )
+#endif
+
+
+template <typename T> class aligned_allocator
+{
+public:
+ // The following will be the same for virtually all allocators.
+ typedef T * pointer;
+ typedef const T * const_pointer;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef T value_type;
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+
+ T * address(T& r) const
+ {
+ return &r;
+ }
+
+ const T * address(const T& s) const
+ {
+ return &s;
+ }
+
+ size_t max_size() const
+ {
+ // The following has been carefully written to be independent of
+ // the definition of size_t and to avoid signed/unsigned warnings.
+ return (static_cast<size_t>(0) - static_cast<size_t>(1)) / sizeof(T);
+ }
+
+ // The following must be the same for all allocators.
+ template <typename U> struct rebind
+ {
+ typedef aligned_allocator<U> other;
+ };
+
+ bool operator!=(const aligned_allocator& other) const
+ {
+ return !(*this == other);
+ }
+
+ void construct(T * const p, const T& t) const
+ {
+ void * const pv = static_cast<void *>(p);
+ new (pv) T(t);
+ }
+
+ void destroy(T * const p) const; // Defined below.
+
+ // Returns true if and only if storage allocated from *this
+ // can be deallocated from other, and vice versa.
+ // Always returns true for stateless allocators.
+ bool operator==(const aligned_allocator& other) const
+ {
+ return true;
+ }
+
+ // Default constructor, copy constructor, rebinding constructor, and destructor.
+ // Empty for stateless allocators.
+ aligned_allocator() { }
+ aligned_allocator(const aligned_allocator&) { }
+ template <typename U> aligned_allocator(const aligned_allocator<U>&) { }
+ ~aligned_allocator() { }
+
+ // The following will be different for each allocator.
+ T * allocate(const size_t n) const
+ {
+// std::cout << "Allocating " << n << (n == 1 ? " object" : "objects") << " of size " << sizeof(T) << "." << std::endl;
+ // The return value of allocate(0) is unspecified.
+ // aligned_allocator returns NULL in order to avoid depending
+ // on malloc(0)'s implementation-defined behavior
+ // (the implementation can define malloc(0) to return NULL,
+ // in which case the bad_alloc check below would fire).
+ // All allocators can return NULL in this case.
+ if (n == 0)
+ {
+ return NULL;
+ }
+
+ // All allocators should contain an integer overflow check.
+ // The Standardization Committee recommends that std::length_error
+ // be thrown in the case of integer overflow.
+ if (n > max_size())
+ {
+ throw std::length_error("aligned_allocator<T>::allocate() - Integer overflow.");
+ }
+
+ // Allocators should throw std::bad_alloc in the case of memory allocation failure.
+ void * pv;
+ if (MEMALIGN( &pv, 16, n * sizeof(T)))
+ throw std::bad_alloc();
+
+ return static_cast<T *>(pv);
+ }
+
+ void deallocate(T * const p, const size_t n) const
+ {
+// std::cout << "Deallocating " << n << (n == 1 ? " object" : "objects") << " of size " << sizeof(T) << "." << std::endl;
+ // aligned_allocator wraps free().
+ UNUSED(n);
+ FREE(p);
+ }
+
+ // The following will be the same for all allocators that ignore hints.
+ template <typename U> T * allocate(const size_t n, const U * /* const hint */) const
+ {
+ return allocate(n);
+ }
+
+ // Allocators are not required to be assignable, so
+ // all allocators should have a private unimplemented
+ // assignment operator. Note that this will trigger the
+ // off-by-default (enabled under /Wall) warning C4626
+ // "assignment operator could not be generated because a
+ // base class assignment operator is inaccessible" within
+ // the STL headers, but that warning is useless.
+
+private:
+ aligned_allocator& operator=(const aligned_allocator&);
+};
+
+// A compiler bug causes it to believe that p->~T() doesn't reference p.
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable: 4100) // unreferenced formal parameter
+#endif
+
+// The definition of destroy() must be the same for all allocators.
+template <typename T> void aligned_allocator<T>::destroy(T * const p) const
+{
+ p->~T();
+}
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
diff --git a/openEMS/tools/array_ops.cpp b/openEMS/tools/array_ops.cpp
new file mode 100644
index 0000000..8710b3c
--- /dev/null
+++ b/openEMS/tools/array_ops.cpp
@@ -0,0 +1,144 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "array_ops.h"
+#include <ostream>
+
+using namespace std;
+
+#ifdef WIN32
+#define __MSVCRT_VERSION__ 0x0700
+#include <malloc.h>
+//(void**)&array, 16, sizeof(typeof(f4vector**))*numLines[0]
+#define MEMALIGN( array, alignment, size ) !(*array = _aligned_malloc( size, alignment ))
+#define FREE( array ) _aligned_free( array )
+#else
+#define MEMALIGN( array, alignment, size ) posix_memalign( array, alignment, size )
+#define FREE( array ) free( array )
+#endif
+
+void Delete1DArray_v4sf(f4vector* array)
+{
+ if (array==NULL) return;
+ FREE( array );
+}
+
+
+void Delete3DArray_v4sf(f4vector*** array, const unsigned int* numLines)
+{
+ if (array==NULL) return;
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ FREE( array[pos[0]][pos[1]] );
+ //delete[] array[pos[0]][pos[1]];
+ }
+ FREE( array[pos[0]] );
+ //delete[] array[pos[0]];
+ }
+ FREE( array );
+ //delete[] array;
+}
+
+void Delete_N_3DArray_v4sf(f4vector**** array, const unsigned int* numLines)
+{
+ if (array==NULL) return;
+ for (int n=0; n<3; ++n)
+ {
+ Delete3DArray_v4sf(array[n],numLines);
+ }
+ FREE( array );
+ //delete[] array;
+}
+
+f4vector* Create1DArray_v4sf(const unsigned int numLines)
+{
+ f4vector* array=NULL;
+ if (MEMALIGN( (void**)&array, 16, sizeof(typeof(f4vector))*numLines ))
+ {
+ cerr << "cannot allocate aligned memory" << endl;
+ exit(3);
+ }
+ for (unsigned int pos=0; pos<numLines; ++pos)
+ {
+ array[pos].f[0] = 0;
+ array[pos].f[1] = 0;
+ array[pos].f[2] = 0;
+ array[pos].f[3] = 0;
+ }
+ return array;
+}
+
+//! \brief this function allocates a 3D array, which is aligned to 16 byte
+f4vector*** Create3DArray_v4sf(const unsigned int* numLines)
+{
+ unsigned int numZ = ceil((double)numLines[2]/4.0);
+
+ f4vector*** array=NULL;
+ unsigned int pos[3];
+ if (MEMALIGN( (void**)&array, 16, sizeof(typeof(f4vector**))*numLines[0] ))
+ {
+ cerr << "cannot allocate aligned memory" << endl;
+ exit(3);
+ }
+ //array = new f4vector**[numLines[0]];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ if (MEMALIGN( (void**)&array[pos[0]], 16, sizeof(typeof(f4vector*))*numLines[1] ))
+ {
+ cerr << "cannot allocate aligned memory" << endl;
+ exit(3);
+ }
+ //array[pos[0]] = new f4vector*[numLines[1]];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ if (MEMALIGN( (void**)&array[pos[0]][pos[1]], 16, sizeof(typeof(f4vector))*numZ ))
+ {
+ cerr << "cannot allocate aligned memory" << endl;
+ exit(3);
+ }
+ //array[pos[0]][pos[1]] = new f4vector[numZ];
+ for (pos[2]=0; pos[2]<numZ; ++pos[2])
+ {
+ array[pos[0]][pos[1]][pos[2]].f[0] = 0;
+ array[pos[0]][pos[1]][pos[2]].f[1] = 0;
+ array[pos[0]][pos[1]][pos[2]].f[2] = 0;
+ array[pos[0]][pos[1]][pos[2]].f[3] = 0;
+ }
+ }
+ }
+ return array;
+}
+
+f4vector**** Create_N_3DArray_v4sf(const unsigned int* numLines)
+{
+ f4vector**** array=NULL;
+ if (MEMALIGN( (void**)&array, 16, sizeof(typeof(f4vector***))*3 ))
+ {
+ cerr << "cannot allocate aligned memory" << endl;
+ exit(3);
+ }
+ //array = new f4vector***[3];
+ for (int n=0; n<3; ++n)
+ {
+ array[n]=Create3DArray_v4sf(numLines);
+ }
+ return array;
+}
+
diff --git a/openEMS/tools/array_ops.h b/openEMS/tools/array_ops.h
new file mode 100644
index 0000000..5c2fd7f
--- /dev/null
+++ b/openEMS/tools/array_ops.h
@@ -0,0 +1,196 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ARRAY_OPS_H
+#define ARRAY_OPS_H
+
+#ifdef __SIZEOF_FLOAT__
+#if __SIZEOF_FLOAT__ != 4
+#error wrong size of float
+#endif
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <iostream>
+#include <string>
+#include <math.h>
+#include "constants.h"
+
+typedef float v4sf __attribute__ ((vector_size (16))); // vector of four single floats
+typedef int v4si __attribute__ ((vector_size (4*sizeof(int)))); // vector of four single ints
+
+union f4vector
+{
+ v4sf v;
+ float f[4];
+};
+
+void Delete1DArray_v4sf(f4vector* array);
+void Delete3DArray_v4sf(f4vector*** array, const unsigned int* numLines);
+void Delete_N_3DArray_v4sf(f4vector**** array, const unsigned int* numLines);
+f4vector* Create1DArray_v4sf(const unsigned int numLines);
+f4vector*** Create3DArray_v4sf(const unsigned int* numLines);
+f4vector**** Create_N_3DArray_v4sf(const unsigned int* numLines);
+
+// *************************************************************************************
+// templates
+// *************************************************************************************
+template <typename T>
+T** Create2DArray(const unsigned int* numLines)
+{
+ T** array=NULL;
+ unsigned int pos[3];
+ array = new T*[numLines[0]];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ array[pos[0]] = new T[numLines[1]];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ array[pos[0]][pos[1]] = 0;
+ }
+ }
+ return array;
+}
+
+template <typename T>
+void Delete2DArray(T** array, const unsigned int* numLines)
+{
+ if (array==NULL) return;
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ delete[] array[pos[0]];
+ }
+ delete[] array;
+}
+
+template <typename T>
+inline T& Access_N_3DArray(T**** array, unsigned int n, unsigned int* pos)
+{
+ return array[n][pos[0]][pos[1]][pos[2]];
+}
+
+template <typename T>
+inline T& Access_N_3DArray(T**** array, unsigned int n, unsigned int x, unsigned int y, unsigned int z )
+{
+ return array[n][x][y][z];
+}
+
+template <typename T>
+T*** Create3DArray(const unsigned int* numLines)
+{
+ T*** array=NULL;
+ unsigned int pos[3];
+ array = new T**[numLines[0]];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ array[pos[0]] = new T*[numLines[1]];
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ array[pos[0]][pos[1]] = new T[numLines[2]];
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ array[pos[0]][pos[1]][pos[2]] = 0;
+ }
+ }
+ }
+ return array;
+}
+
+template <typename T>
+T*** Copy3DArray(T*** array_in, T*** array_out, const unsigned int* numLines)
+{
+ if (array_out==NULL)
+ array_out = Create3DArray<T>(numLines);
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ array_out[pos[0]][pos[1]][pos[2]] = array_in[pos[0]][pos[1]][pos[2]];
+ return array_out;
+}
+
+template <typename T>
+T**** Create_N_3DArray(const unsigned int* numLines)
+{
+ T**** array=NULL;
+ array = new T***[3];
+ for (int n=0; n<3; ++n)
+ {
+ array[n]=Create3DArray<T>( numLines );
+ }
+ return array;
+}
+
+template <typename T>
+T**** Copy_N_3DArray(T**** array_in, T**** array_out, const unsigned int* numLines)
+{
+ if (array_out==NULL)
+ array_out = Create_N_3DArray<T>(numLines);
+ for (int n=0; n<3; ++n)
+ array_out[n]=Copy3DArray<T>( array_in[n], array_out[n], numLines);
+ return array_out;
+}
+
+template <typename T>
+void Delete3DArray(T*** array, const unsigned int* numLines)
+{
+ if (!array) return;
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ delete[] array[pos[0]][pos[1]];
+ }
+ delete[] array[pos[0]];
+ }
+ delete[] array;
+}
+
+template <typename T>
+void Delete_N_3DArray(T**** array, const unsigned int* numLines)
+{
+ if (!array) return;
+ for (int n=0; n<3; ++n)
+ {
+ Delete3DArray<T>(array[n],numLines);
+ }
+ delete[] array;
+}
+
+template <typename T>
+void Dump_N_3DArray2File(std::ostream &file, T**** array, const unsigned int* numLines)
+{
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<numLines[2]; ++pos[2])
+ {
+ file << pos[0] << "\t" << pos[1] << "\t" << pos[2];
+ for (int n=0; n<3; ++n)
+ file << "\t" << (float)array[n][pos[0]][pos[1]][pos[2]];
+ file << std::endl;
+ }
+ }
+ }
+}
+
+#endif // ARRAY_OPS_H
diff --git a/openEMS/tools/constants.h b/openEMS/tools/constants.h
new file mode 100644
index 0000000..9707fdf
--- /dev/null
+++ b/openEMS/tools/constants.h
@@ -0,0 +1,29 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef CONSTANTS_H
+#define CONSTANTS_H
+
+#define FDTD_FLOAT float
+
+#define __EPS0__ 8.85418781762e-12
+#define __MUE0__ 1.256637062e-6
+#define __C0__ 299792458
+#define __Z0__ 376.730313461
+#define PI 3.141592653589793238462643383279
+
+#endif // CONSTANTS_H
diff --git a/openEMS/tools/global.cpp b/openEMS/tools/global.cpp
new file mode 100644
index 0000000..3e97fac
--- /dev/null
+++ b/openEMS/tools/global.cpp
@@ -0,0 +1,78 @@
+/*
+* Copyright (C) 2010 Sebastian Held <sebastian.held@gmx.de>
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <cstring>
+#include <iostream>
+#include "global.h"
+
+using namespace std;
+
+// create global object
+Global g_settings;
+
+Global::Global()
+{
+ m_showProbeDiscretization = false;
+ m_nativeFieldDumps = false;
+ m_VerboseLevel = 0;
+}
+
+void Global::ShowArguments(ostream& ostr, string front)
+{
+ ostr << front << "--showProbeDiscretization\tShow probe discretization information" << endl;
+ ostr << front << "--nativeFieldDumps\t\tDump all fields using the native field components" << endl;
+ ostr << front << "-v,-vv,-vvv\t\t\tSet debug level: 1 to 3" << endl;
+}
+
+//! \brief This function initializes the object
+bool Global::parseCommandLineArgument( const char *argv )
+{
+ if (!argv)
+ return false;
+
+ if (strcmp(argv,"--showProbeDiscretization")==0)
+ {
+ cout << "openEMS - showing probe discretization information" << endl;
+ m_showProbeDiscretization = true;
+ return true;
+ }
+ else if (strcmp(argv,"--nativeFieldDumps")==0)
+ {
+ cout << "openEMS - dumping all fields using the native field components" << endl;
+ m_nativeFieldDumps = true;
+ return true;
+ }
+ else if (strcmp(argv,"-v")==0)
+ {
+ cout << "openEMS - verbose level 1" << endl;
+ m_VerboseLevel = 1;
+ return true;
+ }
+ else if (strcmp(argv,"-vv")==0)
+ {
+ cout << "openEMS - verbose level 2" << endl;
+ m_VerboseLevel = 2;
+ return true;
+ }
+ else if (strcmp(argv,"-vvv")==0)
+ {
+ cout << "openEMS - verbose level 3" << endl;
+ m_VerboseLevel = 3;
+ return true;
+ }
+ return false;
+}
diff --git a/openEMS/tools/global.h b/openEMS/tools/global.h
new file mode 100644
index 0000000..c3bb524
--- /dev/null
+++ b/openEMS/tools/global.h
@@ -0,0 +1,65 @@
+/*
+* Copyright (C) 2010 Sebastian Held <sebastian.held@gmx.de>
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef GLOBAL_H
+#define GLOBAL_H
+
+#include <sstream>
+
+#define UNUSED(x) (void)(x);
+
+class Global
+{
+public:
+ Global();
+
+ //! Show all possible (global) command line arguments
+ void ShowArguments(std::ostream& ostr, std::string front=std::string());
+
+ //! Parse the given command line arguments
+ bool parseCommandLineArgument( const char *argv );
+
+ bool showProbeDiscretization() const {return m_showProbeDiscretization;}
+
+ //! Returns true if native field dumps are requested...
+ bool NativeFieldDumps() const {return m_nativeFieldDumps;}
+ //! Set dumps to use native fields.
+ void SetNativeFieldDumps(bool val) {m_nativeFieldDumps=val;}
+
+ //! Set the verbose level
+ void SetVerboseLevel(int level) {m_VerboseLevel=level;m_SavedVerboseLevel=level;}
+ //! Get the verbose level
+ int GetVerboseLevel() const {return m_VerboseLevel;}
+
+ //! Set a new verbose level temporarily, restore it with RestoreVerboseLevel()
+ void SetTempVerboseLevel(int level) {m_SavedVerboseLevel=m_VerboseLevel;m_VerboseLevel=level;}
+ //! Restore the temporarily overwritten verbose level
+ void RestoreVerboseLevel() {m_VerboseLevel=m_SavedVerboseLevel;}
+
+protected:
+ bool m_showProbeDiscretization;
+ bool m_nativeFieldDumps;
+ int m_VerboseLevel;
+ int m_SavedVerboseLevel;
+};
+
+extern Global g_settings;
+
+// declare a parameter as unused
+#define UNUSED(x) (void)(x);
+
+#endif // GLOBAL_H
diff --git a/openEMS/tools/hdf5_file_reader.cpp b/openEMS/tools/hdf5_file_reader.cpp
new file mode 100644
index 0000000..5e81614
--- /dev/null
+++ b/openEMS/tools/hdf5_file_reader.cpp
@@ -0,0 +1,689 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "hdf5_file_reader.h"
+#include "../tools/array_ops.h"
+#include <hdf5.h>
+
+#include <sstream>
+#include <iostream>
+#include <iomanip>
+
+using namespace std;
+
+HDF5_File_Reader::HDF5_File_Reader(string filename)
+{
+ m_filename = filename;
+ //suppress hdf5 error output
+ //H5Eset_auto(NULL, NULL);
+}
+
+HDF5_File_Reader::~HDF5_File_Reader()
+{
+}
+
+bool HDF5_File_Reader::IsValid()
+{
+ htri_t val = H5Fis_hdf5(m_filename.c_str());
+ if (val<0)
+ {
+ cerr << "HDF5_File_Reader::IsValid: the given file """ << m_filename << """ is not accessible..." << endl;
+ return false;
+ }
+ if (val==0)
+ {
+ cerr << "HDF5_File_Reader::IsValid: the given file """ << m_filename << """ is invalid..." << endl;
+ return false;
+ }
+ if (val==0)
+ cerr << "HDF5_File_Reader::IsValid: the given file """ << m_filename << """ is valid..." << endl;
+ return true;
+}
+
+bool HDF5_File_Reader::OpenGroup(hid_t &file, hid_t &group, string groupName)
+{
+ file = H5Fopen( m_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT );
+ if (file==-1)
+ {
+ cerr << "HDF5_File_Reader::OpenGroup: opening the given file """ << m_filename << """ failed" << endl;
+ return 0;
+ }
+ if (H5Lexists(file, groupName.c_str(), H5P_DEFAULT)<=0)
+ {
+ H5Fclose(file);
+ return 0;
+ }
+
+ group = H5Gopen(file, groupName.c_str() );
+ if (group<0)
+ {
+ cerr << "HDF5_File_Reader::OpenGroup: can't open group """ << groupName << """" << endl;
+ H5Fclose(file);
+ return 0;
+ }
+ return true;
+}
+
+bool HDF5_File_Reader::ReadAttribute(string grp_name, string attr_name, vector<float> &attr_values)
+{
+ vector<double> d_attr_values;
+ if (ReadAttribute(grp_name, attr_name, d_attr_values)==false)
+ return false;
+ attr_values.resize(d_attr_values.size(),0);
+ for (size_t n=0;n<d_attr_values.size();++n)
+ attr_values.at(n)=d_attr_values.at(n);
+ return true;
+}
+
+bool HDF5_File_Reader::ReadAttribute(string grp_name, string attr_name, vector<double> &attr_values)
+{
+ attr_values.clear();
+
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT );
+ if (hdf5_file==-1)
+ {
+ cerr << "HDF5_File_Reader::OpenGroup: opening the given file """ << m_filename << """ failed" << endl;
+ return 0;
+ }
+
+ if (H5Lexists(hdf5_file, grp_name.c_str(), H5P_DEFAULT)<=0)
+ {
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ hid_t attr = H5Aopen_by_name(hdf5_file, grp_name.c_str(), attr_name.c_str(), H5P_DEFAULT, H5P_DEFAULT);
+ if (attr==-1)
+ {
+ cerr << "HDF5_File_Reader::ReadAttribute: Opening the given Attribute: """ << attr_name << """ failed" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ hid_t type = H5Aget_type(attr);
+ if (type<0)
+ {
+ cerr << "HDF5_File_Reader::ReadAttribute: Dataset type error" << endl;
+ H5Aclose(attr);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ attr_values.clear();
+ if (H5Tget_class(type)==H5T_FLOAT)
+ {
+ size_t numVal = H5Aget_storage_size(attr)/H5Tget_size(type);
+ hid_t datatype=-1;
+ void *value=NULL;
+ float *f_value=NULL;
+ double *d_value=NULL;
+ if (H5Tget_size(type)==sizeof(float))
+ {
+ f_value = new float[numVal];
+ value = f_value;
+ datatype = H5T_NATIVE_FLOAT;
+ }
+ if (H5Tget_size(type)==sizeof(double))
+ {
+ d_value = new double[numVal];
+ value = d_value;
+ datatype = H5T_NATIVE_DOUBLE;
+ }
+ if (H5Aread(attr, datatype, value)<0)
+ {
+ cerr << "HDF5_File_Reader::ReadAttribute: Reading the given Attribute failed" << endl;
+ H5Aclose(attr);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ if (f_value)
+ for (size_t n=0;n<numVal;++n)
+ attr_values.push_back(f_value[n]);
+ if (d_value)
+ for (size_t n=0;n<numVal;++n)
+ attr_values.push_back(d_value[n]);
+ delete[] f_value;
+ delete[] d_value;
+ }
+ else
+ {
+ cerr << "HDF5_File_Reader::ReadAttribute: Attribute type not supported" << endl;
+ H5Aclose(attr);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ H5Aclose(attr);
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+bool HDF5_File_Reader::ReadDataSet(string ds_name, hsize_t &nDim, hsize_t* &dims, float* &data)
+{
+ double* d_data;
+ if (ReadDataSet(ds_name, nDim, dims, d_data)==false)
+ return false;
+ hsize_t data_size = 1;
+ for (unsigned int d=0;d<nDim;++d)
+ data_size*=dims[d];
+ data = new float[data_size];
+ for (size_t n=0;n<data_size;++n)
+ data[n]=d_data[n];
+ delete[] d_data;
+ return true;
+}
+
+bool HDF5_File_Reader::ReadDataSet(string ds_name, hsize_t &nDim, hsize_t* &dims, double* &data)
+{
+ if (IsValid()==false)
+ return false;
+
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT );
+ if (hdf5_file==-1)
+ {
+ cerr << "HDF5_File_Reader::ReadDataSet: opening the given file """ << m_filename << """ failed" << endl;
+ return false;
+ }
+
+ hid_t dataset = H5Dopen(hdf5_file, ds_name.c_str() );
+ if (dataset<0)
+ {
+ cerr << "HDF5_File_Reader::ReadDataSet: dataset not found" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ hid_t type = H5Dget_type(dataset);
+ if (type<0)
+ {
+ cerr << "HDF5_File_Reader::ReadDataSet: dataset type error" << endl;
+ H5Dclose(dataset);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ if (H5Tget_class(type)!=H5T_FLOAT)
+ {
+ cerr << "HDF5_File_Reader::ReadDataSet: dataset type not a float" << endl;
+ H5Dclose(dataset);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ hid_t space = H5Dget_space(dataset);
+ nDim = H5Sget_simple_extent_ndims(space);
+ dims = new hsize_t[nDim];
+ H5Sget_simple_extent_dims(space, dims, NULL );
+ hsize_t data_size = 1;
+ for (unsigned int d=0;d<nDim;++d)
+ data_size*=dims[d];
+
+ void *value=NULL;
+ float *f_value=NULL;
+ data = new double[data_size];
+ if (H5Tget_size(type)==sizeof(float))
+ {
+ f_value = new float[data_size];
+ value = f_value;
+ }
+ else
+ value = data;
+
+ if (H5Dread(dataset,type,H5S_ALL,H5S_ALL,H5P_DEFAULT,value)<0)
+ {
+ cerr << "HDF5_File_Reader::ReadDataSet: error reading data" << endl;
+ H5Dclose(dataset);
+ H5Fclose(hdf5_file);
+ delete[] data;
+ delete[] f_value;
+ data=NULL;
+ return false;
+ }
+ if (f_value)
+ for (size_t n=0;n<data_size;++n)
+ data[n]=f_value[n];
+ delete[] f_value;
+ H5Dclose(dataset);
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+bool HDF5_File_Reader::ReadMesh(float** lines, unsigned int* numLines, int &meshType)
+{
+ if (IsValid()==false)
+ return false;
+
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT );
+ if (hdf5_file==-1)
+ {
+ cerr << "HDF5_File_Reader::ReadMesh: opening the given file """ << m_filename << """ failed" << endl;
+ return false;
+ }
+
+ vector<string> Mesh_Names;
+ if (H5Lexists(hdf5_file, "/Mesh/x", H5P_DEFAULT) && H5Lexists(hdf5_file, "/Mesh/y", H5P_DEFAULT) && H5Lexists(hdf5_file, "/Mesh/z", H5P_DEFAULT))
+ {
+ meshType = 0;
+ Mesh_Names.push_back("/Mesh/x");
+ Mesh_Names.push_back("/Mesh/y");
+ Mesh_Names.push_back("/Mesh/z");
+ }
+ else if (H5Lexists(hdf5_file, "/Mesh/rho", H5P_DEFAULT) && H5Lexists(hdf5_file, "/Mesh/alpha", H5P_DEFAULT) && H5Lexists(hdf5_file, "/Mesh/z", H5P_DEFAULT))
+ {
+ meshType = 1;
+ Mesh_Names.push_back("/Mesh/rho");
+ Mesh_Names.push_back("/Mesh/alpha");
+ Mesh_Names.push_back("/Mesh/z");
+ }
+ else
+ {
+ cerr << "HDF5_File_Reader::ReadMesh: no falid mesh information found" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ for (int n=0;n<3;++n)
+ {
+ hsize_t nDim;
+ hsize_t* dims=NULL;
+ float* data=NULL;
+ ReadDataSet(Mesh_Names.at(n), nDim, dims, data);
+ if (nDim!=1)
+ {
+ cerr << "HDF5_File_Reader::ReadMesh: mesh dimension error" << endl;
+ delete[] dims;
+ delete[] data;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ numLines[n]=dims[0];
+ delete[] dims;
+ lines[n]=data;
+ }
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+unsigned int HDF5_File_Reader::GetNumTimeSteps()
+{
+ if (IsValid()==false)
+ return false;
+
+ hid_t hdf5_file;
+ hid_t TD_grp;
+ if (OpenGroup(hdf5_file, TD_grp, "/FieldData/TD")==false)
+ return false;
+
+ hsize_t numObj;
+ if (H5Gget_num_objs(TD_grp,&numObj)<0)
+ {
+ cerr << "HDF5_File_Reader::GetNumTimeSteps: can't read number of datasets" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return 0;
+ }
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return numObj;
+}
+
+bool HDF5_File_Reader::ReadTimeSteps(vector<unsigned int> &timestep, vector<string> &names)
+{
+ if (IsValid()==false)
+ return false;
+
+ hid_t hdf5_file;
+ hid_t TD_grp;
+ if (OpenGroup(hdf5_file, TD_grp, "/FieldData/TD")==false)
+ return false;
+
+ hsize_t numObj;
+ if (H5Gget_num_objs(TD_grp,&numObj)<0)
+ {
+ cerr << "HDF5_File_Reader::ReadTimeSteps: can't read number of datasets" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ char name[100];
+ timestep.clear();
+ timestep.resize(numObj,0);
+ names.clear();
+ names.resize(numObj);
+ for (hsize_t n=0;n<numObj;++n)
+ {
+ if (H5Gget_objtype_by_idx(TD_grp, n) != H5G_DATASET)
+ {
+ cerr << "HDF5_File_Reader::ReadTimeSteps: invalid timestep found!" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ H5Gget_objname_by_idx(TD_grp, n, name, 100 );
+ istringstream is(name);
+ unsigned int num;
+ if (is >> num)
+ {
+ timestep.at(n)=num;
+ names.at(n)=name;
+ }
+ else
+ {
+ cerr << "HDF5_File_Reader::ReadTimeSteps: invalid timestep format found!" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ }
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+float**** HDF5_File_Reader::GetTDVectorData(size_t idx, float &time, unsigned int data_size[])
+{
+ if (IsValid()==false)
+ return NULL;
+
+ hid_t hdf5_file;
+ hid_t TD_grp;
+ if (OpenGroup(hdf5_file, TD_grp, "/FieldData/TD")==false)
+ return NULL;
+
+ hsize_t numObj;
+ if (H5Gget_num_objs(TD_grp,&numObj)<0)
+ {
+ cerr << "HDF5_File_Reader::GetTDVectorData: can't read number of datasets" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+ if (idx>=numObj)
+ {
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+
+ if (H5Gget_objtype_by_idx(TD_grp, idx) != H5G_DATASET)
+ {
+ cerr << "HDF5_File_Reader::GetTDVectorData: invalid timestep found!" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+
+ char name[100];
+ H5Gget_objname_by_idx(TD_grp, idx, name, 100 );
+ string ds_name = "/FieldData/TD/" + string(name);
+
+ hid_t attr = H5Aopen_by_name(hdf5_file, ds_name.c_str(), "time", H5P_DEFAULT, H5P_DEFAULT);
+ if (attr<0)
+ {
+ cerr << "HDF5_File_Reader::GetTDVectorData: time attribute not found!" << endl;
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+ if (H5Aread(attr, H5T_NATIVE_FLOAT, &time)<0)
+ {
+ cerr << "HDF5_File_Reader::GetTDVectorData: can't read time attribute!" << endl;
+ H5Aclose(attr);
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+
+ hsize_t nDim;
+ hsize_t* dims=NULL;
+ double* data=NULL;
+ ReadDataSet(ds_name, nDim, dims, data);
+ if (nDim!=4)
+ {
+ cerr << "HDF5_File_Reader::GetTDVectorData: data dimension invalid" << endl;
+ delete[] dims;
+ H5Aclose(attr);
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+ if (dims[0]!=3)
+ {
+ cerr << "HDF5_File_Reader::GetTDVectorData: vector data dimension invalid" << endl;
+ delete[] dims;
+ H5Aclose(attr);
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return NULL;
+ }
+ data_size[0]=dims[3];
+ data_size[1]=dims[2];
+ data_size[2]=dims[1];
+ delete[] dims;
+ data_size[3]=3;
+ size_t pos = 0;
+ float**** field = Create_N_3DArray<float>(data_size);
+ for (unsigned int d=0;d<3;++d)
+ for (unsigned int k=0;k<data_size[2];++k)
+ for (unsigned int j=0;j<data_size[1];++j)
+ for (unsigned int i=0;i<data_size[0];++i)
+ {
+ field[d][i][j][k]=data[pos++];
+ }
+ delete[] data;
+ H5Aclose(attr);
+ H5Gclose(TD_grp);
+ H5Fclose(hdf5_file);
+ return field;
+}
+
+unsigned int HDF5_File_Reader::GetNumFrequencies()
+{
+ vector<float> frequencies;
+ if (ReadFrequencies(frequencies)==false)
+ return 0;
+ return frequencies.size();
+}
+
+bool HDF5_File_Reader::ReadFrequencies(vector<float> &frequencies)
+{
+ if (IsValid()==false)
+ return false;
+
+ return ReadAttribute("/FieldData/FD","frequency",frequencies);
+}
+
+bool HDF5_File_Reader::ReadFrequencies(vector<double> &frequencies)
+{
+ if (IsValid()==false)
+ return false;
+
+ return ReadAttribute("/FieldData/FD","frequency",frequencies);
+}
+
+
+complex<float>**** HDF5_File_Reader::GetFDVectorData(size_t idx, unsigned int data_size[])
+{
+ hsize_t nDim;
+ hsize_t* dims=NULL;
+ double* data=NULL;
+ stringstream ds_name;
+
+ // read real values
+ ds_name << "/FieldData/FD/f" << idx << "_real";
+ if (ReadDataSet(ds_name.str(), nDim, dims, data) == false)
+ return NULL;
+ if (nDim!=4)
+ {
+ cerr << "HDF5_File_Reader::GetFDVectorData: data dimension invalid" << endl;
+ delete[] dims;
+ delete[] data;
+ return NULL;
+ }
+ if (dims[0]!=3)
+ {
+ cerr << "HDF5_File_Reader::GetFDVectorData: vector data dimension invalid" << endl;
+ delete[] dims;
+ delete[] data;
+ return NULL;
+ }
+ data_size[0]=dims[3];
+ data_size[1]=dims[2];
+ data_size[2]=dims[1];
+ delete[] dims;
+ data_size[3]=3;
+ size_t pos = 0;
+ complex<float>**** field = Create_N_3DArray<complex<float> >(data_size);
+ for (unsigned int d=0;d<3;++d)
+ for (unsigned int k=0;k<data_size[2];++k)
+ for (unsigned int j=0;j<data_size[1];++j)
+ for (unsigned int i=0;i<data_size[0];++i)
+ {
+ field[d][i][j][k]=data[pos++];
+ }
+ delete[] data;
+
+ // read imaginary values
+ ds_name.str("");
+ ds_name << "/FieldData/FD/f" << idx << "_imag";
+ if (ReadDataSet(ds_name.str(), nDim, dims, data) == false)
+ {
+ Delete_N_3DArray<complex<float> >(field, data_size);
+ return NULL;
+ }
+ if (nDim!=4)
+ {
+ cerr << "HDF5_File_Reader::GetFDVectorData: data dimension invalid" << endl;
+ delete[] dims;
+ delete[] data;
+ Delete_N_3DArray<complex<float> >(field, data_size);
+ return NULL;
+ }
+ if (dims[0]!=3)
+ {
+ cerr << "HDF5_File_Reader::GetFDVectorData: vector data dimension invalid" << endl;
+ delete[] dims;
+ delete[] data;
+ Delete_N_3DArray<complex<float> >(field, data_size);
+ return NULL;
+ }
+ if ((data_size[0]!=dims[3]) || (data_size[1]!=dims[2]) || (data_size[2]!=dims[1]))
+ {
+ cerr << "HDF5_File_Reader::GetFDVectorData: data dimension mismatch" << endl;
+ delete[] dims;
+ delete[] data;
+ Delete_N_3DArray<complex<float> >(field, data_size);
+ return NULL;
+ }
+ delete[] dims;
+
+ pos = 0;
+ complex<double> I(0,1);
+ for (unsigned int d=0;d<3;++d)
+ for (unsigned int k=0;k<data_size[2];++k)
+ for (unsigned int j=0;j<data_size[1];++j)
+ for (unsigned int i=0;i<data_size[0];++i)
+ {
+ field[d][i][j][k]+= I*data[pos++];
+ }
+ delete[] data;
+
+ return field;
+}
+
+bool HDF5_File_Reader::CalcFDVectorData(vector<float> &frequencies, vector<complex<float>****> &FD_data, unsigned int data_size[4])
+{
+ FD_data.clear();
+
+ if (GetNumTimeSteps()<=0)
+ {
+ cerr << "HDF5_File_Reader::CalcFDVectorData: error, no TD data found..." << endl;
+ return false;
+ }
+
+ float time;
+ //read first TD data
+ float**** field = this->GetTDVectorData(0,time,data_size);
+ if (field==NULL)
+ {
+ cerr << "HDF5_File_Reader::CalcFDVectorData: error, no TD data found..." << endl;
+ return false;
+ }
+
+ //init
+ FD_data.resize(frequencies.size(), NULL);
+ for (size_t fn=0;fn<frequencies.size();++fn)
+ FD_data.at(fn) = Create_N_3DArray<complex<float> >(data_size);
+
+ size_t ts=0;
+ unsigned int pos[3];
+ complex<float> PI_2_I(0.0,-2.0*M_PI);
+ complex<float> exp_jwt_2_dt;
+ float time_diff=0;
+ float time_old =0;
+ complex<float>**** field_fd = NULL;
+ while (field)
+ {
+ if ((ts>1) && abs(time_diff - (time - time_old))>1e15)
+ {
+ cerr << "HDF5_File_Reader::CalcFDVectorData: time interval error..." << endl;
+ for (size_t fn=0;fn<frequencies.size();++fn)
+ Delete_N_3DArray(FD_data.at(fn),data_size);
+ FD_data.clear();
+ return false;
+ }
+ time_diff = time - time_old;
+ for (size_t fn=0;fn<frequencies.size();++fn)
+ {
+ exp_jwt_2_dt = exp( (complex<float>)(PI_2_I * frequencies.at(fn) * time) );
+ field_fd = FD_data.at(fn);
+ for (pos[0]=0; pos[0]<data_size[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<data_size[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<data_size[2]; ++pos[2])
+ {
+ field_fd[0][pos[0]][pos[1]][pos[2]] += field[0][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[1][pos[0]][pos[1]][pos[2]] += field[1][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ field_fd[2][pos[0]][pos[1]][pos[2]] += field[2][pos[0]][pos[1]][pos[2]] * exp_jwt_2_dt;
+ }
+ }
+ }
+ }
+ ++ts;
+ Delete_N_3DArray(field,data_size);
+ time_old = time;
+ field = this->GetTDVectorData(ts,time,data_size);
+ }
+
+ // finalize data
+ time_diff*=2;
+ for (size_t fn=0;fn<frequencies.size();++fn)
+ {
+ field_fd = FD_data.at(fn);
+ for (pos[0]=0; pos[0]<data_size[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<data_size[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<data_size[2]; ++pos[2])
+ {
+ field_fd[0][pos[0]][pos[1]][pos[2]] *= time_diff;
+ field_fd[1][pos[0]][pos[1]][pos[2]] *= time_diff;
+ field_fd[2][pos[0]][pos[1]][pos[2]] *= time_diff;
+ }
+ }
+ }
+ }
+ return true;
+}
diff --git a/openEMS/tools/hdf5_file_reader.h b/openEMS/tools/hdf5_file_reader.h
new file mode 100644
index 0000000..f190240
--- /dev/null
+++ b/openEMS/tools/hdf5_file_reader.h
@@ -0,0 +1,78 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef HDF5_FILE_READER_H
+#define HDF5_FILE_READER_H
+
+#include <string>
+#include <vector>
+#include <complex>
+#include <hdf5.h>
+
+class HDF5_File_Reader
+{
+public:
+ HDF5_File_Reader(std::string filename);
+ virtual ~HDF5_File_Reader();
+
+ bool ReadMesh(float** lines, unsigned int* numLines, int &meshType);
+
+ //! Get the number of timesteps stored at /FieldData/TD/<NUMBER_OF_TS>
+ unsigned int GetNumTimeSteps();
+ bool ReadTimeSteps(std::vector<unsigned int> &timestep, std::vector<std::string> &names);
+
+ /*!
+ Get time-domain data stored at /FieldData/TD/<NUMBER_OF_TS>
+ \param[in] idx time step index to extract
+ \param[out] time time attribute for the given timestep
+ \param[out] data_size data size found
+ \return field data found in given timestep, caller must delete array, returns NULL if timestep was not found
+ */
+ float**** GetTDVectorData(size_t idx, float &time, unsigned int data_size[4]);
+
+ unsigned int GetNumFrequencies();
+ bool ReadFrequencies(std::vector<float> &frequencies);
+ bool ReadFrequencies(std::vector<double> &frequencies);
+
+ /*!
+ Get frequency-domain data stored at "/FieldData/FD/f<idx>_real" and "/FieldData/FD/f<idx>_imag"
+ \param[in] idx frequency index to extract
+ \param[out] data_size data size found
+ \return complex field data found for the given frequency, caller must delete array, returns NULL if frequency was not found
+ */
+ std::complex<float>**** GetFDVectorData(size_t idx, unsigned int data_size[4]);
+
+ /*!
+ Calculate
+ */
+ bool CalcFDVectorData(std::vector<float> &frequencies, std::vector<std::complex<float>****> &FD_data, unsigned int data_size[4]);
+
+ bool ReadAttribute(std::string grp_name, std::string attr_name, std::vector<double> &attr_values);
+ bool ReadAttribute(std::string grp_name, std::string attr_name, std::vector<float> &attr_values);
+
+ bool IsValid();
+
+protected:
+ std::string m_filename;
+
+ bool ReadDataSet(std::string ds_name, hsize_t &nDim, hsize_t* &dims, double* &data);
+ bool ReadDataSet(std::string ds_name, hsize_t &nDim, hsize_t* &dims, float* &data);
+
+ bool OpenGroup(hid_t &file, hid_t &group, std::string groupName);
+};
+
+#endif // HDF5_FILE_READER_H
diff --git a/openEMS/tools/hdf5_file_writer.cpp b/openEMS/tools/hdf5_file_writer.cpp
new file mode 100644
index 0000000..81c5692
--- /dev/null
+++ b/openEMS/tools/hdf5_file_writer.cpp
@@ -0,0 +1,515 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+using namespace std;
+
+#include "hdf5_file_writer.h"
+#include <boost/algorithm/string.hpp>
+#include <hdf5.h>
+
+#include <sstream>
+#include <iostream>
+#include <iomanip>
+
+HDF5_File_Writer::HDF5_File_Writer(string filename)
+{
+ m_filename = filename;
+ m_Group = "/";
+ hid_t hdf5_file = H5Fcreate(m_filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
+ if (hdf5_file<0)
+ {
+ cerr << "HDF5_File_Writer::HDF5_File_Writer: Error, creating the given file """ << m_filename << """ failed" << endl;
+ }
+ H5Fclose(hdf5_file);
+}
+
+HDF5_File_Writer::~HDF5_File_Writer()
+{
+}
+
+hid_t HDF5_File_Writer::OpenGroup(hid_t hdf5_file, string group)
+{
+ if (hdf5_file<0)
+ {
+ cerr << "HDF5_File_Writer::CreateGroup: Error, invalid file id" << endl;
+ return -1;
+ }
+
+ vector<string> results;
+ boost::split(results, group, boost::is_any_of("/"));
+
+ hid_t grp=H5Gopen(hdf5_file,"/");
+ if (grp<0)
+ {
+ cerr << "HDF5_File_Writer::OpenGroup: Error, opening root group " << endl;
+ return -1;
+ }
+
+ for (size_t n=0;n<results.size();++n)
+ {
+ hid_t old_grp = grp;
+ if (!results.at(n).empty())
+ {
+ if (H5Lexists(grp, results.at(n).c_str(), H5P_DEFAULT))
+ {
+ grp = H5Gopen(grp, results.at(n).c_str());
+ H5Gclose(old_grp);
+ if (grp<0)
+ {
+ cerr << "HDF5_File_Writer::OpenGroup: Error, failed to open existing group" << endl;
+ return -1;
+ }
+ }
+ else
+ {
+ grp = H5Gcreate(grp,results.at(n).c_str(),0);
+ H5Gclose(old_grp);
+ if (grp<0)
+ {
+ cerr << "HDF5_File_Writer::OpenGroup: Error, creating group """ << group << """ failed" << endl;
+ return -1;
+ }
+ }
+ }
+ }
+ return grp;
+}
+
+void HDF5_File_Writer::SetCurrentGroup(std::string group, bool createGrp)
+{
+ m_Group = group;
+ if (createGrp==false)
+ return;
+
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT );
+ if (hdf5_file<0)
+ {
+ cerr << "HDF5_File_Writer::SetCurrentGroup: Error, opening the given file """ << m_filename << """ failed" << endl;
+ return;
+ }
+ hid_t hdf5_group = OpenGroup(hdf5_file, m_Group);
+ if (hdf5_group<0)
+ cerr << "HDF5_File_Writer::WriteData: Error opening group" << endl;
+ H5Gclose(hdf5_group);
+ H5Fclose(hdf5_file);
+}
+
+bool HDF5_File_Writer::WriteRectMesh(unsigned int const* numLines, double const* const* discLines, int MeshType, double scaling)
+{
+ float* array[3];
+ for (int n=0; n<3; ++n)
+ {
+ array[n] = new float[numLines[n]];
+ for (unsigned int i=0; i<numLines[n]; ++i)
+ array[n][i]=discLines[n][i];
+
+ }
+ bool success = WriteRectMesh(numLines,array,MeshType,scaling);
+ for (int n=0; n<3; ++n)
+ delete[] array[n];
+ return success;
+}
+
+bool HDF5_File_Writer::WriteRectMesh(unsigned int const* numLines, float const* const* discLines, int MeshType, float scaling)
+{
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT );
+ if (hdf5_file<0)
+ {
+ cerr << "HDF5_File_Writer::WriteRectMesh: Error, opening the given file """ << m_filename << """ failed" << endl;
+ return false;
+ }
+
+ if (H5Lexists(hdf5_file, "/Mesh", H5P_DEFAULT))
+ {
+ cerr << "HDF5_File_Writer::WriteRectMesh: Error, group ""/Mesh"" already exists" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ hid_t mesh_grp = H5Gcreate(hdf5_file,"/Mesh",0);
+ if (mesh_grp<0)
+ {
+ cerr << "HDF5_File_Writer::WriteRectMesh: Error, creating group ""/Mesh"" failed" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ string names[] = {"x","y","z"};
+ if (MeshType==1)
+ {
+ names[0]="rho";
+ names[1]="alpha";
+ }
+ if (MeshType==2)
+ {
+ names[0]="r";
+ names[1]="theta";
+ names[2]="phi";
+ }
+
+ for (int n=0; n<3; ++n)
+ {
+ hsize_t dims[1]={numLines[n]};
+ hid_t space = H5Screate_simple(1, dims, NULL);
+ hid_t dataset = H5Dcreate(mesh_grp, names[n].c_str(), H5T_NATIVE_FLOAT, space, H5P_DEFAULT);
+ float* array = new float[numLines[n]];
+ for (unsigned int i=0; i<numLines[n]; ++i)
+ {
+ if ((MeshType==1) && (n==1)) //check for alpha-direction
+ array[i] = discLines[n][i];
+ else if ((MeshType==2) && (n>0)) //check for theta/phi-direction
+ array[i] = discLines[n][i];
+ else
+ array[i] = discLines[n][i] * scaling;
+ }
+ if (H5Dwrite(dataset, H5T_NATIVE_FLOAT, space, H5P_DEFAULT, H5P_DEFAULT, array))
+ {
+ cerr << "HDF5_File_Writer::WriteRectMesh: Error, writing to dataset failed" << endl;
+ delete[] array;
+ H5Dclose(dataset);
+ H5Sclose(space);
+ H5Gclose(mesh_grp);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ delete[] array;
+ H5Dclose(dataset);
+ H5Sclose(space);
+ }
+ H5Gclose(mesh_grp);
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+bool HDF5_File_Writer::WriteScalarField(std::string dataSetName, float const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2];
+ size_t n_size[3]={datasize[2],datasize[1],datasize[0]};
+ float* buffer = new float[size];
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=field[i][j][k];
+ }
+ bool success = WriteData(dataSetName,buffer,3,n_size);
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteScalarField(std::string dataSetName, double const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2];
+ size_t n_size[3]={datasize[2],datasize[1],datasize[0]};
+ double* buffer = new double[size];
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=field[i][j][k];
+ }
+ bool success = WriteData(dataSetName,buffer,3,n_size);
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteScalarField(std::string dataSetName, std::complex<float> const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2];
+ size_t n_size[3]={datasize[2],datasize[1],datasize[0]};
+ float* buffer = new float[size];
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=real(field[i][j][k]);
+ }
+ bool success = WriteData(dataSetName + "_real",buffer,3,n_size);
+
+ pos = 0;
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=imag(field[i][j][k]);
+ }
+ success &= WriteData(dataSetName + "_imag",buffer,3,n_size);
+
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteScalarField(std::string dataSetName, std::complex<double> const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2];
+ size_t n_size[3]={datasize[2],datasize[1],datasize[0]};
+ double* buffer = new double[size];
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=real(field[i][j][k]);
+ }
+ bool success = WriteData(dataSetName + "_real",buffer,3,n_size);
+
+ pos = 0;
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=imag(field[i][j][k]);
+ }
+ success &= WriteData(dataSetName + "_imag",buffer,3,n_size);
+
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteVectorField(std::string dataSetName, float const* const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2]*3;
+ float* buffer = new float[size];
+ for (int n=0;n<3;++n)
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=field[n][i][j][k];
+ }
+ size_t n_size[4]={3,datasize[2],datasize[1],datasize[0]};
+ bool success = WriteData(dataSetName,buffer,4,n_size);
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteVectorField(std::string dataSetName, double const* const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2]*3;
+ double* buffer = new double[size];
+ for (int n=0;n<3;++n)
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=field[n][i][j][k];
+ }
+ size_t n_size[4]={3,datasize[2],datasize[1],datasize[0]};
+ bool success = WriteData(dataSetName,buffer,4,n_size);
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteVectorField(std::string dataSetName, std::complex<float> const* const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2]*3;
+ size_t n_size[4]={3,datasize[2],datasize[1],datasize[0]};
+ float* buffer = new float[size];
+ for (int n=0;n<3;++n)
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=real(field[n][i][j][k]);
+ }
+ bool success = WriteData(dataSetName + "_real",buffer,4,n_size);
+
+ pos = 0;
+ for (int n=0;n<3;++n)
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=imag(field[n][i][j][k]);
+ }
+ success &= WriteData(dataSetName + "_imag",buffer,4,n_size);
+
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteVectorField(std::string dataSetName, std::complex<double> const* const* const* const* field, size_t datasize[3])
+{
+ size_t pos = 0;
+ size_t size = datasize[0]*datasize[1]*datasize[2]*3;
+ size_t n_size[4]={3,datasize[2],datasize[1],datasize[0]};
+ double* buffer = new double[size];
+ for (int n=0;n<3;++n)
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=real(field[n][i][j][k]);
+ }
+ bool success = WriteData(dataSetName + "_real",buffer,4,n_size);
+
+ pos = 0;
+ for (int n=0;n<3;++n)
+ for (size_t k=0;k<datasize[2];++k)
+ for (size_t j=0;j<datasize[1];++j)
+ for (size_t i=0;i<datasize[0];++i)
+ {
+ buffer[pos++]=imag(field[n][i][j][k]);
+ }
+ success &= WriteData(dataSetName + "_imag",buffer,4,n_size);
+
+ delete[] buffer;
+ return success;
+}
+
+bool HDF5_File_Writer::WriteData(std::string dataSetName, float const* field_buf, size_t dim, size_t* datasize)
+{
+ return WriteData(dataSetName, H5T_NATIVE_FLOAT, field_buf,dim, datasize);
+}
+
+bool HDF5_File_Writer::WriteData(std::string dataSetName, double const* field_buf, size_t dim, size_t* datasize)
+{
+ return WriteData(dataSetName, H5T_NATIVE_DOUBLE, field_buf,dim, datasize);
+}
+
+bool HDF5_File_Writer::WriteData(std::string dataSetName, hid_t mem_type, void const* field_buf, size_t dim, size_t* datasize)
+{
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT );
+ if (hdf5_file<0)
+ {
+ cerr << "HDF5_File_Writer::WriteData: Error, opening the given file """ << m_filename << """ failed" << endl;
+ return false;
+ }
+
+ hid_t group = OpenGroup(hdf5_file,m_Group);
+ if (group<0)
+ {
+ cerr << "HDF5_File_Writer::WriteData: Error opening group" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ hsize_t dims[dim];
+ for (size_t n=0;n<dim;++n)
+ dims[n]=datasize[n];
+ hid_t space = H5Screate_simple(dim, dims, NULL);
+ hid_t dataset = H5Dcreate(group, dataSetName.c_str(), mem_type, space, H5P_DEFAULT);
+ if (H5Dwrite(dataset, mem_type, space, H5P_DEFAULT, H5P_DEFAULT, field_buf))
+ {
+ cerr << "HDF5_File_Writer::WriteData: Error, writing to dataset failed" << endl;
+ H5Dclose(dataset);
+ H5Sclose(space);
+ H5Gclose(group);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ H5Dclose(dataset);
+ H5Sclose(space);
+ H5Gclose(group);
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, void const* value, hsize_t size, hid_t mem_type)
+{
+ hid_t hdf5_file = H5Fopen( m_filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT );
+ if (hdf5_file<0)
+ {
+ cerr << "HDF5_File_Writer::WriteAtrribute: Error, opening the given file """ << m_filename << """ failed" << endl;
+ return false;
+ }
+
+ if (H5Lexists(hdf5_file, locName.c_str(), H5P_DEFAULT)<0)
+ {
+ cerr << "HDF5_File_Writer::WriteAtrribute: Error, failed to find location: """ << locName << """" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ hid_t loc = H5Oopen(hdf5_file, locName.c_str(), H5P_DEFAULT);
+ if (loc<0)
+ {
+ cerr << "HDF5_File_Writer::WriteAtrribute: Error, failed to open location: """ << locName << """" << endl;
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ hid_t dataspace_id = H5Screate_simple(1, &size, NULL);
+
+ /* Create a dataset attribute. */
+ hid_t attribute_id = H5Acreate(loc, attr_name.c_str(), mem_type, dataspace_id,H5P_DEFAULT);
+ if (attribute_id<0)
+ {
+ cerr << "HDF5_File_Writer::WriteAtrribute: Error, failed to create the attrbute" << endl;
+ H5Sclose(dataspace_id);
+ H5Oclose(loc);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+
+ /* Write the attribute data. */
+ if (H5Awrite(attribute_id, mem_type, value)<0)
+ {
+ cerr << "HDF5_File_Writer::WriteAtrribute: Error, failed to write the attrbute" << endl;
+ H5Aclose(attribute_id);
+ H5Sclose(dataspace_id);
+ H5Oclose(loc);
+ H5Fclose(hdf5_file);
+ return false;
+ }
+ H5Aclose(attribute_id);
+ H5Sclose(dataspace_id);
+ H5Oclose(loc);
+ H5Fclose(hdf5_file);
+ return true;
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, float const* value, hsize_t size)
+{
+ return WriteAtrribute(locName,attr_name, value, size, H5T_NATIVE_FLOAT);
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, double const* value, hsize_t size)
+{
+ return WriteAtrribute(locName,attr_name, value, size, H5T_NATIVE_DOUBLE);
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, vector<float> values)
+{
+ float val[values.size()];
+ for (size_t n=0;n<values.size();++n)
+ val[n]=values.at(n);
+ return HDF5_File_Writer::WriteAtrribute(locName, attr_name,val,values.size(),H5T_NATIVE_FLOAT);
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, vector<double> values)
+{
+ double val[values.size()];
+ for (size_t n=0;n<values.size();++n)
+ val[n]=values.at(n);
+ return HDF5_File_Writer::WriteAtrribute(locName, attr_name, val, values.size(), H5T_NATIVE_DOUBLE);
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, float value)
+{
+ return HDF5_File_Writer::WriteAtrribute(locName, attr_name,&value,1, H5T_NATIVE_FLOAT);
+}
+
+bool HDF5_File_Writer::WriteAtrribute(std::string locName, std::string attr_name, double value)
+{
+ return HDF5_File_Writer::WriteAtrribute(locName, attr_name,&value,1, H5T_NATIVE_DOUBLE);
+}
diff --git a/openEMS/tools/hdf5_file_writer.h b/openEMS/tools/hdf5_file_writer.h
new file mode 100644
index 0000000..7ad975c
--- /dev/null
+++ b/openEMS/tools/hdf5_file_writer.h
@@ -0,0 +1,68 @@
+/*
+* Copyright (C) 2011 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef HDF5_FILE_WRITER_H
+#define HDF5_FILE_WRITER_H
+
+#include <string>
+#include <vector>
+#include <complex>
+#include <hdf5.h>
+
+class HDF5_File_Writer
+{
+public:
+ HDF5_File_Writer(std::string filename);
+ ~HDF5_File_Writer();
+
+ bool WriteRectMesh(unsigned int const* numLines, double const* const* discLines, int MeshType=0, double scaling=1);
+ bool WriteRectMesh(unsigned int const* numLines, float const* const* discLines, int MeshType=0, float scaling=1);
+
+ bool WriteScalarField(std::string dataSetName, float const* const* const* field, size_t datasize[3]);
+ bool WriteScalarField(std::string dataSetName, double const* const* const* field, size_t datasize[3]);
+
+ bool WriteScalarField(std::string dataSetName, std::complex<float> const* const* const* field, size_t datasize[3]);
+ bool WriteScalarField(std::string dataSetName, std::complex<double> const* const* const* field, size_t datasize[3]);
+
+ bool WriteVectorField(std::string dataSetName, float const* const* const* const* field, size_t datasize[3]);
+ bool WriteVectorField(std::string dataSetName, double const* const* const* const* field, size_t datasize[3]);
+
+ bool WriteVectorField(std::string dataSetName, std::complex<float> const* const* const* const* field, size_t datasize[3]);
+ bool WriteVectorField(std::string dataSetName, std::complex<double> const* const* const* const* field, size_t datasize[3]);
+
+ bool WriteData(std::string dataSetName, float const* field_buf, size_t dim, size_t* datasize);
+ bool WriteData(std::string dataSetName, double const* field_buf, size_t dim, size_t* datasize);
+
+ bool WriteAtrribute(std::string locName, std::string attr_name, void const* value, hsize_t size, hid_t mem_type);
+ bool WriteAtrribute(std::string locName, std::string attr_name, float const* value, hsize_t size);
+ bool WriteAtrribute(std::string locName, std::string attr_name, double const* value, hsize_t size);
+ bool WriteAtrribute(std::string locName, std::string attr_name, std::vector<float> values);
+ bool WriteAtrribute(std::string locName, std::string attr_name, std::vector<double> values);
+ bool WriteAtrribute(std::string locName, std::string attr_name, float value);
+ bool WriteAtrribute(std::string locName, std::string attr_name, double value);
+
+ void SetCurrentGroup(std::string group, bool createGrp=true);
+
+protected:
+ std::string m_filename;
+ std::string m_Group;
+
+ hid_t OpenGroup(hid_t hdf5_file, std::string group);
+ bool WriteData(std::string dataSetName, hid_t mem_type, void const* field_buf, size_t dim, size_t* datasize);
+};
+
+#endif // HDF5_FILE_WRITER_H
diff --git a/openEMS/tools/sar_calculation.cpp b/openEMS/tools/sar_calculation.cpp
new file mode 100644
index 0000000..343aa07
--- /dev/null
+++ b/openEMS/tools/sar_calculation.cpp
@@ -0,0 +1,656 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+
+#include "sar_calculation.h"
+#include "cfloat"
+#include "array_ops.h"
+#include "global.h"
+
+using namespace std;
+
+SAR_Calculation::SAR_Calculation()
+{
+ m_Vx_Used = NULL;
+ m_Vx_Valid = NULL;
+ m_DebugLevel = 0;
+ SetAveragingMethod(SIMPLE, true);
+ Reset();
+}
+
+void SAR_Calculation::Reset()
+{
+ Delete3DArray(m_Vx_Used,m_numLines);
+ m_Vx_Used = NULL;
+ Delete3DArray(m_Vx_Valid,m_numLines);
+ m_Vx_Valid = NULL;
+
+ m_avg_mass = 0;
+ m_numLines[0]=m_numLines[1]=m_numLines[2]=0;
+ m_cellWidth[0]=m_cellWidth[1]=m_cellWidth[2]=NULL;
+
+ m_cell_volume = NULL;
+ m_cell_density = NULL;
+ m_cell_conductivity = NULL;
+ m_E_field = NULL;
+ m_J_field = NULL;
+
+ Delete3DArray(m_Vx_Used,m_numLines);
+ m_Vx_Used = NULL;
+ Delete3DArray(m_Vx_Valid,m_numLines);
+ m_Vx_Valid = NULL;
+}
+
+void SAR_Calculation::SetAveragingMethod(string method, bool silent)
+{
+ if (method.compare("IEEE_C95_3")==0)
+ return SetAveragingMethod(IEEE_C95_3, silent);
+ if (method.compare("IEEE_62704")==0)
+ return SetAveragingMethod(IEEE_62704, silent);
+ if (method.compare("Simple")==0)
+ return SetAveragingMethod(SIMPLE, silent);
+
+ cerr << __func__ << ": Error, """ << method << """ is an unknown averaging method..." << endl;
+ // unknown method, fallback to simple
+ SetAveragingMethod(SIMPLE, false);
+}
+
+void SAR_Calculation::SetAveragingMethod(SARAveragingMethod method, bool silent)
+{
+ if (method==IEEE_62704)
+ {
+ m_massTolerance = 0.0001;
+ m_maxMassIterations = 100;
+ m_maxBGRatio = 0.1;
+ m_markPartialAsUsed = false;
+ m_UnusedRelativeVolLimit = 1.05;
+ m_IgnoreFaceValid = false;
+ if (!silent)
+ cerr << __func__ << ": Setting averaging method to IEEE_62704" << endl;
+ return;
+ }
+ else if (method==IEEE_C95_3)
+ {
+ m_massTolerance = 0.05;
+ m_maxMassIterations = 100;
+ m_maxBGRatio = 1;
+ m_markPartialAsUsed = true;
+ m_UnusedRelativeVolLimit = 1;
+ m_IgnoreFaceValid = false;
+ if (!silent)
+ cerr << __func__ << ": Setting averaging method to IEEE_C95_3" << endl;
+ return;
+ }
+ else if (method==SIMPLE)
+ {
+ m_massTolerance = 0.05;
+ m_maxMassIterations = 100;
+ m_maxBGRatio = 1;
+ m_markPartialAsUsed = true;
+ m_UnusedRelativeVolLimit = 1;
+ m_IgnoreFaceValid = true;
+ if (!silent)
+ cerr << __func__ << ": Setting averaging method to SIMPLE" << endl;
+ return;
+ }
+
+ cerr << __func__ << ": Error, unknown averaging method..." << endl;
+ // unknown method, fallback to simple
+ SetAveragingMethod(SIMPLE, false);
+}
+
+void SAR_Calculation::SetNumLines(unsigned int numLines[3])
+{
+ Delete3DArray(m_Vx_Used,m_numLines);
+ m_Vx_Used = NULL;
+ Delete3DArray(m_Vx_Valid,m_numLines);
+ m_Vx_Valid = NULL;
+
+ for (int n=0;n<3;++n)
+ m_numLines[n]=numLines[n];
+}
+
+void SAR_Calculation::SetCellWidth(float* cellWidth[3])
+{
+ for (int n=0;n<3;++n)
+ m_cellWidth[n]=cellWidth[n];
+}
+
+float*** SAR_Calculation::CalcSAR(float*** SAR)
+{
+ if (CheckValid()==false)
+ {
+ cerr << "SAR_Calculation::CalcSAR: SAR calculation is invalid due to missing values... Abort..." << endl;
+ return NULL;
+ }
+ if (m_avg_mass<=0)
+ return CalcLocalSAR(SAR);
+ return CalcAveragedSAR(SAR);
+}
+
+bool SAR_Calculation::CheckValid()
+{
+ for (int n=0;n<3;++n)
+ if (m_cellWidth[n]==NULL)
+ return false;
+ if (m_E_field==NULL)
+ return false;
+ if ((m_J_field==NULL) && (m_cell_conductivity==NULL))
+ return false;
+ if (m_cell_density==NULL)
+ return false;
+ if (m_avg_mass<0)
+ return false;
+ return true;
+}
+
+double SAR_Calculation::CalcSARPower()
+{
+ if (CheckValid()==false)
+ {
+ cerr << "SAR_Calculation::CalcSARPower: SAR calculation is invalid due to missing values... Abort..." << endl;
+ return 0;
+ }
+ double power=0;
+ unsigned int pos[3];
+ for (pos[0]=0; pos[0]<m_numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<m_numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<m_numLines[2]; ++pos[2])
+ {
+ power += CalcLocalPowerDensity(pos)*CellVolume(pos);
+ }
+ }
+ }
+ return power;
+}
+
+double SAR_Calculation::CalcLocalPowerDensity(unsigned int pos[3])
+{
+ double l_pow=0;
+ if (m_cell_conductivity==NULL)
+ {
+ l_pow = abs(m_E_field[0][pos[0]][pos[1]][pos[2]]) * abs(m_J_field[0][pos[0]][pos[1]][pos[2]]);
+ l_pow += abs(m_E_field[1][pos[0]][pos[1]][pos[2]]) * abs(m_J_field[1][pos[0]][pos[1]][pos[2]]);
+ l_pow += abs(m_E_field[2][pos[0]][pos[1]][pos[2]]) * abs(m_J_field[2][pos[0]][pos[1]][pos[2]]);
+ }
+ else
+ {
+ l_pow = m_cell_conductivity[pos[0]][pos[1]][pos[2]]*abs(m_E_field[0][pos[0]][pos[1]][pos[2]]) * abs(m_E_field[0][pos[0]][pos[1]][pos[2]]);
+ l_pow += m_cell_conductivity[pos[0]][pos[1]][pos[2]]*abs(m_E_field[1][pos[0]][pos[1]][pos[2]]) * abs(m_E_field[1][pos[0]][pos[1]][pos[2]]);
+ l_pow += m_cell_conductivity[pos[0]][pos[1]][pos[2]]*abs(m_E_field[2][pos[0]][pos[1]][pos[2]]) * abs(m_E_field[2][pos[0]][pos[1]][pos[2]]);
+ }
+ l_pow*=0.5;
+ return l_pow;
+}
+
+float*** SAR_Calculation::CalcLocalSAR(float*** SAR)
+{
+ unsigned int pos[3];
+ m_Valid=0;
+ m_Used=0;
+ m_Unused=0;
+ m_AirVoxel=0;
+ for (pos[0]=0; pos[0]<m_numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<m_numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<m_numLines[2]; ++pos[2])
+ {
+ if (m_cell_density[pos[0]][pos[1]][pos[2]]>0)
+ {
+ ++m_Valid;
+ SAR[pos[0]][pos[1]][pos[2]] = CalcLocalPowerDensity(pos)/m_cell_density[pos[0]][pos[1]][pos[2]];
+ }
+ else
+ {
+ ++m_AirVoxel;
+ SAR[pos[0]][pos[1]][pos[2]] = 0;
+ }
+ }
+ }
+ }
+ return SAR;
+}
+
+int SAR_Calculation::FindFittingCubicalMass(unsigned int pos[3], float box_size, unsigned int start[3], unsigned int stop[3],
+ float partial_start[3], float partial_stop[3], double &mass, double &volume, double &bg_ratio, int disabledFace, bool ignoreFaceValid)
+{
+ unsigned int mass_iterations = 0;
+ double old_mass=0;
+ double old_box_size=0;
+ bool face_valid;
+ bool mass_valid;
+ bool voxel_valid;
+
+ //iterate over cubical sizes to find fitting volume to mass
+ while (mass_iterations<m_maxMassIterations)
+ {
+ // calculate cubical mass
+ face_valid = GetCubicalMass(pos, box_size/2, start, stop, partial_start, partial_stop, mass, volume, bg_ratio, disabledFace);
+
+ // check if found mass is valid
+ mass_valid = abs(mass-m_avg_mass)<=m_massTolerance*m_avg_mass;
+ voxel_valid = mass_valid && (face_valid==true) && (bg_ratio<m_maxBGRatio);
+
+ if ((face_valid==false) && (mass<m_avg_mass*(1.0-m_massTolerance)) && (ignoreFaceValid==false))
+ {
+ // this is an invalid cube with a too small total mass --> increasing the box will not yield a valid cube
+ return 1;
+ }
+ else if ((face_valid==false || bg_ratio>=m_maxBGRatio) && (mass_valid))
+ {
+ // this is an invalid cube with a valid total mass
+ if (ignoreFaceValid)
+ return 0;
+ return 2;
+ }
+ if (voxel_valid)
+ {
+ // valid cube found
+ return 0;
+ }
+
+ // if no valid or finally invalid cube is found, calculate an alternaive cube size
+ if (mass_iterations==0)
+ {
+ // on first interation, try a relative resize
+ old_box_size=box_size;
+ box_size*=pow(m_avg_mass/mass,1.0/3.0);
+ }
+ else
+ {
+ // on later interations, try a newton approach
+ float new_box_size = box_size - (mass-m_avg_mass)/(mass-old_mass)*(box_size-old_box_size);
+ old_box_size = box_size;
+ box_size = new_box_size;
+ }
+ old_mass=mass;
+
+ ++mass_iterations;
+ }
+
+ // m_maxMassIterations iterations are exhausted...
+ return -1;
+}
+
+bool SAR_Calculation::GetCubicalMass(unsigned int pos[3], double box_size, unsigned int start[3], unsigned int stop[3],
+ float partial_start[3], float partial_stop[3], double &mass, double &volume, double &bg_ratio, int disabledFace)
+{
+ if ((box_size<=0) || isnan(box_size) || isinf(box_size))
+ {
+ cerr << "SAR_Calculation::GetCubicalMass: critical error: invalid averaging box size!! EXIT" << endl;
+ exit(-1);
+ }
+ bool face_valid=true;
+ for (int n=0;n<3;++n)
+ {
+ // check start position
+ start[n]=pos[n];
+ partial_start[n]=1;
+ float dist=m_cellWidth[n][pos[n]]/2;
+ if (disabledFace==2*n)
+ dist=box_size;
+ else
+ {
+ while (dist<box_size)
+ {
+ // box is outside of domain
+ if (start[n]==0)
+ {
+ partial_start[n]=-1;
+ break;
+ }
+ --start[n];
+ dist+=m_cellWidth[n][start[n]];
+ }
+
+ if (partial_start[n]!=-1)
+ { // box ends inside stop[n] voxel
+ partial_start[n]=1-(dist-box_size)/m_cellWidth[n][start[n]];
+ }
+ if ((partial_start[n]!=-1) && (pos[n]==start[n]))
+ partial_start[n]=2*box_size/m_cellWidth[n][start[n]];
+ }
+
+ // check stop position
+ stop[n]=pos[n];
+ partial_stop[n]=1;
+ dist=m_cellWidth[n][pos[n]]/2;
+ if (disabledFace==2*n+1)
+ dist=box_size;
+ else
+ {
+ while (dist<box_size)
+ {
+ // box is outside of domain
+ if (stop[n]==m_numLines[n]-1)
+ {
+ partial_stop[n]=-1;
+ break;
+ }
+ ++stop[n];
+ dist+=m_cellWidth[n][stop[n]];
+ }
+
+ if (partial_stop[n]!=-1)
+ { // box ends inside stop[n] voxel
+ partial_stop[n]=1-(dist-box_size)/m_cellWidth[n][stop[n]];
+ }
+ if ((partial_stop[n]!=-1) && (pos[n]==stop[n]))
+ partial_stop[n]=2*box_size/m_cellWidth[n][stop[n]];
+ }
+ }
+
+ for (int n=0;n<3;++n)
+ {
+ if (partial_start[n]==-1)
+ face_valid=false;
+ if (partial_stop[n]==-1)
+ face_valid=false;
+ }
+
+ mass = 0;
+ volume = 0;
+ double bg_volume=0;
+ double weight[3];
+ unsigned int f_pos[3];
+ bool face_intersect[6] = {false,false,false,false,false,false};
+ for (f_pos[0]=start[0];f_pos[0]<=stop[0];++f_pos[0])
+ {
+ weight[0]=1;
+ if (f_pos[0]==start[0])
+ weight[0]*=abs(partial_start[0]);
+ if (f_pos[0]==stop[0])
+ weight[0]*=abs(partial_stop[0]);
+
+ for (f_pos[1]=start[1];f_pos[1]<=stop[1];++f_pos[1])
+ {
+ weight[1]=1;
+ if (f_pos[1]==start[1])
+ weight[1]*=abs(partial_start[1]);
+ if (f_pos[1]==stop[1])
+ weight[1]*=abs(partial_stop[1]);
+
+ for (f_pos[2]=start[2];f_pos[2]<=stop[2];++f_pos[2])
+ {
+ weight[2]=1;
+ if (f_pos[2]==start[2])
+ weight[2]*=abs(partial_start[2]);
+ if (f_pos[2]==stop[2])
+ weight[2]*=abs(partial_stop[2]);
+
+ mass += CellMass(f_pos)*weight[0]*weight[1]*weight[2];
+ volume += CellVolume(f_pos)*weight[0]*weight[1]*weight[2];
+
+ if (m_cell_density[f_pos[0]][f_pos[1]][f_pos[2]]==0)
+ bg_volume += CellVolume(f_pos)*weight[0]*weight[1]*weight[2];
+ else
+ {
+ for (int n=0;n<3;++n)
+ {
+ if (start[n]==f_pos[n])
+ face_intersect[2*n]=true;
+ if (stop[n]==f_pos[n])
+ face_intersect[2*n+1]=true;
+ }
+ }
+ }
+ }
+ }
+ //check if all bounds have intersected a material boundary
+ for (int n=0;n<6;++n)
+ face_valid *= face_intersect[n];
+
+ bg_ratio = bg_volume/volume;
+
+ return face_valid;
+}
+
+float SAR_Calculation::CalcCubicalSAR(float*** SAR, unsigned int pos[3], unsigned int start[3], unsigned int stop[3], float partial_start[3], float partial_stop[3], bool assignUsed)
+{
+ double power_mass=0;
+ double mass=0;
+ double weight[3];
+ unsigned int f_pos[3];
+ for (f_pos[0]=start[0];f_pos[0]<=stop[0];++f_pos[0])
+ {
+ weight[0]=1;
+ if (f_pos[0]==start[0])
+ weight[0]*=abs(partial_start[0]);
+ if (f_pos[0]==stop[0])
+ weight[0]*=abs(partial_stop[0]);
+
+ for (f_pos[1]=start[1];f_pos[1]<=stop[1];++f_pos[1])
+ {
+ weight[1]=1;
+ if (f_pos[1]==start[1])
+ weight[1]*=abs(partial_start[1]);
+ if (f_pos[1]==stop[1])
+ weight[1]*=abs(partial_stop[1]);
+
+ for (f_pos[2]=start[2];f_pos[2]<=stop[2];++f_pos[2])
+ {
+ weight[2]=1;
+ if (f_pos[2]==start[2])
+ weight[2]*=abs(partial_start[2]);
+ if (f_pos[2]==stop[2])
+ weight[2]*=abs(partial_stop[2]);
+
+ if (m_cell_density[f_pos[0]][f_pos[1]][f_pos[2]]>=0)
+ {
+ mass += CellMass(f_pos)*weight[0]*weight[1]*weight[2];
+ power_mass += CalcLocalPowerDensity(f_pos) * CellVolume(f_pos)*weight[0]*weight[1]*weight[2];
+ }
+ }
+ }
+ }
+ float vx_SAR = power_mass/mass;
+ if (SAR==NULL)
+ return vx_SAR;
+
+ SAR[pos[0]][pos[1]][pos[2]]=vx_SAR;
+
+ if (assignUsed==false)
+ return vx_SAR;
+
+ // assign SAR to all used voxel
+ bool is_partial[3];
+ for (f_pos[0]=start[0];f_pos[0]<=stop[0];++f_pos[0])
+ {
+ if ( ((f_pos[0]==start[0]) && (partial_start[0]!=1)) || ((f_pos[0]==stop[0]) && (partial_stop[0]!=1)) )
+ is_partial[0]=true;
+ else
+ is_partial[0]=false;
+
+ for (f_pos[1]=start[1];f_pos[1]<=stop[1];++f_pos[1])
+ {
+ if ( ((f_pos[1]==start[1]) && (partial_start[1]!=1)) || ((f_pos[1]==stop[1]) && (partial_stop[1]!=1)) )
+ is_partial[1]=true;
+ else
+ is_partial[1]=false;
+
+ for (f_pos[2]=start[2];f_pos[2]<=stop[2];++f_pos[2])
+ {
+ if ( ((f_pos[2]==start[2]) && (partial_start[2]!=1)) || ((f_pos[2]==stop[2]) && (partial_stop[2]!=1)) )
+ is_partial[2]=true;
+ else
+ is_partial[2]=false;
+
+ if ( (!is_partial[0] && !is_partial[1] && !is_partial[2]) || m_markPartialAsUsed)
+ {
+ if (!m_Vx_Valid[f_pos[0]][f_pos[1]][f_pos[2]] && (m_cell_density[f_pos[0]][f_pos[1]][f_pos[2]]>0))
+ {
+ m_Vx_Used[f_pos[0]][f_pos[1]][f_pos[2]]=true;
+ SAR[f_pos[0]][f_pos[1]][f_pos[2]]=max(SAR[f_pos[0]][f_pos[1]][f_pos[2]], vx_SAR);
+ }
+ }
+ }
+ }
+ }
+ return vx_SAR;
+}
+
+
+float*** SAR_Calculation::CalcAveragedSAR(float*** SAR)
+{
+ unsigned int pos[3];
+ m_Vx_Used = Create3DArray<bool>(m_numLines);
+ m_Vx_Valid = Create3DArray<bool>(m_numLines);
+
+ double voxel_volume;
+ double total_mass;
+ unsigned int start[3];
+ unsigned int stop[3];
+ float partial_start[3];
+ float partial_stop[3];
+ double bg_ratio;
+ int EC=0;
+
+ // debug counter
+ unsigned int cnt_case1=0;
+ unsigned int cnt_case2=0;
+ unsigned int cnt_NoConvergence=0;
+
+ m_Valid=0;
+ m_Used=0;
+ m_Unused=0;
+ m_AirVoxel=0;
+
+ for (pos[0]=0; pos[0]<m_numLines[0]; ++pos[0])
+ {
+ for (pos[1]=0; pos[1]<m_numLines[1]; ++pos[1])
+ {
+ for (pos[2]=0; pos[2]<m_numLines[2]; ++pos[2])
+ {
+ if (m_cell_density[pos[0]][pos[1]][pos[2]]==0)
+ {
+ SAR[pos[0]][pos[1]][pos[2]] = 0;
+ ++m_AirVoxel;
+ continue;
+ }
+
+ // guess an initial box size and find a fitting cube
+ EC = FindFittingCubicalMass(pos, pow(m_avg_mass/m_cell_density[pos[0]][pos[1]][pos[2]],1.0/3.0)/2, start, stop,
+ partial_start, partial_stop, total_mass, voxel_volume, bg_ratio, -1, m_IgnoreFaceValid);
+
+ if (EC==0)
+ {
+ m_Vx_Valid[pos[0]][pos[1]][pos[2]] = true;
+ m_Vx_Used[pos[0]][pos[1]][pos[2]] = true;
+ ++m_Valid;
+ CalcCubicalSAR(SAR, pos, start, stop, partial_start, partial_stop, true);
+ }
+ else if (EC==1)
+ ++cnt_case1;
+ else if (EC==2)
+ ++cnt_case2;
+ else if (EC==-1)
+ ++cnt_NoConvergence;
+ else
+ cerr << "other EC" << EC << endl;
+ }
+ }
+ }
+ if (cnt_NoConvergence>0)
+ {
+ cerr << "SAR_Calculation::CalcAveragedSAR: Warning, for some voxel a valid averaging cube could not be found (no convergence)... " << endl;
+ }
+ if (m_DebugLevel>0)
+ {
+ cerr << "Number of invalid cubes (case 1): " << cnt_case1 << endl;
+ cerr << "Number of invalid cubes (case 2): " << cnt_case2 << endl;
+ cerr << "Number of invalid cubes (failed to converge): " << cnt_NoConvergence << endl;
+ }
+
+ // count all used and unused etc. + special handling of unused voxels!!
+ m_Used=0;
+ m_Unused=0;
+ for (pos[0]=0;pos[0]<m_numLines[0];++pos[0])
+ {
+ for (pos[1]=0;pos[1]<m_numLines[1];++pos[1])
+ {
+ for (pos[2]=0;pos[2]<m_numLines[2];++pos[2])
+ {
+ if (!m_Vx_Valid[pos[0]][pos[1]][pos[2]] && m_Vx_Used[pos[0]][pos[1]][pos[2]])
+ ++m_Used;
+ if ((m_cell_density[pos[0]][pos[1]][pos[2]]>0) && !m_Vx_Valid[pos[0]][pos[1]][pos[2]] && !m_Vx_Used[pos[0]][pos[1]][pos[2]])
+ {
+ ++m_Unused;
+
+ SAR[pos[0]][pos[1]][pos[2]] = 0;
+ double unused_volumes[6];
+ float unused_SAR[6];
+
+ double min_Vol=FLT_MAX;
+
+ // special handling of unused voxels:
+ for (int n=0;n<6;++n)
+ {
+ EC = FindFittingCubicalMass(pos, pow(m_avg_mass/m_cell_density[pos[0]][pos[1]][pos[2]],1.0/3.0)/2, start, stop,
+ partial_start, partial_stop, total_mass, unused_volumes[n], bg_ratio, n, true);
+ if ((EC!=0) && (EC!=2))
+ {
+ // this should not happen
+ cerr << "SAR_Calculation::CalcAveragedSAR: Error handling unused voxels, can't find fitting cubical averaging volume' " << endl;
+ unused_SAR[n]=0;
+ }
+ else
+ {
+ unused_SAR[n]=CalcCubicalSAR(NULL, pos, start, stop, partial_start, partial_stop, false);
+ min_Vol = min(min_Vol,unused_volumes[n]);
+ }
+ }
+ for (int n=0;n<6;++n)
+ {
+ if (unused_volumes[n]<=m_UnusedRelativeVolLimit*min_Vol)
+ SAR[pos[0]][pos[1]][pos[2]] = max(SAR[pos[0]][pos[1]][pos[2]],unused_SAR[n]);
+ }
+ }
+ }
+ }
+ }
+
+ if (m_Valid+m_Used+m_Unused+m_AirVoxel!=m_numLines[0]*m_numLines[1]*m_numLines[2])
+ {
+ cerr << "SAR_Calculation::CalcAveragedSAR: critical error, mismatch in voxel status count... EXIT" << endl;
+ exit(1);
+ }
+
+ if (m_DebugLevel>0)
+ cerr << "SAR_Calculation::CalcAveragedSAR: Stats: Valid=" << m_Valid << " Used=" << m_Used << " Unused=" << m_Unused << " Air-Voxel=" << m_AirVoxel << endl;
+
+ return SAR;
+}
+
+double SAR_Calculation::CellVolume(unsigned int pos[3])
+{
+ if (m_cell_volume)
+ return m_cell_volume[pos[0]][pos[1]][pos[2]];
+
+ double volume=1;
+ for (int n=0;n<3;++n)
+ volume*=m_cellWidth[n][pos[n]];
+ return volume;
+}
+
+double SAR_Calculation::CellMass(unsigned int pos[3])
+{
+ return m_cell_density[pos[0]][pos[1]][pos[2]]*CellVolume(pos);
+}
+
diff --git a/openEMS/tools/sar_calculation.h b/openEMS/tools/sar_calculation.h
new file mode 100644
index 0000000..58d9ab8
--- /dev/null
+++ b/openEMS/tools/sar_calculation.h
@@ -0,0 +1,122 @@
+/*
+* Copyright (C) 2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef SAR_CALCULATION_H
+#define SAR_CALCULATION_H
+
+#include <complex>
+
+class SAR_Calculation
+{
+public:
+ SAR_Calculation();
+
+ enum SARAveragingMethod { IEEE_C95_3, IEEE_62704, SIMPLE};
+
+ //! Reset and initialize all values (will keep all SAR settings)
+ void Reset();
+
+ //! Set the debug level
+ void SetDebugLevel(int level) {m_DebugLevel=level;}
+
+ //! Set the used averaging method
+ void SetAveragingMethod(SARAveragingMethod method, bool silent=false);
+
+ //! Set the used averaging method
+ void SetAveragingMethod(std::string method, bool silent=false);
+
+ //! Set number of lines in all direcitions. (mandatory information)
+ void SetNumLines(unsigned int numLines[3]);
+ //! Set cell width in all direcitions. (mandatory information for averaging)
+ void SetCellWidth(float* cellWidth[3]);
+
+ //! Set the averaging mash. (mandatory information for averaging)
+ void SetAveragingMass(float mass) {m_avg_mass=mass;}
+
+ //! Set the cell volumes (optional for speedup)
+ void SetCellVolumes(float*** cell_volume) {m_cell_volume=cell_volume;}
+
+ //! Set the cell densities (mandatory information)
+ void SetCellDensities(float*** cell_density) {m_cell_density=cell_density;}
+
+ //! Set the cell conductivities (mandatory if no current density field is given)
+ void SetCellCondictivity(float*** cell_conductivity) {m_cell_conductivity=cell_conductivity;}
+
+ //! Set the electric field (mandatory information)
+ void SetEField(std::complex<float>**** field) {m_E_field=field;}
+ //! Set the current density field (mandatory if no conductivity distribution is given)
+ void SetJField(std::complex<float>**** field) {m_J_field=field;}
+
+ //! Calculate the SAR, requires a preallocated 3D array
+ float*** CalcSAR(float*** SAR);
+
+ //! Calculate the total power dumped
+ double CalcSARPower();
+
+protected:
+ unsigned int m_numLines[3];
+ float* m_cellWidth[3];
+
+ float m_avg_mass;
+ float*** m_cell_volume;
+ float*** m_cell_density;
+ float*** m_cell_conductivity;
+ std::complex<float>**** m_E_field;
+ std::complex<float>**** m_J_field;
+
+ bool*** m_Vx_Used;
+ bool*** m_Vx_Valid;
+
+ unsigned int m_Valid;
+ unsigned int m_Used;
+ unsigned int m_Unused;
+ unsigned int m_AirVoxel;
+
+ int m_DebugLevel;
+
+ /*********** SAR calculation parameter and settings ***********/
+ float m_massTolerance;
+ unsigned int m_maxMassIterations;
+ float m_maxBGRatio;
+ bool m_markPartialAsUsed;
+ float m_UnusedRelativeVolLimit;
+ bool m_IgnoreFaceValid;
+
+ /*********** SAR calculations methods ********/
+ double CalcLocalPowerDensity(unsigned int pos[3]);
+
+ //! Calculate the local SAR
+ float*** CalcLocalSAR(float*** SAR);
+
+ /****** start SAR averaging and all necessary methods ********/
+ //! Calculate the averaged SAR
+ float*** CalcAveragedSAR(float*** SAR);
+
+ int FindFittingCubicalMass(unsigned int pos[3], float box_size, unsigned int start[3], unsigned int stop[3],
+ float partial_start[3], float partial_stop[3], double &mass, double &volume, double &bg_ratio, int disabledFace=-1, bool ignoreFaceValid=false);
+ bool GetCubicalMass(unsigned int pos[3], double box_size, unsigned int start[3], unsigned int stop[3],
+ float partial_start[3], float partial_stop[3], double &mass, double &volume, double &bg_ratio, int disabledFace=-1);
+
+ float CalcCubicalSAR(float*** SAR, unsigned int pos[3], unsigned int start[3], unsigned int stop[3], float partial_start[3], float partial_stop[3], bool assignUsed=false);
+ /****** end SAR averaging and all necessary methods ********/
+
+ bool CheckValid();
+ double CellVolume(unsigned int pos[3]);
+ double CellMass(unsigned int pos[3]);
+};
+
+#endif // SAR_CALCULATION_H
diff --git a/openEMS/tools/useful.cpp b/openEMS/tools/useful.cpp
new file mode 100644
index 0000000..50aacfb
--- /dev/null
+++ b/openEMS/tools/useful.cpp
@@ -0,0 +1,185 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "useful.h"
+#include <cstdio>
+#include <cstdlib>
+#include <cmath>
+#include <climits>
+#include <stdio.h>
+#include <stdlib.h>
+#include <iomanip>
+#include <sstream>
+#include <boost/algorithm/string.hpp>
+#include <iostream>
+
+unsigned int CalcNyquistNum(double fmax, double dT)
+{
+ if (fmax==0) return UINT_MAX;
+ if (dT==0) return 1;
+ double T0 = 1/fmax;
+ return floor(T0/2/dT);
+}
+
+double CalcNyquistFrequency(unsigned int nyquist, double dT)
+{
+ if (nyquist==0) return 0;
+ if (dT==0) return 0;
+ return floor(1/(double)nyquist/2/dT);
+}
+
+std::vector<unsigned int> AssignJobs2Threads(unsigned int jobs, unsigned int nrThreads, bool RemoveEmpty)
+{
+ std::vector<unsigned int> jpt; //jobs per thread
+
+ unsigned int ui_jpt = jobs/nrThreads;
+ for (unsigned int n=0; n<nrThreads; ++n)
+ {
+ jpt.push_back(ui_jpt);
+ jobs-=ui_jpt;
+ }
+
+ for (unsigned int n=0; n<nrThreads; ++n)
+ {
+ if (jobs>0)
+ {
+ ++jpt.at(n);
+ --jobs;
+ }
+ }
+
+ if (jobs>0)
+ std::cerr << "AssignJobs2Threads: Error, " << jobs << " remain to be assigned, this should not have happend..." << std::endl;
+
+ if (RemoveEmpty)
+ {
+ while (jpt.back()==0)
+ jpt.pop_back();
+ }
+
+ return jpt;
+}
+
+std::vector<float> SplitString2Float(std::string str, std::string delimiter)
+{
+ std::vector<float> v_f;
+ std::vector<std::string> results;
+ boost::split(results, str, boost::is_any_of(delimiter));
+
+ for (size_t n=0;n<results.size();++n)
+ {
+ std::istringstream is(results.at(n));
+ float num;
+ if (is >> num)
+ v_f.push_back(num);
+ }
+ return v_f;
+}
+
+std::vector<double> SplitString2Double(std::string str, std::string delimiter)
+{
+ std::vector<double> v_f;
+ std::vector<std::string> results;
+ boost::split(results, str, boost::is_any_of(delimiter));
+
+ for (size_t n=0;n<results.size();++n)
+ {
+ std::istringstream is(results.at(n));
+ double num;
+ if (is >> num)
+ v_f.push_back(num);
+ }
+ return v_f;
+}
+
+bool CrossProd(const double *v1, const double *v2, double* out)
+{
+ int nP,nPP;
+ for (int n=0;n<3;++n)
+ {
+ nP = (n+1)%3;
+ nPP = (n+2)%3;
+ out[n] = v1[nP]*v2[nPP] - v1[nPP]*v2[nP];
+ }
+ return ((out[0]+out[1]+out[2])>0);
+}
+
+double ScalarProd(const double *v1, const double *v2)
+{
+ double out=0;
+ for (int n=0;n<3;++n)
+ out+=v1[n]*v2[n];
+ return out;
+}
+
+double Determinant(const double *mat)
+{
+ return mat[0]*mat[4]*mat[8]+mat[1]*mat[5]*mat[6]+mat[2]*mat[3]*mat[7]-mat[2]*mat[4]*mat[6]-mat[1]*mat[3]*mat[8]-mat[0]*mat[5]*mat[7];
+}
+
+double* Invert(const double* in, double* out)
+{
+ double det = Determinant(in);
+ out[0] = (in[4]*in[8]-in[5]*in[7])/det;
+ out[1] = (in[2]*in[7]-in[1]*in[8])/det;
+ out[2] = (in[1]*in[5]-in[2]*in[4])/det;
+ out[3] = (in[5]*in[6]-in[3]*in[8])/det;
+ out[4] = (in[0]*in[8]-in[2]*in[6])/det;
+ out[5] = (in[2]*in[3]-in[0]*in[5])/det;
+ out[6] = (in[3]*in[7]-in[4]*in[6])/det;
+ out[7] = (in[1]*in[6]-in[0]*in[7])/det;
+ out[8] = (in[0]*in[4]-in[1]*in[3])/det;
+ return out;
+}
+
+int LinePlaneIntersection(const double *p0, const double *p1, const double *p2, const double *l_start, const double *l_stop, double* is_point, double &dist)
+{
+ dist = 0;
+ double mat[9];
+ for (int n=0;n<3;++n)
+ {
+ is_point[n] = 0;
+ mat[3*n] = l_start[n]-l_stop[n];
+ mat[3*n+1] = p1[n]-p0[n];
+ mat[3*n+2] = p2[n]-p0[n];
+ }
+ double det = Determinant(mat);
+ if (fabs(det)<1e-50)
+ return -1;
+
+ double inv_mat[9];
+ Invert(mat, inv_mat);
+
+ double t=0,u=0,v=0;
+ for (int n=0;n<3;++n)
+ {
+ t+=inv_mat[n]*(l_start[n]-p0[n]);
+ u+=inv_mat[3+n]*(l_start[n]-p0[n]);
+ v+=inv_mat[6+n]*(l_start[n]-p0[n]);
+ }
+ dist = t;
+
+ for (int n=0;n<3;++n)
+ is_point[n] = l_start[n]*(1-dist) + l_stop[n]*dist;
+
+ if ((u<0) || (u>1) || (v<0) || (v>1))
+ return 1;
+ if ((t<0) || (t>1))
+ return 2;
+
+ return 0;
+}
diff --git a/openEMS/tools/useful.h b/openEMS/tools/useful.h
new file mode 100644
index 0000000..dec13ab
--- /dev/null
+++ b/openEMS/tools/useful.h
@@ -0,0 +1,44 @@
+/*
+* Copyright (C) 2010 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef USEFUL_H
+#define USEFUL_H
+
+#include <vector>
+#include <string>
+
+//! Calc the nyquist number of timesteps for a given frequency and timestep
+unsigned int CalcNyquistNum(double fmax, double dT);
+
+//! Calc the highest frequency allowed for a given nyquist number of timesteps and timestep
+double CalcNyquistFrequency(unsigned int nyquist, double dT);
+
+//! Calculate an optimal job distribution to a given number of threads. Will return a vector with the jobs for each thread.
+std::vector<unsigned int> AssignJobs2Threads(unsigned int jobs, unsigned int nrThreads, bool RemoveEmpty=false);
+
+std::vector<float> SplitString2Float(std::string str, std::string delimiter=",");
+std::vector<double> SplitString2Double(std::string str, std::string delimiter=",");
+
+bool CrossProd(const double* v1, const double* v2, double* out);
+double ScalarProd(const double* v1, const double* v2);
+
+double Determinant(const double* mat);
+double* Invert(const double* in, double* out);
+
+int LinePlaneIntersection(const double *p0, const double* p1, const double* p2, const double* l_start, const double* l_stop, double* is_point, double &dist);
+
+#endif // USEFUL_H
diff --git a/openEMS/tools/vtk_file_writer.cpp b/openEMS/tools/vtk_file_writer.cpp
new file mode 100644
index 0000000..79c40f3
--- /dev/null
+++ b/openEMS/tools/vtk_file_writer.cpp
@@ -0,0 +1,340 @@
+/*
+* Copyright (C) 2011,2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+using namespace std;
+
+#include "vtk_file_writer.h"
+
+#include <vtkRectilinearGrid.h>
+#include <vtkRectilinearGridWriter.h>
+#include <vtkXMLRectilinearGridWriter.h>
+#include <vtkStructuredGrid.h>
+#include <vtkStructuredGridWriter.h>
+#include <vtkXMLStructuredGridWriter.h>
+#include <vtkZLibDataCompressor.h>
+#include <vtkFloatArray.h>
+#include <vtkDoubleArray.h>
+#include <vtkFieldData.h>
+#include <vtkPointData.h>
+
+#include <sstream>
+#include <iomanip>
+
+
+VTK_File_Writer::VTK_File_Writer(string filename, int meshType)
+{
+ SetFilename(filename);
+ m_MeshType = meshType;
+ m_NativeDump = false;
+ m_Binary = true;
+ m_Compress = true;
+ m_AppendMode = false;
+ m_ActiveTS = false;
+
+ if (m_MeshType==0) //cartesian mesh
+ m_GridData = vtkRectilinearGrid::New();
+ else if (m_MeshType==1) //cylindrical mesh
+ m_GridData = vtkStructuredGrid::New();
+ else
+ {
+ cerr << "VTK_File_Writer::VTK_File_Writer: Error, unknown mesh type: " << m_MeshType << endl;
+ m_GridData=NULL;
+ }
+}
+
+VTK_File_Writer::~VTK_File_Writer()
+{
+ if (m_GridData)
+ m_GridData->Delete();
+ m_GridData = NULL;
+}
+
+void VTK_File_Writer::SetMeshLines(double const* const* lines, unsigned int const* count, double scaling)
+{
+ if (m_MeshType==0) //cartesian mesh
+ {
+ vtkRectilinearGrid* RectGrid = dynamic_cast<vtkRectilinearGrid*>(m_GridData);
+ if (RectGrid==NULL)
+ {
+ cerr << "VTK_File_Writer::SetMeshLines: Error, grid invalid, this should not have happend! " << endl;
+ exit(1);
+ }
+ RectGrid->SetDimensions(count[0],count[1],count[2]);
+ vtkDoubleArray *Coords[3];
+ for (int n=0;n<3;++n)
+ {
+ m_MeshLines[n].clear();
+ m_MeshLines[n].reserve(count[n]);
+ Coords[n] = vtkDoubleArray::New();
+ for (unsigned int i=0; i<count[n]; i++)
+ {
+ Coords[n]->InsertNextValue(lines[n][i]*scaling);
+ m_MeshLines[n].push_back(lines[n][i]*scaling);
+ }
+ }
+ RectGrid->SetXCoordinates(Coords[0]);
+ RectGrid->SetYCoordinates(Coords[1]);
+ RectGrid->SetZCoordinates(Coords[2]);
+ for (int n=0;n<3;++n)
+ Coords[n]->Delete();
+ }
+ else if (m_MeshType==1) //cylindrical mesh
+ {
+ vtkStructuredGrid* StructGrid = dynamic_cast<vtkStructuredGrid*>(m_GridData);
+ if (StructGrid==NULL)
+ {
+ cerr << "VTK_File_Writer::SetMeshLines: Error, grid invalid, this should not have happend! " << endl;
+ exit(1);
+ }
+
+ for (int n=0;n<3;++n)
+ {
+ m_MeshLines[n].clear();
+ m_MeshLines[n].reserve(count[n]);
+ double scale=1;
+ if (n!=1)
+ scale*=scaling;
+ for (unsigned int i=0; i<count[n]; i++)
+ m_MeshLines[n].push_back(lines[n][i]*scale);
+ }
+
+ StructGrid->SetDimensions(count[0],count[1],count[2]);
+ vtkPoints *points = vtkPoints::New();
+ points->SetNumberOfPoints(count[0]*count[1]*count[2]);
+ double r[3];
+ int id=0;
+ for (unsigned int k=0; k<count[2]; ++k)
+ for (unsigned int j=0; j<count[1]; ++j)
+ for (unsigned int i=0; i<count[0]; ++i)
+ {
+ r[0] = lines[0][i] * cos(lines[1][j]) * scaling;
+ r[1] = lines[0][i] * sin(lines[1][j]) * scaling;
+ r[2] = lines[2][k] * scaling;
+ points->SetPoint(id++,r);
+ }
+ StructGrid->SetPoints(points);
+ points->Delete();
+ }
+ else
+ {
+ cerr << "VTK_File_Writer::SetMeshLines: Error, unknown mesh type: " << m_MeshType << endl;
+ }
+}
+
+void VTK_File_Writer::AddScalarField(string fieldname, double const* const* const* field)
+{
+ vtkDoubleArray* array = vtkDoubleArray::New();
+ array->SetNumberOfTuples(m_MeshLines[0].size()*m_MeshLines[1].size()*m_MeshLines[2].size());
+ array->SetName(fieldname.c_str());
+ int id=0;
+ for (unsigned int k=0;k<m_MeshLines[2].size();++k)
+ {
+ for (unsigned int j=0;j<m_MeshLines[1].size();++j)
+ {
+ for (unsigned int i=0;i<m_MeshLines[0].size();++i)
+ {
+ array->SetTuple1(id++,field[i][j][k]);
+ }
+ }
+ }
+ m_GridData->GetPointData()->AddArray(array);
+ array->Delete();
+}
+
+void VTK_File_Writer::AddScalarField(string fieldname, float const* const* const* field)
+{
+ vtkFloatArray* array = vtkFloatArray::New();
+ array->SetNumberOfTuples(m_MeshLines[0].size()*m_MeshLines[1].size()*m_MeshLines[2].size());
+ array->SetName(fieldname.c_str());
+ int id=0;
+ for (unsigned int k=0;k<m_MeshLines[2].size();++k)
+ {
+ for (unsigned int j=0;j<m_MeshLines[1].size();++j)
+ {
+ for (unsigned int i=0;i<m_MeshLines[0].size();++i)
+ {
+ array->SetTuple1(id++,field[i][j][k]);
+ }
+ }
+ }
+ m_GridData->GetPointData()->AddArray(array);
+ array->Delete();
+}
+
+void VTK_File_Writer::AddVectorField(string fieldname, double const* const* const* const* field)
+{
+ vtkDoubleArray* array = vtkDoubleArray::New();
+ array->SetNumberOfComponents(3);
+ array->SetNumberOfTuples(m_MeshLines[0].size()*m_MeshLines[1].size()*m_MeshLines[2].size());
+ array->SetName(fieldname.c_str());
+ int id=0;
+ double out[3];
+ for (unsigned int k=0;k<m_MeshLines[2].size();++k)
+ {
+ for (unsigned int j=0;j<m_MeshLines[1].size();++j)
+ {
+ double cos_a = cos(m_MeshLines[1].at(j)); //needed only for m_MeshType==1 (cylindrical mesh)
+ double sin_a = sin(m_MeshLines[1].at(j)); //needed only for m_MeshType==1 (cylindrical mesh)
+ for (unsigned int i=0;i<m_MeshLines[0].size();++i)
+ {
+ if ((m_MeshType==0) || (m_NativeDump))
+ array->SetTuple3(id++,field[0][i][j][k],field[1][i][j][k],field[2][i][j][k]);
+ else
+ {
+ out[0] = field[0][i][j][k] * cos_a - field[1][i][j][k] * sin_a;
+ out[1] = field[0][i][j][k] * sin_a + field[1][i][j][k] * cos_a;
+ out[2] = field[2][i][j][k];
+ array->SetTuple3(id++,out[0],out[1],out[2]);
+ }
+ }
+ }
+ }
+ m_GridData->GetPointData()->AddArray(array);
+ array->Delete();
+}
+
+void VTK_File_Writer::AddVectorField(string fieldname, float const* const* const* const* field)
+{
+ vtkFloatArray* array = vtkFloatArray::New();
+ array->SetNumberOfComponents(3);
+ array->SetNumberOfTuples(m_MeshLines[0].size()*m_MeshLines[1].size()*m_MeshLines[2].size());
+ array->SetName(fieldname.c_str());
+ int id=0;
+ float out[3];
+ for (unsigned int k=0;k<m_MeshLines[2].size();++k)
+ {
+ for (unsigned int j=0;j<m_MeshLines[1].size();++j)
+ {
+ float cos_a = cos(m_MeshLines[1].at(j)); //needed only for m_MeshType==1 (cylindrical mesh)
+ float sin_a = sin(m_MeshLines[1].at(j)); //needed only for m_MeshType==1 (cylindrical mesh)
+ for (unsigned int i=0;i<m_MeshLines[0].size();++i)
+ {
+ if ((m_MeshType==0) || (m_NativeDump))
+ array->SetTuple3(id++,field[0][i][j][k],field[1][i][j][k],field[2][i][j][k]);
+ else
+ {
+ out[0] = field[0][i][j][k] * cos_a - field[1][i][j][k] * sin_a;
+ out[1] = field[0][i][j][k] * sin_a + field[1][i][j][k] * cos_a;
+ out[2] = field[2][i][j][k];
+ array->SetTuple3(id++,out[0],out[1],out[2]);
+ }
+ }
+ }
+ }
+ m_GridData->GetPointData()->AddArray(array);
+ array->Delete();
+}
+
+
+int VTK_File_Writer::GetNumberOfFields() const
+{
+ return m_GridData->GetPointData()->GetNumberOfArrays();
+}
+
+void VTK_File_Writer::ClearAllFields()
+{
+ while (m_GridData->GetPointData()->GetNumberOfArrays()>0)
+ {
+ const char* name = m_GridData->GetPointData()->GetArrayName(0);
+ m_GridData->GetPointData()->RemoveArray(name);
+ }
+}
+
+bool VTK_File_Writer::Write()
+{
+ return WriteXML();
+}
+
+string VTK_File_Writer::GetTimestepFilename(int pad_length) const
+{
+ if (m_ActiveTS==false)
+ return m_filename;
+
+ stringstream ss;
+ ss << m_filename << "_" << std::setw( pad_length ) << std::setfill( '0' ) << m_timestep;
+
+ return ss.str();
+}
+
+
+bool VTK_File_Writer::WriteASCII()
+{
+ vtkDataWriter* writer = NULL;
+ if (m_MeshType==0) //cartesian mesh
+ writer = vtkRectilinearGridWriter::New();
+ else if (m_MeshType==1) //cylindrical mesh
+ writer = vtkStructuredGridWriter::New();
+ else
+ {
+ cerr << "VTK_File_Writer::WriteASCII: Error, unknown mesh type: " << m_MeshType << endl;
+ return false;
+ }
+
+ writer->SetHeader(m_header.c_str());
+#if VTK_MAJOR_VERSION>=6
+ writer->SetInputData(m_GridData);
+#else
+ writer->SetInput(m_GridData);
+#endif
+
+ string filename = GetTimestepFilename() + ".vtk";
+ writer->SetFileName(filename.c_str());
+ if (m_Binary)
+ writer->SetFileTypeToBinary();
+ else
+ writer->SetFileTypeToASCII();
+
+ writer->Write();
+ writer->Delete();
+ return true;
+}
+
+bool VTK_File_Writer::WriteXML()
+{
+ vtkXMLStructuredDataWriter* writer = NULL;
+ if (m_MeshType==0) //cartesian mesh
+ writer = vtkXMLRectilinearGridWriter::New();
+ else if (m_MeshType==1) //cylindrical mesh
+ writer = vtkXMLStructuredGridWriter::New();
+ else
+ {
+ cerr << "VTK_File_Writer::WriteXML: Error, unknown mesh type: " << m_MeshType << endl;
+ return false;
+ }
+
+#if VTK_MAJOR_VERSION>=6
+ writer->SetInputData(m_GridData);
+#else
+ writer->SetInput(m_GridData);
+#endif
+
+ string filename = GetTimestepFilename() + "." + writer->GetDefaultFileExtension();
+ writer->SetFileName(filename.c_str());
+ if (m_Compress)
+ writer->SetCompressor(vtkZLibDataCompressor::New());
+ else
+ writer->SetCompressor(NULL);
+
+ if (m_Binary)
+ writer->SetDataModeToBinary();
+ else
+ writer->SetDataModeToAscii();
+
+ writer->Write();
+ writer->Delete();
+ return true;
+}
diff --git a/openEMS/tools/vtk_file_writer.h b/openEMS/tools/vtk_file_writer.h
new file mode 100644
index 0000000..428d859
--- /dev/null
+++ b/openEMS/tools/vtk_file_writer.h
@@ -0,0 +1,94 @@
+/*
+* Copyright (C) 2011,2012 Thorsten Liebig (Thorsten.Liebig@gmx.de)
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef VTK_FILE_WRITER_H
+#define VTK_FILE_WRITER_H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <iostream>
+#include <string>
+#include <vector>
+#include <complex>
+
+class vtkDataSet;
+
+class VTK_File_Writer
+{
+public:
+ VTK_File_Writer(std::string filename, int meshType=0);
+ virtual ~VTK_File_Writer();
+
+ //! Set the filename
+ virtual void SetFilename(std::string filename) {m_filename=filename;}
+ //! Set the header information. May not be supported by all file types or setting.
+ virtual void SetHeader(std::string header) {m_header=header;}
+
+ //! Tell write to append data. May fail if filename has changed or filetype doesn't support this.
+ virtual void SetAppendMode(bool val) {m_AppendMode=val;}
+ //! Set binary flag (if the file type supports it)
+ virtual void SetBinary(bool val) {m_Binary=val;}
+ //! Set compression flag (if the file type supports it)
+ virtual void SetCompress(bool val) {m_Compress=val;}
+
+ void SetNativeDump(bool val) {m_NativeDump=val;}
+
+ virtual void SetMeshLines(double const* const* lines, unsigned int const* count, double scaling=1);
+
+ virtual void AddScalarField(std::string fieldname, double const* const* const* field);
+ virtual void AddScalarField(std::string fieldname, float const* const* const* field);
+ virtual void AddVectorField(std::string fieldname, double const* const* const* const* field);
+ virtual void AddVectorField(std::string fieldname, float const* const* const* const* field);
+
+ virtual int GetNumberOfFields() const;
+ virtual void ClearAllFields();
+
+ //! Get if timestep file series is active. \sa SetTimestepActive
+ virtual bool GetTimestepActive() {return m_ActiveTS;}
+ //! Set the timestep file series flag. \sa GetTimestepActive \sa SetTimestep
+ virtual void SetTimestepActive(bool val) {m_ActiveTS = val;}
+ //! Set the current timestep, this will set the timestep flag to true. \sa SetTimestepActive
+ virtual void SetTimestep(unsigned int ts) {m_timestep=ts;SetTimestepActive(true);}
+
+ virtual bool Write();
+
+ virtual bool WriteASCII();
+ virtual bool WriteXML();
+
+protected:
+ std::string m_filename;
+ std::string m_header;
+
+ //timestep properties
+ bool m_ActiveTS;
+ unsigned int m_timestep;
+
+ vtkDataSet* m_GridData;
+
+ //mesh information
+ int m_MeshType;
+ std::vector<double> m_MeshLines[3];
+ bool m_NativeDump;
+
+ bool m_AppendMode;
+ bool m_Binary;
+ bool m_Compress;
+
+ virtual std::string GetTimestepFilename(int pad_length=10) const;
+};
+
+#endif // VTK_FILE_Writer_H