|
| 1 | +import portpy.photon as pp |
| 2 | +import algorithms |
| 3 | +import numpy as np |
| 4 | +import math |
| 5 | +import matplotlib.pyplot as plt |
| 6 | + |
| 7 | +def objective_function_value(x): |
| 8 | + obj_funcs = opt_params['objective_functions'] if 'objective_functions' in opt_params else [] |
| 9 | + obj = 0 |
| 10 | + for i in range(len(obj_funcs)): |
| 11 | + if obj_funcs[i]['type'] == 'quadratic-overdose': |
| 12 | + if obj_funcs[i]['structure_name'] in opt.my_plan.structures.get_structures(): |
| 13 | + struct = obj_funcs[i]['structure_name'] |
| 14 | + if len(inf_matrix_full.get_opt_voxels_idx(struct)) == 0: # check if there are any opt voxels for the structure |
| 15 | + continue |
| 16 | + dose_gy = opt.get_num(obj_funcs[i]['dose_gy']) / clinical_criteria.get_num_of_fractions() |
| 17 | + dO = np.maximum(A[inf_matrix_full.get_opt_voxels_idx(struct), :] @ x - dose_gy, 0) |
| 18 | + obj += (1 / len(inf_matrix_full.get_opt_voxels_idx(struct))) * (obj_funcs[i]['weight'] * np.sum(dO ** 2)) |
| 19 | + elif obj_funcs[i]['type'] == 'quadratic-underdose': |
| 20 | + if obj_funcs[i]['structure_name'] in opt.my_plan.structures.get_structures(): |
| 21 | + struct = obj_funcs[i]['structure_name'] |
| 22 | + if len(inf_matrix_full.get_opt_voxels_idx(struct)) == 0: |
| 23 | + continue |
| 24 | + dose_gy = opt.get_num(obj_funcs[i]['dose_gy']) / clinical_criteria.get_num_of_fractions() |
| 25 | + dU = np.minimum(A[inf_matrix_full.get_opt_voxels_idx(struct), :] @ x - dose_gy, 0) |
| 26 | + obj += (1 / len(inf_matrix_full.get_opt_voxels_idx(struct))) * (obj_funcs[i]['weight'] * np.sum(dU ** 2)) |
| 27 | + elif obj_funcs[i]['type'] == 'quadratic': |
| 28 | + if obj_funcs[i]['structure_name'] in opt.my_plan.structures.get_structures(): |
| 29 | + struct = obj_funcs[i]['structure_name'] |
| 30 | + if len(inf_matrix_full.get_opt_voxels_idx(struct)) == 0: |
| 31 | + continue |
| 32 | + obj += (1 / len(inf_matrix_full.get_opt_voxels_idx(struct))) * (obj_funcs[i]['weight'] * np.sum((A[inf_matrix_full.get_opt_voxels_idx(struct), :] @ x) ** 2)) |
| 33 | + elif obj_funcs[i]['type'] == 'smoothness-quadratic': |
| 34 | + [Qx, Qy, num_rows, num_cols] = opt.get_smoothness_matrix(inf_matrix.beamlets_dict) |
| 35 | + smoothness_X_weight = 0.6 |
| 36 | + smoothness_Y_weight = 0.4 |
| 37 | + obj += obj_funcs[i]['weight'] * (smoothness_X_weight * (1 / num_cols) * np.sum((Qx @ x) ** 2) + |
| 38 | + smoothness_Y_weight * (1 / num_rows) * np.sum((Qy @ x) ** 2)) |
| 39 | + print("objective function value:", obj) |
| 40 | + |
| 41 | +def l2_norm(matrix): |
| 42 | + values, vectors = np.linalg.eig(np.transpose(matrix) @ matrix) |
| 43 | + return math.sqrt(np.max(np.abs(values))) |
| 44 | + |
| 45 | +if __name__ == '__main__': |
| 46 | + import argparse |
| 47 | + |
| 48 | + parser = argparse.ArgumentParser() |
| 49 | + |
| 50 | + parser.add_argument( |
| 51 | + '--method', type=str, choices=['Naive', 'AHK06', 'AKL13', 'DZ11', 'RMR'], help='The name of method.' |
| 52 | + ) |
| 53 | + parser.add_argument( |
| 54 | + '--patient', type=str, help='Patient\'s name' |
| 55 | + ) |
| 56 | + parser.add_argument( |
| 57 | + '--threshold', type=float, help='The threshold using for the input of algorithm.' |
| 58 | + ) |
| 59 | + parser.add_argument( |
| 60 | + '--solver', type=str, default='SCS', help='The name of solver for solving the optimization problem' |
| 61 | + ) |
| 62 | + |
| 63 | + args = parser.parse_args() |
| 64 | + # Use PortPy DataExplorer class to explore PortPy data |
| 65 | + data = pp.DataExplorer(data_dir='') |
| 66 | + # Pick a patient |
| 67 | + data.patient_id = args.patient |
| 68 | + # Load ct, structure set, beams for the above patient using CT, Structures, and Beams classes |
| 69 | + ct = pp.CT(data) |
| 70 | + structs = pp.Structures(data) |
| 71 | + beams = pp.Beams(data) |
| 72 | + # Pick a protocol |
| 73 | + protocol_name = 'Lung_2Gy_30Fx' |
| 74 | + # Load clinical criteria for a specified protocol |
| 75 | + clinical_criteria = pp.ClinicalCriteria(data, protocol_name=protocol_name) |
| 76 | + # Load hyper-parameter values for optimization problem for a specified protocol |
| 77 | + opt_params = data.load_config_opt_params(protocol_name=protocol_name) |
| 78 | + # Create optimization structures (i.e., Rinds) |
| 79 | + structs.create_opt_structures(opt_params=opt_params) |
| 80 | + # create plan_full object by specifying load_inf_matrix_full=True |
| 81 | + beams_full = pp.Beams(data, load_inf_matrix_full=True) |
| 82 | + # load influence matrix based upon beams and structure set |
| 83 | + inf_matrix_full = pp.InfluenceMatrix(ct=ct, structs=structs, beams=beams_full, is_full=True) |
| 84 | + plan_full = pp.Plan(ct, structs, beams, inf_matrix_full, clinical_criteria) |
| 85 | + # Load influence matrix |
| 86 | + inf_matrix = pp.InfluenceMatrix(ct=ct, structs=structs, beams=beams) |
| 87 | + |
| 88 | + opt_full = pp.Optimization(plan_full, opt_params=opt_params) |
| 89 | + opt_full.create_cvxpy_problem() |
| 90 | + |
| 91 | + A = inf_matrix_full.A |
| 92 | + print("number of non-zeros of the original matrix: ", len(A.nonzero()[0])) |
| 93 | + |
| 94 | + method = getattr(algorithms, args.method) |
| 95 | + S = method(A, args.threshold) |
| 96 | + print("number of non-zeros of the sparsed matrix: ", len(S.nonzero()[0])) |
| 97 | + print("relative L2 norm (%): ", l2_norm(A - S) / l2_norm(A) * 100) |
| 98 | + |
| 99 | + inf_matrix.A = S |
| 100 | + plan = pp.Plan(ct=ct, structs=structs, beams=beams, inf_matrix=inf_matrix, clinical_criteria=clinical_criteria) |
| 101 | + opt = pp.Optimization(plan, opt_params=opt_params) |
| 102 | + opt.create_cvxpy_problem() |
| 103 | + x = opt.solve(solver=args.solver, verbose=False) |
| 104 | + |
| 105 | + opt_full.vars['x'].value = x['optimal_intensity'] |
| 106 | + violation = 0 |
| 107 | + for constraint in opt_full.constraints[2:]: |
| 108 | + violation += np.sum(constraint.violation()) |
| 109 | + print("feasibility violation:", violation) |
| 110 | + objective_function_value(x['optimal_intensity']) |
| 111 | + |
| 112 | + dose_1d = S @ (x['optimal_intensity'] * plan.get_num_of_fractions()) |
| 113 | + dose_full = A @ (x['optimal_intensity'] * plan.get_num_of_fractions()) |
| 114 | + print("relative dose discrepancy (%): ", (np.linalg.norm(dose_full - dose_1d) / np.linalg.norm(dose_full)) * 100) |
| 115 | + |
| 116 | + struct_names = ['PTV', 'ESOPHAGUS', 'HEART', 'CORD', 'LUNGS_NOT_GTV'] |
| 117 | + |
| 118 | + fig, ax = plt.subplots(figsize=(12, 8)) |
| 119 | + # Turn on norm flag for same normalization for sparse and full dose. |
| 120 | + ax = pp.Visualization.plot_dvh(plan, dose_1d=dose_1d , struct_names=struct_names, style='solid', ax=ax, norm_flag=True) |
| 121 | + ax = pp.Visualization.plot_dvh(plan_full, dose_1d=dose_full, struct_names=struct_names, style='dotted', ax=ax, norm_flag=True) |
| 122 | + plt.savefig(str(args.method) + "_" + str(args.threshold) + "_" + str(args.patient) + ".pdf") |
0 commit comments