Class: RTP::Plan

Inherits:
Record show all
Includes:
Logging
Defined in:
lib/rtp-connect/plan.rb,
lib/rtp-connect/plan_to_dcm.rb

Overview

Note:

Relations:

  • Parent: nil

  • Children: Prescription, DoseTracking

The Plan class is the highest level Record in the RTPConnect records hierarchy, and the one the user will interact with to read, modify and write files.

Constant Summary

Constants inherited from Record

Record::NR_SURPLUS_ATTRIBUTES

Instance Attribute Summary collapse

Attributes inherited from Record

#attributes, #crc, #keyword

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logging

included, #logger

Methods inherited from Record

#encode, #get_parent, #load, #to_record, #to_s, #values

Constructor Details

#initializePlan

Creates a new Plan.



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/rtp-connect/plan.rb', line 156

def initialize
  super('PLAN_DEF', 10, 28)
  @current_parent = self
  # Child records:
  @extended_plan = nil
  @prescriptions = Array.new
  @dose_trackings = Array.new
  # No parent (by definition) for the Plan record:
  @parent = nil
  @attributes = [
    # Required:
    :keyword,
    :patient_id,
    :patient_last_name,
    :patient_first_name,
    :patient_middle_initial,
    :plan_id,
    :plan_date,
    :plan_time,
    :course_id,
    # Optional:
    :diagnosis,
    :md_last_name,
    :md_first_name,
    :md_middle_initial,
    :md_approve_last_name,
    :md_approve_first_name,
    :md_approve_middle_initial,
    :phy_approve_last_name,
    :phy_approve_first_name,
    :phy_approve_middle_initial,
    :author_last_name,
    :author_first_name,
    :author_middle_initial,
    :rtp_mfg,
    :rtp_model,
    :rtp_version,
    :rtp_if_protocol,
    :rtp_if_version
  ]
end

Instance Attribute Details

#author_first_nameObject

Returns the value of attribute author_first_name.



55
56
57
# File 'lib/rtp-connect/plan.rb', line 55

def author_first_name
  @author_first_name
end

#author_last_nameObject

Returns the value of attribute author_last_name.



54
55
56
# File 'lib/rtp-connect/plan.rb', line 54

def author_last_name
  @author_last_name
end

#author_middle_initialObject

Returns the value of attribute author_middle_initial.



56
57
58
# File 'lib/rtp-connect/plan.rb', line 56

def author_middle_initial
  @author_middle_initial
end

#course_idObject

Returns the value of attribute course_id.



43
44
45
# File 'lib/rtp-connect/plan.rb', line 43

def course_id
  @course_id
end

#current_collimatorObject

Returns the value of attribute current_collimator.



6
7
8
# File 'lib/rtp-connect/plan_to_dcm.rb', line 6

def current_collimator
  @current_collimator
end

#current_couch_angleObject

Returns the value of attribute current_couch_angle.



7
8
9
# File 'lib/rtp-connect/plan_to_dcm.rb', line 7

def current_couch_angle
  @current_couch_angle
end

#current_couch_lateralObject

Returns the value of attribute current_couch_lateral.



9
10
11
# File 'lib/rtp-connect/plan_to_dcm.rb', line 9

def current_couch_lateral
  @current_couch_lateral
end

#current_couch_longitudinalObject

Returns the value of attribute current_couch_longitudinal.



10
11
12
# File 'lib/rtp-connect/plan_to_dcm.rb', line 10

def current_couch_longitudinal
  @current_couch_longitudinal
end

#current_couch_pedestalObject

Returns the value of attribute current_couch_pedestal.



8
9
10
# File 'lib/rtp-connect/plan_to_dcm.rb', line 8

def current_couch_pedestal
  @current_couch_pedestal
end

#current_couch_verticalObject

Returns the value of attribute current_couch_vertical.



11
12
13
# File 'lib/rtp-connect/plan_to_dcm.rb', line 11

def current_couch_vertical
  @current_couch_vertical
end

#current_gantryObject

Returns the value of attribute current_gantry.



5
6
7
# File 'lib/rtp-connect/plan_to_dcm.rb', line 5

def current_gantry
  @current_gantry
end

#diagnosisObject

Returns the value of attribute diagnosis.



44
45
46
# File 'lib/rtp-connect/plan.rb', line 44

def diagnosis
  @diagnosis
end

#dose_trackingsObject (readonly)

An array of DoseTracking records (if any) that belongs to this Plan.



35
36
37
# File 'lib/rtp-connect/plan.rb', line 35

def dose_trackings
  @dose_trackings
end

#extended_planObject (readonly)

The ExtendedPlan record (if any) that belongs to this Plan.



33
34
35
# File 'lib/rtp-connect/plan.rb', line 33

def extended_plan
  @extended_plan
end

#md_approve_first_nameObject

Returns the value of attribute md_approve_first_name.



49
50
51
# File 'lib/rtp-connect/plan.rb', line 49

def md_approve_first_name
  @md_approve_first_name
end

#md_approve_last_nameObject

Returns the value of attribute md_approve_last_name.



48
49
50
# File 'lib/rtp-connect/plan.rb', line 48

def md_approve_last_name
  @md_approve_last_name
end

#md_approve_middle_initialObject

Returns the value of attribute md_approve_middle_initial.



50
51
52
# File 'lib/rtp-connect/plan.rb', line 50

def md_approve_middle_initial
  @md_approve_middle_initial
end

#md_first_nameObject

Returns the value of attribute md_first_name.



46
47
48
# File 'lib/rtp-connect/plan.rb', line 46

def md_first_name
  @md_first_name
end

#md_last_nameObject

Returns the value of attribute md_last_name.



45
46
47
# File 'lib/rtp-connect/plan.rb', line 45

def md_last_name
  @md_last_name
end

#md_middle_initialObject

Returns the value of attribute md_middle_initial.



47
48
49
# File 'lib/rtp-connect/plan.rb', line 47

def md_middle_initial
  @md_middle_initial
end

#parentObject (readonly)

The Record which this instance belongs to (nil by definition).



29
30
31
# File 'lib/rtp-connect/plan.rb', line 29

def parent
  @parent
end

#patient_first_nameObject

Returns the value of attribute patient_first_name.



38
39
40
# File 'lib/rtp-connect/plan.rb', line 38

def patient_first_name
  @patient_first_name
end

#patient_idObject

Returns the value of attribute patient_id.



36
37
38
# File 'lib/rtp-connect/plan.rb', line 36

def patient_id
  @patient_id
end

#patient_last_nameObject

Returns the value of attribute patient_last_name.



37
38
39
# File 'lib/rtp-connect/plan.rb', line 37

def patient_last_name
  @patient_last_name
end

#patient_middle_initialObject

Returns the value of attribute patient_middle_initial.



39
40
41
# File 'lib/rtp-connect/plan.rb', line 39

def patient_middle_initial
  @patient_middle_initial
end

#phy_approve_first_nameObject

Returns the value of attribute phy_approve_first_name.



52
53
54
# File 'lib/rtp-connect/plan.rb', line 52

def phy_approve_first_name
  @phy_approve_first_name
end

#phy_approve_last_nameObject

Returns the value of attribute phy_approve_last_name.



51
52
53
# File 'lib/rtp-connect/plan.rb', line 51

def phy_approve_last_name
  @phy_approve_last_name
end

#phy_approve_middle_initialObject

Returns the value of attribute phy_approve_middle_initial.



53
54
55
# File 'lib/rtp-connect/plan.rb', line 53

def phy_approve_middle_initial
  @phy_approve_middle_initial
end

#plan_dateObject

Returns the value of attribute plan_date.



41
42
43
# File 'lib/rtp-connect/plan.rb', line 41

def plan_date
  @plan_date
end

#plan_idObject

Returns the value of attribute plan_id.



40
41
42
# File 'lib/rtp-connect/plan.rb', line 40

def plan_id
  @plan_id
end

#plan_timeObject

Returns the value of attribute plan_time.



42
43
44
# File 'lib/rtp-connect/plan.rb', line 42

def plan_time
  @plan_time
end

#prescriptionsObject (readonly)

An array of Prescription records (if any) that belongs to this Plan.



31
32
33
# File 'lib/rtp-connect/plan.rb', line 31

def prescriptions
  @prescriptions
end

#rtp_if_protocolObject

Returns the value of attribute rtp_if_protocol.



60
61
62
# File 'lib/rtp-connect/plan.rb', line 60

def rtp_if_protocol
  @rtp_if_protocol
end

#rtp_if_versionObject

Returns the value of attribute rtp_if_version.



61
62
63
# File 'lib/rtp-connect/plan.rb', line 61

def rtp_if_version
  @rtp_if_version
end

#rtp_mfgObject

Returns the value of attribute rtp_mfg.



57
58
59
# File 'lib/rtp-connect/plan.rb', line 57

def rtp_mfg
  @rtp_mfg
end

#rtp_modelObject

Returns the value of attribute rtp_model.



58
59
60
# File 'lib/rtp-connect/plan.rb', line 58

def rtp_model
  @rtp_model
end

#rtp_versionObject

Returns the value of attribute rtp_version.



59
60
61
# File 'lib/rtp-connect/plan.rb', line 59

def rtp_version
  @rtp_version
end

Class Method Details

.load(string, options = {}) ⇒ Plan

Note:

This method does not perform crc verification on the given string. If such verification is desired, use methods ::parse or ::read instead.

Creates a new Plan by loading a plan definition string (i.e. a single line).

Parameters:

  • string (#to_s)

    the plan definition record string line

  • options (Hash) (defaults to: {})

    the options to use for loading the plan definition string

Options Hash (options):

  • :repair (Boolean)

    if true, a record containing invalid CSV will be attempted fixed and loaded

Returns:

  • (Plan)

    the created Plan instance

Raises:

  • (ArgumentError)

    if given a string containing an invalid number of elements



73
74
75
76
# File 'lib/rtp-connect/plan.rb', line 73

def self.load(string, options={})
  rtp = self.new
  rtp.load(string, options)
end

.parse(string, options = {}) ⇒ Plan

Creates a Plan instance by parsing an RTPConnect string.

Parameters:

  • string (#to_s)

    an RTPConnect ascii string (with single or multiple lines/records)

  • options (Hash) (defaults to: {})

    the options to use for parsing the RTP string

Options Hash (options):

  • :ignore_crc (Boolean)

    if true, the RTP records will be successfully loaded even if their checksums are invalid

  • :repair (Boolean)

    if true, any RTP records containing invalid CSV will be attempted fixed and loaded

  • :skip_unknown (Boolean)

    if true, unknown records will be skipped, and record instances will be built from the remaining recognized string records

Returns:

  • (Plan)

    the created Plan instance

Raises:

  • (ArgumentError)

    if given an invalid string record



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/rtp-connect/plan.rb', line 88

def self.parse(string, options={})
  lines = string.to_s.split("\r\n")
  # Create the Plan object:
  line = lines.first
  RTP.verify(line, options)
  rtp = self.load(line, options)
  lines[1..-1].each do |line|
    # Validate, determine type, and process the line accordingly to
    # build the hierarchy of records:
    RTP.verify(line, options)
    values = line.values(options[:repair])
    keyword = values.first
    method = RTP::PARSE_METHOD[keyword]
    if method
      rtp.send(method, line)
    else
      if options[:skip_unknown]
        logger.warn("Skipped unknown record definition: #{keyword}")
      else
        raise ArgumentError, "Unknown keyword #{keyword} extracted from string."
      end
    end
  end
  return rtp
end

.read(file, options = {}) ⇒ Plan

Creates an Plan instance by reading and parsing an RTPConnect file.

Parameters:

  • file (String)

    a string which specifies the path of the RTPConnect file to be loaded

  • options (Hash) (defaults to: {})

    the options to use for reading the RTP file

Options Hash (options):

  • :ignore_crc (Boolean)

    if true, the RTP records will be successfully loaded even if their checksums are invalid

  • :repair (Boolean)

    if true, any RTP records containing invalid CSV will be attempted fixed and loaded

  • :skip_unknown (Boolean)

    if true, unknown records will be skipped, and record instances will be built from the remaining recognized string records

Returns:

  • (Plan)

    the created Plan instance

Raises:

  • (ArgumentError)

    if given an invalid file or the file given contains an invalid record



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/rtp-connect/plan.rb', line 124

def self.read(file, options={})
  raise ArgumentError, "Invalid argument 'file'. Expected String, got #{file.class}." unless file.is_a?(String)
  # Read the file content:
  str = nil
  unless File.exist?(file)
    logger.error("Invalid (non-existing) file: #{file}")
  else
    unless File.readable?(file)
      logger.error("File exists but I don't have permission to read it: #{file}")
    else
      if File.directory?(file)
        logger.error("Expected a file, got a directory: #{file}")
      else
        if File.size(file) < 10
          logger.error("This file is too small to contain valid RTP information: #{file}.")
        else
          str = File.open(file, 'rb:ISO8859-1') { |f| f.read }
        end
      end
    end
  end
  # Parse the file contents and create the RTP instance:
  if str
    rtp = self.parse(str, options)
  else
    raise "An RTP::Plan object could not be created from the specified file. Check the log for more details."
  end
  return rtp
end

Instance Method Details

#==(other) ⇒ Boolean Also known as: eql?

Checks for equality.

Other and self are considered equivalent if they are of compatible types and their attributes are equivalent.

Parameters:

  • other

    an object to be compared with self.

Returns:

  • (Boolean)

    true if self and other are considered equivalent



206
207
208
209
210
# File 'lib/rtp-connect/plan.rb', line 206

def ==(other)
  if other.respond_to?(:to_plan)
    other.send(:state) == state
  end
end

#add_dose_tracking(child) ⇒ Object

Adds a dose tracking record to this instance.

Parameters:

  • child (DoseTracking)

    a DoseTracking instance which is to be associated with self



218
219
220
221
# File 'lib/rtp-connect/plan.rb', line 218

def add_dose_tracking(child)
  @dose_trackings << child.to_dose_tracking
  child.parent = self
end

#add_extended_plan(child) ⇒ Object

Adds an extended plan record to this instance.

Parameters:

  • child (ExtendedPlan)

    an ExtendedPlan instance which is to be associated with self



227
228
229
230
# File 'lib/rtp-connect/plan.rb', line 227

def add_extended_plan(child)
  @extended_plan = child.to_extended_plan
  child.parent = self
end

#add_prescription(child) ⇒ Object

Adds a prescription site record to this instance.

Parameters:

  • child (Prescription)

    a Prescription instance which is to be associated with self



236
237
238
239
# File 'lib/rtp-connect/plan.rb', line 236

def add_prescription(child)
  @prescriptions << child.to_prescription
  child.parent = self
end

#childrenArray<Prescription, DoseTracking>

Collects the child records of this instance in a properly sorted array.

Returns:



245
246
247
# File 'lib/rtp-connect/plan.rb', line 245

def children
  return [@extended_plan, @prescriptions, @dose_trackings].flatten.compact
end

#delete(record) ⇒ Object

Removes the reference of the given instance from this instance.

Parameters:



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/rtp-connect/plan.rb', line 253

def delete(record)
  case record
  when Prescription
    delete_child(:prescriptions, record)
  when DoseTracking
    delete_child(:dose_trackings, record)
  when ExtendedPlan
    delete_extended_plan
  else
    logger.warn("Unknown class (record) given to Plan#delete: #{record.class}")
  end
end

#delete_dose_trackingsObject

Removes all dose_tracking references from this instance.



268
269
270
# File 'lib/rtp-connect/plan.rb', line 268

def delete_dose_trackings
  delete_children(:dose_trackings)
end

#delete_extended_planObject

Removes the extended plan reference from this instance.



274
275
276
# File 'lib/rtp-connect/plan.rb', line 274

def delete_extended_plan
  delete_child(:extended_plan)
end

#delete_prescriptionsObject

Removes all prescription references from this instance.



280
281
282
# File 'lib/rtp-connect/plan.rb', line 280

def delete_prescriptions
  delete_children(:prescriptions)
end

#hashFixnum

Note:

Two objects with the same attributes will have the same hash code.

Computes a hash code for this object.

Returns:

  • (Fixnum)

    the object’s hash code



290
291
292
# File 'lib/rtp-connect/plan.rb', line 290

def hash
  state.hash
end

#to_dcm(options = {}) ⇒ DICOM::DObject

Note:

Only photon plans have been tested. Electron beams beams may give an invalid DICOM file. Also note that, due to limitations in the RTP file format, some original values can not be recreated, like e.g. Study UID or Series UID.

Converts the Plan (and child) records to a DICOM::DObject of modality RTPLAN.

Parameters:

  • options (Hash) (defaults to: {})

    the options to use for creating the DICOM object

Options Hash (options):

  • :dose_ref (Boolean)

    if set, Dose Reference & Referenced Dose Reference sequences will be included in the generated DICOM file

  • :manufacturer (String)

    the value used for the manufacturer tag (0008,0070) in the beam sequence

  • :model (String)

    the value used for the manufacturer’s model name tag (0008,1090) in the beam sequence

  • :scale (Symbol)

    if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)

  • :serial_number (String)

    the value used for the device serial number tag (0018,1000) in the beam sequence

Returns:

  • (DICOM::DObject)

    the converted DICOM object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/rtp-connect/plan_to_dcm.rb', line 28

def to_dcm(options={})
  #
  # FIXME: This method is rather big, with a few sections of somewhat similar, repeating code.
  # Refactoring and simplifying it at some stage might be a good idea.
  #
  require 'dicom'
  original_level = DICOM.logger.level
  DICOM.logger.level = Logger::FATAL
  p = @prescriptions.first
  # If no prescription is present, we are not going to be able to make a valid DICOM object:
  logger.error("No Prescription Record present. Unable to build a valid RTPLAN DICOM object.") unless p
  dcm = DICOM::DObject.new
  #
  # TOP LEVEL TAGS:
  #
  # Specific Character Set:
  DICOM::Element.new('0008,0005', 'ISO_IR 100', :parent => dcm)
  # Instance Creation Date
  DICOM::Element.new('0008,0012', Time.now.strftime("%Y%m%d"), :parent => dcm)
  # Instance Creation Time:
  DICOM::Element.new('0008,0013', Time.now.strftime("%H%M%S"), :parent => dcm)
  # SOP Class UID:
  DICOM::Element.new('0008,0016', '1.2.840.10008.5.1.4.1.1.481.5', :parent => dcm)
  # SOP Instance UID (if an original UID is not present, we make up a UID):
  begin
    sop_uid = p.fields.first.extended_field.original_plan_uid.empty? ? DICOM.generate_uid : p.fields.first.extended_field.original_plan_uid
  rescue
    sop_uid = DICOM.generate_uid
  end
  DICOM::Element.new('0008,0018', sop_uid, :parent => dcm)
  # Study Date
  DICOM::Element.new('0008,0020', Time.now.strftime("%Y%m%d"), :parent => dcm)
  # Study Time:
  DICOM::Element.new('0008,0030', Time.now.strftime("%H%M%S"), :parent => dcm)
  # Accession Number:
  DICOM::Element.new('0008,0050', '', :parent => dcm)
  # Modality:
  DICOM::Element.new('0008,0060', 'RTPLAN', :parent => dcm)
  # Manufacturer:
  DICOM::Element.new('0008,0070', 'rtp-connect', :parent => dcm)
  # Referring Physician's Name:
  DICOM::Element.new('0008,0090', "#{@md_last_name}^#{@md_first_name}^#{@md_middle_name}^^", :parent => dcm)
  # Operator's Name:
  DICOM::Element.new('0008,1070', "#{@author_last_name}^#{@author_first_name}^#{@author_middle_name}^^", :parent => dcm)
  # Patient's Name:
  DICOM::Element.new('0010,0010', "#{@patient_last_name}^#{@patient_first_name}^#{@patient_middle_name}^^", :parent => dcm)
  # Patient ID:
  DICOM::Element.new('0010,0020', @patient_id, :parent => dcm)
  # Patient's Birth Date:
  DICOM::Element.new('0010,0030', '', :parent => dcm)
  # Patient's Sex:
  DICOM::Element.new('0010,0040', '', :parent => dcm)
  # Manufacturer's Model Name:
  DICOM::Element.new('0008,1090', 'RTP-to-DICOM', :parent => dcm)
  # Software Version(s):
  DICOM::Element.new('0018,1020', "RubyRTP#{VERSION}", :parent => dcm)
  # Study Instance UID:
  DICOM::Element.new('0020,000D', DICOM.generate_uid, :parent => dcm)
  # Series Instance UID:
  DICOM::Element.new('0020,000E', DICOM.generate_uid, :parent => dcm)
  # Study ID:
  DICOM::Element.new('0020,0010', '1', :parent => dcm)
  # Series Number:
  DICOM::Element.new('0020,0011', '1', :parent => dcm)
  # Frame of Reference UID (if an original UID is not present, we make up a UID):
  begin
    for_uid = p.site_setup.frame_of_ref_uid.empty? ? DICOM.generate_uid : p.site_setup.frame_of_ref_uid
  rescue
    for_uid = DICOM.generate_uid
  end
  DICOM::Element.new('0020,0052', for_uid, :parent => dcm)
  # Position Reference Indicator:
  DICOM::Element.new('0020,1040', '', :parent => dcm)
  # RT Plan Label (max 16 characters):
  plan_label = p ? p.rx_site_name[0..15] : @course_id
  DICOM::Element.new('300A,0002', plan_label, :parent => dcm)
  # RT Plan Name:
  plan_name = p ? p.rx_site_name : @course_id
  DICOM::Element.new('300A,0003', plan_name, :parent => dcm)
  # RT Plan Description:
  plan_desc = p ? p.technique : @diagnosis
  DICOM::Element.new('300A,0004', plan_desc, :parent => dcm)
  # RT Plan Date:
  plan_date = @plan_date.empty? ? Time.now.strftime("%Y%m%d") : @plan_date
  DICOM::Element.new('300A,0006', plan_date, :parent => dcm)
  # RT Plan Time:
  plan_time = @plan_time.empty? ? Time.now.strftime("%H%M%S") : @plan_time
  DICOM::Element.new('300A,0007', plan_time, :parent => dcm)
  # Approval Status:
  DICOM::Element.new('300E,0002', 'UNAPPROVED', :parent => dcm)
  #
  # SEQUENCES:
  #
  # Tolerance Table Sequence:
  if p && p.fields.first && !p.fields.first.tolerance_table.empty?
    tt_seq = DICOM::Sequence.new('300A,0040', :parent => dcm)
    tt_item = DICOM::Item.new(:parent => tt_seq)
    # Tolerance Table Number:
    DICOM::Element.new('300A,0042', p.fields.first.tolerance_table, :parent => tt_item)
  end
  # Structure set information:
  if p && p.site_setup && !p.site_setup.structure_set_uid.empty?
    #
    # Referenced Structure Set Sequence:
    #
    ss_seq = DICOM::Sequence.new('300C,0060', :parent => dcm)
    ss_item = DICOM::Item.new(:parent => ss_seq)
    # Referenced SOP Class UID:
    DICOM::Element.new('0008,1150', '1.2.840.10008.5.1.4.1.1.481.3', :parent => ss_item)
    DICOM::Element.new('0008,1155', p.site_setup.structure_set_uid, :parent => ss_item)
    # RT Plan Geometry:
    DICOM::Element.new('300A,000C', 'PATIENT', :parent => dcm)
  else
    # RT Plan Geometry:
    DICOM::Element.new('300A,000C', 'TREATMENT_DEVICE', :parent => dcm)
  end
  #
  # Patient Setup Sequence:
  #
  ps_seq = DICOM::Sequence.new('300A,0180', :parent => dcm)
  ps_item = DICOM::Item.new(:parent => ps_seq)
  # Patient Position:
  begin
    pat_pos = p.site_setup.patient_orientation.empty? ? 'HFS' : p.site_setup.patient_orientation
  rescue
    pat_pos = 'HFS'
  end
  DICOM::Element.new('0018,5100', pat_pos, :parent => ps_item)
  # Patient Setup Number:
  DICOM::Element.new('300A,0182', '1', :parent => ps_item)
  # Setup Technique (assume Isocentric):
  DICOM::Element.new('300A,01B0', 'ISOCENTRIC', :parent => ps_item)
  #
  # Dose Reference Sequence:
  #
  create_dose_reference(dcm, plan_name) if options[:dose_ref]
  #
  # Fraction Group Sequence:
  #
  fg_seq = DICOM::Sequence.new('300A,0070', :parent => dcm)
  fg_item = DICOM::Item.new(:parent => fg_seq)
  # Fraction Group Number:
  DICOM::Element.new('300A,0071', '1', :parent => fg_item)
  # Number of Fractions Planned (try to derive from total dose/fraction dose, or use 1 as default):
  begin
    num_frac = p.dose_ttl.empty? || p.dose_tx.empty? ? '1' : (p.dose_ttl.to_i / p.dose_tx.to_f).round.to_s
  rescue
    num_frac = '0'
  end
  DICOM::Element.new('300A,0078', num_frac, :parent => fg_item)
  # Number of Brachy Application Setups:
  DICOM::Element.new('300A,00A0', '0', :parent => fg_item)
  # Referenced Beam Sequence (items created for each beam below):
  rb_seq = DICOM::Sequence.new('300C,0004', :parent => fg_item)
  #
  # Beam Sequence:
  #
  b_seq = DICOM::Sequence.new('300A,00B0', :parent => dcm)
  if p
    # If no fields are present, we are not going to be able to make a valid DICOM object:
    logger.error("No Field Record present. Unable to build a valid RTPLAN DICOM object.") unless p.fields.length > 0
    p.fields.each_with_index do |field, i|
      # Fields with modality 'Unspecified' (e.g. CT or 2dkV) must be skipped:
      unless field.modality == 'Unspecified'
        # If this is an electron beam, a warning should be printed, as these are less reliably converted:
        logger.warn("This is not a photon beam (#{field.modality}). Beware that DICOM conversion of Electron beams are experimental, and other modalities are unsupported.") if field.modality != 'Xrays'
        # Reset control point 'current value' attributes:
        reset_cp_current_attributes
        # Beam number and name:
        beam_number = field.extended_field ? field.extended_field.original_beam_number : (i + 1).to_s
        beam_name = field.extended_field ? field.extended_field.original_beam_name : field.field_name
        # Ref Beam Item:
        rb_item = DICOM::Item.new(:parent => rb_seq)
        # Beam Dose (convert from cGy to Gy):
        field_dose = field.field_dose.empty? ? '' : (field.field_dose.to_f * 0.01).round(4).to_s
        DICOM::Element.new('300A,0084', field_dose, :parent => rb_item)
        # Beam Meterset:
        DICOM::Element.new('300A,0086', field.field_monitor_units, :parent => rb_item)
        # Referenced Beam Number:
        DICOM::Element.new('300C,0006', beam_number, :parent => rb_item)
        # Beam Item:
        b_item = DICOM::Item.new(:parent => b_seq)
        # Optional method values:
        # Manufacturer:
        DICOM::Element.new('0008,0070', options[:manufacturer], :parent => b_item) if options[:manufacturer]
        # Manufacturer's Model Name:
        DICOM::Element.new('0008,1090', options[:model], :parent => b_item) if options[:model]
        # Device Serial Number:
        DICOM::Element.new('0018,1000', options[:serial_number], :parent => b_item) if options[:serial_number]
        # Treatment Machine Name (max 16 characters):
        DICOM::Element.new('300A,00B2', field.treatment_machine[0..15], :parent => b_item)
        # Primary Dosimeter Unit:
        DICOM::Element.new('300A,00B3', 'MU', :parent => b_item)
        # Source-Axis Distance (convert to mm):
        DICOM::Element.new('300A,00B4', "#{field.sad.to_f * 10}", :parent => b_item)
        # Beam Number:
        DICOM::Element.new('300A,00C0', beam_number, :parent => b_item)
        # Beam Name:
        DICOM::Element.new('300A,00C2', beam_name, :parent => b_item)
        # Beam Description:
        DICOM::Element.new('300A,00C3', field.field_note, :parent => b_item)
        # Beam Type:
        beam_type = case field.treatment_type
          when 'Static' then 'STATIC'
          when 'StepNShoot' then 'STATIC'
          when 'VMAT' then 'DYNAMIC'
          else logger.error("The beam type (treatment type) #{field.treatment_type} is not yet supported.")
        end
        DICOM::Element.new('300A,00C4', beam_type, :parent => b_item)
        # Radiation Type:
        rad_type = case field.modality
          when 'Elect' then 'ELECTRON'
          when 'Xrays' then 'PHOTON'
          else logger.error("The radiation type (modality) #{field.modality} is not yet supported.")
        end
        DICOM::Element.new('300A,00C6', rad_type, :parent => b_item)
        # Treatment Delivery Type:
        DICOM::Element.new('300A,00CE', 'TREATMENT', :parent => b_item)
        # Number of Wedges:
        DICOM::Element.new('300A,00D0', (field.wedge.empty? ? '0' : '1'), :parent => b_item)
        # Number of Compensators:
        DICOM::Element.new('300A,00E0', (field.compensator.empty? ? '0' : '1'), :parent => b_item)
        # Number of Boli:
        DICOM::Element.new('300A,00ED', (field.bolus.empty? ? '0' : '1'), :parent => b_item)
        # Number of Blocks:
        DICOM::Element.new('300A,00F0', (field.block.empty? ? '0' : '1'), :parent => b_item)
        # Final Cumulative Meterset Weight:
        DICOM::Element.new('300A,010E', 1, :parent => b_item)
        # Referenced Patient Setup Number:
        DICOM::Element.new('300C,006A', '1', :parent => b_item)
        #
        # Beam Limiting Device Sequence:
        #
        create_beam_limiting_devices(b_item, field)
        #
        # Block Sequence (if any):
        # FIXME: It seems that the Block Sequence (300A,00F4) may be
        # difficult (impossible?) to reconstruct based on the RTP file's
        # information, and thus it is skipped altogether.
        #
        #
        # Applicator Sequence (if any):
        #
        unless field.e_applicator.empty?
          app_seq = DICOM::Sequence.new('300A,0107', :parent => b_item)
          app_item = DICOM::Item.new(:parent => app_seq)
          # Applicator ID:
          DICOM::Element.new('300A,0108', field.e_field_def_aperture, :parent => app_item)
          # Applicator Type:
          DICOM::Element.new('300A,0109', "ELECTRON_#{field.e_applicator.upcase}", :parent => app_item)
          # Applicator Description:
          DICOM::Element.new('300A,010A', "Appl. #{field.e_field_def_aperture}", :parent => app_item)
        end
        #
        # Control Point Sequence:
        #
        # A field may have 0 (no MLC), 1 (conventional beam with MLC) or 2n (IMRT) control points.
        # The DICOM file shall always contain 2n control points (minimum 2).
        #
        cp_seq = DICOM::Sequence.new('300A,0111', :parent => b_item)
        if field.control_points.length < 2
          # When we have 0 or 1 control point, use settings from field, and insert MLC settings if present:
          # First CP:
          cp_item = DICOM::Item.new(:parent => cp_seq)
          # Control Point Index:
          DICOM::Element.new('300A,0112', "0", :parent => cp_item)
          # Nominal Beam Energy:
          DICOM::Element.new('300A,0114', "#{field.energy.to_f}", :parent => cp_item)
          # Dose Rate Set:
          DICOM::Element.new('300A,0115', field.doserate, :parent => cp_item)
          # Gantry Angle:
          DICOM::Element.new('300A,011E', field.gantry_angle, :parent => cp_item)
          # Gantry Rotation Direction:
          DICOM::Element.new('300A,011F', (field.arc_direction.empty? ? 'NONE' : field.arc_direction), :parent => cp_item)
          # Beam Limiting Device Angle:
          DICOM::Element.new('300A,0120', field.collimator_angle, :parent => cp_item)
          # Beam Limiting Device Rotation Direction:
          DICOM::Element.new('300A,0121', 'NONE', :parent => cp_item)
          # Patient Support Angle:
          DICOM::Element.new('300A,0122', field.couch_pedestal, :parent => cp_item)
          # Patient Support Rotation Direction:
          DICOM::Element.new('300A,0123', 'NONE', :parent => cp_item)
          # Table Top Eccentric Angle:
          DICOM::Element.new('300A,0125', field.couch_angle, :parent => cp_item)
          # Table Top Eccentric Rotation Direction:
          DICOM::Element.new('300A,0126', 'NONE', :parent => cp_item)
          # Table Top Vertical Position:
          couch_vert = field.couch_vertical.empty? ? '' : (field.couch_vertical.to_f * 10).to_s
          DICOM::Element.new('300A,0128', couch_vert, :parent => cp_item)
          # Table Top Longitudinal Position:
          couch_long = field.couch_longitudinal.empty? ? '' : (field.couch_longitudinal.to_f * 10).to_s
          DICOM::Element.new('300A,0129', couch_long, :parent => cp_item)
          # Table Top Lateral Position:
          couch_lat = field.couch_lateral.empty? ? '' : (field.couch_lateral.to_f * 10).to_s
          DICOM::Element.new('300A,012A', couch_lat, :parent => cp_item)
          # Isocenter Position (x\y\z):
          if p.site_setup
            DICOM::Element.new('300A,012C', "#{(p.site_setup.iso_pos_x.to_f * 10).round(2)}\\#{(p.site_setup.iso_pos_y.to_f * 10).round(2)}\\#{(p.site_setup.iso_pos_z.to_f * 10).round(2)}", :parent => cp_item)
          else
            logger.warn("No Site Setup record exists for this plan. Unable to provide an isosenter position.")
            DICOM::Element.new('300A,012C', '', :parent => cp_item)
          end
          # Source to Surface Distance:
          add_ssd(field.ssd, cp_item)
          # Cumulative Meterset Weight:
          DICOM::Element.new('300A,0134', '0', :parent => cp_item)
          # Beam Limiting Device Position Sequence:
          if field.control_points.length > 0
            create_beam_limiting_device_positions(cp_item, field.control_points.first, options)
          else
            create_beam_limiting_device_positions_from_field(cp_item, field, options)
          end
          # Referenced Dose Reference Sequence:
          create_referenced_dose_reference(cp_item) if options[:dose_ref]
          # Second CP:
          cp_item = DICOM::Item.new(:parent => cp_seq)
          # Control Point Index:
          DICOM::Element.new('300A,0112', "1", :parent => cp_item)
          # Cumulative Meterset Weight:
          DICOM::Element.new('300A,0134', '1', :parent => cp_item)
        else
          # When we have multiple (2 or more) control points, iterate each control point:
          field.control_points.each { |cp| create_control_point(cp, cp_seq, options) }
          # Make sure that hte cumulative meterset weight of the last control
          # point is '1' (exactly equal to final cumulative meterset weight):
          cp_seq.items.last['300A,0134'].value = '1'
        end
        # Number of Control Points:
        DICOM::Element.new('300A,0110', b_item['300A,0111'].items.length, :parent => b_item)
      end
    end
    # Number of Beams:
    DICOM::Element.new('300A,0080', fg_item['300C,0004'].items.length, :parent => fg_item)
  end
  # Restore the DICOM logger:
  DICOM.logger.level = original_level
  return dcm
end

#to_planPlan

Returns self.

Returns:



298
299
300
# File 'lib/rtp-connect/plan.rb', line 298

def to_plan
  self
end

#to_rtpPlan

Returns self.

Returns:



306
307
308
# File 'lib/rtp-connect/plan.rb', line 306

def to_rtp
  self
end

#write(file, options = {}) ⇒ Object

Writes the Plan object, along with its hiearchy of child objects, to a properly formatted RTPConnect ascii file.

Parameters:

  • file (String)

    a path/file string

  • options (Hash) (defaults to: {})

    an optional hash parameter

Options Hash (options):

  • :version (Float)

    the Mosaiq compatibility version number (e.g. 2.4) used for the output



317
318
319
320
321
# File 'lib/rtp-connect/plan.rb', line 317

def write(file, options={})
  f = open_file(file)
  f.write(to_s(options))
  f.close
end