def plotclick(clickdata):
    if (clickdata.inaxes is None):
        return
    else:
        z = axes.index(clickdata.inaxes)
        y = int(clickdata.ydata / TN_size)
        x = int(clickdata.xdata / TN_size)
        if (ShowXinsteadOfZ): x, z = z, x  # swap
        #print(str([y,x,z]))
        patch = [p for p in region['patches']
                 if p['patchstep'] == [y, x, z]][0]
        plotting.print_dict(patch)
        if (clickdata.button is 1):
            set_to_core(patch['id'])
        elif (clickdata.button is 2):
            set_to_boundary(patch['id'])
        else:
            set_to_outside(patch['id'])
region = filehandling.pload(BASEP + 'data/F15/region.pickledump')
segmentation = filehandling.pload(BASEP + 'data/F15/segmentation.pickledump')
segmentation_patch_515 = filehandling.pload(
    BASEP + 'data/F15/segmentations/segmentation_patch_515.pickledump')

tumor_volume_515 = filehandling.readNifti(
    ROOTP + 'LocalData/F15/C02_tumorBoost/patchvolume_515.nii'
)  # we're reading in a .nii file, so it's real image data, not just metadata

#%% Main code

# print dictionary in structured format to console

print("--- Region (meta data for patch locations):")
plotting.print_dict(region)
print("\n\n")

print("--- Segmentation (aggregated list of metastases across all patches):")
plotting.print_dict(segmentation)

print("\n\n")
print("--- Single segmentation (list of metastases for one patch):")
plotting.print_dict(segmentation_patch_515)

# Print metastases of patch 515 (probably we don't need this)
print(
    "\nHere are all the metastases of patch 515, described by ID and Volume:")
metastases_in_patch515 = segmentation_patch_515['metastases']
for metastasis in metastases_in_patch515:
    print('ID: ' + str(metastasis['id']) + '\tVolume: ' +
Beispiel #3
0
#%% Main code

# print dictionary in structured format to console
'''
print("--- Region (meta data for patch locations):")
plotting.print_dict(region)
print("\n\n")

print("--- Segmentation (aggregated list of metastases across all patches):")
plotting.print_dict(segmentation)
'''

print("\n\n")
print("--- Single segmentation (list of metastases for one patch):")
plotting.print_dict(segmentation_patch_515)
'''
# Print metastases of patch 515 (probably we don't need this)
print("\nHere are all the metastases of patch 515, described by ID and Volume")
metastases_in_patch515 = segmentation_patch_515['metastases']
for metastasis in metastases_in_patch515:
    print('ID:',str(metastasis['id']),'Volume:',str(metastasis['volume']))
print("There are " + str(len(metastases_in_patch515)) + " metastases in patch 515")
'''

# ALTERNATIVE:  Print metastases of patch 515
print(
    "Here are all metastases of patch 515, described by their global ID and volume:"
)
all_metastases = segmentation['metastases']
metastases_in_p515 = {}
Beispiel #4
0
    model = load_model('model_1/KERAS_check_best_model.h5', custom_objects=co)

import plotting
from sklearn.metrics import accuracy_score
y_keras = model.predict(X_test)
print("Accuracy: {}".format(
    accuracy_score(np.argmax(y_test, axis=1), np.argmax(y_keras, axis=1))))

import hls4ml
hls4ml.model.optimizer.OutputRoundingSaturationMode.layers = ['Activation']
hls4ml.model.optimizer.OutputRoundingSaturationMode.rounding_mode = 'AP_RND'
hls4ml.model.optimizer.OutputRoundingSaturationMode.saturation_mode = 'AP_SAT'
config = hls4ml.utils.config_from_keras_model(model, granularity='name')
config['LayerName']['softmax']['exp_table_t'] = 'ap_fixed<18,8>'
config['LayerName']['softmax']['inv_table_t'] = 'ap_fixed<18,4>'
print("-----------------------------------")
plotting.print_dict(config)
print("-----------------------------------")

hls_model = hls4ml.converters.convert_from_keras_model(
    model,
    hls_config=config,
    output_dir='model_1/hls4ml_prj',
    fpga_part='xc7z020clg400-1',
    backend='Pynq')
hls_model.compile()
y_hls = hls_model.predict(X_test)
hls_model.build(csim=False, synth=True, export=True)
hls4ml.report.read_vivado_report('model_1/hls4ml_prj/')
hls4ml.templates.PynqBackend.make_bitfile(hls_model)
Beispiel #5
0
def yaml_load(config):
    with open(config, 'r') as stream:
        param = yaml.safe_load(stream)
    return param


model_file = 'keras_model.h5'

model = keras_model.load_model(model_file)

model.summary()

hls_config = yaml_load('hls4ml_config.yml')
hls_config = hls_config['HLSConfig']

backend_config = hls4ml.converters.create_vivado_config(
    fpga_part='xczu7ev-ffvc1156-2-e')
backend_config['ProjectName'] = 'anomaly_detector'
backend_config['KerasModel'] = model
backend_config['HLSConfig'] = hls_config
backend_config['OutputDir'] = 'anomaly_detector_prj'
backend_config['Backend'] = 'Vivado'
backend_config['Implementation'] = 'serial'
backend_config['ClockPeriod'] = 10

plotting.print_dict(backend_config)

hls_model = hls4ml.converters.keras_to_hls(backend_config)

_ = hls_model.compile()
def inspect_update_plot():
    global metastasis, CoM_abs, inspect_fig, inspect_ax_plt_list, inspect_addremove_STATUS, inspect_maskvis
    plt.figure(num=inspect_fig.number)
    try:
        for ax in inspect_ax_plt_list:
            inspect_fig.delaxes(ax)
    except:
        pass
    plt.draw()
    if(OoI is None):
        return
    min_padding = segmentation['autosegmentation']['min_padding']
    if(type(OoI)==int): 
        metastasis = next((m for m in metastases if m["id"] == OoI))
        if(metastasis['characterization']['NofSTDs'] is None): metastasis['characterization']['NofSTDs'] = 4
        padding = np.max([np.round(1*metastasis['max_dist']),min_padding]) # diameter of seedblob, but at least 5 voxel
        CoM_abs = metastasis['offset'] + metastasis['CoM']
        inspect_addremove_STATUS = 'remove'
    else:
        metastasis = None
        inspect_addremove_STATUS = 'add'
        inspect_maskvis = False
        padding = min_padding
        CoM_abs = OoI
    inspect_maskvis_updaterender()
    inspect_masksize_updaterender()
    inspect_flag_updaterender()
    inspect_addremove_updaterender()
    
    miny = np.clip(int(CoM_abs[0] - padding), 0, volume_vis.shape[0])
    maxy = np.clip(int(CoM_abs[0] + padding), 0, volume_vis.shape[0])
    minx = np.clip(int(CoM_abs[1] - padding), 0, volume_vis.shape[1])
    maxx = np.clip(int(CoM_abs[1] + padding), 0, volume_vis.shape[1])
    minz = np.clip(int(CoM_abs[2] - padding), 0, volume_vis.shape[2])
    maxz = np.clip(int(CoM_abs[2] + padding), 0, volume_vis.shape[2])
    mybox = volume_vis[miny:maxy,minx:maxx,minz:maxz]
    mask = np.zeros(mybox.shape).astype(np.bool)
    ax2 = None
    if(type(OoI)==int):
        abs_points = metastasis['points']
        pointarray = np.asarray(abs_points) - np.asarray([miny,minx,minz])
        mask[pointarray[:,0],pointarray[:,1],pointarray[:,2]] = 1
        plotting.print_dict(metastasis)
        #if(inspect_view is not '3D view'):
            #ax2 = inspect_fig.add_subplot(2,2,2)
            #ax2.text(0,0.3,plotting.print_dict(metastasis,filterlist='volume,max_dist,characterization,medianFG,maxFG,maxBG,avgSTDabovelocalmean,NofSTDs,evaluation,last_inspection,manually_added',printit=False),family='monospace',fontsize=fs[1])
            #ax2.axis('off')
    ############## Autofluo instead of metastasis info (which is the code above within the if statement)
    if(inspect_view is not '3D view'):
        ax2 = inspect_fig.add_subplot(2,2,2)
        autofluo_projection = np.max(volume_autofluo[miny:maxy,minx:maxx,minz:maxz],2)
        plotting.intensity(autofluo_projection,color='white',cap=np.max(autofluo_projection),ahandle=ax2)
        plt.title('Autofluorescence (z-Projection)')
    ##############
    
    if(inspect_view=='Max. Projections'):
        ax1 = inspect_fig.add_subplot(2,2,1)
        ax3 = inspect_fig.add_subplot(2,2,3)
        ax4 = inspect_fig.add_subplot(2,2,4)
        inspect_ax_plt_list = [ax1, ax3, ax4, ax2]
        plotting.projections(mybox, mask=mask, ahandles=inspect_ax_plt_list[0:3], outline=inspect_maskvis)
    if(inspect_view=='Cum. Projections'):
        ax1 = inspect_fig.add_subplot(2,2,1)
        ax3 = inspect_fig.add_subplot(2,2,3)
        ax4 = inspect_fig.add_subplot(2,2,4)
        inspect_ax_plt_list = [ax1, ax3, ax4, ax2]
        plotting.projections(mybox, mask=mask, ahandles=inspect_ax_plt_list[0:3], outline=inspect_maskvis, mode='cum')
    elif(inspect_view=='Slices through center'):
        ax1 = inspect_fig.add_subplot(2,2,1)
        ax3 = inspect_fig.add_subplot(2,2,3)
        ax4 = inspect_fig.add_subplot(2,2,4)
        inspect_ax_plt_list = [ax1, ax3, ax4, ax2]
        plotting.orthoslices(mybox, mask=mask, ahandles=inspect_ax_plt_list[0:3], outline=inspect_maskvis)
    elif(inspect_view=='3D view'):
        inspect_ax_plt_list = [inspect_fig.gca(projection='3d')]
        plotting.voxelintensity(mybox, mask=mask, ahandle=inspect_ax_plt_list[0],threshold=0.08)
        inspect_rotate_3dplot_to('YX')

    # Render updated plot
    plt.draw()
    plt.subplots_adjust(top=0.8)
    inspect_update_title()
    
    # Update last inspection
    if(type(OoI)==int):
        metastasis['evaluation']['last_inspection'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")  
        save_updated_metastasis()