r/esapi • u/Rostar974 • 2d ago
HDV while optimization
Hi everyone,
Could you know how can I get informations during optimization ? I want to launch an exe and manipulate information from optimization in real time.
r/esapi • u/Rostar974 • 2d ago
Hi everyone,
Could you know how can I get informations during optimization ? I want to launch an exe and manipulate information from optimization in real time.
r/esapi • u/brjdenis • 12d ago
Hi. I wonder if anyone has an opinion on how to properly name scripts.
Say, you have a script called MyScript that you would like to update frequently.
One option is to keep the dll named MyScript.esapi.dll. Of course, internally you increase the version number. In this case, each time you update the script you have to delete the previous file and replace it with a new one. However, you cannot do this if at least one user hasn't closed Aria completely after the last usage of the script. Finding this user or users is very hard. But until you do so, you cannot update the script.
Another option is to have a different name for each new version with increased version number, for example MyScript_v1.10. The downside of this option is that each user has to re-load the script from Tools.
What do you use?
r/esapi • u/kang__23 • 19d ago
Apologies, not quote ESAPI, but does anyone know if you can access the patient weight values enter in 'Vital Signs' via SQL, reporting or otherwise? I have about 500 patients I need to get this data from. Unfortunately 'ActualPatientWeight' column in the 'Slice' table isn't what I'm after.
r/esapi • u/MedPhys90 • 22d ago
I am having trouble getting the dose to a point for electron beams. The point is a vvector, not a reference point. The calculation and dose collection methods seem to work for photon fields but electron fields. Is there different way in which to calculate the depth for electrons?
r/esapi • u/Major-Passenger-7610 • Oct 19 '26
Ciao a tutti!
Sto sviluppando un tool di automazione con Varian Eclipse ESAPI v18 e ho riscontrato un problema che sembra essere già stato discusso in vecchi post su Reddit e altri forum. Vorrei sapere se, rispetto alle discussioni precedenti, qualcuno abbia trovato una soluzione definitiva.
Sto lavorando con una TAC sintetica (sCT) generata da un software esterno e importata in Eclipse insieme alle strutture anatomiche propagate.
Il relativo Structure Set contiene due strutture del lettino:
CouchSurfaceCouchInteriorEntrambe hanno il campo DicomType vuoto ("") e StructureCode nullo.
Quando provo a eliminarle tramite ESAPI:
structureSet.RemoveStructure(structure);ottengo questa eccezione:
System.ArgumentException:
Removing structure of type '' is not allowed.La cosa interessante è che entrambe le strutture possono essere eliminate manualmente dall’interfaccia grafica di Eclipse.
Ho provato anche a utilizzare il metodo specifico dell’API:
structureSet.RemoveCouchStructures(
out IReadOnlyList<string> removedStructureIds,
out string error);Il metodo restituisce true, ma le due strutture rimangono nello Structure Set.
Inoltre, CanRemoveStructure() restituisce false per entrambe, nonostante sia possibile eliminarle manualmente da Eclipse.
Ho già provato a:
Qualcuno ha riscontrato lo stesso problema con ESAPI, in particolare con strutture aventi DicomType vuoto?
Il comportamento è stato corretto nelle versioni più recenti di ESAPI?
Esiste un metodo supportato per eliminare queste strutture via codice, mantenendo tutte le altre strutture anatomiche propagate?
È possibile ricreare o copiare uno Structure Set senza queste strutture problematiche, mantenendo la corretta associazione con la sCT?
Qualcuno ha trovato una soluzione definitiva rispetto a quelle discusse nei vecchi post?
Vorrei trovare una soluzione supportata da ESAPI, evitando workaround non documentati o modifiche dirette al database di Eclipse.
Qualsiasi suggerimento, esperienza o aggiornamento rispetto alle vecchie discussioni sarebbe molto utile, soprattutto se qualcuno è riuscito a risolvere il problema in un ambiente clinico con Eclipse.
Grazie a tutti!
r/esapi • u/ProtonBeamMachine • Oct 09 '26
Hi all,
I’m building a read-only script for Eclipse 16.1 that generates a treatment completion certificate as a PDF. I need to read what shows up in the RT Summary tab (not RT Administration as the title says, my mistake): actual start and end dates, completed fractions per plan, and delivered dose per plan/treated volume.
As far as I can tell, ESAPI doesn’t expose those records. The options I’ve found are ARIA Access, the ARIA API, or querying the ARIA database directly, and I’m not sure which one makes sense.
Are there any examples or repos doing something similar? Any pointers would be much appreciated.
Thanks!
r/esapi • u/Major-Passenger-7610 • Sep 24 '26
Ciao a tutti,
sto lavorando con ESAPI v18 e ho un problema relativo alla Tolerance Table dei beam.
In pratica, sto creando/copiando un piano tramite ESAPI e ricreando i relativi beam. Nel piano originale un beam può avere, ad esempio:
Beam.ToleranceTableLabel = "Table-UD"ma nel beam creato nel nuovo piano la ToleranceTableLabel rimane vuota.
Ho verificato BeamParameters e ApplyParameters(), ma non trovo la tolerance table tra i parametri modificabili. Inoltre Beam.ToleranceTableLabel sembra essere una proprietà read-only.
Qualcuno sa se in ESAPI v18 esiste un modo per:
In alternativa, esiste qualche workaround conosciuto per mantenere la Tolerance Table quando si copia/ricrea un piano, senza dover utilizzare necessariamente dei beam/template già preconfigurati?
Grazie a chiunque abbia qualche esperienza in merito!
r/esapi • u/Major-Passenger-7610 • Sep 24 '26
Title: How can I monitor which Eclipse/ESAPI calculation servers (“servants”) are active?
Hi everyone,
I’m working with Eclipse TPS / ESAPI (v18) and I’m trying to understand how Eclipse manages calculation jobs when a dose calculation is launched programmatically through ESAPI.
In particular, I’m looking for a way to monitor:
For example, if I launch something like:
plan.CalculateDose();(or the corresponding ESAPI calculation workflow), I would like to know where the calculation is actually being processed and whether I can identify/monitor the remote calculation server/servant handling the job.
Is there an official Varian tool or recommended way to monitor this?
I’m mainly interested in the server-side architecture and monitoring, rather than how to optimize the ESAPI code itself.
Thanks!
r/esapi • u/Major-Passenger-7610 • Sep 04 '26
Ciao a tutti,
sto sviluppando un plugin ESAPI per Eclipse v18 (.NET Framework 4.8) e sto cercando di utilizzare il DICOM Database Daemon di Varian per recuperare oggetti DICOM tramite C-MOVE, utilizzando un SCP locale basato su fo-dicom 4.0.8.
Il test viene effettuato in un ambiente di test/non produzione.
Per motivi di privacy e sicurezza non inserisco IP, AE Title, informazioni sui pazienti o percorsi locali.
Configurazione
Eclipse / ESAPI v18
.NET Framework 4.8
fo-dicom 4.0.8
Varian DICOM Database Daemon
C-MOVE verso un SCP locale
porta SCP: 104
TLS disabilitato
configurazione DICOM/trusted entity già effettuata sul sistema di test
Problema
Ho creato inizialmente una console application indipendente utilizzando fo-dicom 4.0.8 come DICOM SCP.
In questo caso tutto funziona correttamente.
Il DICOM Database Daemon effettua la connessione e lo SCP riceve:
A-ASSOCIATE-RQ
Calling AE: VMSDBD
Called AE: <destination AE>
A-ASSOCIATE-AC
C-STORE REQUEST
Calling AE: VMSDBD
Called AE: <destination AE>I file DICOM vengono quindi ricevuti e salvati correttamente.
Quindi sembrano funzionare correttamente:
Quando faccio la stessa cosa dentro ESAPI
Ho successivamente integrato praticamente lo stesso SCP fo-dicom direttamente nel mio plugin ESAPI, quindi all’interno del processo Eclipse/ExternalBeam.
Lo SCP viene avviato correttamente e risulta in ascolto sulla porta 104.
Il C-MOVE viene inoltre accettato dal DICOM Database Daemon.
Ad esempio ricevo:
Status: Pending
Completed: 1
Remaining: 275
Failures: 0fino ad arrivare a:
Status: Success
Status Code: 0000
Completed: 276
Remaining: 0
Failures: 0Quindi il DICOM Database Daemon considera il C-MOVE completamente riuscito.
Il problema è che lo SCP integrato nel plugin non riceve alcun C-STORE.
Non viene visualizzato nemmeno l’evento relativo alla nuova associazione, ad esempio:
A-ASSOCIATE-RQ receivede naturalmente non compare:
C-STORE REQUEST receivedDi conseguenza non viene salvato nessun file.
Cosa mi confonde
Lo stesso SCP fo-dicom, con la stessa configurazione generale, funziona perfettamente quando viene eseguito come applicazione standalone.
Quando invece viene eseguito all’interno del processo Eclipse/ExternalBeam tramite ESAPI:
Qualcuno ha mai avuto un problema simile utilizzando fo-dicom come SCP all’interno di un plugin ESAPI/Eclipse?
Potrebbe essere legato a:
ExternalBeam.exe;DicomServer.Create<T>() gestisce il listener;Mi interessa soprattutto capire se esiste un approccio consigliato per implementare un SCP temporaneo per ricevere il risultato di un C-MOVE direttamente da un plugin ESAPI.
La cosa interessante è che il test standalone dimostra che la parte DICOM e la configurazione del Varian DICOM Daemon funzionano correttamente. Per questo sospetto che il problema sia specificamente legato all’esecuzione dello SCP all’interno del processo Eclipse/ESAPI.
Qualsiasi esperienza, suggerimento o esempio di implementazione è molto apprezzato.
Grazie!
r/esapi • u/Paintasaurus • Sep 03 '26
Is there any way to figure out what plan a CBCT is attached to? Am trying to figure out which CBCT corresponds to which plan in a case where there is a single planning structure set but two different plans in a treatment session.
There is this "References" tab in the CBCT properties (see picture) which seems to have what I want, but can't seem to find any way of accessing it using the API.
r/esapi • u/branstarkkk • Sep 02 '26
Hey everyone, having issues strictly when source plans are using FFF beams. I keep getting an exception.
Documented mapping: energy 'EX', fluence 'FFF', MLC 'C419'. Error: Unable to cast object of type "VMS.TP5. Common.Model.AddOn' to type "VMS.TPS.Common.Model.PrimaryFluenceMode'.
Legacy mapping: energy '6X-FFF', fluence empty, MLC 'C419. Error: External beam configuration not found
Commissioned add-on mapping: energy '6X, fluence empty, MLC 'C419'. Error: Unable to cast object of type 'VMS.TPS. Common.Model.AddOn' to type "VMS.TPS.Common.Model.PrimaryFluenceMode'.Has anyone dealt with this before? I'm on Eclipse 15.6 but we are upgrading to 18.1 in the next month or so
Thanks!
r/esapi • u/NegativeSpend4798 • Sep 01 '26
I want to draft a journal note and encounter as part of a script, anyone done this and know what calls to make?
r/esapi • u/Major-Passenger-7610 • Aug 25 '26
Sto cercando di utilizzare le API FHIR di Varian ARIA da una applicazione .NET Framework 4.8 tramite OAuth2 Client Credentials.
La connessione al Token Service funziona correttamente e la richiesta arriva all'endpoint OAuth, ma la risposta è:
{"error":"invalid_client"}Quindi non sembra essere un problema di rete, DNS, certificati o porte, ma di configurazione del client OAuth.
Finora ho verificato che:
client_id o client_secret utilizzabile.Qualcuno che ha già lavorato con ARIA FHIR sa:
client_id esistente?Qualsiasi indicazione sull'architettura OAuth/FHIR di ARIA sarebbe molto utile.
r/esapi • u/franchae • Aug 18 '26
Has anyone used OptiMate(https://github.com/NickChng/OptiMate) for structure template generation? Looking for feedback on reliability/clinical validation before pursuing internal approval at my institution.
Also curious if anyone has insight into whether Contouring workspace scripting (VMS.CA.Scripting) supports structure creation/modification, or if that's read-only by design.
r/esapi • u/Major-Passenger-7610 • Aug 17 '26
Ciao a tutti,
sto cercando di sviluppare uno script personalizzato per Eclipse 18 Contouring e sono bloccato su un problema che sembra legato al framework IRS/CA.
Ambiente
Riferimenti:
Le DLL si trovano in:
C:\Program Files (x86)\Varian\ProductLine\Workspaces\VMS.IRS.WorkspaceObiettivo
Vorrei realizzare uno strumento che generi automaticamente PTV a partire da GTV/CTV, ma per il momento sto cercando semplicemente di far partire uno script minimale.
Il codice di test è:
using System.Windows;
using VMS.CA.Scripting;
namespace VMS.TPS
{
public class Script
{
public void Execute(ScriptContext_ context)
{
MessageBox.Show("CONTOURING SCRIPT OK");
}
}
}La soluzione compila senza errori e genera correttamente la DLL.
Quando però provo a lanciarla da:
Contouring → Tools → Scriptsottengo sempre il messaggio:
The script does not contain a public type with name 'VMS.IRS.Scripting'Cose già provate
VMS.TPS.Script)VMS.IRS.ScriptingVMS.CA.Scripting<appSettings>
<add key="AssemblyPath"
value="C:\Program Files (x86)\Varian\ProductLine\Workspaces\VMS.IRS.Workspace\" />
</appSettings>Cartella script contenente solo:
ScriptContext_ esiste in VMS.CA.Scripting.dllDomande
ScriptBase, IScript, ecc.)?Qualsiasi esempio di progetto funzionante, screenshot della struttura o indicazione sulla corretta configurazione IRS/CA sarebbe molto utile.
Grazie mille!
r/esapi • u/Major-Passenger-7610 • Aug 13 '26
Hi everyone,
Does anyone know if there is a way in ESAPI v18 to copy the dose calculation grid/resolution from one plan to another?
For example, I have an original plan calculated with AcurosXB using a 1,25 mm dose grid, and I would like to create another plan and calculate the dose using exactly the same grid (resolution, size and position).
I can read the grid information from the Dose object using:
plan.Dose.XRes
plan.Dose.YRes
plan.Dose.ZRes
plan.Dose.XSize
plan.Dose.YSize
plan.Dose.ZSize
but I haven't found a way to set these values on another plan before calculating the dose.
Is there a supported ESAPI method to copy the dose calculation grid from an existing plan to another plan?
I found some older discussions mentioning CopyEvaluationDose(), but I am not sure if this is applicable to ESAPI v18 or if there is another recommended approach.
Thanks!
r/esapi • u/LaurieCho • Jul 30 '26
Running ESAPI v18.1 standalone (tested with both IronPython 2.7.12 and PyESAPI/pythonnet on Python 3.13).
Every attempt to connect crashes with:
System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.
at System.Security.Cryptography.SHA256Managed..ctor()
at VMS.SF.Gateway.VarianApplicationToken.Generate(String message)
at VMS.SF.Gateway.Client.GatewayClientForInternalUse.Process(Request request)Looks like VarianApplicationToken.Generate calls SHA256Managed (a non-FIPS-validated implementation) to build the auth token, which fails outright on a machine with FIPS mode enabled (Local Security Policy: "System cryptography: Use FIPS compliant algorithms...").
This same workstation/script worked fine under v16 — this VMS.SF.Gateway auth token mechanism seems to be new since v18.
Digging into Windows-level FIPS policy is outside my area of expertise.
Has anyone dealt with this on a FIPS-enforced hospital workstation? Is disabling FIPS the only fix, or is there a known workaround / config on Varian's side (e.g. an app.config redirect for the gateway assembly) that avoids touching the machine-wide FIPS policy?
Thanks.
r/esapi • u/DefiantLeague356 • Jul 18 '26
My hospital is trying to adopt adpative planning and would like to use script for automatic plan setup. I have successfully automatically create the plan and optimization process, but I want to check if the following steps can be done with scripting?
the eclipse version is 16.1 in T-box and 18.1 for clinical planning system
Thanks for your valuable comments and opinions
r/esapi • u/Invictus_Shoe • Jul 17 '26
I exported hundreds of patients from out clinical system to the research system. Now I can't generate treatment plans automatically via ESAPI v15.6, because the scanner and the CT image of the patients are not connected. At the moment I have to open Eclipse manually, open the VMAT optimization view and select the scanner. Then save and then I can start with the automatic planning. Is is possible to connect the scanner to the CT images automatically?
Thank you!
r/esapi • u/schmatt_schmitt • Jul 09 '26
Join us for a Vibe Coding Hackathon Saturday night before AAPM, sign up here: https://events.bizzabo.com/891767 with Matthew Schmidt, Michael Folkerts, PhD, Ryan Clark, MS, CMD, R.T.(T), and Taoran Li, Ph.D., DABR
Low stress, high impact: vibe coding for physicists - Saturday, July 18, 2026 - 6:00pm to 8:30pm
Join us with your charged laptop for a follow-along, hackathon workshop-style event, previously known as the Varian Developer Symposium. Along with pizza and beverages, the evening will include:
* ARIA API examples integrating with ESAPI projects
* Examples of ESAPI launchers into full standalone .html client browser-based tools using vibe coding software development environments to handle the HTML5/JavaScript tooling
* IDE-less pure C# simple LLM based vibe coding examples and experimentation
r/esapi • u/Major-Passenger-7610 • Jul 09 '26

Ciao a tutti,
sto lavorando su uno script ESAPI con l’obiettivo di automatizzare il flusso di lavoro CreateVerificationPlan dei PSQC (Patient Specific Quality Control).
L’obiettivo è creare automaticamente un verification plan riproducendo la geometria del piano originale su un fantoccio importato, evitando i passaggi manuali attualmente necessari.
Sono riuscito a ottenere una soluzione parziale. Attualmente il mio script è in grado di:
Il problema principale riguarda la copia delle MLC. Lo script non riesce ancora a trasferire correttamente le posizioni delle leaf/control point. Di conseguenza il calcolo delle MU non è corretto e tutti i field weight rimangono impostati a 1.
Ho inoltre configurato la TBox (ambiente di testing Varian non clinico) per lo sviluppo. Qui ho riscontrato un comportamento differente rispetto all’ambiente clinico: utilizzando esattamente lo stesso codice, nella TBox ottengo un errore che non si presenta nell’ambiente clinico.
Allego lo screenshot dell’errore ottenuto in TBox per riferimento.
Sto cercando di capire se questa differenza possa essere dovuta a:
Allego anche il progetto completo con tutti i progressi fatti finora.
Qualcuno ha già sviluppato un flusso simile per automatizzare la creazione dei verification plan PSQC tramite ESAPI? Avete esperienza con:
Qualsiasi suggerimento o esperienza sarebbe molto utile.
Grazie in anticipo!
// =====================================================
// CREATE VERIFICATION BEAMS
// =====================================================
foreach (var beam in beams)
{
if (beam.IsSetupField)
continue;
var machineParams = new ExternalBeamMachineParameters(
beam.TreatmentUnit.Id,
beam.EnergyModeDisplayName,
beam.DoseRate,
beam.Technique.Id,
string.Empty);
if (beam.MLCPlanType == MLCPlanType.VMAT)
{
var meterset = beam.ControlPoints
.Select(cp => cp.MetersetWeight);
verificationPlan.AddVMATBeam(
machineParams,
meterset,
beam.ControlPoints.First().CollimatorAngle,
beam.ControlPoints.First().GantryAngle,
beam.ControlPoints.Last().GantryAngle,
beam.GantryDirection,
0.0,
iso);
}
else if (beam.MLCPlanType == MLCPlanType.DoseDynamic)
{
var meterset = beam.ControlPoints
.Select(cp => cp.MetersetWeight);
verificationPlan.AddSlidingWindowBeam(
machineParams,
meterset,
beam.ControlPoints.First().CollimatorAngle,
beam.ControlPoints.First().GantryAngle,
0.0,
iso);
}
else
{
throw new Exception(
$"Unsupported beam type: {beam.MLCPlanType}");
}
}r/esapi • u/Major-Passenger-7610 • Jul 09 '26
Ciao a tutti,
sto lavorando su uno script ESAPI con l’obiettivo di automatizzare il flusso di lavoro CreateVerificationPlan dei PSQC.
L’obiettivo è creare automaticamente un verification plan riproducendo la geometria del piano originale su un fantoccio importato, evitando i passaggi manuali attualmente necessari.
Sono riuscito a ottenere una soluzione parziale. Attualmente il mio script è in grado di:
Il problema principale riguarda la copia delle MLC. Lo script non riesce ancora a trasferire correttamente le posizioni delle leaf/control point. Di conseguenza il calcolo delle MU non è corretto e tutti i field weight rimangono impostati a 1.
Ho inoltre configurato la TBox (ambiente di testing Varian non clinico) per lo sviluppo. Qui ho riscontrato un comportamento differente rispetto all’ambiente clinico: utilizzando esattamente lo stesso codice, nella TBox ottengo un errore che non si presenta nell’ambiente clinico (di cui allego screenshot).
Allego lo screenshot dell’errore ottenuto in TBox per riferimento.
Sto cercando di capire se questa differenza possa essere dovuta a:
Allego anche il progetto completo con tutti i progressi fatti finora.
Qualcuno ha già sviluppato un flusso simile per automatizzare la creazione dei verification plan PSQC tramite ESAPI? Avete esperienza con:
Qualsiasi suggerimento o esperienza sarebbe molto utile.
Grazie in anticipo! (vi allego codice e screenshot dell'errore su TBOX)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using VMS.TPS.Common.Model.API;
using VMS.TPS.Common.Model.Types;
namespace PSQC_Automation.Services
{
public static class QAService
{
private class PhantomInfo
{
public string PatientId;
public string StudyId;
public string ImageId;
}
private static readonly Dictionary<string, PhantomInfo> PhantomDB =
new Dictionary<string, PhantomInfo>
{
{ "ArcCHECK_AXB", new PhantomInfo { PatientId="A0016502", StudyId="CT1", ImageId="Series 57" } },
{ "ArcCHECK_AAA", new PhantomInfo { PatientId="A0016502", StudyId="CT1", ImageId="Series 31" } },
{ "2AXB_SRSMapcheck", new PhantomInfo { PatientId="A0098581", StudyId="23356", ImageId="Series 30" } },
{ "Delta4_STx", new PhantomInfo { PatientId="A0114297", StudyId="S", ImageId="Series 2" } },
{ "Delta4_Halcyon", new PhantomInfo { PatientId="A0112099", StudyId="S", ImageId="Series 4" } },
{ "SNC", new PhantomInfo { PatientId="A0016502", StudyId="CT1", ImageId="ArcCheckHALO_AXB" } }
};
public static void RunQA(
Patient patient,
ExternalPlanSetup originalPlan,
string phantom,
string exportPath,
string machine)
{
try
{
MessageBox.Show("START QA AUTOMATION");
// =====================================================
// COURSE
// =====================================================
var courseId = $"PSQC_{DateTime.Now.Year}";
var course = patient.Courses.FirstOrDefault(c => c.Id == courseId);
if (course == null)
{
course = patient.AddCourse();
course.Id = courseId;
}
if (course.CompletedDateTime.HasValue)
{
MessageBox.Show("QA course is COMPLETED. Set it ACTIVE.");
return;
}
// =====================================================
// PHANTOM IMPORT
// =====================================================
var ssQA = GetOrImportPhantom(patient, phantom);
if (ssQA == null)
{
MessageBox.Show("ERROR: phantom import failed");
return;
}
// =====================================================
// SAFETY CHECK (COUCH)
// =====================================================
foreach (var beam in originalPlan.Beams)
{
if (Math.Abs(beam.ControlPoints.First().PatientSupportAngle) > 0.01)
{
MessageBox.Show(
$"Couch rotation detected in beam {beam.Id}\nManual verification required.");
return;
}
}
// =====================================================
// CREATE VERIFICATION PLAN (VARIAN OFFICIAL ONLY)
// =====================================================
var qaPlan = CreateVerificationPlan(
course,
originalPlan.Beams,
originalPlan,
ssQA,
calculateDose: true);
// =====================================================
// RENAME PLAN
// =====================================================
qaPlan.Id = GenerateQAId(originalPlan);
// =====================================================
// PRESCRIPTION
// =====================================================
qaPlan.SetPrescription(
1,
originalPlan.DosePerFraction,
originalPlan.TreatmentPercentage);
// =====================================================
// DOSE MODEL
// =====================================================
qaPlan.SetCalculationModel(
CalculationType.PhotonVolumeDose,
originalPlan.GetCalculationModel(CalculationType.PhotonVolumeDose));
// =====================================================
// DOSE CALCULATION
// =====================================================
CalculationResult result;
bool isIMRT = qaPlan.Beams.Any(b => b.MLCPlanType == MLCPlanType.DoseDynamic);
if (isIMRT)
{
var preset = originalPlan.Beams
.Where(b => !b.IsSetupField)
.Select(b =>
new KeyValuePair<string, MetersetValue>(
b.Id,
b.Meterset))
.ToList();
result = qaPlan.CalculateDoseWithPresetValues(preset);
}
else
{
result = qaPlan.CalculateDose();
}
if (!result.Success)
{
MessageBox.Show("DOSE CALCULATION FAILED\n\n" + result);
return;
}
// =====================================================
// SUCCESS
// =====================================================
MessageBox.Show(
"QA COMPLETED SUCCESSFULLY\n\n" +
$"Plan: {qaPlan.Id}\n" +
$"Beams: {qaPlan.Beams.Count()}");
}
catch (Exception ex)
{
MessageBox.Show("FATAL ERROR\n\n" + ex);
}
}
// =====================================================
// VARIAN OFFICIAL VERIFICATION PLAN CREATION
// =====================================================
public static ExternalPlanSetup CreateVerificationPlan(
Course course,
IEnumerable<Beam> beams,
ExternalPlanSetup verifiedPlan,
StructureSet verificationStructures,
bool calculateDose)
{
var verificationPlan =
course.AddExternalPlanSetupAsVerificationPlan(
verificationStructures,
verifiedPlan);
// =====================================================
// PLAN ID
// =====================================================
string id;
if (verifiedPlan.Id.Length >= 13)
id = verifiedPlan.Id.Substring(0, verifiedPlan.Id.Length - 2) + "_QA";
else
id = verifiedPlan.Id + "_QA";
verificationPlan.Id = id;
// =====================================================
// ISO CENTER
// =====================================================
VVector iso = verificationPlan.StructureSet.Image.UserOrigin;
var originalBeams = beams.Where(b => !b.IsSetupField).ToList();
// =====================================================
// CREATE BEAMS
// =====================================================
foreach (var beam in beams)
{
if (beam.IsSetupField)
continue;
var machineParams = new ExternalBeamMachineParameters(
beam.TreatmentUnit.Id,
beam.EnergyModeDisplayName,
beam.DoseRate,
beam.Technique.Id,
string.Empty);
if (beam.MLCPlanType == MLCPlanType.VMAT)
{
var meterset = beam.ControlPoints.Select(cp => cp.MetersetWeight);
verificationPlan.AddVMATBeam(
machineParams,
meterset,
beam.ControlPoints.First().CollimatorAngle,
beam.ControlPoints.First().GantryAngle,
beam.ControlPoints.Last().GantryAngle,
beam.GantryDirection,
0.0,
iso);
}
else if (beam.MLCPlanType == MLCPlanType.DoseDynamic)
{
var meterset = beam.ControlPoints.Select(cp => cp.MetersetWeight);
verificationPlan.AddSlidingWindowBeam(
machineParams,
meterset,
beam.ControlPoints.First().CollimatorAngle,
beam.ControlPoints.First().GantryAngle,
0.0,
iso);
}
else
{
throw new Exception($"Unsupported beam type: {beam.MLCPlanType}");
}
}
// =====================================================
// ALIGN IDS
// =====================================================
int i = 0;
foreach (var vb in verificationPlan.Beams)
{
if (vb.IsSetupField) continue;
vb.Id = originalBeams[i].Id;
i++;
}
// =====================================================
// IMRT ISO FIX
// =====================================================
foreach (var vb in verificationPlan.Beams)
{
foreach (var ob in originalBeams)
{
if (vb.Id == ob.Id &&
vb.MLCPlanType == MLCPlanType.DoseDynamic)
{
var editable = ob.GetEditableParameters();
editable.Isocenter = iso;
vb.ApplyParameters(editable);
}
}
}
// =====================================================
// PRESCRIPTION
// =====================================================
verificationPlan.SetPrescription(
1,
verifiedPlan.DosePerFraction,
verifiedPlan.TreatmentPercentage);
verificationPlan.SetCalculationModel(
CalculationType.PhotonVolumeDose,
verifiedPlan.GetCalculationModel(CalculationType.PhotonVolumeDose));
// =====================================================
// DOSE CALC
// =====================================================
CalculationResult res;
if (verificationPlan.Beams.Any(b => b.MLCPlanType == MLCPlanType.DoseDynamic))
{
var preset = beams
.Where(b => !b.IsSetupField)
.Select(b =>
new KeyValuePair<string, MetersetValue>(
b.Id,
b.Meterset))
.ToList();
res = verificationPlan.CalculateDoseWithPresetValues(preset);
}
else
{
res = verificationPlan.CalculateDose();
}
if (!res.Success)
throw new Exception("Dose calculation failed");
return verificationPlan;
}
// =====================================================
// PHANTOM IMPORT
// =====================================================
private static StructureSet GetOrImportPhantom(
Patient patient,
string phantom)
{
var existing = patient.StructureSets.FirstOrDefault(s => s.Id == phantom);
if (existing != null) return existing;
if (!PhantomDB.ContainsKey(phantom))
return null;
var info = PhantomDB[phantom];
var ss = patient.CopyImageFromOtherPatient(
info.PatientId,
info.StudyId,
info.ImageId);
if (ss != null)
ss.Id = phantom;
return ss;
}
private static string GenerateQAId(ExternalPlanSetup plan)
{
return plan.Id.Length > 10
? plan.Id.Substring(0, 10) + "_QA"
: plan.Id + "_QA";
}
}
}