Beispiel #1
0
    def test_mcnamara_cube(self):
        """ McNamara test on real cubes.
        """
        dose = pt.DosCube()
        dose.read(self.cube001)
        let = pt.LETCube()
        let.read(self.cube001)
        v = pt.VdxCube(dose)
        logger.info("Adding VDX from path " + self.vdx)
        v.read(self.vdx)

        # increasing LET should increase RBE
        abx = 10.0  # alpha/beta ratio for x-rays [Gy]
        rbe1 = rbe_mcnamara(dose.cube, let.cube, abx)
        rbe2 = rbe_mcnamara(dose.cube, let.cube, 2.0)

        self.assertTrue(np.all(rbe2 >= rbe1))  # RBE goes up as abx goes down.
Beispiel #2
0
def load_data_cube(filename):
    """ Loads either a Dos or LET-cube.

    :params str filname: path to Dos or LET-cube.
    :returns: a DosCube or LETCube object and a str containing the path to the basename.
    """

    if not filename:
        logger.warn("Empty data cube filename")
        return None, None

    logger.info("Reading " + filename)

    d = None
    basename_cube = None

    # try to load LET cube
    data_header, _ = pt.LETCube.parse_path(filename)
    if data_header is not None:
        basename_cube = os.path.splitext(data_header)[0]
        d = pt.LETCube()

    # try to load DOS cube
    data_header, _ = pt.DosCube.parse_path(filename)
    if d is None and data_header is not None:
        basename_cube = os.path.splitext(data_header)[0]
        d = pt.DosCube()

    if d is not None:
        d.read(filename)
        logger.info("Data cube shape" + str(d.cube.shape))
        if isinstance(d, pt.DosCube):
            d *= 0.1  # convert %% to %

        dmax = d.cube.max()
        dmin = d.cube.min()
        logger.info("Data min, max values: {:g} {:g}".format(dmin, dmax))

    if d is None:
        logger.warn("Filename " + filename +
                    " is neither valid DOS neither LET cube")

    return d, basename_cube
Beispiel #3
0
    def import_dos(self, dos_path):
        """
        Import a dos cube, add it to the list of loaded dos cubes.
        """

        model = self.model    # local object of plot_model
        pm = self.model.plot  # local object of plot_model

        logger.debug("Open DosCube {:s}".format(dos_path))
        dos = pt.DosCube()

        dos.read(dos_path)

        # update model
        model.dos.append(dos)
        pm.dos = dos  # display new loaded cube immediately.

        # add cube to the treeview
        self.tree.update_tree()
        self.plot.update_viewcanvas()
Beispiel #4
0
#    PyTRiP98 is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with PyTRiP98.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Simple example of how to do arithmetic on Cube objects in PyTRiP.
"""
import pytrip as pt

# sum two dose cubes, write result:
print("Two half boxes: out.dos")
d1 = pt.DosCube()
d2 = pt.DosCube()
d1.read("box052000.dos")
d2.read("box053000.dos")
d = (d1 + d2)
d.write("out.dos")

# print minium and maximum value found in cubes
print(d1.cube.min(), d1.cube.max())
print(d2.cube.min(), d2.cube.max())

# calculate new dose average LET cube
l1 = pt.LETCube()
l2 = pt.LETCube()
l1.read("box052000.dosemlet.dos")
l2.read("box053000.dosemlet.dos")
Beispiel #5
0
 def import_dose_from_file(self, path):
     logger.debug("Open DosCube {:s}".format(path))
     cube = pt.DosCube()
     cube.read(path)
     self.set_dose(cube)
Beispiel #6
0
def main(args=sys.argv[1:]):
    """ Main function for dvhplot.py
    """

    # parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "cube",
        help="Path to input cube. May also be a .dos or dosemlet.dos cube",
        type=str)
    parser.add_argument("vdx",
                        help="Path to .vdx file holding the structures",
                        type=str)
    parser.add_argument(
        "rois",
        nargs="?",
        help=
        "Comma-seperated list for ROIs to be analyzed. If not set, print list.",
        type=str,
        default=None)
    parser.add_argument("-d",
                        "--dose",
                        type=float,
                        dest='dose',
                        metavar='dose',
                        help="Taget dose in [Gy]",
                        default=-1.0)
    parser.add_argument("-o",
                        "--output",
                        type=str,
                        dest='output',
                        metavar='filename',
                        help="Don't open GUI, save to filename instead.",
                        default=None)
    parser.add_argument("-l",
                        "--legend",
                        dest='legend',
                        default=False,
                        action='store_true',
                        help="Print legend box")
    parser.add_argument("-v",
                        "--verbosity",
                        action='count',
                        help="increase output verbosity",
                        default=0)
    parser.add_argument('-V',
                        '--version',
                        action='version',
                        version=pt.__version__)
    parsed_args = parser.parse_args(args)

    if parsed_args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    elif parsed_args.verbosity > 1:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig()

    path_cube = parsed_args.cube
    path_vdx = parsed_args.vdx
    rois_arg = parsed_args.rois
    dose = parsed_args.dose
    legend = parsed_args.legend
    outfile = parsed_args.output

    # there are some cases when this script is run on systems without DISPLAY variable being set
    # in such case matplotlib backend has to be explicitly specified
    # despite the fact interleaving imports with code lines is discouraged, we do it here
    # as it depends on the users options
    if outfile:
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    d = pt.DosCube()
    d.read(path_cube)

    v = pt.VdxCube(d)
    v.read(path_vdx)

    vois = v.get_voi_names()

    if not rois_arg:
        print("Available ROIs:")
        for voi in vois:
            print("'{:s}'".format(voi))
        return

    rois = rois_arg.split(",")

    if d.type == 'DOS':
        if dose < 0.0:
            plt.xlabel("Dose [%]")
        else:
            plt.xlabel("Dose [Gy]")
    elif d.type == 'LET':
        plt.xlabel("LET [keV/um]")
    else:
        plt.xlabel("")  # unknown data cube

    for roi in rois:
        logger.info("Processing ROI '{:s}'...".format(roi))
        voi = v.get_voi_by_name(roi)
        x, y = volume_histogram(d.cube, voi)
        if d.type == 'DOS':
            if dose < 0.0:
                x = x * 0.1
            else:
                x = x * 0.001 * dose

        plt.plot(x, y, label=roi)

    plt.ylabel("Volume [%]")
    plt.grid(True)
    if legend:
        plt.legend()

    if outfile:
        plt.savefig(outfile)
    else:
        plt.show()
Beispiel #7
0
def main(args=sys.argv[1:]):
    """ Main function for dvhplot.py
    """

    # parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("cube", help="path to input cube. May also be a .dos or dosemlet.dos cube", type=str)
    parser.add_argument("vdx", help="path to .vdx file holding the structures", type=str)
    parser.add_argument("rois", nargs="?", help="comma-seperated list for ROIs to be analyzed. If not set, print list.",
                        type=str, default=None)
    parser.add_argument("-d", "--dose", type=float, dest='dose', metavar='dose',
                        help="target dose in [Gy] (if target_dose is unavailable in cube)", default=None)
    parser.add_argument("-o", "--output", type=str, dest='output', metavar='filename',
                        help="don't open GUI, save figure to <filename> instead.", default=None)
    parser.add_argument("-t", "--tofile", type=str, dest='tofile', metavar='filename',
                        help="save histogram data to <filename>.", default=None)
    parser.add_argument("-l", "--legend", dest='legend', default=False, action='store_true',
                        help="print legend box")
    parser.add_argument("-v", "--verbosity", action='count', help="increase output verbosity", default=0)
    parser.add_argument('-V', '--version', action='version', version=pt.__version__)
    parsed_args = parser.parse_args(args)

    if parsed_args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    elif parsed_args.verbosity > 1:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig()

    path_cube = parsed_args.cube
    path_vdx = parsed_args.vdx
    rois_arg = parsed_args.rois
    dose = parsed_args.dose
    legend = parsed_args.legend
    outfile = parsed_args.output
    tofile = parsed_args.tofile

    # there are some cases when this script is run on systems without DISPLAY variable being set
    # in such case matplotlib backend has to be explicitly specified
    # despite the fact interleaving imports with code lines is discouraged, we do it here
    # as it depends on the users options
    if outfile:
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    d = pt.DosCube()
    d.read(path_cube)

    v = pt.VdxCube(d)
    v.read(path_vdx)

    vois = v.voi_names()

    if not rois_arg:
        print("Available ROIs:")
        for voi in vois:
            print("'{:s}'".format(voi))
        return

    rois = rois_arg.split(",")

    for roi in rois:
        voi = v.get_voi_by_name(roi)
        vh = VolHist(d, voi, target_dose=dose)

        plt.xlabel(vh.xlabel)
        plt.ylabel(vh.ylabel)
        plt.plot(vh.x, vh.y, label=vh.name)

    plt.ylabel("Volume [%]")
    plt.grid(True)
    if legend:
        plt.legend()

    if tofile:
        logger.info("Write {}".format(tofile))
        f = open(tofile, "w+")
        for _x, _y in zip(vh.x, vh.y):
            f.write("{:.3f} {:.3f}\n".format(_x, _y))
        f.close()

    if outfile:
        plt.savefig(outfile)
    else:
        plt.show()