Skip to main content

ZOS-API interface 2025 R1 SP01

CSharpStandalone_25_source_spectrum_diffraction_grating

Last update: 17.07.2025
using System;
using ZOSAPI;
namespace CSharpStandaloneApplication
{
class Program
{
static void Main(string[] args)
{
// Find the installed version of OpticStudio
bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize();
// Note -- uncomment the following line to use a custom initialization path
//bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(@"C:\Program Files\OpticStudio\");
if (isInitialized)
{
LogInfo("Found OpticStudio at: " + ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory());
}
else
{
HandleError("Failed to locate OpticStudio!");
return;
}
BeginStandaloneApplication();
}
static void BeginStandaloneApplication()
{
// Create the initial connection class
ZOSAPI_Connection TheConnection = new ZOSAPI_Connection();
// Attempt to create a Standalone connection
IZOSAPI_Application TheApplication = TheConnection.CreateNewApplication();
if (TheApplication == null)
{
HandleError("An unknown connection error occurred!");
return;
}
// Check the connection status
if (!TheApplication.IsValidLicenseForAPI)
{
HandleError("Failed to connect to OpticStudio: " + TheApplication.LicenseStatus);
return;
}
if (TheApplication.Mode != ZOSAPI_Mode.Server)
{
HandleError("User plugin was started in the wrong mode: expected Server, found " + TheApplication.Mode.ToString());
return;
}
IOpticalSystem TheSystem = TheApplication.PrimarySystem;
// creates new directory
string strPath = System.IO.Path.Combine(TheApplication.SamplesDir, @"API\CS");
System.IO.Directory.CreateDirectory(strPath);
// Set up primary optical system
TheSystem = TheApplication.CreateNewSystem(ZOSAPI.SystemType.NonSequential);
// Initializes NCE and loads surfaces
// Inserts objects
INonSeqEditor TheNCE = TheSystem.NCE;
TheNCE.InsertNewObjectAt(1);
TheNCE.InsertNewObjectAt(1);
TheNCE.InsertNewObjectAt(1);
TheNCE.InsertNewObjectAt(1);
INCERow o1 = TheNCE.GetObjectAt(1);
INCERow o2 = TheNCE.GetObjectAt(2);
INCERow o3 = TheNCE.GetObjectAt(3);
INCERow o4 = TheNCE.GetObjectAt(4);
INCERow o5 = TheNCE.GetObjectAt(5);
// Changes Object Type
o1.ChangeType(o1.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.SourceDiode));
o2.ChangeType(o2.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.SourceDiode));
o3.ChangeType(o3.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.NullObject));
o4.ChangeType(o4.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.DiffractionGrating));
o5.ChangeType(o5.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.DetectorColor));
// Sets positions & materials
o3.ZPosition = 10;
o3.TiltAboutX = 10;
o4.RefObject = 3;
o4.Material = "MIRROR";
o5.YPosition = 8.45;
o5.TiltAboutX = 40;
// Sets parameters
o1.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par7).DoubleValue = 5;
o2.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par7).DoubleValue = 5;
o4.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par10).DoubleValue = 0.6;
o4.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par11).DoubleValue = 1;
// Changes sourcecolor to Blackbody, sets temperature, min/ max wavelength
o1.SourcesData.SourceColor = ZOSAPI.Editors.NCE.SourceColorMode.BlackBodySpectrum;
o1.SourcesData.SourceColorSettings._S_BlackBodySpectrum.TemperatureK = 6000;
o1.SourcesData.SourceColorSettings._S_BlackBodySpectrum.WavelengthFrom = 0.45;
o1.SourcesData.SourceColorSettings._S_BlackBodySpectrum.WavelengthTo = 0.65;
o2.SourcesData.SourceColor = ZOSAPI.Editors.NCE.SourceColorMode.BlackBodySpectrum;
o2.SourcesData.SourceColorSettings._S_BlackBodySpectrum.TemperatureK = 6000;
o2.SourcesData.SourceColorSettings._S_BlackBodySpectrum.SpectrumCount = 100;
o2.SourcesData.SourceColorSettings._S_BlackBodySpectrum.WavelengthFrom = 0.4;
o2.SourcesData.SourceColorSettings._S_BlackBodySpectrum.WavelengthTo = 0.7;
// Sets up the MCE, adds configuration &operands
TheMCE.AddConfiguration(false);
TheMCE.AddOperand();
TheMCE.AddOperand();
TheMCE.AddOperand();
// change MCE to NPAR, modifies the number of Layout Rays for a Source
for (int a = 1; a <= 4; a++)
{
TheMCE.GetOperandAt(a).ChangeType(ZOSAPI.Editors.MCE.MultiConfigOperandType.NPAR);
}
TheMCE.GetOperandAt(1).Param2 = 1;
TheMCE.GetOperandAt(1).Param3 = 1;
TheMCE.GetOperandAt(2).Param2 = 1;
TheMCE.GetOperandAt(2).Param3 = 2;
TheMCE.GetOperandAt(2).GetOperandCell(1).DoubleValue = 1000000;
TheMCE.GetOperandAt(3).Param2 = 2;
TheMCE.GetOperandAt(3).Param3 = 1;
TheMCE.GetOperandAt(4).Param2 = 2;
TheMCE.GetOperandAt(4).Param3 = 2;
TheMCE.GetOperandAt(4).GetOperandCell(2).DoubleValue = 1000000;
// Setup detector color
double x_width = 1.5, y_width = 1.5;
int x_pixel = 500, y_pixel = 500;
(o5.ObjectData as IObjectDetectorColor).XHalfWidth = x_width;
(o5.ObjectData as IObjectDetectorColor).YHalfWidth = y_width;
(o5.ObjectData as IObjectDetectorColor).NumberXPixels = x_pixel;
(o5.ObjectData as IObjectDetectorColor).NumberYPixels = y_pixel;
// initializes StringBuilder
System.Text.StringBuilder sbReport = new System.Text.StringBuilder();
string resFile;
for (var a = 1; a <= TheMCE.NumberOfConfigurations; a++)
{
// Setup and run the ray trace
ZOSAPI.Tools.RayTrace.INSCRayTrace NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace();
NSCRayTrace.ClearDetectors(0);
NSCRayTrace.SplitNSCRays = false;
NSCRayTrace.ScatterNSCRays = false;
NSCRayTrace.UsePolarization = false;
NSCRayTrace.IgnoreErrors = true;
NSCRayTrace.SaveRays = false;
NSCRayTrace.RunAndWaitForCompletion();
NSCRayTrace.Close();
Console.WriteLine("Finished ray trace");
// Creates a new detector viewer window, changes to true color
ZOSAPI.Analysis.IA_ det = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.DetectorViewer);
det_settings.ShowAs = ZOSAPI.Analysis.DetectorViewerShowAsTypes.TrueColor;
// Creates System.Single[] buffers to store pixel data
Single[] rData = new float[(int)(x_pixel * y_pixel)];
Single[] gData = new float[(int)(x_pixel * y_pixel)];
Single[] bData = new float[(int)(x_pixel * y_pixel)];
// Loads RGB data into System.Single buffer
det_raw.FillValues((uint)(x_pixel * y_pixel), rData, gData, bData);
sbReport.Append(string.Concat("Red: ", string.Join(", ", rData), "\nGreen: ", string.Join(", ", gData), "\nBlue: ", string.Join(", ", bData)));
resFile = TheApplication.SamplesDir + "\\API\\CS\\e25_source_spectrum_diffraction_grating_" + a + ".txt";
System.IO.File.WriteAllText(resFile, sbReport.ToString());
sbReport.Clear();
}
TheSystem.SaveAs(TheApplication.SamplesDir + "\\API\\CS\\e25_source_spectrum_diffraction_grating.zos");
// Clean up
FinishStandaloneApplication(TheApplication);
}
static void FinishStandaloneApplication(IZOSAPI_Application TheApplication)
{
// Note - TheApplication will close automatically when this application exits, so this isn't strictly necessary in most cases
if (TheApplication != null)
{
TheApplication.CloseApplication();
}
}
static void LogInfo(string message)
{
// TODO - add custom logging
Console.WriteLine(message);
}
static void HandleError(string errorMessage)
{
// TODO - add custom error handling
throw new Exception(errorMessage);
}
}
}
Definition: ZemaxService.cs:198
IZOSAPI_Application CreateNewApplication()
Attempts to launch a new instance of Optic Studio in 'headless' mode. Note that although the Optic St...
Definition: ZemaxService.cs:864
Definition: IAR_Base.cs:286
void FillValues(uint fullSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] rData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] gData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] bData)
Retries all RGB data at once, into the specified buffers.
Properties and methods for retrieving analysis window data. This interface can be accessed via the IA...
Definition: IAR_Base.cs:21
IAR_DataGridRgb GetDataGridRgb(int index)
Base interface for all analysis windows. This interface can be accessed via the I_Analyses interface.
Definition: IA_Base.cs:29
IAR_ GetResults()
Gets the result data (if available) for the current analysis.
IAS_ GetSettings()
Gets the settings for the current analysis.
IMessage ApplyAndWaitForCompletion()
Re-runs the analysis with the current settings and waits for it to finish calculating.
Definition: IAS_DetectorViewer.cs:23
double DoubleValue
Gets or sets the double precision value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:340
int Param2
Definition: InterfacesMCE.cs:499
bool ChangeType(MultiConfigOperandType type)
Changes to the specified operand type.
IEditorCell GetOperandCell(int configuration)
Gets the specified operand cell data.
int Param3
Definition: InterfacesMCE.cs:513
This interface defines all properties and methods needed to interact with the Multiple Configuration ...
Definition: InterfacesMCE.cs:158
IMCERow GetOperandAt(int OperandNumber)
Gets the specified operand data.
IMCERow AddOperand()
Adds a new operand to the end of the editor.
bool AddConfiguration(bool withPickups)
Adds a new, last configuration.
bool SetCurrentConfiguration(int ConfigurationNumber)
Sets the currently active configuration for the system (1 to NumberOfConfigurations).
int NumberOfConfigurations
Gets the total number of configurations.
Definition: InterfacesMCE.cs:195
All data for a Non-Sequential Component Editor object. This interface can be accessed via the INonSeq...
Definition: InterfacesNCE.cs:1198
bool ChangeType(IObjectTypeSettings settings)
Changes the current object to the specified type. Use GetObjectTypeSettings to get the relevant setti...
IEditorCell GetObjectCell(ObjectColumn Col)
Gets the specified object cell data.
IObjectTypeSettings GetObjectTypeSettings(ObjectType type)
Create the settings for the specified type. Use this method to specify any extra data required to cha...
This interface defines all properties and methods needed to interact with the Non-Sequential Componen...
Definition: InterfacesNCE.cs:363
INCERow GetObjectAt(int ObjectNumber)
Gets the object at the specified position.
INCERow InsertNewObjectAt(int ObjectNumber)
Inserts a new object at the specified position.
Definition: InterfacesNCE.cs:3202
Represent a complete optical system. A IOpticalSystem corresponds to a single .ZMX file....
Definition: Interfaces.cs:687
void SaveAs(string fileName)
Saves the current system to the specified file. All future calls to Save will use the same file.
I_Analyses Analyses
Gets the analyses for the current system.
Definition: Interfaces.cs:925
INonSeqEditor NCE
Gets the non-sequential component editor.
Definition: Interfaces.cs:884
IOpticalSystemTools Tools
Gets an interface used to run various tools on the optical system.
Definition: Interfaces.cs:932
IMultiConfigEditor MCE
Gets the multi-configuration editor.
Definition: Interfaces.cs:917
This interface contains all information about the current ZOS-API connection, as well as methods for ...
Definition: Interfaces.cs:261
IOpticalSystem CreateNewSystem(SystemType mode)
Creates a new empty optical system, in the specified mode.
bool IsValidLicenseForAPI
Gets a value indicating whether this the API is currently useable.
Definition: Interfaces.cs:287
ZOSAPI_Mode Mode
Gets the current connetion mode. Use this to check if Optic Studio is expecting a user operand / anal...
Definition: Interfaces.cs:306
LicenseStatusType LicenseStatus
Gets the license status. Note that this displays the license edition if successful,...
Definition: Interfaces.cs:280
void CloseApplication()
Shut down the Optic Studio process.
IOpticalSystem PrimarySystem
Gets the primary system. When Mode is ZOSAPI_Mode.Server, this will initially be an empty sequential ...
Definition: Interfaces.cs:328
string SamplesDir
Gets the full path for the current user's samples directory (in the My Documents\Zemax\Samples\ folde...
Definition: Interfaces.cs:505
bool RunAndWaitForCompletion()
Sames as calling Run followed by WaitForCompletion.
bool Close()
Closes this tool and frees up and associated resources.
Interfaces and methods for running a non-sequential ray trace. This interface can be accessed via the...
Definition: RayTrace.cs:45
ErrorType ClearDetectors(int DetectorNumber)
Clears the specified detectors.
Definition: IAR_Base.cs:11
Definition: IAS_DetectorViewer.cs:6
Definition: IAS_FieldCurvatureAndDistortion.cs:5
Definition: IAS_FieldCurvatureAndDistortion.cs:5
Definition: InterfacesMCE.cs:11
Definition: InterfacesNCE.cs:19
Definition: InterfacesEditors.cs:12
The ZOSAPI namespace contains classes for initially connecting to zemax. See also ZOSAPI_Connection,...
Definition: IAS_FieldCurvatureAndDistortion.cs:5
ZOSAPI_Mode
Definition: Interfaces.cs:77

Connect with Ansys