Exemple #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)
Exemple #2
0
 def construct_star(cls):
     filename = cls.get_filename()
     if cls.is_dir:
         files = [osp.join(filename, file) for file in os.listdir(filename)]
         star = Starshot.from_multiple_images(files, **cls.kwargs)
     else:
         star = Starshot(filename, **cls.kwargs)
     return star
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)
 def setUpClass(cls):
     img_dir = osp.join(TEST_DIR, 'set')
     img_files = [
         osp.join(img_dir, filename) for filename in os.listdir(img_dir)
     ]
     cls.star = Starshot.from_multiple_images(img_files)
     cls.star.analyze(radius=0.8)
 def test_image_inverted(self):
     """Check that the demo image was actually inverted, as it needs to be."""
     star = Starshot.from_demo_image()
     top_left_corner_val_before = star.image.array[0, 0]
     star._check_image_inversion()
     top_left_corner_val_after = star.image.array[0, 0]
     self.assertNotEqual(top_left_corner_val_before, top_left_corner_val_after)
Exemple #7
0
 def test_image_inverted(self):
     """Check that the demo image was actually inverted, as it needs to be."""
     star = Starshot.from_demo_image()
     top_left_corner_val_before = star.image.array[0, 0]
     star.image.check_inversion_by_histogram(percentiles=[4, 50, 96])
     top_left_corner_val_after = star.image.array[0, 0]
     self.assertNotEqual(top_left_corner_val_before, top_left_corner_val_after)
 def construct_star(cls):
     filename = cls.get_filename()
     if cls.is_dir:
         files = [osp.join(filename, file) for file in os.listdir(filename)]
         star = Starshot.from_multiple_images(files, **cls.kwargs)
     else:
         star = Starshot(filename, **cls.kwargs)
     return star
 def setUp(self):
     self.star = Starshot.from_demo_image()
     self.star.analyze()
Exemple #10
0
 def test_loading_from_zip(self):
     img_zip = get_file_from_cloud_test_repo(['Starshot', 'set.zip'])
     star = Starshot.from_zip(img_zip)
     # shouldn't raise
     star.analyze()
Exemple #11
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)
Exemple #12
0
 def test_no_dpi(self):
     # raise error when DPI isn't in image or given
     with self.assertRaises(ValueError):
         Starshot.from_url(self.real_url)
     # but is fine when DPI is given
     Starshot.from_url(self.real_url, **self.kwargs)
Exemple #13
0
 def setUpClass(cls):
     img_dir = osp.join(TEST_DIR, 'set')
     img_files = [osp.join(img_dir, filename) for filename in os.listdir(img_dir)]
     cls.star = Starshot.from_multiple_images(img_files)
     cls.star.analyze(radius=0.8)
Exemple #14
0
 def test_fails_with_tight_tol(self):
     star = Starshot.from_demo_image()
     star.analyze(tolerance=0.1)
     self.assertFalse(star.passed)
Exemple #15
0
 def construct_star(cls):
     return Starshot.from_demo_image()
Exemple #16
0
 def construct_star(cls):
     return Starshot.from_demo_image()
Exemple #17
0
 def setUp(self):
     self.star = Starshot.from_demo_image()
     self.star.analyze()
Exemple #18
0
 def test_no_dpi(self):
     # raise error when DPI isn't in image or given
     with self.assertRaises(ValueError):
         Starshot.from_url(self.full_url)
     # but is fine when DPI is given
     Starshot.from_url(self.full_url, **self.kwargs)
Exemple #19
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)
Exemple #20
0
 def test_fails_with_tight_tol(self):
     star = Starshot.from_demo_image()
     star.analyze(tolerance=0.1)
     self.assertFalse(star.passed)
Exemple #21
0
 def test_loading_from_zip(self):
     img_zip = osp.join(TEST_DIR, 'set.zip')
     star = Starshot.from_zip(img_zip)
     # shouldn't raise
     star.analyze()