Esempio n. 1
0
 def test_load_from_stream(self):
     with open(osp.join(TEST_DIR, 'Starshot-30-deg-perfect.dcm'),
               'rb') as f:
         s = io.BytesIO(f.read())
         star = Starshot(s)
         star.analyze()
     self.assertIsInstance(star, Starshot)
def run_star(path):
    """Function to pass to the process pool executor to process starshot images."""
    try:
        mystar = Starshot(path, sid=1000)
        mystar.analyze()
        if mystar.wobble.diameter_mm > 3:
            raise Exception("Diamater was > 3mm.")
        return 'Success'
    except Exception as e:
        return 'Failure: {} @ {}'.format(e, path)
def run_star(path):
    """Function to pass to the process pool executor to process starshot images."""
    try:
        mystar = Starshot(path, sid=1000)
        mystar.analyze()
        if mystar.wobble.diameter_mm > 3:
            raise Exception("Diamater was > 3mm.")
        return 'Success'
    except Exception as e:
        return 'Failure: {} @ {}'.format(e, path)
Esempio n. 4
0
def starshot_helperf(args):
    imgtype = args["imgtype"]
    w = args["w"]
    clip_box = args["clip_box"]
    radius = args["radius"]
    min_peak_height = args["min_peak_height"]
    start_x = args["start_x"]
    start_y = args["start_y"]
    dpi = args["dpi"]
    sid = args["sid"]
    fwhm = args["fwhm"]
    recursive = args["recursive"]
    invert = args["invert"]
    temp_folder = args["temp_folder"]
    file_path = args["file_path"]
    imgdescription = args["imgdescription"]
    station = args["station"]
    displayname = args["displayname"]
    acquisition_datetime = args["acquisition_datetime"]
    general_functions.set_configuration(args["config"])

    # Collect data for "save results"
    dicomenergy = general_functions.get_energy_from_imgdescription(imgdescription)
    user_machine, user_energy = general_functions.get_user_machine_and_energy(station, dicomenergy)
    machines_and_energies = general_functions.get_machines_and_energies(general_functions.get_treatmentunits_starshot())
    tolerances = general_functions.get_tolerance_user_machine_starshot(user_machine)  # If user_machne has specific tolerance
    if not tolerances:
        tolerance, pdf_report_enable = general_functions.get_settings_starshot()
    else:
        tolerance, pdf_report_enable = tolerances[0]

    tolerance = float(tolerance)  # If more than this, the test is "borderline", but not "failed"
    
    save_results = {
                    "user_machine": user_machine,
                    "user_energy": user_energy,
                    "machines_and_energies": machines_and_energies,
                    "testtype": ["Collimator", "Couch", "Gantry"],
                    "displayname": displayname
                    }

    if start_x==0 or start_y==0:
        start_point=None
    else:
        start_point=(start_x, start_y)

    if sid==0.0 and dpi==0:
        try:
            star = Starshot(file_path)
        except Exception as e:
            return template("error_template", {"error_message": "The Starshot module cannot calculate. "+str(e)})
    elif sid==0.0 and dpi!=0:
        try:
            star = Starshot(file_path, dpi=dpi)
        except Exception as e:
            return template("error_template", {"error_message": "The Starshot module cannot calculate. "+str(e)})
    elif sid!=0.0 and dpi==0:
        try:
            star = Starshot(file_path, sid=sid)
        except Exception as e:
            return template("error_template", {"error_message": "The Starshot module cannot calculate. "+str(e)})
    else:
        try:
            star = Starshot(file_path, dpi=dpi, sid=sid)
        except Exception as e:
            return template("error_template", {"error_message": "The Starshot module cannot calculate. "+str(e)})
    
    # Here we force pixels to background outside of box:
    if clip_box != 0:
        try:
            star.image.check_inversion_by_histogram(percentiles=[4, 50, 96]) # Check inversion otherwise this might not work
            general_functions.clip_around_image(star.image, clip_box)
        except Exception as e:
            return template("error_template", {"error_message": "Unable to apply clipbox. "+str(e)})
    
    # If inversion is selected:
    if invert:
        star.image.invert()

    # Now we try to analyse
    try:
        star.analyze(radius=radius, min_peak_height=min_peak_height, tolerance=tolerance,
                     start_point=start_point, fwhm=fwhm, recursive=recursive)
    except Exception as e:
        return template("error_template", {"error_message": "Module Starshot cannot calculate. "+str(e)})

    fig_ss = Figure(figsize=(10, 6), tight_layout={"w_pad":4})
    img_ax = fig_ss.add_subplot(1,2,1)
    wobble_ax = fig_ss.add_subplot(1,2,2)

    img_ax.imshow(star.image.array, cmap=matplotlib.cm.gray, interpolation="none", aspect="equal", origin='upper')

    star.lines.plot(img_ax)
    star.wobble.plot2axes(img_ax, edgecolor='green')
    star.circle_profile.plot2axes(img_ax, edgecolor='green')
    img_ax.axis('off')
    img_ax.autoscale(tight=True)
    img_ax.set_aspect(1)
    img_ax.set_xticks([])
    img_ax.set_yticks([])

    star.lines.plot(wobble_ax)
    star.wobble.plot2axes(wobble_ax, edgecolor='green')
    star.circle_profile.plot2axes(wobble_ax, edgecolor='green')
    wobble_ax.axis('off')
    xlims = [star.wobble.center.x + star.wobble.diameter, star.wobble.center.x - star.wobble.diameter]
    ylims = [star.wobble.center.y + star.wobble.diameter, star.wobble.center.y - star.wobble.diameter]
    wobble_ax.set_xlim(xlims)
    wobble_ax.set_ylim(ylims)
    wobble_ax.axis('on')
    wobble_ax.set_aspect(1)

    script = mpld3.fig_to_html(fig_ss, d3_url=D3_URL, mpld3_url=MPLD3_URL)

    variables = {
                 "script": script,
                 "passed": star.passed,
                 "radius": star.wobble.radius_mm,
                 "tolerance": star.tolerance,
                 "circle_center": star.wobble.center,
                 "pdf_report_enable": pdf_report_enable,
                 "save_results": save_results,
                 "acquisition_datetime": acquisition_datetime
                 }
 
    # Generate pylinac report:
    if pdf_report_enable == "True":
        pdf_file = tempfile.NamedTemporaryFile(delete=False, prefix="Starshot_", suffix=".pdf", dir=config.PDF_REPORT_FOLDER)
        if imgtype == "dicom":
            metadata = RestToolbox.GetInstances(config.ORTHANC_URL, [w])
            try:
                patient = metadata[0]["PatientName"]
            except:
                patient = ""
            try:
                stationname = metadata[0]["StationName"]
            except:
                stationname = ""
            try:
                date_time = RestToolbox.get_datetime(metadata[0])
                date_var = datetime.datetime.strptime(date_time[0], "%Y%m%d").strftime("%d/%m/%Y")
            except:
                date_var = ""

            star.publish_pdf(pdf_file, notes=["Date = "+date_var, "Patient = "+patient, "Station = "+stationname])
        else:
            star.publish_pdf(pdf_file)
        variables["pdf_report_filename"] = os.path.basename(pdf_file.name)

    general_functions.delete_figure([fig_ss])
    general_functions.delete_files_in_subfolders([temp_folder]) # Delete image
    return template("starshot_results", variables)
Esempio n. 5
0
 def test_load_from_file_object(self):
     with open(osp.join(TEST_DIR, 'Starshot-30-deg-perfect.dcm'),
               'rb') as f:
         star = Starshot(f)
         star.analyze()
     self.assertIsInstance(star, Starshot)