<commit_before>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib as mpl
from matplotlib import mlab
import numpy as np
import time
import bisect

from nested_sampling import NestedSampling, MonteCarloWalker, Replica
from nested_sampling.utils.rotations import vector_random_uniform_hypersphere
from scipy.optimize import Result
from _bisect import bisect_left

class Pot(object):
    def get_energy(self, coords):
        assert len(coords) == 2
        return f(coords[::2], coords[1::2])[0]

def do_nested_sampling(nreplicas=10, niter=200, mciter=1000, stepsize=.8, estop=-.9,
                       x0=[1,1], r0=2):
    path = []
    def mc_record_position_event(coords=None, **kwargs):
        if len(path) == 0 or not np.all(path[-1] == coords):
            path.append(coords)

    p = Pot()
    print p.get_energy(np.array([1,2.]))
    mc_walker = MonteCarloWalker(p, mciter=mciter, events=[mc_record_position_event])

    # initialize the replicas with random positions
    replicas = []
    for i in xrange(nreplicas):
        # choose points uniformly in a circle
        coords = vector_random_uniform_hypersphere(2) * r0 + x0
#         coords = np.random.uniform(-1,3,size=2)
        r = Replica(coords, p.get_energy(coords))
        replicas.append(r)

    ns = NestedSampling(replicas, mc_walker, stepsize=stepsize)
    results = [Result()]
    results[0].replicas = [r.copy() for r in replicas]
    for i in xrange(niter):
        ns.one_iteration()
        new_res = Result()
        new_res.replicas = [r.copy() for r in replicas]
        new_res.starting_replica = ns.starting_replicas[0].copy()
        new_res.new_replica = ns.new_replicas[0].copy()
        path.insert(0, new_res.starting_replica.x)
        new_res.mc_path = path
        results.append(new_res)
        path = []

        if ns.replicas[-1].energy < estop:
            break

#    plt.plot(ns.max_energies)
#    plt.show()

    return ns, results

def ig(x, y, x0, y0, sigx, sigy):
    """inverse gausian"""
    return np.exp(-( ((x-x0)/sigx)**2 + ((y-y0)/sigy)**2 ))

def f1(x, y):
    z = -1. *   ig(x, y, 0, 0, .3, .3)
    z += -0.6 * ig(x, y, 1.5, .5, 1, 1)
    z += -0.2 * ig(x, y, 1, 1, 3, 3)
    return z

def f2(x, y):
#    z =  -1.0 * ig(x, y, 0, -1, 1.3, 0.7)
#    z += -0.3 * ig(x, y, 1, 0.7, 0.45, 0.5)
#    z += -2.0 * ig(x, y, -1, 1, 2, 2)
    z =  -1.2 * ig(x, y, 0, -1, 1.3, 0.7)
    z += -1.5 * ig(x, y, 1, 0.7, 0.45, 0.5)
    z += -1.0 * ig(x, y, -1, 1, 2, 2)
    return z

def styblinski_tang(x, y):
    e1 = x**4 + 16*x**2 + 5*x
    e2 = y**4 + 16*y**2 + 5*y
    return (e1 + e2) / 2

f = f2

def plot3d():
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = np.arange(-1, 3, 0.1)
    Y = np.arange(-1, 3, 0.1)
    X, Y = np.meshgrid(X, Y)
    Z = f(X, Y)
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=mpl.cm.coolwarm,
            linewidth=0, antialiased=False)
    ax.set_zlim(-1.01, 1.01)

    plt.show()

class NSViewer(object):
    def __init__(self, ns, results, xlim=[-1,3], ylim=[-1,3], better_dos=None):
        self.ns = ns
        self.results = results
        self.xmin = xlim[0]
        self.xmax = xlim[1]
        self.ymin = ylim[0]
        self.ymax = ylim[1]
        self.X = np.arange(self.xmin, self.xmax, 0.1)
        self.Y = np.arange(self.ymin, self.ymax, 0.1)
        self.X, self.Y = np.meshgrid(self.X, self.Y)
        self.Z = f(self.X, self.Y)
        self.zmin = np.min(self.Z)
        print "zmin", self.zmin
        self.zmax = 0
        self.vmax = self.Z.max() + .05

        self.Zlinear = np.array(sorted(self.Z.flatten(), reverse=True))
        self.Zlinear = self.Zlinear.reshape([-1,1])
        self.Zlinear_sorted = np.array(sorted(self.Zlinear.reshape(-1)))

        self.fig = plt.figure(figsize=(12,7))
        n = 10

        self.axes1 = plt.subplot2grid((n, 2*n+1), (0, 0), colspan=n, rowspan=n)
        self.axes2 = plt.subplot2grid((n, 2*n+1), (0, n), colspan=1, rowspan=n)
        self.axes3 = plt.subplot2grid((n, 2*n+1), (0, n+1), colspan=n, rowspan=n)

#         self.axes1 = self.fig.add_subplot(1,2,1)
#         self.axes2 = self.fig.add_subplot(1,2,2)

        self.cmap = mpl.cm.gist_heat
        self.cmap = mpl.cm.hot
        self.cmap = mpl.cm.gist_earth
#        self.cmap.set_clim(vmax=1.)

        max_energy_sidebar_indices = [self.sidebar_e_to_index(e)
                                           for e in self.ns.max_energies]
        self.sidebar_line_segments = [[(-0.5, y), (0.5, y)]
                 for y in max_energy_sidebar_indices]

        # copute the density of states
        self.better_dos = better_dos
        self.dos = self.compute_dos(self.ns.max_energies)
        self.get_exact_dos()

    def plot_background(self):
        ax = self.axes1
        ax.clear()
        ax.set_xlim(self.xmin, self.xmax)
        ax.set_ylim(self.ymin, self.ymax)

        im = ax.imshow(self.Z, interpolation='bilinear', origin='lower',
                    cmap=self.cmap, extent=(self.xmin, self.xmax, self.ymin, self.ymax),
                    vmax=self.vmax, aspect="auto")

        self.plot_sidebar_background()

    def plot_contours_old(self, i):
        if i == 0: return
        ax = self.axes1
        ax.contour(self.X, self.Y, self.Z, levels=self.ns.max_energies[:i],
                    vmin=self.zmin, vmax=self.vmax,
                    colors="k", linestyles="solid")
        self.plot_sidebar_contours_old(i)

    def plot_contours_new(self, i):
        ax = self.axes1
        ax.contour(self.X, self.Y, self.Z, levels=self.ns.max_energies[i:(i+1)],
                    vmin=self.zmin, vmax=self.vmax,
                    colors="k", linestyles="solid")
        self.plot_sidebar_contours_new(i)

    def plot_replicas(self, i):
        # plot replicas
        ax = self.axes1
        results = self.results
        xrep = np.array([r.x[0] for r in results[i].replicas])
        yrep = np.array([r.x[1] for r in results[i].replicas])
        ax.scatter(xrep, yrep, c='k', facecolors="none")

        self.plot_sidebar_replicas(i)

    def plot_replica_to_delete(self, i):
        r = self.results[i].replicas[-1]
        self.axes1.scatter(r.x[0], r.x[1], marker='x', s=160, c='r')

    def plot_mc_path(self, i):
        ax = self.axes1
#            r = self.results[i].starting_replica
#            ax.scatter(r.x[0], r.x[1], c='b',
#                       )

        r = self.results[i+1].new_replica
        ax.scatter(r.x[0], r.x[1], c='r')

        path = np.array(self.results[i+1].mc_path)
        ax.plot(path[:,0], path[:,1], '--k', lw=.5)

    def sidebar_e_to_index(self, energy):
        n = self.Zlinear.size
        return n-1-bisect.bisect_left(self.Zlinear_sorted, energy)

    def plot_sidebar_background(self):
        ax = self.axes2
        ax.clear()
        ax.set_yticks([])
        ax.set_xticks([])
        ax.imshow(self.Zlinear, aspect="auto", cmap=self.cmap, vmax=self.vmax)
        ax.set_ylim(self.Zlinear.size, 0)
        ax.set_xlim(-0.5,0.5)

    def plot_sidebar_replicas(self, i):
        ax = self.axes2
        ypos = [self.sidebar_e_to_index(r.energy)
                for r in self.results[i].replicas]
        xpos = [0] * len(ypos)
        ax.scatter(xpos, ypos, c='k', facecolors="none")

    def plot_sidebar_contours_old(self, i):
        # plot line segments
        lc = mpl.collections.LineCollection(self.sidebar_line_segments[:(i)],
                                            colors='k')
        self.axes2.add_collection(lc)

    def plot_sidebar_contours_new(self, i):
        # plot line segments
        lc = mpl.collections.LineCollection(self.sidebar_line_segments[i:(i+1)],
                                            colors='k')
        self.axes2.add_collection(lc)

    def get_exact_dos(self):
        V = len(self.Zlinear_sorted)
        K = float(len(self.ns.replicas))
        n = len(self.ns.max_energies)
        for k in xrange(n):
            vk = 1./(K+1) * 1./(K+1) * (K/(K+1))**k
            ek = self.Zlinear_sorted[int(vk*V)]
        self.better_dos = Result()
        self.better_dos.energies = [ self.Zlinear_sorted[int(V/(K+1) * 1./(K+1) * (K/(K+1))**i)] for i in xrange(n)]
        self.better_dos.dos = self.compute_dos(self.better_dos.energies)

    def compute_dos(self, energies):
        K = float(len(self.ns.replicas))
        dos = [1./(K+1) * (K/(K+1))**i
                    for i, e in enumerate(energies)]
#        if self.better_dos is not None:
#            self.better_dos.dos = np.array(self.better_dos.dos)
#            self.better_dos.dos *= len(self.better_dos.energies) / len(self.dos)
        return dos

    def plot_dos(self, i):
        self.axes3.clear()
        if self.better_dos is not None:
            self.axes3.plot(self.better_dos.energies, np.log(self.better_dos.dos), '--r')
        self.axes3.plot(self.ns.max_energies[:(i+1)], np.log(self.dos[:(i+1)]))

    def pause(self):
        if not hasattr(self, "_pause_skip"):
            self._pause_skip = 0
        if self._pause_skip > 0:
            self._pause_skip -= 1
            plt.pause(.03)
            return
        plt.pause(.05)
        n = raw_input("press any key to continue. enter a number to skip future pauses")
        try:
            n = int(n)
            self._pause_skip = n
        except ValueError:
            return

    def title(self, str):
        if not hasattr(self, "_title"):
            self._title = self.fig.suptitle(str)
        self._title.set_text(str)

    def run(self):
        plt.ion()
        for i in xrange(len(self.results)-1):
            self.plot_background()
            self.plot_contours_old(i)
            if i == 0:
                self.title("the replicas are uniformly distributed in space")
            else:
                self.title("the replicas are uniformly distributed in the space with energy < Emax")
            self.plot_replicas(i)
            self.pause()
            self.plot_contours_new(i)
#            self.pause()
            self.title("the replica with the highest energy is removed.  It's energy becomes the next Emax")
            self.plot_replica_to_delete(i)
            self.pause()
            self.title("a new replica is generated via a MC walk")
            self.plot_mc_path(i)
            self.plot_dos(i)
            print "finishing iteration", i
            self.pause()
        plt.show(block=True)

def main1():
    ns, results = do_nested_sampling(nreplicas=15, niter=100, mciter=20)
    viewer = NSViewer(ns, results)
    viewer.run()

def main_st():
    r0 = 3
    xlim = ylim = [-r0,r0]
    x0 = [0,0]
    ns, results = do_nested_sampling(nreplicas=15, niter=100, mciter=20,
                                     x0=x0, r0=r0)
    viewer = NSViewer(ns, results, xlim=xlim, ylim=ylim)
    viewer.run()

def get_better_dos_2(nreplicas, niter, x0, r0, xlim, ylim, load_pickle=True):
    import pickle
    fname = "f2.better_dos.pkl"
    if load_pickle:
        try:
            better_dos = pickle.load(open(fname, "rb"))
            return better_dos
        except:
            pass
    ns, results = do_nested_sampling(nreplicas=nreplicas, niter=niter, mciter=20,
                                     x0=x0, r0=r0, estop=-1.7)
    viewer = NSViewer(ns, results, xlim=xlim, ylim=ylim)
    better_dos = Result()
    better_dos.dos = viewer.dos
    better_dos.energies = ns.max_energies
    pickle.dump(better_dos, open(fname, "wb"), protocol=pickle.HIGHEST_PROTOCOL)
    return better_dos

def main2():
    xlim = [-4, 3]
    ylim = [-3, 4]
    x0 = [np.mean(xlim), np.mean(ylim)]
    r0 = np.abs(xlim[1] - xlim[0]) / 2
    nreplicas = 15
    niter = 100
    # do a longer NS run to get a better estimate
    better_dos = None
#    if True:
#        better_dos = get_better_dos_2(nreplicas*100, niter*100, x0, r0, xlim, ylim, load_pickle=False)

    ns, results = do_nested_sampling(nreplicas=nreplicas, niter=niter, mciter=20,
                                     x0=x0, r0=r0, estop=-1.7)
    viewer = NSViewer(ns, results, xlim=xlim, ylim=ylim,
                      better_dos=better_dos)
    viewer.run()

if __name__ == "__main__":
    main2()

    <commit_msg>add exact dos calculation<commit_after>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib as mpl
from matplotlib import mlab
import numpy as np
import time
import bisect

from nested_sampling import NestedSampling, MonteCarloWalker, Replica
from nested_sampling.utils.rotations import vector_random_uniform_hypersphere
from scipy.optimize import Result

class Pot(object):
    def get_energy(self, coords):
        assert len(coords) == 2
        return f(coords[::2], coords[1::2])[0]

def do_nested_sampling(nreplicas=10, niter=200, mciter=1000, stepsize=.8, estop=-.9,
                       x0=[1,1], r0=2):
    path = []
    def mc_record_position_event(coords=None, **kwargs):
        if len(path) == 0 or not np.all(path[-1] == coords):
            path.append(coords)

    p = Pot()
    print p.get_energy(np.array([1,2.]))
    mc_walker = MonteCarloWalker(p, mciter=mciter, events=[mc_record_position_event])

    # initialize the replicas with random positions
    replicas = []
    for i in xrange(nreplicas):
        # choose points uniformly in a circle
        coords = vector_random_uniform_hypersphere(2) * r0 + x0
#         coords = np.random.uniform(-1,3,size=2)
        r = Replica(coords, p.get_energy(coords))
        replicas.append(r)

    ns = NestedSampling(replicas, mc_walker, stepsize=stepsize)
    results = [Result()]
    results[0].replicas = [r.copy() for r in replicas]
    for i in xrange(niter):
        ns.one_iteration()
        new_res = Result()
        new_res.replicas = [r.copy() for r in replicas]
        new_res.starting_replica = ns.starting_replicas[0].copy()
        new_res.new_replica = ns.new_replicas[0].copy()
        path.insert(0, new_res.starting_replica.x)
        new_res.mc_path = path
        results.append(new_res)
        path = []

        if ns.replicas[-1].energy < estop:
            break

#    plt.plot(ns.max_energies)
#    plt.show()

    return ns, results

def ig(x, y, x0, y0, sigx, sigy):
    """inverse gausian"""
    return np.exp(-( ((x-x0)/sigx)**2 + ((y-y0)/sigy)**2 ))

def f1(x, y):
    z = -1. *   ig(x, y, 0, 0, .3, .3)
    z += -0.6 * ig(x, y, 1.5, .5, 1, 1)
    z += -0.2 * ig(x, y, 1, 1, 3, 3)
    return z

def f2(x, y):
#    z =  -1.0 * ig(x, y, 0, -1, 1.3, 0.7)
#    z += -0.3 * ig(x, y, 1, 0.7, 0.45, 0.5)
#    z += -2.0 * ig(x, y, -1, 1, 2, 2)
    z =  -1.2 * ig(x, y, 0, -1, 1.3, 0.7)
    z += -1.5 * ig(x, y, 1, 0.7, 0.45, 0.5)
    z += -1.0 * ig(x, y, -1, 1, 2, 2)
    return z

def styblinski_tang(x, y):
    e1 = x**4 + 16*x**2 + 5*x
    e2 = y**4 + 16*y**2 + 5*y
    return (e1 + e2) / 2

f = f2

def plot3d():
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = np.arange(-1, 3, 0.1)
    Y = np.arange(-1, 3, 0.1)
    X, Y = np.meshgrid(X, Y)
    Z = f(X, Y)
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=mpl.cm.coolwarm,
            linewidth=0, antialiased=False)
    ax.set_zlim(-1.01, 1.01)

    plt.show()

class NSViewer(object):
    def __init__(self, ns, results, xlim=[-1,3], ylim=[-1,3], better_dos=None):
        self.ns = ns
        self.results = results
        self.xmin = xlim[0]
        self.xmax = xlim[1]
        self.ymin = ylim[0]
        self.ymax = ylim[1]
        self.X = np.arange(self.xmin, self.xmax, 0.1)
        self.Y = np.arange(self.ymin, self.ymax, 0.1)
        self.X, self.Y = np.meshgrid(self.X, self.Y)
        self.Z = f(self.X, self.Y)
        self.zmin = np.min(self.Z)
        print "zmin", self.zmin
        self.zmax = 0
        self.vmax = self.Z.max() + .05

        self.Zlinear = np.array(sorted(self.Z.flatten(), reverse=True))
        self.Zlinear = self.Zlinear.reshape([-1,1])
        self.Zlinear_sorted = np.array(sorted(self.Zlinear.reshape(-1)))

        self.fig = plt.figure(figsize=(12,7))
        n = 10

        self.axes1 = plt.subplot2grid((n, 2*n+1), (0, 0), colspan=n, rowspan=n)
        self.axes2 = plt.subplot2grid((n, 2*n+1), (0, n), colspan=1, rowspan=n)
        self.axes3 = plt.subplot2grid((n, 2*n+1), (0, n+1), colspan=n, rowspan=n)

#         self.axes1 = self.fig.add_subplot(1,2,1)
#         self.axes2 = self.fig.add_subplot(1,2,2)

        self.cmap = mpl.cm.gist_heat
        self.cmap = mpl.cm.hot
        self.cmap = mpl.cm.gist_earth
#        self.cmap.set_clim(vmax=1.)

        max_energy_sidebar_indices = [self.sidebar_e_to_index(e)
                                           for e in self.ns.max_energies]
        self.sidebar_line_segments = [[(-0.5, y), (0.5, y)]
                 for y in max_energy_sidebar_indices]

        # copute the density of states
        self.better_dos = better_dos
        self.dos = self.compute_dos(self.ns.max_energies)
        self.get_exact_dos()

    def plot_background(self):
        ax = self.axes1
        ax.clear()
        ax.set_xlim(self.xmin, self.xmax)
        ax.set_ylim(self.ymin, self.ymax)

        im = ax.imshow(self.Z, interpolation='bilinear', origin='lower',
                    cmap=self.cmap, extent=(self.xmin, self.xmax, self.ymin, self.ymax),
                    vmax=self.vmax, aspect="auto")

        self.plot_sidebar_background()

    def plot_contours_old(self, i):
        if i == 0: return
        ax = self.axes1
        ax.contour(self.X, self.Y, self.Z, levels=self.ns.max_energies[:i],
                    vmin=self.zmin, vmax=self.vmax,
                    colors="k", linestyles="solid")
        self.plot_sidebar_contours_old(i)

    def plot_contours_new(self, i):
        ax = self.axes1
        ax.contour(self.X, self.Y, self.Z, levels=self.ns.max_energies[i:(i+1)],
                    vmin=self.zmin, vmax=self.vmax,
                    colors="k", linestyles="solid")
        self.plot_sidebar_contours_new(i)

    def plot_replicas(self, i):
        # plot replicas
        ax = self.axes1
        results = self.results
        xrep = np.array([r.x[0] for r in results[i].replicas])
        yrep = np.array([r.x[1] for r in results[i].replicas])
        ax.scatter(xrep, yrep, c='k', facecolors="none")

        self.plot_sidebar_replicas(i)

    def plot_replica_to_delete(self, i):
        r = self.results[i].replicas[-1]
        self.axes1.scatter(r.x[0], r.x[1], marker='x', s=160, c='r')

    def plot_mc_path(self, i):
        ax = self.axes1
#            r = self.results[i].starting_replica
#            ax.scatter(r.x[0], r.x[1], c='b',
#                       )

        r = self.results[i+1].new_replica
        ax.scatter(r.x[0], r.x[1], c='r')

        path = np.array(self.results[i+1].mc_path)
        ax.plot(path[:,0], path[:,1], '--k', lw=.5)

    def sidebar_e_to_index(self, energy):
        n = self.Zlinear.size
        return n-1-bisect.bisect_left(self.Zlinear_sorted, energy)

    def plot_sidebar_background(self):
        ax = self.axes2
        ax.clear()
        ax.set_yticks([])
        ax.set_xticks([])
        ax.imshow(self.Zlinear, aspect="auto", cmap=self.cmap, vmax=self.vmax)
        ax.set_ylim(self.Zlinear.size, 0)
        ax.set_xlim(-0.5,0.5)

    def plot_sidebar_replicas(self, i):
        ax = self.axes2
        ypos = [self.sidebar_e_to_index(r.energy)
                for r in self.results[i].replicas]
        xpos = [0] * len(ypos)
        ax.scatter(xpos, ypos, c='k', facecolors="none")

    def plot_sidebar_contours_old(self, i):
        # plot line segments
        lc = mpl.collections.LineCollection(self.sidebar_line_segments[:(i)],
                                            colors='k')
        self.axes2.add_collection(lc)

    def plot_sidebar_contours_new(self, i):
        # plot line segments
        lc = mpl.collections.LineCollection(self.sidebar_line_segments[i:(i+1)],
                                            colors='k')
        self.axes2.add_collection(lc)

    def get_exact_dos(self):
        N = len(self.Zlinear_sorted)
        V = N-1-self.sidebar_e_to_index(self.ns.max_energies[0])
        print self.ns.max_energies[0], self.Zlinear_sorted[V]
        K = float(len(self.ns.replicas))
        n = len(self.ns.max_energies)
        self.better_dos = Result()
        self.better_dos.energies = [ self.Zlinear_sorted[np.round(V * (K/(K+1))**i)] for i in xrange(n)]
        self.better_dos.dos = self.compute_dos(self.better_dos.energies)

    def compute_dos(self, energies):
        K = float(len(self.ns.replicas))
        dos = [1./(K+1) * (K/(K+1))**i
                    for i, e in enumerate(energies)]
#        if self.better_dos is not None:
#            self.better_dos.dos = np.array(self.better_dos.dos)
#            self.better_dos.dos *= len(self.better_dos.energies) / len(self.dos)
        return dos

    def plot_dos(self, i):
        self.axes3.clear()
        if self.better_dos is not None:
            self.axes3.plot(self.better_dos.energies, np.log(self.better_dos.dos), '--r')
        self.axes3.plot(self.ns.max_energies[:(i+1)], np.log(self.dos[:(i+1)]))

    def pause(self):
        if not hasattr(self, "_pause_skip"):
            self._pause_skip = 0
        if self._pause_skip > 0:
            self._pause_skip -= 1
            plt.pause(.03)
            return
        plt.pause(.05)
        n = raw_input("press any key to continue. enter a number to skip future pauses")
        try:
            n = int(n)
            self._pause_skip = n
        except ValueError:
            return

    def title(self, str):
        if not hasattr(self, "_title"):
            self._title = self.fig.suptitle(str)
        self._title.set_text(str)

    def run(self):
        plt.ion()
        for i in xrange(len(self.results)-1):
            self.plot_background()
            self.plot_contours_old(i)
            if i == 0:
                self.title("the replicas are uniformly distributed in space")
            else:
                self.title("the replicas are uniformly distributed in the space with energy < Emax")
            self.plot_replicas(i)
            self.pause()
            self.plot_contours_new(i)
#            self.pause()
            self.title("the replica with the highest energy is removed.  It's energy becomes the next Emax")
            self.plot_replica_to_delete(i)
            self.pause()
            self.title("a new replica is generated via a MC walk")
            self.plot_mc_path(i)
            self.plot_dos(i)
            print "finishing iteration", i
            self.pause()
        plt.show(block=True)

def main1():
    ns, results = do_nested_sampling(nreplicas=15, niter=100, mciter=20)
    viewer = NSViewer(ns, results)
    viewer.run()

def main_st():
    r0 = 3
    xlim = ylim = [-r0,r0]
    x0 = [0,0]
    ns, results = do_nested_sampling(nreplicas=15, niter=100, mciter=20,
                                     x0=x0, r0=r0)
    viewer = NSViewer(ns, results, xlim=xlim, ylim=ylim)
    viewer.run()

def main2():
    xlim = [-4, 3]
    ylim = [-3, 4]
    x0 = [np.mean(xlim), np.mean(ylim)]
    r0 = np.abs(xlim[1] - xlim[0]) / 2
    nreplicas = 15
    niter = 100

    ns, results = do_nested_sampling(nreplicas=nreplicas, niter=niter, mciter=20,
                                     x0=x0, r0=r0, estop=-1.7)
    viewer = NSViewer(ns, results, xlim=xlim, ylim=ylim)
    viewer.run()

if __name__ == "__main__":
    main2()

    <|endoftext|>


<commit_before># -*- coding: utf-8 -*-

__LIBRARY_VERSION__ = '1.0.1'
__SII_VERSION__ = '1.0'
<commit_msg>Bump to 1.1.0<commit_after># -*- coding: utf-8 -*-

__LIBRARY_VERSION__ = '1.1.0'
__SII_VERSION__ = '1.0'
<|endoftext|>


<commit_before>#Author: L. Tibaldo, ltibaldo@slac.stanford.edu

from SourceModel import SourceModel
import numpy as np

class ExtendedSource(SourceModel):
    def __init__(self,name,spatialModel,spectralModel):

        self.name                 = name
        self.functionName         = "Extended source"

        if(not callable(spatialModel)):

            raise RuntimeError("The provided spatial model must be callable")

        else:

            self.spatialModel      = spatialModel

        if(not callable(spectralModel)):

            raise RuntimeError("The provided spectral model must be callable")

        else:

            self.spectralModel      = spectralModel

        pass
    pass

    def getFlux(self,energies):
        return self.spatialModel.integratedFlux(energies)*self.spectralModel(energies)

    def getBrightness(self,RA,Dec,energies):
        return self.spatialModel(RA,Dec,energies)*self.spectralModel(energies)

pass<commit_msg>Extended source must import the parameters from its spatial and spectral model<commit_after>#Author: L. Tibaldo, ltibaldo@slac.stanford.edu

from SourceModel import SourceModel
import numpy as np

import collections

class ExtendedSource(SourceModel):
    def __init__(self,name,spatialModel,spectralModel):

        self.name                 = name
        self.functionName         = "Extended source"

        if(not callable(spatialModel)):

            raise RuntimeError("The provided spatial model must be callable")

        else:

            self.spatialModel      = spatialModel

        if(not callable(spectralModel)):

            raise RuntimeError("The provided spectral model must be callable")

        else:

            self.spectralModel      = spectralModel

        pass

        self.parameters           = collections.OrderedDict()

        for k,v in self.spatialModel.parameters.iteritems():

            self.parameters[ k ] = v

        for k,v in self.spectralModel.parameters.iteritems():

            self.parameters[ k ] = v

        self.formula = self.spatialModel.formula

    pass

    def getFlux(self,energies):
        return self.spatialModel.integratedFlux(energies)*self.spectralModel(energies)

    def getBrightness(self,RA,Dec,energies):
        return self.spatialModel(RA,Dec,energies)*self.spectralModel(energies)

    def getBoundaries(self):

        return self.spatialModel.getBoundaries()

pass
<|endoftext|>


<commit_before>def transform_scalars(dataset):
    """This filter computes a binary threshold on the data set and
    stores the result in a label map in the data set."""

    returnValue = None

    # Try imports to make sure we have everything that is needed
    try:
        import itk
        import vtk
        from tomviz import utils
    except Exception as exc:
        print("Could not import necessary module(s)")
        print(exc)

    # Set some filter parameters
    #----USER SPECIFIED VARIABLES-----#
    ###LOWERTHRESHOLD### # Specify lower threshold
    ###UPPERTHRESHOLD### # Specify upper threshold

    # Add a try/except around the ITK portion. ITK exceptions are
    # passed up to the Python layer, so we can at least report what
    # went wrong with the script, e.g,, unsupported image type.
    try:
        # Get the ITK image
        itk_image = utils.convert_vtk_to_itk_image(dataset)
        itk_input_image_type = type(itk_image)

        # We change the output type to unsigned char 3D
        # (itk.Image.UC3D) to save memory in the output label map
        # representation.
        itk_output_image_type = itk.Image.UC3

        # ITK's BinaryThresholdImageFilter does the hard work
        threshold_filter = itk.BinaryThresholdImageFilter[itk_input_image_type,itk_output_image_type].New()
        threshold_filter.SetLowerThreshold(lower_threshold)
        threshold_filter.SetUpperThreshold(upper_threshold)
        threshold_filter.SetInsideValue(1)
        threshold_filter.SetOutsideValue(0)
        threshold_filter.SetInput(itk_image)
        threshold_filter.Update()

        #utils.add_vtk_array_from_itk_image(threshold_filter.GetOutput(), dataset, 'LabelMap')

        # Set the output as a new child data object of the current data set
        itk_image_data = threshold_filter.GetOutput()
        label_buffer = itk.PyBuffer[itk_output_image_type].GetArrayFromImage(itk_image_data)
        label_map_data_set = vtk.vtkImageData()
        label_map_data_set.CopyStructure(dataset)

        utils.set_label_map(label_map_data_set, label_buffer)
        returnValue = \
          {
            "thresholded_segmentation" : label_map_data_set
          }

    except Exception as exc:
        print("Exception encountered while running BinaryThreshold");
        print(exc);

    return returnValue
<commit_msg>Remove commented out code<commit_after>def transform_scalars(dataset):
    """This filter computes a binary threshold on the data set and
    stores the result in a label map in the data set."""

    returnValue = None

    # Try imports to make sure we have everything that is needed
    try:
        import itk
        import vtk
        from tomviz import utils
    except Exception as exc:
        print("Could not import necessary module(s)")
        print(exc)

    # Set some filter parameters
    #----USER SPECIFIED VARIABLES-----#
    ###LOWERTHRESHOLD### # Specify lower threshold
    ###UPPERTHRESHOLD### # Specify upper threshold

    # Add a try/except around the ITK portion. ITK exceptions are
    # passed up to the Python layer, so we can at least report what
    # went wrong with the script, e.g,, unsupported image type.
    try:
        # Get the ITK image
        itk_image = utils.convert_vtk_to_itk_image(dataset)
        itk_input_image_type = type(itk_image)

        # We change the output type to unsigned char 3D
        # (itk.Image.UC3D) to save memory in the output label map
        # representation.
        itk_output_image_type = itk.Image.UC3

        # ITK's BinaryThresholdImageFilter does the hard work
        threshold_filter = itk.BinaryThresholdImageFilter[itk_input_image_type,itk_output_image_type].New()
        threshold_filter.SetLowerThreshold(lower_threshold)
        threshold_filter.SetUpperThreshold(upper_threshold)
        threshold_filter.SetInsideValue(1)
        threshold_filter.SetOutsideValue(0)
        threshold_filter.SetInput(itk_image)
        threshold_filter.Update()

        # Set the output as a new child data object of the current data set
        itk_image_data = threshold_filter.GetOutput()
        label_buffer = itk.PyBuffer[itk_output_image_type].GetArrayFromImage(itk_image_data)
        label_map_data_set = vtk.vtkImageData()
        label_map_data_set.CopyStructure(dataset)

        utils.set_label_map(label_map_data_set, label_buffer)
        returnValue = \
          {
            "thresholded_segmentation" : label_map_data_set
          }

    except Exception as exc:
        print("Exception encountered while running BinaryThreshold");
        print(exc);

    return returnValue
<|endoftext|>


<commit_before>__author__ = 'jeff'
import os
import re
from .renderer import ALIASES

class Parser(object):
    def __init__(self, template_dir, dest_dir, args):
        self.template_dir = template_dir
        self.dest_dir = dest_dir
        self.args = args

    def resolve_key(self, match):
        """
        Resolve the matched key and process it's value based on the supplied renderer
        :param match:
        :return:
        :rtype: str
        """
        args = match.group(1).split('|')
        key = args[0]
        processor_funcs = args[1:]

        value = self.args.get(key,'')
        for func_name in processor_funcs:
            # get renderer func or use to string func
            value = ALIASES.get(func_name,str)(value)

        return value

    def _parse_line(self, line):
        pattern = r'{{(.*?)}}'
        line = re.sub(pattern,self.resolve_key, line)

        return line

    def _parse_path(self,path):
        return self._parse_line(path)

    def _parse_file(self,fp):
        new_data = []
        with open(fp, 'r') as f:
            data = f.readlines()
            for line in data:
                new_data.append(self._parse_line(line))

        return "".join(new_data)

    def parse(self):
        dir_content = []
        for cur_path, dirs, files in os.walk(self.template_dir):

            new_path = re.sub(self.template_dir, self.dest_dir, cur_path)

            path = self._parse_path(new_path)
            file_paths = [self._parse_path(fp) for fp in files]
            file_contents = [self._parse_file(os.path.join(cur_path,fp)) for fp in files]

            dir_content.append((path, file_paths, file_contents))

        return dir_content
<commit_msg>parser fix for windows paths<commit_after>__author__ = 'jeff'
import os
import re
from .renderer import ALIASES

class Parser(object):
    def __init__(self, template_dir, dest_dir, args):
        self.template_dir = template_dir
        self.dest_dir = dest_dir
        self.args = args

    def resolve_key(self, match):
        """
        Resolve the matched key and process it's value based on the supplied renderer
        :param match:
        :return:
        :rtype: str
        """
        args = match.group(1).split('|')
        key = args[0]
        processor_funcs = args[1:]

        value = self.args.get(key,'')
        for func_name in processor_funcs:
            # get renderer func or use to string func
            value = ALIASES.get(func_name,str)(value)

        return value

    def _parse_line(self, line):
        pattern = r'{{(.*?)}}'
        line = re.sub(pattern,self.resolve_key, line)

        return line

    def _parse_path(self,path):
        return self._parse_line(path)

    def _parse_file(self,fp):
        new_data = []
        with open(fp, 'r') as f:
            data = f.readlines()
            for line in data:
                new_data.append(self._parse_line(line))

        return "".join(new_data)

    def parse(self):
        dir_content = []
        for cur_path, dirs, files in os.walk(self.template_dir):

            new_path =  cur_path.replace(self.template_dir, self.dest_dir)

            path = self._parse_path(new_path)
            file_paths = [self._parse_path(fp) for fp in files]
            file_contents = [self._parse_file(os.path.join(cur_path,fp)) for fp in files]

            dir_content.append((path, file_paths, file_contents))

        return dir_content
<|endoftext|>


<commit_before># encoding: cinje

: log = __import__('logging').getLogger(__name__)

: try
	: from pudb import post_mortem
: except ImportError
	: post_mortem = lambda: False
: end

: from web.theme.bootstrap.base import page

: def render_page_content context, page

: width = 12

: for block in page.content
	: size = block.properties.get('width', 12)
	: width -= size

	: if width < 0
		: width = 12 - size

	: end

	: try
	: use block.__html_stream__ context
	: except
	: log.exception("Error processing block: " + repr(block))
	An unknown error occurred.
	: end
: end

: end

: def render_page context, asset
: using page title=str(asset), styles=['/public/css/site.css'], scripts=['//cdn.ckeditor.com/4.5.4/full/ckeditor.js', '/public/js/site.js']

: flush

: use asset.__html_stream__ context

: flush

				Site Structure

				Page

				Block

				Content

				Site Settings

					Site Structure

				<menu class="list-unstyled wc-cfg-flist">
					: from web.component.asset.model import Asset
					: for child in Asset.objects.only('id').get(path='/careers.illicohodes.com').children

								${child.title['en']}

							: if child.children.count()
							<menu class="list-unstyled">
							: for descendant in child.children

									${descendant.title['en']}

								: if descendant.children.count()
								<menu class="list-unstyled">
								: for d2 in descendant.children

										${d2.title['en']}

								: end
								</menu>
								: end
							: end
							</menu>
							: end

					: end
				</menu>

		: flush

					General

Name

${asset.name}

Title

${asset.title['en']}

Description

					: if asset.description.get('en', None)

${asset.title['en']}

					: else

None entered.

					: end

Tags

					: if asset.tags

${','.join(asset.tags)}

					: else

None entered.

					: end

Created

${asset.created.isoformat()}

Modified

${asset.modified.isoformat()}

					Block Structure

				<menu class="list-unstyled wc-cfg-flist">
					: for child in asset.content

							${str(child)}

					: end
			</menu>

		: flush

		: if asset.content

					Text Block

Unique Identifier

<tt>${asset.content[0].id}</tt>

Format Engine

HTML

					Cascading Style Sheets

Unique Identifier

None entered.

Classes

<tt>${asset.content[0].properties.get('cls', "None entered.")}</tt>

		: end

		: flush

					Important Notices

						You will be running into yor mail quota in about a week.  Learn more about mail quotas.

					Domains

Buy, connect, and manage domains associated with this site.  Learn more about domains.

 Get a Domain

 Connect a Third-Party Domain

Third-Party Domains

						careers.alstom.com

							Primary
							Never Expires

Built-In Domain

						illico-test.webcore.io

							Development
							Never Expires

					E-Mail

Connect and manage mail servers.  Learn more about mail.

 Connect a Third-Party Service

Built-In Mail Service

						illico-test.webcore.io

							Primary
							Sent 18,368 out of 30,000.

						# :: include(asset.theme + 'widget.progress', current=[(30, 'success'), (20, 'warning')], minimum=0, maximum=100)

					Import / Export

 Import

 Export

Heading 2

: end
<commit_msg>Refactored.<commit_after># encoding: cinje

: import traceback

: log = __import__('logging').getLogger(__name__)

: def render_block context, page, block

	: try
		: use block.__html_stream__ context
	: except
		: log.exception("Error processing block: " + repr(block), extra=dict(block=block.id, page=page.id))
		: if __debug__

${traceback.format_exc()}

		: else
			An unknown error occurred.
		: end
	: end
: end

: def render_page_content context, page

	# Load page content if not already loaded.
	: content = page.content if page.content else page.__class__.objects.scalar('content').get(id=page.id)

	: columns = False
	: width = 12

	: for block in page.content
		: size = block.properties.get('width', 12)
		: width -= size

		: if width and not columns
			: columns = True

		: end

		: use render_block context, page, block

		: if width <= 0
			: width = 12
			: if columns
				: columns = False

			: end
		: end
	: end

	: if columns

	: end

	: end
: end

: def render_page context, asset

# First, we work out what the title should look like.
: title = [str(asset), str(context.croot)]
: if context.croot.properties.get('direction', 'rtl') == 'ltr'
	: title.reverse()
: end
: title = context.croot.properties.get('separator', ' - ').join(title)
: title = title.upper() if context.croot.properties.get('titlecase', 'normal') == 'upper' else title

: using context.theme title=title, styles=['/public/css/site.css'], scripts=['/public/js/site.js']

: flush

: for chunk in asset.__html_stream__(context)
	: yield chunk
: end

: end

: end
<|endoftext|>


<commit_before># Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

"""Helpers for referring to React Native open source code.

This lets us build React Native:
 - At Facebook by running buck from the root of the fb repo
 - Outside of Facebook by running buck in the root of the git repo
"""
# @lint-ignore-every BUCKRESTRICTEDSYNTAX

_DEBUG_PREPROCESSOR_FLAGS = []

_APPLE_COMPILER_FLAGS = []

def get_debug_preprocessor_flags():
    return _DEBUG_PREPROCESSOR_FLAGS

def get_apple_compiler_flags():
    return _APPLE_COMPILER_FLAGS

IS_OSS_BUILD = True

GLOG_DEP = "//ReactAndroid/build/third-party-ndk/glog:glog"

INSPECTOR_FLAGS = []

APPLE_JSC_DEPS = []

ANDROID_JSC_INTERNAL_DEPS = [
    "//native/third-party/jsc:jsc",
    "//native/third-party/jsc:jsc_legacy_profiler",
]

ANDROID_JSC_DEPS = ANDROID_JSC_INTERNAL_DEPS

ANDROID = "Android"

APPLE = ""

YOGA_TARGET = "//ReactAndroid/src/main/java/com/facebook:yoga"

YOGA_CXX_TARGET = "//ReactCommon/yoga:yoga"

FBGLOGINIT_TARGET = "//ReactAndroid/src/main/jni/first-party/fbgloginit:fbgloginit"

FBJNI_TARGET = "//ReactAndroid/src/main/jni/first-party/fb:jni"

JNI_TARGET = "//ReactAndroid/src/main/jni/first-party/jni-hack:jni-hack"

KEYSTORE_TARGET = "//keystores:debug"

def get_apple_inspector_flags():
    return []

def get_android_inspector_flags():
    return []

# Building is not supported in OSS right now
def rn_xplat_cxx_library(name, **kwargs):
    new_kwargs = {
        k: v
        for k, v in kwargs.items()
        if k.startswith("exported_")
    }

    native.cxx_library(
        name = name,
        visibility = kwargs.get("visibility", []),
        **new_kwargs
    )

# Example: react_native_target('java/com/facebook/react/common:common')
def react_native_target(path):
    return "//ReactAndroid/src/main/" + path

# Example: react_native_xplat_target('bridge:bridge')
def react_native_xplat_target(path):
    return "//ReactCommon/" + path

def react_native_xplat_target_apple(path):
    return react_native_xplat_target(path) + "Apple"

# Example: react_native_tests_target('java/com/facebook/react/modules:modules')
def react_native_tests_target(path):
    return "//ReactAndroid/src/test/" + path

# Example: react_native_integration_tests_target('java/com/facebook/react/testing:testing')
def react_native_integration_tests_target(path):
    return "//ReactAndroid/src/androidTest/" + path

# Helpers for referring to non-RN code from RN OSS code.
# Example: react_native_dep('java/com/facebook/systrace:systrace')
def react_native_dep(path):
    return "//ReactAndroid/src/main/" + path

# Example: react_native_xplat_dep('java/com/facebook/systrace:systrace')
def react_native_xplat_dep(path):
    return "//ReactCommon/" + path

def rn_debug_flags():
    return []

def rn_feature_flags():
    return []

# React property preprocessor
def rn_android_library(name, deps = [], plugins = [], *args, **kwargs):
    if react_native_target(
        "java/com/facebook/react/uimanager/annotations:annotations",
    ) in deps and name != "processing":
        react_property_plugins = [
            react_native_target(
                "java/com/facebook/react/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_property_plugins))

    if react_native_target(
        "java/com/facebook/react/module/annotations:annotations",
    ) in deps and name != "processing":
        react_module_plugins = [
            react_native_target(
                "java/com/facebook/react/module/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_module_plugins))

    is_androidx = kwargs.pop("is_androidx", False)
    provided_deps = kwargs.pop("provided_deps", [])
    appcompat = react_native_dep("third-party/android/support/v7/appcompat-orig:appcompat")
    support_v4 = react_native_dep("third-party/android/support/v4:lib-support-v4")

    if is_androidx and (appcompat in deps or appcompat in provided_deps):
        # add androidx target to provided_deps
        pass
        # provided_deps.append(
        #     react_native_dep(
        #         ""
        #     )
        # )

    if is_androidx and (support_v4 in deps or support_v4 in provided_deps):
        # add androidx target to provided_deps
        pass
        # provided_deps.append(
        #     react_native_dep(
        #         ""
        #     )
        # )

    native.android_library(name = name, deps = deps, plugins = plugins, provided_deps = provided_deps, *args, **kwargs)

def rn_android_binary(*args, **kwargs):
    native.android_binary(*args, **kwargs)

def rn_android_build_config(*args, **kwargs):
    native.android_build_config(*args, **kwargs)

def rn_android_resource(*args, **kwargs):
    native.android_resource(*args, **kwargs)

def rn_android_prebuilt_aar(*args, **kwargs):
    native.android_prebuilt_aar(*args, **kwargs)

def rn_apple_library(*args, **kwargs):
    kwargs.setdefault("link_whole", True)
    kwargs.setdefault("enable_exceptions", True)
    native.apple_library(*args, **kwargs)

def rn_plugin_apple_library(**kwargs):
    kwargs.setdefault("link_whole", True)

    # This just an alias to apple_library for now.
    native.apple_library(**kwargs)

def rn_java_library(*args, **kwargs):
    native.java_library(*args, **kwargs)

def rn_java_annotation_processor(*args, **kwargs):
    native.java_annotation_processor(*args, **kwargs)

def rn_prebuilt_native_library(*args, **kwargs):
    native.prebuilt_native_library(*args, **kwargs)

def rn_prebuilt_jar(*args, **kwargs):
    native.prebuilt_jar(*args, **kwargs)

def rn_genrule(*args, **kwargs):
    native.genrule(*args, **kwargs)

def rn_robolectric_test(name, srcs, vm_args = None, *args, **kwargs):
    vm_args = vm_args or []

    is_androidx = kwargs.pop("is_androidx", False)

    extra_vm_args = [
        "-XX:+UseConcMarkSweepGC",  # required by -XX:+CMSClassUnloadingEnabled
        "-XX:+CMSClassUnloadingEnabled",
        "-XX:ReservedCodeCacheSize=150M",
        "-Drobolectric.dependency.dir=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric3/robolectric",
        "-Dlibraries=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric3/robolectric/*.jar",
        "-Drobolectric.logging.enabled=true",
        "-XX:MaxPermSize=620m",
        "-Drobolectric.offline=true",
    ]
    if native.read_config("user", "use_dev_shm"):
        extra_vm_args.append("-Djava.io.tmpdir=/dev/shm")

    # RN tests use  Powermock, which means they get their own ClassLoaders.
    # Because the yoga native library (or any native library) can only be loaded into one
    # ClassLoader at a time, we need to run each in its own process, hence fork_mode = 'per_test'.
    native.robolectric_test(
        name = name,
        use_cxx_libraries = True,
        cxx_library_whitelist = [
            "//ReactCommon/yoga:yoga",
            "//ReactAndroid/src/main/jni/first-party/yogajni:jni",
        ],
        fork_mode = "per_test",
        srcs = srcs,
        vm_args = vm_args + extra_vm_args,
        *args,
        **kwargs
    )

def cxx_library(allow_jni_merging = None, **kwargs):
    _ignore = allow_jni_merging
    args = {
        k: v
        for k, v in kwargs.items()
        if not (k.startswith("fbandroid_") or k.startswith("fbobjc_"))
    }
    native.cxx_library(**args)

def _paths_join(path, *others):
    """Joins one or more path components."""
    result = path

    for p in others:
        if p.startswith("/"):  # absolute
            result = p
        elif not result or result.endswith("/"):
            result += p
        else:
            result += "/" + p

    return result

def subdir_glob(glob_specs, exclude = None, prefix = ""):
    """Returns a dict of sub-directory relative paths to full paths.

    The subdir_glob() function is useful for defining header maps for C/C++
    libraries which should be relative the given sub-directory.
    Given a list of tuples, the form of (relative-sub-directory, glob-pattern),
    it returns a dict of sub-directory relative paths to full paths.

    Please refer to native.glob() for explanations and examples of the pattern.

    Args:
      glob_specs: The array of tuples in form of
        (relative-sub-directory, glob-pattern inside relative-sub-directory).
        type: List[Tuple[str, str]]
      exclude: A list of patterns to identify files that should be removed
        from the set specified by the first argument. Defaults to [].
        type: Optional[List[str]]
      prefix: If is not None, prepends it to each key in the dictionary.
        Defaults to None.
        type: Optional[str]

    Returns:
      A dict of sub-directory relative paths to full paths.
    """
    if exclude == None:
        exclude = []

    results = []

    for dirpath, glob_pattern in glob_specs:
        results.append(
            _single_subdir_glob(dirpath, glob_pattern, exclude, prefix),
        )

    return _merge_maps(*results)

def _merge_maps(*file_maps):
    result = {}
    for file_map in file_maps:
        for key in file_map:
            if key in result and result[key] != file_map[key]:
                fail(
                    "Conflicting files in file search paths. " +
                    "\"%s\" maps to both \"%s\" and \"%s\"." %
                    (key, result[key], file_map[key]),
                )

            result[key] = file_map[key]

    return result

def _single_subdir_glob(dirpath, glob_pattern, exclude = None, prefix = None):
    if exclude == None:
        exclude = []
    results = {}
    files = native.glob([_paths_join(dirpath, glob_pattern)], exclude = exclude)
    for f in files:
        if dirpath:
            key = f[len(dirpath) + 1:]
        else:
            key = f
        if prefix:
            key = _paths_join(prefix, key)
        results[key] = f

    return results

def fb_apple_library(*args, **kwargs):
    native.apple_library(*args, **kwargs)

def oss_cxx_library(**kwargs):
    cxx_library(**kwargs)

def jni_instrumentation_test_lib(**_kwargs):
    """A noop stub for OSS build."""
    pass

def fb_xplat_cxx_test(**_kwargs):
    """A noop stub for OSS build."""
    pass

# iOS Plugin support.
def react_module_plugin_providers():
    # Noop for now
    return []
<commit_msg>fix Android CI (#25655)<commit_after># Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

"""Helpers for referring to React Native open source code.

This lets us build React Native:
 - At Facebook by running buck from the root of the fb repo
 - Outside of Facebook by running buck in the root of the git repo
"""
# @lint-ignore-every BUCKRESTRICTEDSYNTAX

_DEBUG_PREPROCESSOR_FLAGS = []

_APPLE_COMPILER_FLAGS = []

def get_debug_preprocessor_flags():
    return _DEBUG_PREPROCESSOR_FLAGS

def get_apple_compiler_flags():
    return _APPLE_COMPILER_FLAGS

IS_OSS_BUILD = True

GLOG_DEP = "//ReactAndroid/build/third-party-ndk/glog:glog"

INSPECTOR_FLAGS = []

APPLE_JSC_DEPS = []

ANDROID_JSC_INTERNAL_DEPS = [
    "//native/third-party/jsc:jsc",
    "//native/third-party/jsc:jsc_legacy_profiler",
]

ANDROID_JSC_DEPS = ANDROID_JSC_INTERNAL_DEPS

ANDROID = "Android"

APPLE = ""

YOGA_TARGET = "//ReactAndroid/src/main/java/com/facebook:yoga"

YOGA_CXX_TARGET = "//ReactCommon/yoga:yoga"

FBGLOGINIT_TARGET = "//ReactAndroid/src/main/jni/first-party/fbgloginit:fbgloginit"

FBJNI_TARGET = "//ReactAndroid/src/main/jni/first-party/fb:jni"

JNI_TARGET = "//ReactAndroid/src/main/jni/first-party/jni-hack:jni-hack"

KEYSTORE_TARGET = "//keystores:debug"

def get_apple_inspector_flags():
    return []

def get_android_inspector_flags():
    return []

# Building is not supported in OSS right now
def rn_xplat_cxx_library(name, **kwargs):
    new_kwargs = {
        k: v
        for k, v in kwargs.items()
        if k.startswith("exported_")
    }

    native.cxx_library(
        name = name,
        visibility = kwargs.get("visibility", []),
        **new_kwargs
    )

# Example: react_native_target('java/com/facebook/react/common:common')
def react_native_target(path):
    return "//ReactAndroid/src/main/" + path

# Example: react_native_xplat_target('bridge:bridge')
def react_native_xplat_target(path):
    return "//ReactCommon/" + path

def react_native_xplat_target_apple(path):
    return react_native_xplat_target(path) + "Apple"

# Example: react_native_tests_target('java/com/facebook/react/modules:modules')
def react_native_tests_target(path):
    return "//ReactAndroid/src/test/" + path

# Example: react_native_integration_tests_target('java/com/facebook/react/testing:testing')
def react_native_integration_tests_target(path):
    return "//ReactAndroid/src/androidTest/" + path

# Helpers for referring to non-RN code from RN OSS code.
# Example: react_native_dep('java/com/facebook/systrace:systrace')
def react_native_dep(path):
    return "//ReactAndroid/src/main/" + path

# Example: react_native_xplat_dep('java/com/facebook/systrace:systrace')
def react_native_xplat_dep(path):
    return "//ReactCommon/" + path

def rn_debug_flags():
    return []

def rn_feature_flags():
    return []

# React property preprocessor
def rn_android_library(name, deps = [], plugins = [], *args, **kwargs):
    if react_native_target(
        "java/com/facebook/react/uimanager/annotations:annotations",
    ) in deps and name != "processing":
        react_property_plugins = [
            react_native_target(
                "java/com/facebook/react/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_property_plugins))

    if react_native_target(
        "java/com/facebook/react/module/annotations:annotations",
    ) in deps and name != "processing":
        react_module_plugins = [
            react_native_target(
                "java/com/facebook/react/module/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_module_plugins))

    is_androidx = kwargs.pop("is_androidx", False)
    provided_deps = kwargs.pop("provided_deps", [])
    appcompat = react_native_dep("third-party/android/support/v7/appcompat-orig:appcompat")
    support_v4 = react_native_dep("third-party/android/support/v4:lib-support-v4")

    if is_androidx and (appcompat in deps or appcompat in provided_deps):
        # add androidx target to provided_deps
        pass
        # provided_deps.append(
        #     react_native_dep(
        #         ""
        #     )
        # )

    if is_androidx and (support_v4 in deps or support_v4 in provided_deps):
        # add androidx target to provided_deps
        pass
        # provided_deps.append(
        #     react_native_dep(
        #         ""
        #     )
        # )

    native.android_library(name = name, deps = deps, plugins = plugins, provided_deps = provided_deps, *args, **kwargs)

def rn_android_binary(*args, **kwargs):
    native.android_binary(*args, **kwargs)

def rn_android_build_config(*args, **kwargs):
    native.android_build_config(*args, **kwargs)

def rn_android_resource(*args, **kwargs):
    native.android_resource(*args, **kwargs)

def rn_android_prebuilt_aar(*args, **kwargs):
    native.android_prebuilt_aar(*args, **kwargs)

def rn_apple_library(*args, **kwargs):
    kwargs.setdefault("link_whole", True)
    kwargs.setdefault("enable_exceptions", True)
    native.apple_library(*args, **kwargs)

def rn_plugin_apple_library(**kwargs):
    kwargs.setdefault("link_whole", True)

    # This just an alias to apple_library for now.
    native.apple_library(**kwargs)

def rn_java_library(*args, **kwargs):
    is_androidx = kwargs.pop("is_androidx", False)
    native.java_library(*args, **kwargs)

def rn_java_annotation_processor(*args, **kwargs):
    native.java_annotation_processor(*args, **kwargs)

def rn_prebuilt_native_library(*args, **kwargs):
    native.prebuilt_native_library(*args, **kwargs)

def rn_prebuilt_jar(*args, **kwargs):
    native.prebuilt_jar(*args, **kwargs)

def rn_genrule(*args, **kwargs):
    native.genrule(*args, **kwargs)

def rn_robolectric_test(name, srcs, vm_args = None, *args, **kwargs):
    vm_args = vm_args or []

    is_androidx = kwargs.pop("is_androidx", False)

    extra_vm_args = [
        "-XX:+UseConcMarkSweepGC",  # required by -XX:+CMSClassUnloadingEnabled
        "-XX:+CMSClassUnloadingEnabled",
        "-XX:ReservedCodeCacheSize=150M",
        "-Drobolectric.dependency.dir=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric3/robolectric",
        "-Dlibraries=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric3/robolectric/*.jar",
        "-Drobolectric.logging.enabled=true",
        "-XX:MaxPermSize=620m",
        "-Drobolectric.offline=true",
    ]
    if native.read_config("user", "use_dev_shm"):
        extra_vm_args.append("-Djava.io.tmpdir=/dev/shm")

    # RN tests use  Powermock, which means they get their own ClassLoaders.
    # Because the yoga native library (or any native library) can only be loaded into one
    # ClassLoader at a time, we need to run each in its own process, hence fork_mode = 'per_test'.
    native.robolectric_test(
        name = name,
        use_cxx_libraries = True,
        cxx_library_whitelist = [
            "//ReactCommon/yoga:yoga",
            "//ReactAndroid/src/main/jni/first-party/yogajni:jni",
        ],
        fork_mode = "per_test",
        srcs = srcs,
        vm_args = vm_args + extra_vm_args,
        *args,
        **kwargs
    )

def cxx_library(allow_jni_merging = None, **kwargs):
    _ignore = allow_jni_merging
    args = {
        k: v
        for k, v in kwargs.items()
        if not (k.startswith("fbandroid_") or k.startswith("fbobjc_"))
    }
    native.cxx_library(**args)

def _paths_join(path, *others):
    """Joins one or more path components."""
    result = path

    for p in others:
        if p.startswith("/"):  # absolute
            result = p
        elif not result or result.endswith("/"):
            result += p
        else:
            result += "/" + p

    return result

def subdir_glob(glob_specs, exclude = None, prefix = ""):
    """Returns a dict of sub-directory relative paths to full paths.

    The subdir_glob() function is useful for defining header maps for C/C++
    libraries which should be relative the given sub-directory.
    Given a list of tuples, the form of (relative-sub-directory, glob-pattern),
    it returns a dict of sub-directory relative paths to full paths.

    Please refer to native.glob() for explanations and examples of the pattern.

    Args:
      glob_specs: The array of tuples in form of
        (relative-sub-directory, glob-pattern inside relative-sub-directory).
        type: List[Tuple[str, str]]
      exclude: A list of patterns to identify files that should be removed
        from the set specified by the first argument. Defaults to [].
        type: Optional[List[str]]
      prefix: If is not None, prepends it to each key in the dictionary.
        Defaults to None.
        type: Optional[str]

    Returns:
      A dict of sub-directory relative paths to full paths.
    """
    if exclude == None:
        exclude = []

    results = []

    for dirpath, glob_pattern in glob_specs:
        results.append(
            _single_subdir_glob(dirpath, glob_pattern, exclude, prefix),
        )

    return _merge_maps(*results)

def _merge_maps(*file_maps):
    result = {}
    for file_map in file_maps:
        for key in file_map:
            if key in result and result[key] != file_map[key]:
                fail(
                    "Conflicting files in file search paths. " +
                    "\"%s\" maps to both \"%s\" and \"%s\"." %
                    (key, result[key], file_map[key]),
                )

            result[key] = file_map[key]

    return result

def _single_subdir_glob(dirpath, glob_pattern, exclude = None, prefix = None):
    if exclude == None:
        exclude = []
    results = {}
    files = native.glob([_paths_join(dirpath, glob_pattern)], exclude = exclude)
    for f in files:
        if dirpath:
            key = f[len(dirpath) + 1:]
        else:
            key = f
        if prefix:
            key = _paths_join(prefix, key)
        results[key] = f

    return results

def fb_apple_library(*args, **kwargs):
    native.apple_library(*args, **kwargs)

def oss_cxx_library(**kwargs):
    cxx_library(**kwargs)

def jni_instrumentation_test_lib(**_kwargs):
    """A noop stub for OSS build."""
    pass

def fb_xplat_cxx_test(**_kwargs):
    """A noop stub for OSS build."""
    pass

# iOS Plugin support.
def react_module_plugin_providers():
    # Noop for now
    return []
<|endoftext|>


<commit_before># Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

"""Helpers for referring to React Native open source code.

This lets us build React Native:
 - At Facebook by running buck from the root of the fb repo
 - Outside of Facebook by running buck in the root of the git repo
"""
# @lint-ignore-every BUCKRESTRICTEDSYNTAX

_DEBUG_PREPROCESSOR_FLAGS = []

_APPLE_COMPILER_FLAGS = []

def get_apple_compiler_flags():
    return _APPLE_COMPILER_FLAGS

def get_preprocessor_flags_for_build_mode():
    return _DEBUG_PREPROCESSOR_FLAGS

def get_static_library_ios_flags():
    return _APPLE_COMPILER_FLAGS

def get_objc_arc_preprocessor_flags():
    return [
        "-fobjc-arc",
        "-fno-objc-arc-exceptions",
        "-Qunused-arguments",
    ]

IS_OSS_BUILD = True

GLOG_DEP = "//ReactAndroid/build/third-party-ndk/glog:glog"

INSPECTOR_FLAGS = []

# Platform Definitions
CXX = "Default"

ANDROID = "Android"

APPLE = "Apple"

# Apple SDK Definitions
IOS = "ios"

MACOSX = "macosx"

YOGA_TARGET = "//ReactAndroid/src/main/java/com/facebook:yoga"

YOGA_CXX_TARGET = "//ReactCommon/yoga:yoga"

FBGLOGINIT_TARGET = "//ReactAndroid/src/main/jni/first-party/fbgloginit:fbgloginit"

FBJNI_TARGET = "//ReactAndroid/src/main/jni/first-party/fb:jni"

JNI_TARGET = "//ReactAndroid/src/main/jni/first-party/jni-hack:jni-hack"

KEYSTORE_TARGET = "//keystores:debug"

def get_apple_inspector_flags():
    return []

def get_android_inspector_flags():
    return []

# Building is not supported in OSS right now
def rn_xplat_cxx_library(name, **kwargs):
    new_kwargs = {
        k: v
        for k, v in kwargs.items()
        if k.startswith("exported_")
    }

    native.cxx_library(
        name = name,
        visibility = kwargs.get("visibility", []),
        **new_kwargs
    )

# Example: react_native_target('java/com/facebook/react/common:common')
def react_native_target(path):
    return "//ReactAndroid/src/main/" + path

# Example: react_native_xplat_target('bridge:bridge')
def react_native_xplat_target(path):
    return "//ReactCommon/" + path

def react_native_xplat_target_apple(path):
    return react_native_xplat_target(path) + "Apple"

def react_native_root_target(path):
    return "//" + path

def react_native_xplat_shared_library_target(path):
    return react_native_xplat_target(path)

# Example: react_native_tests_target('java/com/facebook/react/modules:modules')
def react_native_tests_target(path):
    return "//ReactAndroid/src/test/" + path

# Example: react_native_integration_tests_target('java/com/facebook/react/testing:testing')
def react_native_integration_tests_target(path):
    return "//ReactAndroid/src/androidTest/" + path

# Helpers for referring to non-RN code from RN OSS code.
# Example: react_native_dep('java/com/facebook/systrace:systrace')
def react_native_dep(path):
    return "//ReactAndroid/src/main/" + path

def react_native_android_toplevel_dep(path):
    return react_native_dep(path)

# Example: react_native_xplat_dep('java/com/facebook/systrace:systrace')
def react_native_xplat_dep(path):
    return "//ReactCommon/" + path

def rn_extra_build_flags():
    return []

# React property preprocessor
def rn_android_library(name, deps = [], plugins = [], *args, **kwargs):
    _ = kwargs.pop("autoglob", False)
    _ = kwargs.pop("is_androidx", False)
    if react_native_target(
        "java/com/facebook/react/uimanager/annotations:annotations",
    ) in deps and name != "processing":
        react_property_plugins = [
            react_native_target(
                "java/com/facebook/react/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_property_plugins))

    if react_native_target(
        "java/com/facebook/react/module/annotations:annotations",
    ) in deps and name != "processing":
        react_module_plugins = [
            react_native_target(
                "java/com/facebook/react/module/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_module_plugins))

    native.android_library(name = name, deps = deps, plugins = plugins, *args, **kwargs)

def rn_android_binary(*args, **kwargs):
    native.android_binary(*args, **kwargs)

def rn_android_build_config(*args, **kwargs):
    native.android_build_config(*args, **kwargs)

def rn_android_resource(*args, **kwargs):
    native.android_resource(*args, **kwargs)

def rn_android_prebuilt_aar(*args, **kwargs):
    native.android_prebuilt_aar(*args, **kwargs)

def rn_apple_library(*args, **kwargs):
    kwargs.setdefault("link_whole", True)
    kwargs.setdefault("enable_exceptions", True)
    kwargs.setdefault("target_sdk_version", "11.0")

    # Unsupported kwargs
    _ = kwargs.pop("autoglob", False)
    _ = kwargs.pop("plugins_only", False)
    _ = kwargs.pop("enable_exceptions", False)
    _ = kwargs.pop("extension_api_only", False)
    _ = kwargs.pop("sdks", [])

    native.apple_library(*args, **kwargs)

def rn_java_library(*args, **kwargs):
    _ = kwargs.pop("is_androidx", False)
    native.java_library(*args, **kwargs)

def rn_java_annotation_processor(*args, **kwargs):
    native.java_annotation_processor(*args, **kwargs)

def rn_prebuilt_native_library(*args, **kwargs):
    native.prebuilt_native_library(*args, **kwargs)

def rn_prebuilt_jar(*args, **kwargs):
    native.prebuilt_jar(*args, **kwargs)

def rn_genrule(*args, **kwargs):
    native.genrule(*args, **kwargs)

def rn_robolectric_test(name, srcs, vm_args = None, *args, **kwargs):
    vm_args = vm_args or []

    _ = kwargs.pop("autoglob", False)
    _ = kwargs.pop("is_androidx", False)

    kwargs["deps"] = kwargs.pop("deps", []) + [
        react_native_android_toplevel_dep("third-party/java/mockito2:mockito2"),
        react_native_dep("third-party/java/robolectric/4.4:robolectric"),
        react_native_tests_target("resources:robolectric"),
        react_native_xplat_dep("libraries/fbcore/src/test/java/com/facebook/powermock:powermock2"),
    ]

    extra_vm_args = [
        "-XX:+UseConcMarkSweepGC",  # required by -XX:+CMSClassUnloadingEnabled
        "-XX:+CMSClassUnloadingEnabled",
        "-XX:ReservedCodeCacheSize=150M",
        "-Drobolectric.dependency.dir=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric/4.4",
        "-Dlibraries=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric/4.4/*.jar",
        "-Drobolectric.logging.enabled=true",
        "-XX:MaxPermSize=620m",
        "-Drobolectric.offline=true",
        "-Drobolectric.looperMode=LEGACY",
    ]
    if native.read_config("user", "use_dev_shm"):
        extra_vm_args.append("-Djava.io.tmpdir=/dev/shm")

    # RN tests use  Powermock, which means they get their own ClassLoaders.
    # Because the yoga native library (or any native library) can only be loaded into one
    # ClassLoader at a time, we need to run each in its own process, hence fork_mode = 'per_test'.
    native.robolectric_test(
        name = name,
        use_cxx_libraries = True,
        cxx_library_whitelist = [
            "//ReactCommon/yoga:yoga",
            "//ReactAndroid/src/main/jni/first-party/yogajni:jni",
        ],
        fork_mode = "per_test",
        srcs = srcs,
        vm_args = vm_args + extra_vm_args,
        *args,
        **kwargs
    )

def cxx_library(allow_jni_merging = None, **kwargs):
    _ignore = allow_jni_merging
    args = {
        k: v
        for k, v in kwargs.items()
        if not (k.startswith("fbandroid_") or k.startswith("fbobjc_"))
    }
    native.cxx_library(**args)

def _paths_join(path, *others):
    """Joins one or more path components."""
    result = path

    for p in others:
        if p.startswith("/"):  # absolute
            result = p
        elif not result or result.endswith("/"):
            result += p
        else:
            result += "/" + p

    return result

def subdir_glob(glob_specs, exclude = None, prefix = ""):
    """Returns a dict of sub-directory relative paths to full paths.

    The subdir_glob() function is useful for defining header maps for C/C++
    libraries which should be relative the given sub-directory.
    Given a list of tuples, the form of (relative-sub-directory, glob-pattern),
    it returns a dict of sub-directory relative paths to full paths.

    Please refer to native.glob() for explanations and examples of the pattern.

    Args:
      glob_specs: The array of tuples in form of
        (relative-sub-directory, glob-pattern inside relative-sub-directory).
        type: List[Tuple[str, str]]
      exclude: A list of patterns to identify files that should be removed
        from the set specified by the first argument. Defaults to [].
        type: Optional[List[str]]
      prefix: If is not None, prepends it to each key in the dictionary.
        Defaults to None.
        type: Optional[str]

    Returns:
      A dict of sub-directory relative paths to full paths.
    """
    if exclude == None:
        exclude = []

    results = []

    for dirpath, glob_pattern in glob_specs:
        results.append(
            _single_subdir_glob(dirpath, glob_pattern, exclude, prefix),
        )

    return _merge_maps(*results)

def _merge_maps(*file_maps):
    result = {}
    for file_map in file_maps:
        for key in file_map:
            if key in result and result[key] != file_map[key]:
                fail(
                    "Conflicting files in file search paths. " +
                    "\"%s\" maps to both \"%s\" and \"%s\"." %
                    (key, result[key], file_map[key]),
                )

            result[key] = file_map[key]

    return result

def _single_subdir_glob(dirpath, glob_pattern, exclude = None, prefix = None):
    if exclude == None:
        exclude = []
    results = {}
    files = native.glob([_paths_join(dirpath, glob_pattern)], exclude = exclude)
    for f in files:
        if dirpath:
            key = f[len(dirpath) + 1:]
        else:
            key = f
        if prefix:
            key = _paths_join(prefix, key)
        results[key] = f

    return results

def fb_apple_library(*args, **kwargs):
    native.apple_library(*args, **kwargs)

def oss_cxx_library(**kwargs):
    cxx_library(**kwargs)

def jni_instrumentation_test_lib(**_kwargs):
    """A noop stub for OSS build."""
    pass

def fb_xplat_cxx_test(**_kwargs):
    """A noop stub for OSS build."""
    pass

# iOS Plugin support.
def react_module_plugin_providers():
    # Noop for now
    return []
<commit_msg>Ensure that all Fabric modules are compiled with the same preprocessor flags<commit_after># Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

"""Helpers for referring to React Native open source code.

This lets us build React Native:
 - At Facebook by running buck from the root of the fb repo
 - Outside of Facebook by running buck in the root of the git repo
"""
# @lint-ignore-every BUCKRESTRICTEDSYNTAX

_DEBUG_PREPROCESSOR_FLAGS = []

_APPLE_COMPILER_FLAGS = []

def get_apple_compiler_flags():
    return _APPLE_COMPILER_FLAGS

def get_preprocessor_flags_for_build_mode():
    return _DEBUG_PREPROCESSOR_FLAGS

def get_static_library_ios_flags():
    return _APPLE_COMPILER_FLAGS

def get_objc_arc_preprocessor_flags():
    return [
        "-fobjc-arc",
        "-fno-objc-arc-exceptions",
        "-Qunused-arguments",
    ]

IS_OSS_BUILD = True

GLOG_DEP = "//ReactAndroid/build/third-party-ndk/glog:glog"

INSPECTOR_FLAGS = []

# Platform Definitions
CXX = "Default"

ANDROID = "Android"

APPLE = "Apple"

# Apple SDK Definitions
IOS = "ios"

MACOSX = "macosx"

YOGA_TARGET = "//ReactAndroid/src/main/java/com/facebook:yoga"

YOGA_CXX_TARGET = "//ReactCommon/yoga:yoga"

FBGLOGINIT_TARGET = "//ReactAndroid/src/main/jni/first-party/fbgloginit:fbgloginit"

FBJNI_TARGET = "//ReactAndroid/src/main/jni/first-party/fb:jni"

JNI_TARGET = "//ReactAndroid/src/main/jni/first-party/jni-hack:jni-hack"

KEYSTORE_TARGET = "//keystores:debug"

def get_apple_inspector_flags():
    return []

def get_android_inspector_flags():
    return []

def get_react_native_preprocessor_flags():
    # TODO: use this to define the compiler flag REACT_NATIVE_DEBUG in debug/dev mode builds only.
    # This is a replacement for NDEBUG since NDEBUG is always defined in Buck on all Android builds.
    return []

# Building is not supported in OSS right now
def rn_xplat_cxx_library(name, **kwargs):
    new_kwargs = {
        k: v
        for k, v in kwargs.items()
        if k.startswith("exported_")
    }

    native.cxx_library(
        name = name,
        visibility = kwargs.get("visibility", []),
        **new_kwargs
    )

# Example: react_native_target('java/com/facebook/react/common:common')
def react_native_target(path):
    return "//ReactAndroid/src/main/" + path

# Example: react_native_xplat_target('bridge:bridge')
def react_native_xplat_target(path):
    return "//ReactCommon/" + path

def react_native_xplat_target_apple(path):
    return react_native_xplat_target(path) + "Apple"

def react_native_root_target(path):
    return "//" + path

def react_native_xplat_shared_library_target(path):
    return react_native_xplat_target(path)

# Example: react_native_tests_target('java/com/facebook/react/modules:modules')
def react_native_tests_target(path):
    return "//ReactAndroid/src/test/" + path

# Example: react_native_integration_tests_target('java/com/facebook/react/testing:testing')
def react_native_integration_tests_target(path):
    return "//ReactAndroid/src/androidTest/" + path

# Helpers for referring to non-RN code from RN OSS code.
# Example: react_native_dep('java/com/facebook/systrace:systrace')
def react_native_dep(path):
    return "//ReactAndroid/src/main/" + path

def react_native_android_toplevel_dep(path):
    return react_native_dep(path)

# Example: react_native_xplat_dep('java/com/facebook/systrace:systrace')
def react_native_xplat_dep(path):
    return "//ReactCommon/" + path

def rn_extra_build_flags():
    return []

# React property preprocessor
def rn_android_library(name, deps = [], plugins = [], *args, **kwargs):
    _ = kwargs.pop("autoglob", False)
    _ = kwargs.pop("is_androidx", False)
    if react_native_target(
        "java/com/facebook/react/uimanager/annotations:annotations",
    ) in deps and name != "processing":
        react_property_plugins = [
            react_native_target(
                "java/com/facebook/react/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_property_plugins))

    if react_native_target(
        "java/com/facebook/react/module/annotations:annotations",
    ) in deps and name != "processing":
        react_module_plugins = [
            react_native_target(
                "java/com/facebook/react/module/processing:processing",
            ),
        ]

        plugins = list(set(plugins + react_module_plugins))

    native.android_library(name = name, deps = deps, plugins = plugins, *args, **kwargs)

def rn_android_binary(*args, **kwargs):
    native.android_binary(*args, **kwargs)

def rn_android_build_config(*args, **kwargs):
    native.android_build_config(*args, **kwargs)

def rn_android_resource(*args, **kwargs):
    native.android_resource(*args, **kwargs)

def rn_android_prebuilt_aar(*args, **kwargs):
    native.android_prebuilt_aar(*args, **kwargs)

def rn_apple_library(*args, **kwargs):
    kwargs.setdefault("link_whole", True)
    kwargs.setdefault("enable_exceptions", True)
    kwargs.setdefault("target_sdk_version", "11.0")

    # Unsupported kwargs
    _ = kwargs.pop("autoglob", False)
    _ = kwargs.pop("plugins_only", False)
    _ = kwargs.pop("enable_exceptions", False)
    _ = kwargs.pop("extension_api_only", False)
    _ = kwargs.pop("sdks", [])

    native.apple_library(*args, **kwargs)

def rn_java_library(*args, **kwargs):
    _ = kwargs.pop("is_androidx", False)
    native.java_library(*args, **kwargs)

def rn_java_annotation_processor(*args, **kwargs):
    native.java_annotation_processor(*args, **kwargs)

def rn_prebuilt_native_library(*args, **kwargs):
    native.prebuilt_native_library(*args, **kwargs)

def rn_prebuilt_jar(*args, **kwargs):
    native.prebuilt_jar(*args, **kwargs)

def rn_genrule(*args, **kwargs):
    native.genrule(*args, **kwargs)

def rn_robolectric_test(name, srcs, vm_args = None, *args, **kwargs):
    vm_args = vm_args or []

    _ = kwargs.pop("autoglob", False)
    _ = kwargs.pop("is_androidx", False)

    kwargs["deps"] = kwargs.pop("deps", []) + [
        react_native_android_toplevel_dep("third-party/java/mockito2:mockito2"),
        react_native_dep("third-party/java/robolectric/4.4:robolectric"),
        react_native_tests_target("resources:robolectric"),
        react_native_xplat_dep("libraries/fbcore/src/test/java/com/facebook/powermock:powermock2"),
    ]

    extra_vm_args = [
        "-XX:+UseConcMarkSweepGC",  # required by -XX:+CMSClassUnloadingEnabled
        "-XX:+CMSClassUnloadingEnabled",
        "-XX:ReservedCodeCacheSize=150M",
        "-Drobolectric.dependency.dir=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric/4.4",
        "-Dlibraries=buck-out/gen/ReactAndroid/src/main/third-party/java/robolectric/4.4/*.jar",
        "-Drobolectric.logging.enabled=true",
        "-XX:MaxPermSize=620m",
        "-Drobolectric.offline=true",
        "-Drobolectric.looperMode=LEGACY",
    ]
    if native.read_config("user", "use_dev_shm"):
        extra_vm_args.append("-Djava.io.tmpdir=/dev/shm")

    # RN tests use  Powermock, which means they get their own ClassLoaders.
    # Because the yoga native library (or any native library) can only be loaded into one
    # ClassLoader at a time, we need to run each in its own process, hence fork_mode = 'per_test'.
    native.robolectric_test(
        name = name,
        use_cxx_libraries = True,
        cxx_library_whitelist = [
            "//ReactCommon/yoga:yoga",
            "//ReactAndroid/src/main/jni/first-party/yogajni:jni",
        ],
        fork_mode = "per_test",
        srcs = srcs,
        vm_args = vm_args + extra_vm_args,
        *args,
        **kwargs
    )

def cxx_library(allow_jni_merging = None, **kwargs):
    _ignore = allow_jni_merging
    args = {
        k: v
        for k, v in kwargs.items()
        if not (k.startswith("fbandroid_") or k.startswith("fbobjc_"))
    }
    native.cxx_library(**args)

def _paths_join(path, *others):
    """Joins one or more path components."""
    result = path

    for p in others:
        if p.startswith("/"):  # absolute
            result = p
        elif not result or result.endswith("/"):
            result += p
        else:
            result += "/" + p

    return result

def subdir_glob(glob_specs, exclude = None, prefix = ""):
    """Returns a dict of sub-directory relative paths to full paths.

    The subdir_glob() function is useful for defining header maps for C/C++
    libraries which should be relative the given sub-directory.
    Given a list of tuples, the form of (relative-sub-directory, glob-pattern),
    it returns a dict of sub-directory relative paths to full paths.

    Please refer to native.glob() for explanations and examples of the pattern.

    Args:
      glob_specs: The array of tuples in form of
        (relative-sub-directory, glob-pattern inside relative-sub-directory).
        type: List[Tuple[str, str]]
      exclude: A list of patterns to identify files that should be removed
        from the set specified by the first argument. Defaults to [].
        type: Optional[List[str]]
      prefix: If is not None, prepends it to each key in the dictionary.
        Defaults to None.
        type: Optional[str]

    Returns:
      A dict of sub-directory relative paths to full paths.
    """
    if exclude == None:
        exclude = []

    results = []

    for dirpath, glob_pattern in glob_specs:
        results.append(
            _single_subdir_glob(dirpath, glob_pattern, exclude, prefix),
        )

    return _merge_maps(*results)

def _merge_maps(*file_maps):
    result = {}
    for file_map in file_maps:
        for key in file_map:
            if key in result and result[key] != file_map[key]:
                fail(
                    "Conflicting files in file search paths. " +
                    "\"%s\" maps to both \"%s\" and \"%s\"." %
                    (key, result[key], file_map[key]),
                )

            result[key] = file_map[key]

    return result

def _single_subdir_glob(dirpath, glob_pattern, exclude = None, prefix = None):
    if exclude == None:
        exclude = []
    results = {}
    files = native.glob([_paths_join(dirpath, glob_pattern)], exclude = exclude)
    for f in files:
        if dirpath:
            key = f[len(dirpath) + 1:]
        else:
            key = f
        if prefix:
            key = _paths_join(prefix, key)
        results[key] = f

    return results

def fb_apple_library(*args, **kwargs):
    native.apple_library(*args, **kwargs)

def oss_cxx_library(**kwargs):
    cxx_library(**kwargs)

def jni_instrumentation_test_lib(**_kwargs):
    """A noop stub for OSS build."""
    pass

def fb_xplat_cxx_test(**_kwargs):
    """A noop stub for OSS build."""
    pass

# iOS Plugin support.
def react_module_plugin_providers():
    # Noop for now
    return []
<|endoftext|>