def run_experiment(model, settings={}) -> dict:
    from imi.utils.signal import find_peaks
    peak_settings = settings['tipping']

    # find peaks
    #
    bins = np.linspace(0.01, 1, 20)
    bins = np.asarray([*-bins[::-1], *bins])
    snapshots = find_peaks(model, bins=bins, **peak_settings)
    sim = infcy.Simulator(model)

    conditional = settings.get("conditional")
    mis = {}
    pxs = {}
    cs = {}
    for k, v in snapshots.items():
        try:
            s, c = sim.forward(v, **conditional).values()
            px, mi = infcy.mutualInformation(c, s)
            mis[k] = mi
            cs[k] = c
            pxs[k] = px
        # no states found
        except Exception as e:
            print(e)
    print("-" * 13 + "Tipping points" + "-" * 13)
    for k, v in snapshots.items():
        print(f"{len(v)} \t at {k}")
    # print(f"Found {len(snapshots)}")
    return dict(snapshots=snapshots, mi=mis, px=pxs)
Exemple #2
0
    def run(self):
        model = self.settings.get('model')

        config = self.settings.get('config').copy()
        print(config)
        snapshot_settings = config.get("snapshots").copy()
        conditional_settings = config.get("conditional").copy()
        # setup simulatator object
        sim = infcy.Simulator(model)

        # obtain system snapshots
        snapshots = sim.snapshots(**snapshot_settings)

        same_side = True
        if same_side:
            tmp = dict()
            for k, v in snapshots.items():
                if np.mean(v) > .5:
                    k = np.abs(np.array(k) - 1)
                    k = tuple(k)
                tmp[k] = tmp.get(k, 0) + v
            z = sum(tmp.values())
            tmp = {k: v / z for k, v in tmp.items()}
            snapshots = tmp
        backup = copy.deepcopy(snapshots)

        # conditional sampling
        time = conditional_settings.get('time')
        time = np.arange(time)

        conditional_settings['time'] = time
        output = sim.forward(snapshots, **conditional_settings)

        snapshots = output['snapshots']
        conditional = output['conditional']
        px, mi = infcy.mutualInformation(conditional, snapshots)

        # store results
        results = dict(snapshots=snapshots,
                       conditional=conditional,
                       backup_snapshots=backup,
                       graph=model.graph,
                       config=config,
                       mi=mi,
                       px=px)

        return results
Exemple #3
0
    def run(self):
        m = self.settings.get('model')

        sim = infcy.Simulator(m)
        # get settings configs
        ss = self.settings['config'].get("snapshots")
        cs = self.settings['config'].get("conditional")

        time = cs.get("time", 10)
        if isinstance(time, int):
            time = np.arange(time)
            cs['time'] = time

        snapshots = sim.snapshots(**ss)
        snapshots, conditional = sim.forward(snapshots, **cs).values()
        # get tipping
        tipping = np.mean(m.agentStates)
        df = []
        bins = np.linspace(0, 1, 10)
        bins = np.array([*bins[::-1] * -1, 0, *bins])
        for k, v in snapshots.items():
            idx = np.digitize(np.mean(k) - tipping, bins)
            bins_ = bins[idx]
            c = conditional[k]
            row = dict(state=k, bin=bins_, state_count=v, conditional=c)
            df.append(row)
        df = pd.DataFrame(df)

        mis = {}
        for x, dfi in df.groupby("bin"):
            states = np.stack(dfi.state)
            vals = np.stack(dfi.state_count)
            snap = {tuple(s): v / sum(vals) for s, v in zip(states, vals)}
            cond = np.stack(dfi.conditional)
            cond = {tuple(s): i for s, i in zip(states, cond)}

            try:
                px, mi = infcy.mutualInformation(cond, snap)
                bin = x
                mis[str(bin)] = mi
            except Exception as e:
                print(e)
        # print(f"Found {len(snapshots)}")
        return dict(df=df, mis=mis)
Exemple #4
0
    def run(self):
        model = self.settings.get('model')
        from imi.utils.signal import find_peaks

        peak_settings = self.settings['config']['tipping']

        # find peaks
        #
        bins = np.linspace(0.01, 1, 20)
        bins = np.asarray([*-bins[::-1], *bins])
        snapshots = find_peaks(model, bins=bins, **peak_settings)
        print("-" * 13 + "Tipping points" + "-" * 13)
        for k, v in snapshots.items():
            print(f"{len(v)} \t at {k}")
        sim = infcy.Simulator(model)

        conditional = self.settings['config'].get("conditional", {})
        # conditional sampling
        time = conditional.get('time')
        time = np.arange(time)
        conditional['time'] = time

        mis = {}
        pxs = {}
        cs = {}
        for k, v in snapshots.items():
            try:
                s, c = sim.forward(v, **conditional).values()
                px, mi = infcy.mutualInformation(c, s)
                mis[k] = mi
                cs[k] = c
                pxs[k] = px
            # no states found
            except Exception as e:
                print(e)
        # print(f"Found {len(snapshots)}")
        return dict(snapshots=snapshots,
                    mi=mis,
                    px=pxs,
                    graph=model.graph,
                    config=self.settings.get('config', {}),
                    cs=cs)
Exemple #5
0
print(g)
m = models.Potts(g, t=2)

# print(m.sampleNodes(1).base)
N = 1000
M = 1000
import time

# print(m.simulate(M).shape)
sim = infcy.Simulator(m)

s = time.time()
m.spawn()
print(time.time() - s)
s = time.time()
snaps = sim.snapshots(N)
print(time.time() - s)
print("retrieved snaps")

s = time.time()
S = sim.forward(snaps, repeats=M, time=np.arange(10), n_jobs=1)["conditional"]
print(time.time() - s)
px, mi = infcy.mutualInformation(S, snaps)
fig, ax = plt.subplots()
ax.plot(mi)
fig.show()
plt.show(block=1)

print(mi.sum(0))
def run_experiment(model, settings = {}) -> dict:
    peak_settings =  settings['tipping']

    # find peaks
    #
    # bins = np.linspace(0, 1, 20)
    bins = np.linspace(-1, 1, 21)
    # bins = np.asarray([*-bins[::-1], *bins])

    # hacked in parameter settings
    peak_settings['rtol'] = 2/model.nNodes
    peak_settings['sigma'] = model.nNodes * 10

    # snapshots here is bins, states
    snapshots, isi = find_tipping(model,
                           bins = bins,
                           **peak_settings)
    sim = infcy.Simulator(model)

    conditional = settings.get("conditional")
    mis = {}
    pxs = {}
    cs  = {}
    nStates = sum([len(i) for i in snapshots.values()])
    if nStates == 0:
        nStates = 1
    t = conditional.get("time_steps")

    # check for allocation of results
    bits = t * model.nNodes * nStates * np.float64().itemsize
    bits =  check_allocation(bits)
    if bits < 1:
        bins = np.array([i for i in snapshots.keys()])
        counts = np.asarray([len(i) for i in snapshots.values()])
        n = int(bits * counts.sum())
        print(f"resampling to {n}")
        resampled = resample(counts, bins, snapshots, n)
    else:
        resampled = snapshots



    time_steps = conditional.get("time_steps", 1000)
    time       = np.arange(0, time_steps // 2)
    try:
        del conditional['time_steps']
        logtime    = np.geomspace(min(isi), max(isi), time_steps // 2)
        time = np.concatenate((time, logtime))
    except KeyError:
        print("key not found")

    conditional['time'] = time
    for k, v in resampled.items():
        try:
            s, c = sim.forward(v, **conditional).values()
            c = { k: np.float32(vv) for k, vv in c.items() }
            px, mi = infcy.mutualInformation(c, s)
            mis[k] = np.float32(mi)
            cs[k]  = c
            pxs[k] = px
        # no states found
        except Exception as e :
            print(e)
    print("-" * 13 + "Tipping points" + "-" * 13)
    for k, v in snapshots.items():
        print(f"{len(v)} \t at {k}")
    # print(f"Found {len(snapshots)}")
    print("done")
    return dict(snapshots = snapshots, mi = mis, px = pxs, resampled =
                resampled, isi = isi, time = time, cpx = cs)
    def run(self):
        model = self.settings.get('model')

        # print("here", model.sampleSize)

        config = self.settings.get('config').copy()

        intervention = config.get('intervention', {})
        snapshot_settings = config.get("snapshots").copy()

        conditional_settings = config.get("conditional").copy()
        # setup simulatator object
        sim = infcy.Simulator(model)

        # obtain system snapshots
        snapshots = sim.snapshots(**snapshot_settings)
        # snapshots = self.settings['snapshots']

        same_side = True
        if same_side:
            tmp = dict()
            mapper = {
                i: j
                for i, j in zip(model.agentStates, model.agentStates[::-1])
            }
            # print(mapper)
            for k, v in snapshots.items():
                if np.mean(k) < np.mean(model.agentStates):
                    k = tuple(mapper[ki] for ki in k)
                tmp[k] = tmp.get(k, 0) + v
                # print(k, v)
            z = sum(tmp.values())
            tmp = {k: v / z for k, v in tmp.items()}
            snapshots = tmp
        backup = copy.deepcopy(snapshots)

        # conditional sampling
        time = conditional_settings.get('time')
        time = np.arange(time)

        conditional_settings['time'] = time

        model.nudges = intervention
        print(model.nudges)

        # # model.nudges = intervention
        # for k, v in intervention.items():
        #      idx = model.adj.mapping[str(k)]
        #      model.H[idx] = v
        # print(model.H)

        sim = infcy.Simulator(model)
        output = sim.forward(snapshots, **conditional_settings)

        # snapshots = output['snapshots']
        conditional = output['conditional']
        px, mi = infcy.mutualInformation(conditional, snapshots)

        # store results
        results = dict(snapshots=snapshots,
                       conditional=conditional,
                       backup_snapshots=backup,
                       graph=model.graph,
                       config=config,
                       mi=mi,
                       px=px)

        return results