Exemple #1
0
def eval_lpdf(stan_binary, data, parameters):
    # Get temp directory
    tmpdirec = tempfile.TemporaryDirectory()
    tmpdir = tmpdirec.name

    # create data file
    data_file = os.path.join(tmpdir, "data.R")
    io.rdump(data_file, data)

    # Create continuation file
    param_file = os.path.join(tmpdir, "param.R")
    io.rdump(param_file, parameters)

    # Run it for one iteration
    out_file = os.path.join(tmpdir, "out.csv")
    run = subprocess.run([
        stan_binary, "sample", "num_warmup=0", "num_samples=1", "adapt",
        "engaged=0", "data", f"file={data_file}", f"init={param_file}",
        "output", f"file={out_file}"
    ],
                         capture_output=True)
    assert run.returncode == 0

    # Parse the results
    lp = io.parse_csv(out_file)['lp__'][0]

    return lp
Exemple #2
0
def viz_mean_excitability(sid, rid):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    nreg = regpos.shape[0]
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    cinf = res['c']
    # cmean = np.mean(cinf, axis=0)
    # pexc = np.mean(cinf > 2.0, axis=0)
    scalar = np.percentile(cinf, 50, axis=0)

    # Regions
    cmap = 'plasma'
    # vmin = np.min(scalar)
    # vmax = np.max(scalar)
    vmin, vmax = -2, 2

    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i],
                          r=4,
                          c=vp.colorMap(scalar[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(regpos[i],
                        side=6,
                        c=vp.colorMap(scalar[i], cmap, vmin, vmax)))

    vbar = vp.Points(regpos, r=0.01).pointColors(scalar,
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))

    def slider(widget, event):
        percentile = widget.GetRepresentation().GetValue()
        scalar = np.percentile(cinf, percentile, axis=0)
        for i in range(nreg):
            vpoints[i].color(vp.colorMap(scalar[i], cmap, vmin, vmax))

    vplotter = vp.Plotter(axes=0)
    vplotter.addSlider2D(slider,
                         0.,
                         100.,
                         value=50.0,
                         pos=3,
                         title="Percentile")
    vplotter.show(vpoints, vlines, vmeshes, vcontacts, vbar)
Exemple #3
0
def get_data(surgeries, onset):
    rows = []
    for subject, surgery in surgeries.items():     
        res_dir = f"run/solo/{onset}/vep/{subject}/output/"
        rec_dirs = glob.glob(os.path.join(res_dir, "r*_all/"))

        for rec_dir in rec_dirs:
            rid = int(rec_dir[-7:-5])

            indata = io.rload(f"run/solo/{onset}/vep/{subject}/input/r{rid:02d}_all.R")
            reg_sz = list(indata['reg_sz'].astype(int))
            reg_ns = list(indata['reg_ns'].astype(int))
            reg_obs = reg_sz + reg_ns

            resfiles = [os.path.join(rec_dir, f"chain_{chain}.csv") for chain in CHAINS]
            statuses = [os.path.join(rec_dir, f"chain_{chain}.status") for chain in CHAINS]
            res = io.parse_csv([r for r, s in zip(resfiles, statuses)
                                if int(open(s).read().strip())])
            pez = np.mean(res['c'] > EZ_THRESHOLD, axis=0)

            resec = np.array(surgery['resection'])
            is_resected = np.array(resec) > RESEC_THRESHOLD
            if not np.any(is_resected):
                is_resected[np.argmax(resec)] = True

            for i in range(NREG):
                rows.append(OrderedDict(
                    onset=onset,
                    subject=subject,
                    rid=rid,
                    region=i,

                    observed=(i in reg_obs),
                    seizing=(i in reg_sz),
                    fracsz=(len(reg_sz) / len(reg_obs)),

                    pez=pez[i],
                    resection=resec[i],
                    is_resected=is_resected[i],
                    engel=surgery['engel']
                ))

    df = pd.DataFrame(rows)
    dfg = df.groupby(['onset', 'subject', 'region']).agg(
             {'observed': 'any', 'seizing': 'any', 'fracsz': 'first',
              'pez': 'mean',  'resection': 'first', 'is_resected': 'first',
              'engel': 'first'}).reset_index()
    
    return dfg
Exemple #4
0
def viz_excitability(sid, rid):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    nreg = regpos.shape[0]
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    cinf = res['c']

    ctr = 2.0
    pexc = np.mean(cinf > ctr, axis=0)

    # Regions
    cmap = 'Reds'
    vmin, vmax = 0, 0.15
    # vmin, vmax = -2, 0

    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i],
                          r=4,
                          c=vp.colorMap(pexc[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(regpos[i],
                        side=6,
                        c=vp.colorMap(pexc[i], cmap, vmin, vmax)))

    vbar = vp.Points(regpos, r=0.01).pointColors(pexc,
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))

    def cslider(widget, event):
        ctr = widget.GetRepresentation().GetValue()
        pexc = np.mean(cinf > ctr, axis=0)
        for i in range(nreg):
            vpoints[i].color(vp.colorMap(pexc[i], cmap, vmin, vmax))

    vplotter = vp.Plotter(axes=0)
    vplotter.addSlider2D(cslider, -3.0, 3.0, value=2.0, pos=3, title="c")
    vplotter.show(vpoints, vlines, vmeshes, vcontacts, vbar)
Exemple #5
0
def viz_seizure(sid, rid):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    nreg = regpos.shape[0]
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    tinf = res['t']

    t = 0.0
    psz = np.mean(tinf < t, axis=0)

    # Regions
    cmap = 'bwr'
    vmin, vmax = 0, 1

    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i],
                          r=4,
                          c=vp.colorMap(psz[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(regpos[i],
                        side=6,
                        c=vp.colorMap(psz[i], cmap, vmin, vmax)))

    vbar = vp.Points(regpos, r=0.01).pointColors(psz,
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))

    def tslider(widget, event):
        t = widget.GetRepresentation().GetValue()
        psz = np.mean(tinf < t, axis=0)
        for i in range(nreg):
            vpoints[i].color(vp.colorMap(psz[i], cmap, vmin, vmax))

    vplotter = vp.Plotter(axes=0)
    vplotter.addSlider2D(tslider, 0, 90.0, value=0.0, pos=3, title="t")
    vplotter.show(vpoints, vlines, vmeshes, vcontacts, vbar)
Exemple #6
0
def make_video(sid, rid, video_file):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    tinf = res['t']

    t = 0.0
    psz = np.mean(tinf < t, axis=0)
    nreg = regpos.shape[0]

    # Regions
    cmap = 'bwr'
    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i], r=4, c=vp.colorMap(psz[i], cmap, 0, 1)))
        else:
            vpoints.append(
                vp.Cube(regpos[i], side=6, c=vp.colorMap(psz[i], cmap, 0, 1)))

    vbar = vp.Points(regpos, r=0.01).pointColors(psz,
                                                 cmap=cmap,
                                                 vmin=0,
                                                 vmax=1)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))
    vtext = vp.Text2D(f"t = {t:4.1f} s", pos=0, s=2, c='black')

    center = np.mean(regpos, axis=0)
    dist = 2.5 * (np.max(regpos[:, 1]) - np.min(regpos[:, 1]))

    # Video -------------------------------------------------------
    vplotter = vp.Plotter(axes=0,
                          interactive=0,
                          offscreen=True,
                          size=(1800, 1800))
    nframes = 3000

    vplotter += vpoints
    vplotter += vlines
    vplotter += vmeshes

    video = vp.Video(name=video_file, duration=90)
    ratios = np.array([30, 3, 5, 30, 5, 3, 30, 10])
    frames = (nframes * ratios / np.sum(ratios)).astype(int)

    # Run and pause
    animate(vplotter,
            video,
            frames[0],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            prange=(0, 45),
            time=lambda p: p)
    animate(vplotter,
            video,
            frames[1],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            time=45.)

    ## Fly around
    pos = lambda angle: center + dist * np.array(
        [0, -np.sin(angle), np.cos(angle)])
    animate(vplotter,
            video,
            frames[2],
            vpoints,
            tinf,
            pos=pos,
            foc=center,
            viewup=(0, 1, 1),
            prange=(0, np.pi / 2),
            time=45.,
            endpoint=False)

    pos = lambda angle: center + dist * np.array(
        [-np.sin(angle), -np.cos(angle), 0])
    animate(vplotter,
            video,
            frames[3],
            vpoints,
            tinf,
            pos=pos,
            foc=center,
            viewup=(0, 0, 1),
            prange=(0, 2 * np.pi),
            time=45.)

    pos = lambda angle: center + dist * np.array(
        [0, -np.sin(angle), np.cos(angle)])
    animate(vplotter,
            video,
            frames[4],
            vpoints,
            tinf,
            pos=pos,
            foc=center,
            viewup=(0, 1, 1),
            prange=(np.pi / 2, 0),
            time=45.,
            startpoint=False)

    # Pause + run + pause
    animate(vplotter,
            video,
            frames[5],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            time=45.)
    animate(vplotter,
            video,
            frames[6],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            prange=(45, 90),
            time=lambda p: p)
    animate(vplotter,
            video,
            frames[7],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            time=90.)

    video.close()