两套SHAP完整组合的共享源码

效果图重建;运行时以 templates/shap-composites 中当前代码为准。

   1 """Two complete SHAP compositions reconstructed from image-only references.
   2 
   3 The demo is a synthetic prediction model with exact interventional
   4 SHAP values against an empirical marginal background, not a fitted study.
   5 Real inputs must supply X and SHAP for the same samples and model output.
   6 """
   7 from pathlib import Path
   8 import argparse
   9 import csv
  10 import json
  11 import sys
  12 import numpy as np
  13 import matplotlib
  14 matplotlib.use('Agg')
  15 import matplotlib.pyplot as plt
  16 from matplotlib.colors import LinearSegmentedColormap, Normalize, to_rgb
  17 from matplotlib.cm import ScalarMappable
  18 from matplotlib.lines import Line2D
  19 from matplotlib.ticker import MaxNLocator
  20 
  21 for base in (Path.cwd(), *Path.cwd().parents, *Path(__file__).resolve().parents):
  22     found = next((p for p in (base/'_utils', base/'original/resources/assets/shared-scripts')
  23                   if (p/'vivid_config.py').is_file()), None)
  24     if found is not None:
  25         sys.path.insert(0, str(found))
  26         break
  27 else:
  28     raise RuntimeError('Run Vivid bootstrap in the workspace first.')
  29 import plot_utils as pu
  30 from palette_maps import palette_cmap
  31 
  32 
  33 def validate_data(x, shap, names):
  34     x, shap = np.asarray(x, float), np.asarray(shap, float)
  35     if x.ndim != 2 or x.shape != shap.shape or x.shape[0] < 3 or x.shape[1] < 2:
  36         raise ValueError('X and SHAP must be equal-shaped sample-by-feature matrices (at least 3 x 2).')
  37     if len(names) != x.shape[1] or len(set(names)) != len(names) or any(not str(n).strip() for n in names):
  38         raise ValueError('Feature names must be nonempty, unique, and match the columns.')
  39     if not np.isfinite(x).all() or not np.isfinite(shap).all():
  40         raise ValueError('Resolve missing/nonfinite values before plotting; rows are never silently removed.')
  41     if not np.any(shap):
  42         raise ValueError('All SHAP values are zero; relative contribution is undefined.')
  43     return x, shap
  44 
  45 
  46 def read_table(path):
  47     with Path(path).open(encoding='utf-8-sig', newline='') as f:
  48         rows = list(csv.reader(f))
  49     if not rows or rows[0][0] != 'sample_id' or len(rows[0]) < 3:
  50         raise ValueError('CSV needs sample_id followed by at least two feature columns.')
  51     header = rows[0]
  52     if len(set(header)) != len(header) or any(not s.strip() for s in header):
  53         raise ValueError('Duplicate or empty CSV column names.')
  54     if any(len(row) != len(header) for row in rows[1:]):
  55         raise ValueError('Ragged CSV rows.')
  56     ids = [row[0] for row in rows[1:]]
  57     if len(set(ids)) != len(ids) or any(not s.strip() for s in ids):
  58         raise ValueError('sample_id must be unique and nonempty.')
  59     return ids, header[1:], np.asarray([row[1:] for row in rows[1:]], float)
  60 
  61 
  62 def load_inputs(features, values):
  63     ids, names, x = read_table(features)
  64     sid, snames, shap = read_table(values)
  65     if set(ids) != set(sid) or set(names) != set(snames):
  66         raise ValueError('Feature and SHAP files must contain the same sample IDs and feature names.')
  67     # Explicit keyed alignment protects against independently sorted CSVs.
  68     ri, ci = {s:i for i,s in enumerate(sid)}, {s:i for i,s in enumerate(snames)}
  69     shap = shap[np.ix_([ri[s] for s in ids], [ci[s] for s in names])]
  70     x, shap = validate_data(x, shap, names)
  71     return x, shap, names
  72 
  73 
  74 def summarize(shap, names, groups=None):
  75     importance = np.mean(np.abs(shap), axis=0)
  76     total = float(importance.sum())
  77     if total <= 0 or not np.isfinite(total):
  78         raise ValueError('Positive finite total absolute importance required.')
  79     order = np.argsort(-importance, kind='stable')
  80     result = dict(importance=importance.tolist(), percent=(100*importance/total).tolist(),
  81                   order=order.tolist(), names=list(names), denominator='all input features')
  82     if groups is not None:
  83         if (not isinstance(groups, dict) or set(groups) != set(names)
  84                 or any(not isinstance(v,str) or not v.strip() for v in groups.values())):
  85             raise ValueError('Group mapping must assign every feature exactly one nonempty group.')
  86         group_names = list(dict.fromkeys(groups[n] for n in names))
  87         result['groups'] = [dict(name=g, importance=float(sum(importance[j] for j,n in enumerate(names) if groups[n]==g)))
  88                             for g in group_names]
  89         for g in result['groups']:
  90             g['percent'] = 100*g['importance']/total
  91     return result
  92 
  93 
  94 def normalize_feature(values):
  95     lo, hi = float(np.min(values)), float(np.max(values))
  96     return np.full(len(values), .5) if hi == lo else (values-lo)/(hi-lo)
  97 
  98 
  99 def swarm_offsets(values, bins=45, max_width=.30):
 100     """Deterministic density packing; never perturbs the SHAP x coordinate."""
 101     span = np.ptp(values)
 102     which = np.zeros(len(values), int) if span == 0 else np.minimum(((values-values.min())/span*bins).astype(int), bins-1)
 103     offsets = np.zeros(len(values))
 104     for b in np.unique(which):
 105         ix = np.flatnonzero(which == b)
 106         # Alternate above/below the exact row, increasing with local density.
 107         k = np.arange(len(ix))
 108         offsets[ix] = np.where(k%2, (k+1)//2, -(k//2))
 109     scale = max(1., np.max(np.abs(offsets)))
 110     return offsets/scale*max_width
 111 
 112 
 113 def smooth_trend(x, y):
 114     """Local linear descriptive smoother; no causal or breakpoint inference."""
 115     if len(np.unique(x)) < 5:
 116         return None
 117     grid = np.linspace(x.min(), x.max(), 90)
 118     nhood = min(len(x), max(12, int(np.ceil(len(x)*.28))))
 119     fitted = []
 120     for at in grid:
 121         dist = np.abs(x-at)
 122         radius = np.partition(dist, nhood-1)[nhood-1]
 123         if radius == 0:
 124             fitted.append(float(y[dist == 0].mean()))
 125             continue
 126         u = np.clip(dist/(radius*1.000001), 0, 1)
 127         weights = (1-u**3)**3
 128         design = np.column_stack((np.ones(len(x)), x-at))
 129         coef = np.linalg.lstsq(design*np.sqrt(weights[:,None]), y*np.sqrt(weights), rcond=None)[0]
 130         fitted.append(float(coef[0]))
 131     return grid, np.asarray(fitted)
 132 
 133 
 134 def validate_thresholds(thresholds, x, names):
 135     if not isinstance(thresholds, dict) or not set(thresholds).issubset(names):
 136         raise ValueError('Thresholds must map known feature names to value/method objects.')
 137     for name, item in thresholds.items():
 138         if not isinstance(item,dict) or not isinstance(item.get('method'),str) or not item['method'].strip():
 139             raise ValueError('Every supplied threshold needs a documented method.')
 140         value = float(item['value'])
 141         column = x[:,names.index(name)]
 142         if not np.isfinite(value) or not column.min() <= value <= column.max():
 143             raise ValueError('Threshold outside observed feature range.')
 144 
 145 
 146 def theme(mode, reference=False):
 147     pu.setup_style()
 148     plt.rcParams.update({'font.family':['Times New Roman','SimSun','DejaVu Serif'],
 149                          'font.size':8, 'axes.labelsize':8, 'xtick.labelsize':7,
 150                          'ytick.labelsize':8, 'axes.linewidth':.8, 'axes.grid':False,
 151                          'pdf.fonttype':42, 'svg.fonttype':'none'})
 152     if reference:
 153         # Explicit opt-in reference colors only; the default uses project colors.
 154         ends = ['#333884','#EEEAF0','#C63F54'] if mode=='dependence' else ['#25237A','#EEEAF0','#9A075C']
 155         colors = ['#D71063','#008D98','#2E3688']
 156         cmap = LinearSegmentedColormap.from_list('reference_shap',ends)
 157     else:
 158         colors = list(pu.PALETTE)
 159         cmap = palette_cmap('diverging')
 160     return cmap, colors
 161 
 162 
 163 def clean_axis(ax, box=False):
 164     ax.grid(False)
 165     ax.spines['top'].set_visible(box)
 166     ax.spines['right'].set_visible(box)
 167     ax.tick_params(length=2.5, width=.65, pad=2)
 168     ax.xaxis.set_major_locator(MaxNLocator(4))
 169 
 170 
 171 def feature_colorbar(fig, rect, cmap):
 172     cax = fig.add_axes(rect)
 173     cb = fig.colorbar(ScalarMappable(norm=Normalize(0,1), cmap=cmap), cax=cax)
 174     cb.set_ticks([0,1], labels=['Low','High'])
 175     cb.ax.tick_params(length=0, labelsize=7)
 176     cb.set_label('Feature value (within feature)', fontsize=8, labelpad=5)
 177     cb.outline.set_visible(False)
 178 
 179 
 180 def plot_dependence(x, shap, names, *, top=15, panels=8, thresholds=None, reference=False):
 181     x, shap = validate_data(x,shap,names)
 182     if not 1 <= top <= 25 or not 1 <= panels <= 12:
 183         raise ValueError('top: 1–25; panels: 1–12.')
 184     thresholds = {} if thresholds is None else thresholds
 185     validate_thresholds(thresholds,x,names)
 186     stats = summarize(shap,names)
 187     order = stats['order'][:top]
 188     selected = order[:panels]
 189     cmap, colors = theme('dependence',reference)
 190     # Intended full-width 180 mm: 8 pt * (180/25.4)/7.1 = 7.99 pt.
 191     rows = int(np.ceil(len(selected)/2))
 192     fig = plt.figure(figsize=(7.1,max(4.1,rows*.86+.65)))
 193     ax = fig.add_axes([.10,.13,.32,.75])
 194     bars = ax.twiny()
 195     bars.set_zorder(0); ax.set_zorder(1); ax.patch.set_visible(False)
 196     imp = np.asarray(stats['importance'])
 197     barcolors = [cmap(.92-.75*k/max(1,len(order)-1)) for k in range(len(order))]
 198     bars.barh(np.arange(len(order)),imp[order],height=.63,color=barcolors,
 199               edgecolor='#333333',linewidth=.85,alpha=.70)
 200     bars.set_xlim(0,max(imp)*1.13)
 201     bars.set_xlabel('Importance: mean |SHAP|',fontsize=8,labelpad=7)
 202     bars.xaxis.set_major_locator(MaxNLocator(3))
 203     bars.tick_params(axis='x',labelsize=7,length=2)
 204     ax.axvline(0,color='#666666',lw=.9,zorder=2)
 205     for row,j in enumerate(order):
 206         ax.scatter(shap[:,j],row+swarm_offsets(shap[:,j]),c=normalize_feature(x[:,j]),
 207                    cmap=cmap,vmin=0,vmax=1,s=3.4,alpha=.70,linewidths=0,zorder=3)
 208     bound = max(float(np.max(np.abs(shap[:,order])))*1.09,.01)
 209     ax.set_xlim(-bound,bound)
 210     ax.set_yticks(range(len(order)),[names[j] for j in order])
 211     ax.set_ylim(len(order)-.4,-.6)
 212     ax.set_xlabel('SHAP value')
 213     clean_axis(ax,True)
 214     fig.text(.04,.94,'(a)',weight='bold',fontsize=10)
 215     fig.text(.47,.94,'(b)',weight='bold',fontsize=10)
 216     grid = fig.add_gridspec(rows,2,left=.51,right=.93,bottom=.13,top=.88,wspace=.34,hspace=.64)
 217     medians, trends = {}, {}
 218     for k,j in enumerate(selected):
 219         a = fig.add_subplot(grid[k//2,k%2])
 220         a.scatter(x[:,j],shap[:,j],c=normalize_feature(x[:,j]),cmap=cmap,vmin=0,vmax=1,
 221                   s=3.2,alpha=.65,linewidths=0)
 222         a.axhline(0,color='#CCCCCC',lw=.6,zorder=0)
 223         med = float(np.median(x[:,j])); medians[names[j]] = med
 224         a.axvline(med,color='#333333',ls='--',lw=.85)
 225         trend = smooth_trend(x[:,j],shap[:,j])
 226         if trend is not None:
 227             a.plot(*trend,color='#777777',lw=1.1)
 228             trends[names[j]] = dict(x=trend[0].tolist(),y=trend[1].tolist())
 229         a.text(.97,.92,f'M={med:.2g}',transform=a.transAxes,ha='right',va='top',fontsize=6)
 230         if names[j] in thresholds:
 231             value = float(thresholds[names[j]]['value'])
 232             a.axvline(value,color=colors[0],ls=':',lw=1.1)
 233             a.text(.97,.70,f'T={value:.2g}',transform=a.transAxes,ha='right',va='top',fontsize=6,color=colors[0])
 234         a.set_title(f'({k+1}) {names[j]}',loc='left',fontsize=7.5,pad=3)
 235         if k%2==0:
 236             a.set_ylabel('SHAP',fontsize=7,labelpad=1)
 237         a.yaxis.set_major_locator(MaxNLocator(3))
 238         a.tick_params(labelsize=6)
 239         clean_axis(a,True)
 240     legend = [Line2D([],[],color='#333333',ls='--',lw=.85,label='Median'),
 241               Line2D([],[],color='#777777',lw=1.1,label='Local trend')]
 242     if any(names[j] in thresholds for j in selected):
 243         legend.append(Line2D([],[],color=colors[0],ls=':',label='Supplied threshold'))
 244     fig.legend(handles=legend,loc='upper center',bbox_to_anchor=(.72,.975),ncol=len(legend),
 245                frameon=False,fontsize=6.2,handlelength=1.6,columnspacing=.8)
 246     feature_colorbar(fig,[.95,.16,.012,.68],cmap)
 247     stats.update(displayed=[names[j] for j in order],medians=medians,thresholds=thresholds,trends=trends)
 248     return fig, stats
 249 
 250 
 251 def plot_contribution(x, shap, names, groups, *, top=12, reference=False):
 252     x, shap = validate_data(x,shap,names)
 253     if not 1 <= top <= 25:
 254         raise ValueError('top must be 1–25.')
 255     stats = summarize(shap,names,groups)
 256     if not 2 <= len(stats['groups']) <= 6:
 257         raise ValueError('This grouped composition supports 2–6 meaningful feature groups.')
 258     cmap, colors = theme('contribution',reference)
 259     importance = np.asarray(stats['importance']); percent = np.asarray(stats['percent'])
 260     order = stats['order'][:top]
 261     group_names = [g['name'] for g in stats['groups']]
 262     group_colors = {g:colors[i%len(colors)] for i,g in enumerate(group_names)}
 263     feature_colors = {}
 264     for group in group_names:
 265         members = [j for j in stats['order'] if groups[names[j]]==group]
 266         for k,j in enumerate(members):
 267             mix = .10+.37*k/max(1,len(members)-1)
 268             feature_colors[j] = tuple((1-mix)*np.array(to_rgb(group_colors[group]))+mix)
 269     # 180 mm inclusion gives 8 pt at native width 7.1 in.
 270     fig = plt.figure(figsize=(7.1,max(3.9,len(order)*.23+.9)))
 271     ax = fig.add_axes([.10,.14,.50,.77])
 272     ax.barh(range(len(order)),importance[order],color=[feature_colors[j] for j in order],
 273             height=.63,edgecolor='white',linewidth=.55)
 274     for row,j in enumerate(order):
 275         ax.text(importance[j]+max(importance)*.009,row,
 276                 f'{percent[j]:.2f}%\n({importance[j]:.3f})',va='center',fontsize=6.5,linespacing=.95)
 277     ax.set_ylim(len(order)-.35,-.65)
 278     ax.set_yticks(range(len(order)),[names[j] for j in order])
 279     ax.set_xlim(0,max(importance)*1.30)
 280     ax.set_xlabel('Mean |SHAP value|')
 281     clean_axis(ax)
 282     # Inset occupies the empty right area below the longest ranked bars.
 283     # Position it from actual bar/annotation extent, so it never hides bars.
 284     row_start = max(2,int(np.ceil(len(order)*.25)))
 285     y0 = .21; ring_height = .43
 286     fig.canvas.draw()
 287     renderer = fig.canvas.get_renderer()
 288     lower_labels = ax.texts[row_start:]
 289     right_edge = max([ax.get_position().x0+.12] +
 290                      [t.get_window_extent(renderer).transformed(fig.transFigure.inverted()).x1 for t in lower_labels])
 291     ring_left = max(.30,right_edge+.015)
 292     ring_width = min(.26,.60-ring_left)
 293     if ring_width < .18:
 294         # Flat importance distributions leave no inset space: widen the left
 295         # axis range (not its bar values) to reserve an honest blank area.
 296         ax.set_xlim(0,max(importance)*2.15)
 297         ring_left,ring_width = .35,.25
 298     ring = fig.add_axes([ring_left,y0,ring_width,ring_height])
 299     outer = [g['importance'] for g in stats['groups']]
 300     ring.pie(outer,radius=1,startangle=90,counterclock=False,
 301              colors=[group_colors[g] for g in group_names],
 302              wedgeprops=dict(width=.30,edgecolor='white',linewidth=1))
 303     inner = [j for g in group_names for j in stats['order'] if groups[names[j]]==g]
 304     ring.pie(importance[inner],radius=.70,startangle=90,counterclock=False,
 305              colors=[feature_colors[j] for j in inner],
 306              wedgeprops=dict(width=.23,edgecolor='white',linewidth=.8))
 307     ring.text(0,0,'Feature\ncontribution',ha='center',va='center',fontsize=7,weight='bold')
 308     ring.set_aspect('equal')
 309     # Group labels follow their outer sectors, retaining the reference design.
 310     angle = 90.
 311     for g in stats['groups']:
 312         middle = np.deg2rad(angle-1.8*g['percent'])
 313         xx, yy = 1.12*np.cos(middle), 1.12*np.sin(middle)
 314         ring.text(xx,yy,f"{g['name']}\n{g['percent']:.2f}%",
 315                   ha='left' if xx>.2 else 'right' if xx<-.2 else 'center',
 316                   va='center',fontsize=6.4,color=group_colors[g['name']],weight='bold')
 317         angle -= 3.6*g['percent']
 318     ax2 = fig.add_axes([.68,.14,.25,.77])
 319     for row,j in enumerate(order):
 320         ax2.axhline(row,color='#BBBBBB',lw=.45,ls='--',zorder=0)
 321         ax2.scatter(shap[:,j],row+swarm_offsets(shap[:,j],max_width=.25),
 322                     c=normalize_feature(x[:,j]),cmap=cmap,vmin=0,vmax=1,
 323                     s=9,marker='s',alpha=.67,linewidths=0)
 324     ax2.axvline(0,color='#777777',lw=.8,zorder=0)
 325     ax2.set_ylim(ax.get_ylim()); ax2.set_yticks([])
 326     ax2.set_xlabel('SHAP value')
 327     clean_axis(ax2); ax2.spines['left'].set_visible(False)
 328     feature_colorbar(fig,[.95,.18,.012,.69],cmap)
 329     fig.text(.04,.94,'(a)',fontsize=10,weight='bold')
 330     fig.text(.68,.94,'(b)',fontsize=10,weight='bold')
 331     stats.update(displayed=[names[j] for j in order],ring_features=[names[j] for j in inner],
 332                  grouping_rule='sum of feature mean absolute SHAP, not mean absolute grouped signed SHAP')
 333     return fig,stats
 334 
 335 
 336 def write_table(path, values, names):
 337     with Path(path).open('w',encoding='utf8',newline='') as f:
 338         writer = csv.writer(f); writer.writerow(['sample_id',*names])
 339         writer.writerows([[f'S{i:04}',*row] for i,row in enumerate(values)])
 340 
 341 
 342 def demo_data(directory):
 343     directory = Path(directory); directory.mkdir(parents=True,exist_ok=True)
 344     rng = np.random.default_rng(20260916)
 345     names = ['CUR','Aspect','PRE','ELE','EVI','SAVI','LST','TEM','SIL','Slope','NDWI','NDVI']
 346     x = rng.normal(size=(320,len(names)))
 347     weights = np.array([.58,.28,.24,.20,.18,.15,.12,.105,.085,.07,.055,.032])
 348     effects = x*weights
 349     effects[:,0] = -.7*np.tanh(1.3*x[:,0])
 350     effects[:,1] = -.35*x[:,1]+.13*np.maximum(x[:,1]-.2,0)
 351     effects[:,2] = -.29*x[:,2]+.16*np.maximum(x[:,2]-.4,0)
 352     effects[:,3] = .22*np.tanh(1.4*x[:,3])
 353     effects[:,4] = .17*(x[:,4]**2-1)
 354     effects[:,6] = -.14*np.tanh(x[:,6])
 355     shap = effects-effects.mean(axis=0)
 356     prediction = 2+effects.sum(axis=1)
 357     baseline = float(2+effects.mean(axis=0).sum())
 358     # Exact two-player allocation of pair interactions under the product of
 359     # empirical marginal backgrounds. This creates genuine interaction spread.
 360     interactions = [(0,2,.18),(1,3,.10),(4,6,.08),(5,7,.08),(8,9,.03)]
 361     means = x.mean(axis=0)
 362     for i,j,coefficient in interactions:
 363         prediction += coefficient*x[:,i]*x[:,j]
 364         baseline += coefficient*means[i]*means[j]
 365         shap[:,i] += coefficient*.5*(x[:,i]-means[i])*(x[:,j]+means[j])
 366         shap[:,j] += coefficient*.5*(x[:,j]-means[j])*(x[:,i]+means[i])
 367     groups = {n:('Terrain' if i in [0,1,3,8,9] else 'Climate' if i in [2,6,7] else 'Vegetation') for i,n in enumerate(names)}
 368     thresholds = {'Aspect':dict(value=.2,method='known hinge in the synthetic additive model'),
 369                   'PRE':dict(value=.4,method='known hinge in the synthetic additive model')}
 370     write_table(directory/'features.csv',x,names)
 371     write_table(directory/'shap.csv',shap,names)
 372     write_table(directory/'model.csv',np.column_stack((prediction,np.full(len(x),baseline))),['prediction','base_value'])
 373     for name,data in [('groups',groups),('thresholds',thresholds)]:
 374         (directory/f'{name}.json').write_text(json.dumps(data,indent=2),encoding='utf8')
 375     (directory/'PROVENANCE.md').write_text(
 376         '# Synthetic demonstration\n\nSeed 20260916; 320 independent normal samples, 12 features. '
 377         'Feature names are layout labels, not measured environmental quantities; x values are standardized synthetic inputs. '
 378         'The model is f(x)=2+sum(g_j(x_j))+sum(a_ij*x_i*x_j); demo_data defines every term. '
 379         'Main-term SHAP_j=g_j(x_j)-mean_background(g_j). Each pair contributes '
 380         'a_ij/2*(x_i-mu_i)*(x_j+mu_j) to i and the symmetric expression to j. '
 381         'These are exact interventional SHAP under the product of empirical marginal backgrounds. '
 382         'base_value+sum(SHAP)=prediction. No trained-model accuracy or causal effects are claimed. '
 383         'Thresholds are known hinges of the synthetic model, not estimated findings.\n',encoding='utf8')
 384     return x,shap,names,groups,thresholds
 385 
 386 
 387 def main():
 388     parser = argparse.ArgumentParser(description=__doc__)
 389     parser.add_argument('--mode',choices=['dependence','contribution'],required=True)
 390     parser.add_argument('--features',type=Path); parser.add_argument('--shap',type=Path)
 391     parser.add_argument('--groups-json',type=Path); parser.add_argument('--thresholds-json',type=Path)
 392     parser.add_argument('--demo',action='store_true')
 393     parser.add_argument('--reference-colors',action='store_true')
 394     parser.add_argument('--top',type=int,default=15); parser.add_argument('--panels',type=int,default=8)
 395     parser.add_argument('--output',type=Path,default=Path('figures/fig_shap_composite'))
 396     args = parser.parse_args()
 397     if args.demo and any([args.features,args.shap,args.groups_json,args.thresholds_json]):
 398         parser.error('--demo cannot be combined with real input files.')
 399     if args.mode=='contribution' and args.thresholds_json:
 400         parser.error('Thresholds apply only to dependence mode.')
 401     args.output.parent.mkdir(parents=True,exist_ok=True)
 402     try:
 403         if args.demo:
 404             x,shap,names,groups,thresholds = demo_data(args.output.parent/'demo-data')
 405         else:
 406             if args.features is None or args.shap is None:
 407                 parser.error('Supply --features and --shap, or explicitly select --demo.')
 408             x,shap,names = load_inputs(args.features,args.shap)
 409             groups = json.loads(args.groups_json.read_text(encoding='utf-8-sig')) if args.groups_json else None
 410             thresholds = json.loads(args.thresholds_json.read_text(encoding='utf-8-sig')) if args.thresholds_json else {}
 411         if args.mode=='dependence':
 412             fig,stats = plot_dependence(x,shap,names,top=args.top,panels=args.panels,
 413                                        thresholds=thresholds,reference=args.reference_colors)
 414         else:
 415             if groups is None:
 416                 parser.error('Contribution mode requires --groups-json.')
 417             fig,stats = plot_contribution(x,shap,names,groups,top=args.top,reference=args.reference_colors)
 418     except (ValueError,KeyError,TypeError) as exc:
 419         parser.error(str(exc))
 420     stats.update(mode=args.mode,synthetic_demo=args.demo,reference_colors=args.reference_colors,
 421                  color_normalization='min/max separately within each feature; constant maps to midpoint',
 422                  samples=len(x),feature_count=len(names),
 423                  input_files=None if args.demo else dict(features=str(args.features.resolve()),shap=str(args.shap.resolve())))
 424     for ext in ['png','pdf']:
 425         fig.savefig(args.output.with_suffix('.'+ext),dpi=350,facecolor='white',bbox_inches='tight',pad_inches=.06)
 426     args.output.with_suffix('.json').write_text(json.dumps(stats,ensure_ascii=False,indent=2),encoding='utf8')
 427     plt.close(fig)
 428     print(f'Saved {args.output} (PNG, PDF, JSON)')
 429 
 430 
 431 if __name__=='__main__':
 432     main()