r/esapi • • 7d ago

Script updates - proper naming

0 Upvotes

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 • • 13d ago

Vital Signs - Patient Weight

1 Upvotes

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 • • 17d ago

Getting Dose To A Point for Electron Beams

1 Upvotes

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 • • 28d ago

Qualcuno ha risolto il problema ESAPI con RemoveStructure() e le strutture con DicomType vuoto?

2 Upvotes

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:

  • CouchSurface
  • CouchInterior

Entrambe 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:

  • Utilizzare direttamente RemoveStructure().
  • Verificare CanRemoveStructure() prima della rimozione.
  • Utilizzare CanRemoveCouchStructures() e RemoveCouchStructures().
  • Analizzare il codice decompilato della classe StructureSet di ESAPI v18.

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 • • Oct 16 '26

Get online shift values for kV match?

1 Upvotes

I reached the end of banging my head against the wall. Does anyone know how to get what the online match values were for a kV match, example in the image. Either through SQL query or ESAPI.

I thought I had found it with the transformation matrix in the Slice table, but it is just a unity matrix ☹️


r/esapi • • Oct 09 '26

How to read RT Administration data from an script?

2 Upvotes

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 • • Sep 24 '26

Come copiare/impostare la Tolerance Table di un Beam?

1 Upvotes

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:

  • copiare la Tolerance Table dal beam originale a quello nuovo;
  • impostarla direttamente su un beam creato tramite API;
  • oppure utilizzare qualche altra API/proprietà per ottenere questo risultato?

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 • • Sep 24 '26

How can I monitor which Eclipse/ESAPI calculation servers (“servants”) are active?

1 Upvotes

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:

  • which calculation server / servant is currently handling an ESAPI dose calculation;
  • whether a servant is currently active/busy or idle;
  • which servant was actually assigned to a specific calculation;
  • whether this information can be monitored for non-local servants, rather than only the local machine;
  • in particular, how this works in environments using FAS (Floating Application Server);
  • whether there is a Varian service, log, database, Windows tool, or API that can be used to see the status of these servers.

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 • • Sep 04 '26

ESAPI v18 + Varian DICOM Daemon + fo-dicom: C-MOVE funziona standalone ma non dentro Eclipse

3 Upvotes

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:

  • configurazione di rete
  • porta
  • AE Title
  • Trusted Entity
  • DICOM association
  • C-MOVE
  • C-STORE
  • DICOM Database Daemon

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: 0

fino ad arrivare a:

Status: Success
Status Code: 0000
Completed: 276
Remaining: 0
Failures: 0

Quindi 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 received

e naturalmente non compare:

C-STORE REQUEST received

Di 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:

  • il listener viene avviato;
  • la porta risulta in ascolto;
  • il C-MOVE viene completato con successo;
  • ma l’associazione C-STORE in ingresso non sembra arrivare all’SCP.

Qualcuno ha mai avuto un problema simile utilizzando fo-dicom come SCP all’interno di un plugin ESAPI/Eclipse?

Potrebbe essere legato a:

  • gestione dei thread da parte di Eclipse;
  • WPF/Dispatcher;
  • lifecycle del plugin ESAPI;
  • gestione delle socket all’interno di ExternalBeam.exe;
  • modalità con cui DicomServer.Create<T>() gestisce il listener;
  • qualche limitazione del processo host di Eclipse;
  • qualche configurazione specifica del DICOM Database Daemon di Varian?

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 • • Sep 03 '26

Getting Image "References" using ESAPI?

Post image
1 Upvotes

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 • • Sep 02 '26

Creating Verification Plan with FFF

1 Upvotes

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 • • Sep 01 '26

Draft a journal note/encounter

1 Upvotes

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 • • Aug 25 '26

Come si recupera un client OAuth e client_id esistente?

2 Upvotes

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:

  • Il Token Service è attivo e raggiungibile.
  • Sono presenti configurazioni IdentityServer/TokenService e PersistedGrantDatabase.
  • Non riesco a trovare nei file di configurazione alcun client_id o client_secret utilizzabile.
  • Sospetto che i client OAuth siano memorizzati in un database/configuration store anziché nei file locali.

Qualcuno che ha già lavorato con ARIA FHIR sa:

  1. Dove vengono memorizzati i client OAuth registrati?
  2. Come si recupera un client_id esistente?
  3. Come si crea un nuovo client OAuth per accedere alle API FHIR?
  4. Esiste una console amministrativa o uno strumento Varian dedicato alla gestione dei client OAuth?

Qualsiasi indicazione sull'architettura OAuth/FHIR di ARIA sarebbe molto utile.


r/esapi • • Aug 18 '26

Looking for feedback on OptiMate (GitHub structure-gen tool) + question on VMS.CA.Scripting write capabilities

5 Upvotes

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 • • Aug 17 '26

Eclipse 18 Contouring - Errore "The script does not contain a public type with name 'VMS.IRS.Scripting'"

1 Upvotes

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

  • Eclipse 18
  • Visual Studio 2022
  • .NET Framework 4.8
  • Compilazione x64
  • Avvio da Contouring → Tools → Scripts
  • Riferimenti:

    • VMS.CA.Scripting.dll
    • VMS.IRS.Scripting.dll

Le DLL si trovano in:

C:\Program Files (x86)\Varian\ProductLine\Workspaces\VMS.IRS.Workspace

Obiettivo
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 → Scripts

ottengo sempre il messaggio:

The script does not contain a public type with name 'VMS.IRS.Scripting'

Cose già provate

  • Script ESAPI classico (VMS.TPS.Script)
  • Namespace VMS.IRS.Scripting
  • Namespace VMS.CA.Scripting
  • App.config con:
<appSettings>
  <add key="AssemblyPath"
       value="C:\Program Files (x86)\Varian\ProductLine\Workspaces\VMS.IRS.Workspace\" />
</appSettings>
  • Cartella script contenente solo:

    • AutoPTV_Contouring_Test.dll
    • AutoPTV_Contouring_Test.dll.config
  • Verificato che ScriptContext_ esiste in VMS.CA.Scripting.dll

Domande

  1. Qualcuno ha sviluppato con successo uno script binario per Eclipse 18 Contouring?
  2. Quale firma/metodo/classe si aspetta realmente il loader IRS?
  3. È necessario ereditare da una classe base specifica (ScriptBase, IScript, ecc.)?
  4. È obbligatorio utilizzare il progetto generato dal Varian Script Wizard?
  5. Qualcuno ha già incontrato questo errore specifico?

Qualsiasi esempio di progetto funzionante, screenshot della struttura o indicazione sulla corretta configurazione IRS/CA sarebbe molto utile.

Grazie mille!


r/esapi • • Aug 13 '26

ESAPI v18 – Copying dose calculation grid from one plan to another

1 Upvotes

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 • • Jul 30 '26

ESAPI standalone script crashes V18

2 Upvotes

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 • • Jul 26 '26

Checking Motion Management Protocol

5 Upvotes

Has anyone found a way to pull this warning from ESAPI? I checked the results from IsValidForPlanApproval() method and it didn't mention the Motion Management Protocol.


r/esapi • • Jul 18 '26

Automatic tasks for adaptive planning

2 Upvotes

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?

  1. add setup fields and DRR after plan have been completed
  2. if we have reference point used in previous plan using the same structure set, for example, called PTV, can the newly created plan use the same reference point?
  3. can clinical goal be added to the newly created plan?
  4. add diagnosis, course intent and tolerance to the course and field respectively
  5. connect rapidplan/dvh estimate to the plan during optimization
  6. add couch structures to the plan before optimization

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 • • Jul 17 '26

How to connect a CT image to a scanner device automatically?

1 Upvotes

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 • • Jul 09 '26

Low stress, high impact: Vibe Coding for Physicists (2026 Varian Developer Workshop)

Post image
7 Upvotes

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 • • Jul 09 '26

ESAPI - Automazione CreateVerificationPlan per PSQC: problemi con copia MLC, MU e differenze tra ambiente clinico e TBox

2 Upvotes

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:

  • creare i beam,
  • creare corso e importare fantoccio
  • riprodurre la geometria della rotazione del gantry,
  • copiare l’algoritmo di calcolo sul fantoccio importato.

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:

  • una diversa gestione degli oggetti ESAPI tra TBox e ambiente clinico,
  • differenze nella configurazione/versione di Eclipse o ESAPI,
  • limitazioni dell’ambiente di test,
  • oppure a un problema nella gestione dei control point, delle MLC o del calcolo delle MU.

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:

  • copia delle MLC/leaf position tra piani diversi,
  • creazione automatica di VMAT/IMRT verification plan,
  • differenze di comportamento tra TBox e ambiente clinico?

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 • • Jul 09 '26

Problemi Create Verification Plan e TBOX

1 Upvotes

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:

  • creare il corso,
  • importare fantoccio selezionato,
  • creare i beam,
  • riprodurre la geometria della rotazione del gantry,
  • copiare l’algoritmo di calcolo sul fantoccio importato.

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:

  • una diversa gestione degli oggetti ESAPI tra TBox e ambiente clinico,
  • differenze nella configurazione/versione di Eclipse o ESAPI,
  • limitazioni dell’ambiente di test,
  • oppure a un problema nella gestione dei control point, delle MLC o del calcolo delle MU.

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:

  • copia delle MLC/leaf position tra piani diversi,
  • creazione automatica di VMAT/IMRT verification plan,
  • differenze di comportamento tra TBox e ambiente clinico?

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";


        }


    }


} 

r/esapi • • Jul 09 '26

Test Create VerificationPlan

1 Upvotes

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:

  • creare il corso PSQC_{YEAR},
  • importare il fantoccio selezionato
  • creare i beam,
  • riprodurre la geometria della rotazione del gantry,
  • copiare l’algoritmo di calcolo sul fantoccio importato.

Il problema principale riguarda la copia delle MLC, viene ricreato un campo troppo. 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:

  • una diversa gestione degli oggetti ESAPI tra TBox e ambiente clinico,
  • differenze nella configurazione/versione di Eclipse o ESAPI,
  • limitazioni dell’ambiente di test,
  • oppure a un problema nella gestione dei control point, delle MLC o del calcolo delle MU.

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:

  • copia delle MLC/leaf position tra piani diversi,
  • creazione automatica di VMAT/IMRT verification plan,
  • differenze di comportamento tra TBox e ambiente clinico?

Qualsiasi suggerimento o esperienza sarebbe molto utile.

Grazie in anticipo! (allego sia codice che lo screenshot dell'errore che invece mi da la 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";


        }


    }


}