def structure_plot(fig, molids, activations=None):
    """plot molecule structures"""
    if activations != None:
        assert len(activations[0]) == len(molids[0])
        assert len(activations[1]) == len(molids[1])
    id2name = defaultdict(str, rdl.get_id2name())
    all_molids = molids[0] + molids[1]
    all_activations = np.hstack(activations)
    cr = utils.ceiled_root(len(all_molids))
    for i, molid in enumerate(all_molids):
        ax = fig.add_subplot(cr, cr, i+1)
        try:
            img = plt.imread(os.path.join(structures_path, molid + '.png'))
        except Exception, e:
            img = np.zeros(img.shape)
        ax.imshow(img)
        ax.set_xticks([])
        ax.set_yticks([])
        if i >= len(molids[0]):
            for child in ax.get_children():
                if isinstance(child, plt.matplotlib.spines.Spine):
                    child.set_color('#ff0000')
        if activations != None:
            ax.set_title('{}: {:.2f}'.format(id2name[molid], all_activations[i]),
                         rotation='20')
def plot_search_matrix(fig, desc_res, selection, method, glomeruli):
    """docstring for plot_search_matrix"""
    if not glomeruli:
        tmp_glomeruli = desc_res[selection].keys()
    else:
        tmp_glomeruli = glomeruli
    n = utils.ceiled_root(len(tmp_glomeruli))
    for i_glom, glom in enumerate(tmp_glomeruli):
        mat = desc_res[selection][glom][method]
        ax = fig.add_subplot(n, n, i_glom+1)
        if np.max(mat) < 0:
            ax.imshow(np.zeros(mat.shape), interpolation='nearest', cmap=plt.cm.gray)
        else:
            ax.imshow(mat, interpolation='nearest', cmap=plt.cm.gray, vmin=0)
        ax.set_ylabel('{}'.format(glom))
        ax.set_yticks([])
        ax.set_xticks([])
        ax.set_xlabel('{:.2f}'.format(np.max(mat)))
    fig.subplots_adjust(hspace=0.4)
ax.set_xticks(np.arange(len(cas_numbers)) + 1)
bla = []
for i, g in enumerate(cas_numbers):
    bla.append(g + ' ' * 40 if i % 2 == 0 else '' + g)
ax.set_xticklabels(bla, rotation='90', ha='right')
ax.set_title('number of glomeruli available for a stimulus')
fig.savefig(os.path.join(results_path, 'glomeruli_per_stimulus.' + format))

# histograms for the glomeruli with more than N stimuli
print '\n target distribution of glomeruli with more than %d stimuli' % N
interesting = []
fig = plt.figure(figsize=(10, 10))
larger_n_idx = np.where(np.sum(~np.isnan(rm), axis=0) > 50)[0]
n_avail_with_all_conditions = []
for i, idx in enumerate(larger_n_idx):
    w_c = utils.ceiled_root(len(larger_n_idx))
    ax = fig.add_subplot(w_c, w_c, i + 1)
    glom = rm[:, idx]
    data = glom[~np.isnan(glom)]
    if scoreatpercentile(data, 75) < 0.2:
        ax.hist(data, bins=np.arange(0, 1.1, 0.1), color='#990000')
    else:
        n_avail_with_all_conditions.append(np.sum(~np.isnan(rm[:, idx])))
        interesting.append(glomeruli[idx])
        ax.hist(data, bins=np.arange(0, 1.1, 0.1), color='#38761d')
    ax.set_title(glomeruli[idx])
    ax.set_xticklabels([])  # can be switched of because all values 0 < x < 1
fig.subplots_adjust(hspace=0.3)
fig.savefig(os.path.join(results_path, 'target_quality.' + format))
print ('\tlist of glomeruli with more than %d stimuli and %d percentile > %f' %
       (N, percentile, percentile_thres))
    fig1 = plt.figure()
    # normalize both methods to their maximum value to make them comparable
    max_reg = utils.max_in_values(res[glom]['regression'])
    max_for = utils.max_in_values(res[glom]['forest'])
    for i, kernel_width in enumerate(kernel_widths):

        ax = fig.add_subplot(len(kernel_widths), 1, i+1)
        ax.plot(np.array(res[glom]['regression'][kernel_width]) / max_reg, 'b')
        ax.plot(np.array(res[glom]['forest'][kernel_width]) / max_for, 'r')
        ax.set_ylabel(kernel_width, rotation='0')
        ax.set_xlim([0, res[glom]['regression'][kernel_width].shape[0]])
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.set_ylabel('%.2f' % res[glom]['oob'][kernel_width], rotation='0')

        w_c = utils.ceiled_root(len(kernel_widths))
        ax = fig1.add_subplot(w_c, w_c, i+1)
        ax.scatter(res[glom]['targets'], res[glom]['oob_prediction'][kernel_width])


    fig.savefig(os.path.join(out_folder, 'spectral_features_' + glom + '.' + format))
    fig1.savefig(os.path.join(out_folder, 'target_vs_prediction_' + glom + '.' + format))

# compare kernel width for different glomeruli
fig = plt.figure(figsize=(10,10))
for i, kernel_width in enumerate(kernel_widths):
    ax1 = fig.add_subplot(len(kernel_widths)+1, 2, (i*2)+1)
    ax2 = fig.add_subplot(len(kernel_widths)+1, 2, (i*2)+2)
    for glom in interesting_glomeruli:
        ax1.plot(res[glom]['regression'][kernel_width])
        ax1.set_xticklabels([])