text:
from torch.utils.data import Dataset, DataLoader
import soundfile as sf
import numpy as np
import pandas as pd
import torch
import math
import os
from dataloaders.imbalanced_dataset_sampler import ImbalancedDatasetSampler

class SedDataset(Dataset):
    def __init__( self,
            root_dir, csv_dir, period, bird_code, inv_ebird_label, isTraining,num_test_samples, transform=None, background_audio_dir=None):

        self.root_dir = root_dir
        self.transform = transform
        self.period = period
        self.bird_code = bird_code
        self.inv_ebird_label = inv_ebird_label
        self.isTraining = isTraining
        self.num_test_samples = num_test_samples

        self.additional_loader_params = {
            "worker_init_fn": self.init_workers_fn
        }
        self.sampler = ImbalancedDatasetSampler

        df = pd.read_csv(csv_dir)
        df.secondary_labels = df.secondary_labels.apply(eval)
        self.data = list(df[["filename", "ebird_code", "secondary_labels"]].to_dict('index').values())
        del df

        self.background_audio_dir = background_audio_dir
        has_background = False
        if self.background_audio_dir is not None:
            for bk in background_audio_dir.glob('**/*.wav'):
                self.data.append({
                    "filename": bk
                })
                has_background =True

        if has_background:
            print("Background audio was added to dataloader")
        self.length = len(self.data)

    def get_label(self, dataset, idx):
        return dataset.data[idx]["ebird_code"]

    def __len__(self):
        return self.length

    def init_workers_fn(self, worker_id):
        new_seed = int.from_bytes(os.urandom(4), byteorder='little')
        np.random.seed(new_seed)

    def get_audio(self, idx):
        item = self.data[idx]
        filename = item["filename"]
        if "ebird_code" in item:
            primary_label = item["ebird_code"]

            all_labels = [primary_label]
            for ln in item["secondary_labels"]:
                if ln in self.inv_ebird_label:
                    all_labels.append(self.inv_ebird_label[ln])

            if type(self.root_dir) is dict:
                file_dir = self.root_dir[primary_label[0]]/f"{primary_label}"/f"{filename.replace('.mp3','.wav')}"
            else:
                file_dir = self.root_dir/f"{primary_label}"/f"{filename.replace('.mp3','.wav')}"
        else:
            primary_label = None
            all_labels = []
            file_dir = filename
            filename = filename.stem

        y, sr = sf.read(file_dir)
        return {
            "y": y,
            "all_labels":all_labels,
            "primary_labels": [primary_label] if primary_label is not None else [],
            "secondary_labels": [x for x in all_labels if x != primary_label],
            "sr": sr,
            "duration": len(y),
            "filename": filename
        }

    def convert_labels_to_coded(self, num_images, labels):
        coded_labels = np.zeros((num_images,len(self.bird_code)))
        for index, temp_label in enumerate(labels):
            label_index = self.bird_code[temp_label]
            coded_labels[:,label_index] = 1
        return torch.from_numpy(coded_labels).float()

    def __getitem__(self, idx: int):
        item = self.get_audio(idx)
        y = item["y"]

        if self.transform:
            y = self.transform(y, item["sr"])

        effective_length = item["sr"] * self.period
        list_of_y = []
        if self.isTraining:
            for i in range(self.num_test_samples):
                if item["duration"] < effective_length:
                    new_y = np.zeros(effective_length, dtype=y.dtype)
                    start = np.random.randint(effective_length - item["duration"])
                    new_y[start:start + item["duration"]] = y
                    y_snippet = new_y.astype(np.float32)
                elif item["duration"] > effective_length:
                    start = np.random.randint(item["duration"] - effective_length)
                    y_snippet = y[start:start + effective_length].astype(np.float32)
                else:
                    y_snippet = y.astype(np.float32)
                list_of_y.append(y_snippet)
        else:
            if item["duration"] < effective_length*self.num_test_samples:
                new_y = np.zeros(effective_length*self.num_test_samples, dtype=y.dtype)
                new_y[0:item["duration"]] = y
                y = new_y.astype(np.float32)
                item["duration"] = len(y)

            for i in range(self.num_test_samples):
                y_snippet = y[effective_length*i: effective_length*i+effective_length].astype(np.float32)
                list_of_y.append(y_snippet)

        all_labels = self.convert_labels_to_coded(len(list_of_y), item["all_labels"])
        primary_labels = self.convert_labels_to_coded(len(list_of_y), item["primary_labels"])
        secondary_labels = self.convert_labels_to_coded(len(list_of_y), item["secondary_labels"])

        list_of_y = np.array(list_of_y)
        return {"filename":item["filename"], "waveforms": list_of_y, "all_labels": all_labels, "primary_labels":primary_labels, "secondary_labels": secondary_labels}

ext: py

max_stars_repo_name: Sarajvega/kaggle-birdsong-recognition

max_issues_repo_name: Sarajvega/kaggle-birdsong-recognition

max_forks_repo_name: Sarajvega/kaggle-birdsong-recognition

reason: import numpy


text:
import os
import math
import numpy as np
import modeling.model_collection as mc
import robot_sim._kinematics.jlchain as jl
import basis.robot_math as rm
import robot_sim.end_effectors.external_link.external_link_interface as extl
import modeling.geometric_model as gm

class ExtLink(extl.ExtlinkInterface):

    def __init__(self, pos=np.zeros(3), rotmat=np.eye(3), cdmesh_type='box', name='ext_link', enable_cc=True):
        super().__init__(pos=pos, rotmat=rotmat, cdmesh_type=cdmesh_type, name=name)
        this_dir, this_filename = os.path.split(__file__)
        cpl_end_pos = self.coupling.jnts[-1]['gl_posq']
        cpl_end_rotmat = self.coupling.jnts[-1]['gl_rotmatq']
        self.jlc = jl.JLChain(pos=cpl_end_pos, rotmat=cpl_end_rotmat, homeconf=np.zeros(1), name='ext_link_jlc')
        self.jlc.jnts[1]['loc_pos'] = np.array([.0, .0, .04])
        self.jlc.jnts[1]['loc_motionax'] = np.array([0, 1, 0])
        self.jlc.jnts[2]['loc_pos'] = np.array([.0, .102, .0])
        self.jlc.jnts[2]['loc_motionax'] = np.array([0, 1, 0])
        self.jlc.lnks[0]['name'] = "ext_link_1"
        self.jlc.lnks[0]['loc_pos'] = np.zeros(3)
        self.jlc.lnks[0]['meshfile'] = os.path.join(this_dir, "meshes", "ext_link1.stl")
        self.jlc.lnks[0]['rgba'] = [.5, .5, .5, 1]
        self.jlc.lnks[1]['loc_pos'] = np.array([.0, .04, .0])
        self.jlc.lnks[1]['loc_rotmat'] = rm.rotmat_from_euler(-math.pi/2, 0, 0)
        self.jlc.lnks[1]['meshfile'] = os.path.join(this_dir, "meshes", "ext_link2.stl")
        self.jlc.lnks[1]['rgba'] = [.6, .4, .2, 1]
        # reinitialize
        self.jlc.reinitialize()
        # extlink origin pose relative to the arm end
        self.origin_pos = np.array([0, 0, 0])
        self.origin_rotmat = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
        # extlink center relative to the origin
        self.center_pos = np.array([.0, .102, .04])
        self.center_rotmat = np.array([[1, 0, 0], [0, 0, 1], [0, -1, 0]])
        # collision detection
        self.all_cdelements = []
        self.enable_cc(toggle_cdprimit=enable_cc)

    def enable_cc(self, toggle_cdprimit):
        if toggle_cdprimit:
            super().enable_cc()
            # cdprimit
            self.cc.add_cdlnks(self.jlc, [0])
            activelist = [self.jlc.lnks[0]]
            self.cc.set_active_cdlnks(activelist)
            self.all_cdelements = self.cc.all_cdelements
        # cdmesh
        for cdelement in self.all_cdelements:
            cdmesh = cdelement['collisionmodel'].copy()
            self.cdmesh_collection.add_cm(cdmesh)

    def fix_to(self, pos, rotmat):
        self.pos = pos
        self.rotmat = rotmat
        self.coupling.fix_to(self.pos, self.rotmat)
        cpl_end_pos = self.coupling.jnts[-1]['gl_posq']
        cpl_end_rotmat = self.coupling.jnts[-1]['gl_rotmatq']
        self.jlc.fix_to(cpl_end_pos, cpl_end_rotmat)

    def gen_stickmodel(self,
                       toggle_tcpcs=False,
                       toggle_jntscs=False,
                       toggle_connjnt=False,
                       name='extlink_stickmodel'):
        mm_collection = mc.ModelCollection(name=name)
        self.coupling.gen_stickmodel(toggle_tcpcs=False,
                                     toggle_jntscs=toggle_jntscs).attach_to(mm_collection)
        self.jlc.gen_stickmodel(toggle_tcpcs=False,
                                toggle_jntscs=toggle_jntscs,
                                toggle_connjnt=toggle_connjnt).attach_to(mm_collection)
        if toggle_tcpcs:
            center_gl_pos = self.rotmat.dot(self.center_pos) + self.pos
            center_gl_rotmat = self.rotmat.dot(self.center_rotmat)
            gm.gen_dashstick(spos=self.pos,
                             epos=center_gl_pos,
                             thickness=.0062,
                             rgba=[.5, 0, 1, 1],
                             type="round").attach_to(mm_collection)
            gm.gen_mycframe(pos=center_gl_pos, rotmat=center_gl_rotmat).attach_to(mm_collection)
        return mm_collection

    def gen_meshmodel(self,
                      toggle_tcpcs=False,
                      toggle_jntscs=False,
                      rgba=None,
                      name='extlink_meshmodel'):
        mm_collection = mc.ModelCollection(name=name)
        self.coupling.gen_meshmodel(toggle_tcpcs=False,
                                    toggle_jntscs=toggle_jntscs,
                                    rgba=rgba).attach_to(mm_collection)
        self.jlc.gen_meshmodel(toggle_tcpcs=False,
                               toggle_jntscs=toggle_jntscs,
                               rgba=rgba).attach_to(mm_collection)
        if toggle_tcpcs:
            center_gl_pos = self.rotmat.dot(self.center_pos) + self.pos
            center_gl_rotmat = self.rotmat.dot(self.center_rotmat)
            gm.gen_dashstick(spos=self.pos,
                             epos=center_gl_pos,
                             thickness=.0062,
                             rgba=[.5, 0, 1, 1],
                             type="round").attach_to(mm_collection)
            gm.gen_mycframe(pos=center_gl_pos, rotmat=center_gl_rotmat).attach_to(mm_collection)
        return mm_collection

if __name__ == '__main__':
    import visualization.panda.world as wd
    import modeling.geometric_model as gm

    base = wd.World(cam_pos=[.5, .5, .5], lookat_pos=[0, 0, 0])
    gm.gen_frame().attach_to(base)
    # for angle in np.linspace(0, .85, 8):
    #     grpr = Robotiq85()
    #     grpr.fk(angle)
    #     grpr.gen_meshmodel().attach_to(base)
    grpr = ExtLink(enable_cc=True)
    grpr.gen_meshmodel().attach_to(base)
    grpr.gen_stickmodel(toggle_jntscs=True).attach_to(base)
    grpr.fix_to(pos=np.array([0, .3, .2]), rotmat=rm.rotmat_from_axangle([1, 0, 0], .05))
    grpr.gen_meshmodel(toggle_jntscs=True, toggle_tcpcs=True).attach_to(base)
    grpr.show_cdmesh()
    grpr.show_cdprimit()
    base.run()

max_stars_repo_name: wangyan-hlab/wrs

max_issues_repo_name: wangyan-hlab/wrs

max_forks_repo_name: wangyan-hlab/wrs


text:
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
import pytest

from scipy.sparse import csr_matrix, coo_matrix, diags
from scipy.sparse.csgraph import (
    maximum_bipartite_matching, min_weight_full_bipartite_matching
)

def test_maximum_bipartite_matching_raises_on_dense_input():
    with pytest.raises(TypeError):
        graph = np.array([[0, 1], [0, 0]])
        maximum_bipartite_matching(graph)

def test_maximum_bipartite_matching_empty_graph():
    graph = csr_matrix((0, 0))
    x = maximum_bipartite_matching(graph, perm_type='row')
    y = maximum_bipartite_matching(graph, perm_type='column')
    expected_matching = np.array([])
    assert_array_equal(expected_matching, x)
    assert_array_equal(expected_matching, y)

def test_maximum_bipartite_matching_empty_left_partition():
    graph = csr_matrix((2, 0))
    x = maximum_bipartite_matching(graph, perm_type='row')
    y = maximum_bipartite_matching(graph, perm_type='column')
    assert_array_equal(np.array([]), x)
    assert_array_equal(np.array([-1, -1]), y)

def test_maximum_bipartite_matching_empty_right_partition():
    graph = csr_matrix((0, 3))
    x = maximum_bipartite_matching(graph, perm_type='row')
    y = maximum_bipartite_matching(graph, perm_type='column')
    assert_array_equal(np.array([-1, -1, -1]), x)
    assert_array_equal(np.array([]), y)

def test_maximum_bipartite_matching_graph_with_no_edges():
    graph = csr_matrix((2, 2))
    x = maximum_bipartite_matching(graph, perm_type='row')
    y = maximum_bipartite_matching(graph, perm_type='column')
    assert_array_equal(np.array([-1, -1]), x)
    assert_array_equal(np.array([-1, -1]), y)

def test_maximum_bipartite_matching_graph_that_causes_augmentation():
    # In this graph, column 1 is initially assigned to row 1, but it should be
    # reassigned to make room for row 2.
    graph = csr_matrix([[1, 1], [1, 0]])
    x = maximum_bipartite_matching(graph, perm_type='column')
    y = maximum_bipartite_matching(graph, perm_type='row')
    expected_matching = np.array([1, 0])
    assert_array_equal(expected_matching, x)
    assert_array_equal(expected_matching, y)

def test_maximum_bipartite_matching_graph_with_more_rows_than_columns():
    graph = csr_matrix([[1, 1], [1, 0], [0, 1]])
    x = maximum_bipartite_matching(graph, perm_type='column')
    y = maximum_bipartite_matching(graph, perm_type='row')
    assert_array_equal(np.array([0, -1, 1]), x)
    assert_array_equal(np.array([0, 2]), y)

def test_maximum_bipartite_matching_graph_with_more_columns_than_rows():
    graph = csr_matrix([[1, 1, 0], [0, 0, 1]])
    x = maximum_bipartite_matching(graph, perm_type='column')
    y = maximum_bipartite_matching(graph, perm_type='row')
    assert_array_equal(np.array([0, 2]), x)
    assert_array_equal(np.array([0, -1, 1]), y)

def test_maximum_bipartite_matching_explicit_zeros_count_as_edges():
    data = [0, 0]
    indices = [1, 0]
    indptr = [0, 1, 2]
    graph = csr_matrix((data, indices, indptr), shape=(2, 2))
    x = maximum_bipartite_matching(graph, perm_type='row')
    y = maximum_bipartite_matching(graph, perm_type='column')
    expected_matching = np.array([1, 0])
    assert_array_equal(expected_matching, x)
    assert_array_equal(expected_matching, y)

def test_maximum_bipartite_matching_feasibility_of_result():
    # This is a regression test for GitHub issue #11458
    data = np.ones(50, dtype=int)
    indices = [11, 12, 19, 22, 23, 5, 22, 3, 8, 10, 5, 6, 11, 12, 13, 5, 13,
               14, 20, 22, 3, 15, 3, 13, 14, 11, 12, 19, 22, 23, 5, 22, 3, 8,
               10, 5, 6, 11, 12, 13, 5, 13, 14, 20, 22, 3, 15, 3, 13, 14]
    indptr = [0, 5, 7, 10, 10, 15, 20, 22, 22, 23, 25, 30, 32, 35, 35, 40, 45,
              47, 47, 48, 50]
    graph = csr_matrix((data, indices, indptr), shape=(20, 25))
    x = maximum_bipartite_matching(graph, perm_type='row')
    y = maximum_bipartite_matching(graph, perm_type='column')
    assert (x != -1).sum() == 13
    assert (y != -1).sum() == 13
    # Ensure that each element of the matching is in fact an edge in the graph.
    for u, v in zip(range(graph.shape[0]), y):
        if v != -1:
            assert graph[u, v]
    for u, v in zip(x, range(graph.shape[1])):
        if u != -1:
            assert graph[u, v]

def test_matching_large_random_graph_with_one_edge_incident_to_each_vertex():
    np.random.seed(42)
    A = diags(np.ones(25), offsets=0, format='csr')
    rand_perm = np.random.permutation(25)
    rand_perm2 = np.random.permutation(25)

    Rrow = np.arange(25)
    Rcol = rand_perm
    Rdata = np.ones(25, dtype=int)
    Rmat = coo_matrix((Rdata, (Rrow, Rcol))).tocsr()

    Crow = rand_perm2
    Ccol = np.arange(25)
    Cdata = np.ones(25, dtype=int)
    Cmat = coo_matrix((Cdata, (Crow, Ccol))).tocsr()
    # Randomly permute identity matrix
    B = Rmat * A * Cmat

    # Row permute
    perm = maximum_bipartite_matching(B, perm_type='row')
    Rrow = np.arange(25)
    Rcol = perm
    Rdata = np.ones(25, dtype=int)
    Rmat = coo_matrix((Rdata, (Rrow, Rcol))).tocsr()
    C1 = Rmat * B

    # Column permute
    perm2 = maximum_bipartite_matching(B, perm_type='column')
    Crow = perm2
    Ccol = np.arange(25)
    Cdata = np.ones(25, dtype=int)
    Cmat = coo_matrix((Cdata, (Crow, Ccol))).tocsr()
    C2 = B * Cmat

    # Should get identity matrix back
    assert_equal(any(C1.diagonal() == 0), False)
    assert_equal(any(C2.diagonal() == 0), False)

@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)])
def test_min_weight_full_matching_trivial_graph(num_rows, num_cols):
    biadjacency_matrix = csr_matrix((num_cols, num_rows))
    row_ind, col_ind = min_weight_full_bipartite_matching(biadjacency_matrix)
    assert len(row_ind) == 0
    assert len(col_ind) == 0

@pytest.mark.parametrize('biadjacency_matrix',
                         [
                            [[1, 1, 1], [1, 0, 0], [1, 0, 0]],
                            [[1, 1, 1], [0, 0, 1], [0, 0, 1]],
                            [[1, 0, 0], [2, 0, 0]],
                            [[0, 1, 0], [0, 2, 0]],
                            [[1, 0], [2, 0], [5, 0]]
                         ])
def test_min_weight_full_matching_infeasible_problems(biadjacency_matrix):
    with pytest.raises(ValueError):
        min_weight_full_bipartite_matching(csr_matrix(biadjacency_matrix))

def test_explicit_zero_causes_warning():
    with pytest.warns(UserWarning):
        biadjacency_matrix = csr_matrix(((2, 0, 3), (0, 1, 1), (0, 2, 3)))
        min_weight_full_bipartite_matching(biadjacency_matrix)

max_stars_repo_name: EkremBayar/bayar

max_issues_repo_name: EkremBayar/bayar

max_forks_repo_name: EkremBayar/bayar

reason: import numpy,from numpy,from scipy


text:
from __future__ import print_function, division
import numpy
from galpy import potential

def test_errors():
    #Test that when we set up an interpRZPotential w/ another interpRZPotential, we get an error
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,11),
                                       zgrid=(0.,0.2,11),
                                       logR=False,
                                       interpPot=True,
                                       zsym=True)
    try:
        rzpot2= potential.interpRZPotential(RZPot=rzpot,
                                            rgrid=(0.01,2.,11),
                                            zgrid=(0.,0.2,11),
                                            logR=False,
                                            interpPot=True,
                                            zsym=True)
    except potential.PotentialError: pass
    else: raise AssertionError('Setting up an interpRZPotential w/ another interpRZPotential did not raise PotentialError')

def test_interpolation_potential():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpPot=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    zs= numpy.linspace(-0.2,0.2,41)
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot(r,z)
                              -potential.evaluatePotentials(r,z,potential.MWPotential))/potential.evaluatePotentials(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails at (R,z) = (%g,%g)' % (r,z)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot(r,z)
                              -potential.evaluatePotentials(r,z,potential.MWPotential))/potential.evaluatePotentials(r,z,potential.MWPotential)) < 10.**-6., 'RZPot interpolation w/ interpRZPotential fails at (R,z) = (%g,%g)' % (r,z)
    #Test all at the same time to use vector evaluation
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       zgrid=(0.,0.2,101),
                                       interpPot=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(-0.2,0.2,101),
                                       logR=False,
                                       interpPot=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 2.*10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, w/o zsym'
    #Test the interpolation of the potential, w/o zsym and with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       zgrid=(-0.2,0.2,101),
                                       interpPot=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,20.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 2.*10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input w/o zsym and w/ logR'
    return None

def test_interpolation_potential_diffinputs():
    #Test the interpolation of the potential for different inputs: combination of vector and scalar (we've already done both scalars and both vectors above)
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpPot=True,
                                       zsym=True)
    #Test all at the same time to use vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    #R vector, z scalar
    assert numpy.all(numpy.fabs((rzpot(rs,zs[10])-potential.evaluatePotentials(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential))/potential.evaluatePotentials(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector R and scalar Z'
    #R scalar, z vector
    assert numpy.all(numpy.fabs((rzpot(rs[10],zs)-potential.evaluatePotentials(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential))/potential.evaluatePotentials(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector R and scalar Z'
    return None

def test_interpolation_potential_c():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,151),
                                       zgrid=(0.,0.2,151),
                                       logR=False,
                                       interpPot=True,
                                       enable_c=True,
                                       zsym=True)
    #Test within the grid, using vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, using C'
    #now w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,151),
                                       zgrid=(-0.2,0.2,301),
                                       logR=False,
                                       interpPot=True,
                                       enable_c=True,
                                       zsym=False)
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 2.*10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, using C, w/o zsym'
    #now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              251),
                                       logR= True,
                                       zgrid=(0.,0.2,151),
                                       interpPot=True,
                                       enable_c=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,10.,20) #don't go too far
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, using C, w/ logR'
    #now with logR and w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              251),
                                       logR= True,
                                       zgrid=(-0.2,0.2,301),
                                       interpPot=True,
                                       enable_c=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,10.,20) #don't go too far
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 2.*10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, using C, w/ logR, and w/o zsym'
    return None

def test_interpolation_potential_diffinputs_c():
    #Test the interpolation of the potential for different inputs: combination of vector and scalar (we've already done both scalars and both vectors above)
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,151),
                                       zgrid=(0.,0.2,151),
                                       logR=False,
                                       interpPot=True,
                                       zsym=True,enable_c=True)
    #Test all at the same time to use vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    #R vector, z scalar
    assert numpy.all(numpy.fabs((rzpot(rs,zs[10])-potential.evaluatePotentials(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential))/potential.evaluatePotentials(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector R and scalar Z'
    #R scalar, z vector
    assert numpy.all(numpy.fabs((rzpot(rs[10],zs)-potential.evaluatePotentials(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential))/potential.evaluatePotentials(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector R and scalar Z'
    return None

def test_interpolation_potential_c_vdiffgridsizes():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,271),
                                       zgrid=(0.,0.2,162),
                                       logR=False,
                                       interpPot=True,
                                       enable_c=True,
                                       zsym=True)
    #Test within the grid, using vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot(mr,mz)-potential.evaluatePotentials(mr,mz,potential.MWPotential))/potential.evaluatePotentials(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector input, using C'
    return None

def test_interpolation_potential_use_c():
    #Test the interpolation of the potential, using C to calculate the grid
    rzpot_c= potential.interpRZPotential(RZPot=potential.MWPotential,
                                         rgrid=(0.01,2.,101),
                                         zgrid=(0.,0.2,101),
                                         logR=False,
                                         interpPot=True,
                                         zsym=True,
                                         use_c=False)
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpPot=True,
                                       zsym=True,
                                       use_c=True)
    assert numpy.all(numpy.fabs(rzpot._potGrid-rzpot_c._potGrid) < 10.**-14.), \
        'Potential interpolation grid calculated with use_c does not agree with that calculated in python'
    return None

# Test evaluation outside the grid
def test_interpolation_potential_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpPot=True,
                                       zsym=False)
    rs= [0.005,2.5]
    zs= [-0.1,0.3]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot(r,z)
                               -potential.evaluatePotentials(r,z,potential.MWPotential))/potential.evaluatePotentials(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
    return None

# Test evaluation outside the grid in C
def test_interpolation_potential_outsidegrid_c():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpPot=True,
                                       zsym=False,
                                       enable_c=True)
    rs= [0.005,2.5]
    zs= [-0.1,0.3]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot(r,z)
                               -potential.evaluatePotentials(r,z,potential.MWPotential))/potential.evaluatePotentials(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
    return None

def test_interpolation_potential_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpPot=False,
                                       zsym=True)
    rs= [0.5,1.5]
    zs= [0.075,0.15]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot(r,z)
                               -potential.evaluatePotentials(r,z,potential.MWPotential))/potential.evaluatePotentials(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails when the potential was not interpolated at (R,z) = (%g,%g)' % (r,z)
    return None

# Test Rforce and zforce
def test_interpolation_potential_force():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       zgrid=(0.,0.2,201),
                                       logR=False,
                                       interpRforce=True,
                                       interpzforce=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    zs= numpy.linspace(-0.2,0.2,41)
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot.Rforce(r,z)
                               -potential.evaluateRforces(r,z,potential.MWPotential))/potential.evaluateRforces(r,z,potential.MWPotential))  < 10.**-10., 'RZPot interpolation of Rforce w/ interpRZPotential fails at (R,z) = (%g,%g)' % (r,z)
            assert numpy.fabs((rzpot.zforce(r,z)
                              -potential.evaluatezforces(r,z,potential.MWPotential))/potential.evaluateRforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of zforce w/ interpRZPotential fails at (R,z) = (%g,%g)' % (r,z)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    for r in rs:
        for z in zs:
            rforcediff= numpy.fabs((rzpot.Rforce(r,z)
                              -potential.evaluateRforces(r,z,potential.MWPotential))/potential.evaluateRforces(r,z,potential.MWPotential))
            assert rforcediff < 10.**-5., 'RZPot interpolation of Rforce w/ interpRZPotential fails at (R,z) = (%g,%g) by %g' % (r,z,rforcediff)
            zforcediff= numpy.fabs((rzpot.zforce(r,z)
                              -potential.evaluatezforces(r,z,potential.MWPotential))/potential.evaluatezforces(r,z,potential.MWPotential))
            assert zforcediff < 5.*10.**-5., 'RZPot interpolation of zforce w/ interpRZPotential fails at (R,z) = (%g,%g) by %g' % (r,z,zforcediff)
    #Test all at the same time to use vector evaluation
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       zgrid=(0.,0.2,201),
                                       interpRforce=True,interpzforce=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input, w/ logR'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       zgrid=(-0.2,0.2,301),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 4.*10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input, w/o zsym'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 4.*10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input, w/o zsym'
    #Test the interpolation of the potential, w/o zsym and with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       zgrid=(-0.2,0.2,201),
                                       interpRforce=True,interpzforce=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,20.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input w/o zsym and w/ logR'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input w/o zsym and w/ logR'
    return None

def test_interpolation_potential_force_diffinputs():
    #Test the interpolation of the potential for different inputs: combination of vector and scalar (we've already done both scalars and both vectors above)
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       zgrid=(0.,0.2,201),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       zsym=True)
    #Test all at the same time to use vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    #R vector, z scalar
    assert numpy.all(numpy.fabs((rzpot.Rforce(rs,zs[10])-potential.evaluateRforces(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential))/potential.evaluateRforces(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of of Rforce w/ interpRZPotential fails for vector R and scalar Z'
    assert numpy.all(numpy.fabs((rzpot.zforce(rs,zs[10])-potential.evaluatezforces(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential))/potential.evaluatezforces(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of of zforce w/ interpRZPotential fails for vector R and scalar Z'
    #R scalar, z vector
    assert numpy.all(numpy.fabs((rzpot.Rforce(rs[10],zs)-potential.evaluateRforces(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential))/potential.evaluateRforces(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector R and scalar Z'
    assert numpy.all(numpy.fabs((rzpot.zforce(rs[10],zs)-potential.evaluatezforces(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential))/potential.evaluatezforces(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation w/ interpRZPotential fails for vector R and scalar Z'
    return None

# Test Rforce in C
def test_interpolation_potential_force_c():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,251),
                                       zgrid=(0.,0.2,251),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       enable_c=True,
                                       zsym=True)
    #Test within the grid, using vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input, using C'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input, using C'
    #now w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,251),
                                       zgrid=(-0.2,0.2,351),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       enable_c=True,
                                       zsym=False)
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input, using C, w/o zsym'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input, using C, w/o zsym'
    #now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              351),
                                       logR= True,
                                       zgrid=(0.,0.2,251),
                                       interpRforce=True,interpzforce=True,
                                       enable_c=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,10.,20) #don't go too far
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation Rforcew/ interpRZPotential fails for vector input, using C, w/ logR'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 10.**-5.), 'RZPot interpolation zforcew/ interpRZPotential fails for vector input, using C, w/ logR'
    #now with logR and w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              351),
                                       logR= True,
                                       zgrid=(-0.2,0.2,351),
                                       interpRforce=True,interpzforce=True,
                                       enable_c=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,10.,20) #don't go too far
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input, using C, w/ logR, and w/o zsym'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 2.*10.**-5.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input, using C, w/ logR, and w/o zsym'
    return None

def test_interpolation_potential_force_c_vdiffgridsizes():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,391),
                                       zgrid=(0.,0.2,262),
                                       logR=False,
                                       interpPot=True,
                                       enable_c=True,
                                       zsym=True)
    #Test within the grid, using vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rforce(mr,mz)-potential.evaluateRforces(mr,mz,potential.MWPotential))/potential.evaluateRforces(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation of Rforce w/ interpRZPotential fails for vector input, using C'
    assert numpy.all(numpy.fabs((rzpot.zforce(mr,mz)-potential.evaluatezforces(mr,mz,potential.MWPotential))/potential.evaluatezforces(mr,mz,potential.MWPotential)) < 10.**-6.), 'RZPot interpolation of zforce w/ interpRZPotential fails for vector input, using C'
    return None

def test_interpolation_potential_force_use_c():
    #Test the interpolation of the potential, using C to calculate the grid
    rzpot_c= potential.interpRZPotential(RZPot=potential.MWPotential,
                                         rgrid=(0.01,2.,101),
                                         zgrid=(0.,0.2,101),
                                       logR=False,
                                         interpRforce=True,interpzforce=True,
                                         zsym=True,
                                         use_c=False)
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       zsym=True,
                                       use_c=True)
    assert numpy.all(numpy.fabs(rzpot._rforceGrid-rzpot_c._rforceGrid) < 10.**-14.), \
        'Potential interpolation grid of Rforce  calculated with use_c does not agree with that calculated in python'
    assert numpy.all(numpy.fabs(rzpot._zforceGrid-rzpot_c._zforceGrid) < 10.**-14.), \
        'Potential interpolation grid of zforce  calculated with use_c does not agree with that calculated in python'
    return None

# Test evaluation outside the grid
def test_interpolation_potential_force_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       zsym=False)
    rs= [0.005,2.5]
    zs= [-0.1,0.3]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot.Rforce(r,z)
                               -potential.evaluateRforces(r,z,potential.MWPotential))/potential.evaluateRforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of Rforce w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
            assert numpy.fabs((rzpot.zforce(r,z)
                               -potential.evaluatezforces(r,z,potential.MWPotential))/potential.evaluatezforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of zforce w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
    return None

# Test evaluation outside the grid in C
def test_interpolation_potential_force_outsidegrid_c():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpRforce=True,interpzforce=True,
                                       zsym=False,
                                       enable_c=True)
    rs= [0.005,2.5]
    zs= [-0.1,0.3]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot.Rforce(r,z)
                               -potential.evaluateRforces(r,z,potential.MWPotential))/potential.evaluateRforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of Rforce w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
            assert numpy.fabs((rzpot.zforce(r,z)
                               -potential.evaluatezforces(r,z,potential.MWPotential))/potential.evaluatezforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of zforce w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
    return None

def test_interpolation_potential_force_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpRforce=False,interpzforce=False,
                                       zsym=True)
    rs= [0.5,1.5]
    zs= [0.075,0.15]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot.Rforce(r,z)
                               -potential.evaluateRforces(r,z,potential.MWPotential))/potential.evaluateRforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of Rforce w/ interpRZPotential fails when the potential was not interpolated at (R,z) = (%g,%g)' % (r,z)
            assert numpy.fabs((rzpot.zforce(r,z)
                               -potential.evaluatezforces(r,z,potential.MWPotential))/potential.evaluatezforces(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of zforce w/ interpRZPotential fails when the potential was not interpolated at (R,z) = (%g,%g)' % (r,z)
    return None

# Test RZderiv, taken from the origPot, so quite trivial
def test_interpolation_potential_rzderiv():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       zsym=True)
    #Test all at the same time to use vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.Rzderiv(mr,mz)-potential.evaluateRzderivs(mr,mz,potential.MWPotential))/potential.evaluateRzderivs(mr,mz,potential.MWPotential)) < 10.**-10.), 'RZPot interpolation of Rzderiv (which is not an interpolation at all) w/ interpRZPotential fails for vector input'
    return None

# Test density
def test_interpolation_potential_dens():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       zgrid=(0.,0.2,201),
                                       logR=False,
                                       interpDens=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    zs= numpy.linspace(-0.2,0.2,41)
    for r in rs:
        for z in zs:
            densdiff= numpy.fabs((rzpot.dens(r,z)
                              -potential.evaluateDensities(r,z,potential.MWPotential))/potential.evaluateDensities(r,z,potential.MWPotential))
            assert densdiff < 10.**-10., 'RZPot interpolation of density of density w/ interpRZPotential fails at (R,z) = (%g,%g) by %g' % (r,z,densdiff)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    for r in rs:
        for z in zs:
            densdiff= numpy.fabs((rzpot.dens(r,z)
                               -potential.evaluateDensities(r,z,potential.MWPotential))/potential.evaluateDensities(r,z,potential.MWPotential))
            assert densdiff < 4.*10.**-6., 'RZPot interpolation of density w/ interpRZPotential fails at (R,z) = (%g,%g) by %g' % (r,z,densdiff)
    #Test all at the same time to use vector evaluation
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.dens(mr,mz)-potential.evaluateDensities(mr,mz,potential.MWPotential))/potential.evaluateDensities(mr,mz,potential.MWPotential)) < 4.*10.**-6.), 'RZPot interpolation of density w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              251),
                                       logR=True,
                                       zgrid=(0.,0.2,201),
                                       interpDens=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.dens(mr,mz)-potential.evaluateDensities(mr,mz,potential.MWPotential))/potential.evaluateDensities(mr,mz,potential.MWPotential)) < 4.*10.**-6.), 'RZPot interpolation of density w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, w/o zsym
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       zgrid=(-0.2,0.2,251),
                                       logR=False,
                                       interpDens=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.dens(mr,mz)-potential.evaluateDensities(mr,mz,potential.MWPotential))/potential.evaluateDensities(mr,mz,potential.MWPotential)) < 4.*10.**-6.), 'RZPot interpolation of density w/ interpRZPotential fails for vector input, w/o zsym'
    #Test the interpolation of the potential, w/o zsym and with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              251),
                                       logR=True,
                                       zgrid=(-0.2,0.2,201),
                                       interpDens=True,
                                       zsym=False)
    rs= numpy.linspace(0.01,20.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    mr,mz= numpy.meshgrid(rs,zs)
    mr= mr.flatten()
    mz= mz.flatten()
    assert numpy.all(numpy.fabs((rzpot.dens(mr,mz)-potential.evaluateDensities(mr,mz,potential.MWPotential))/potential.evaluateDensities(mr,mz,potential.MWPotential)) < 4.*10.**-6.), 'RZPot interpolation of density w/ interpRZPotential fails for vector input w/o zsym and w/ logR'
    return None

def test_interpolation_potential_dens_diffinputs():
    #Test the interpolation of the potential for different inputs: combination of vector and scalar (we've already done both scalars and both vectors above)
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       zgrid=(0.,0.2,201),
                                       logR=False,
                                       interpDens=True,
                                       zsym=True)
    #Test all at the same time to use vector evaluation
    rs= numpy.linspace(0.01,2.,20)
    zs= numpy.linspace(-0.2,0.2,40)
    #R vector, z scalar
    assert numpy.all(numpy.fabs((rzpot.dens(rs,zs[10])-potential.evaluateDensities(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential))/potential.evaluateDensities(rs,zs[10]*numpy.ones(len(rs)),potential.MWPotential)) < 4.*10.**-6.), 'RZPot interpolation of the density w/ interpRZPotential fails for vector R and scalar Z'
    #R scalar, z vector
    assert numpy.all(numpy.fabs((rzpot.dens(rs[10],zs)-potential.evaluateDensities(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential))/potential.evaluateDensities(rs[10]*numpy.ones(len(zs)),zs,potential.MWPotential)) < 4.*10.**-6.), 'RZPot interpolation of the density w/ interpRZPotential fails for vector R and scalar Z'
    return None

# Test evaluation outside the grid
def test_interpolation_potential_dens_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpDens=True,
                                       zsym=False)
    rs= [0.005,2.5]
    zs= [-0.1,0.3]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot.dens(r,z)
                               -potential.evaluateDensities(r,z,potential.MWPotential))/potential.evaluateDensities(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of the density w/ interpRZPotential fails outside the grid at (R,z) = (%g,%g)' % (r,z)
    return None

def test_interpolation_potential_density_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,101),
                                       zgrid=(0.,0.2,101),
                                       logR=False,
                                       interpDens=False,
                                       zsym=True)
    rs= [0.5,1.5]
    zs= [0.075,0.15]
    for r in rs:
        for z in zs:
            assert numpy.fabs((rzpot.dens(r,z)
                               -potential.evaluateDensities(r,z,potential.MWPotential))/potential.evaluateDensities(r,z,potential.MWPotential)) < 10.**-10., 'RZPot interpolation of the density w/ interpRZPotential fails when the potential was not interpolated at (R,z) = (%g,%g)' % (r,z)
    return None

# Test the circular velocity
def test_interpolation_potential_vcirc():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpvcirc=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    for r in rs:
        assert numpy.fabs((rzpot.vcirc(r)
                           -potential.vcirc(potential.MWPotential,r))/potential.vcirc(potential.MWPotential,r)) < 10.**-10., 'RZPot interpolation of vcirc w/ interpRZPotential fails at R = %g' % (r)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    for r in rs:
        vcdiff= numpy.fabs((rzpot.vcirc(r)
                            -potential.vcirc(potential.MWPotential,r))/potential.vcirc(potential.MWPotential,r))
        assert vcdiff < 10.**-6., 'RZPot interpolation of vcirc w/ interpRZPotential fails at R = %g by %g' % (r,vcdiff)
    #Test all at the same time to use vector evaluation
    assert numpy.all(numpy.fabs((rzpot.vcirc(rs)-potential.vcirc(potential.MWPotential,rs))/potential.vcirc(potential.MWPotential,rs)) < 10.**-6.), 'RZPot interpolation of vcirc w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       interpvcirc=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    assert numpy.all(numpy.fabs((rzpot.vcirc(rs)-potential.vcirc(potential.MWPotential,rs))/potential.vcirc(potential.MWPotential,rs)) < 10.**-6.), 'RZPot interpolation of vcirc w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, with numcores
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpvcirc=True,
                                       numcores=1,
                                       zsym=True)
    rs= numpy.linspace(0.01,2.,20)
    assert numpy.all(numpy.fabs((rzpot.vcirc(rs)-potential.vcirc(potential.MWPotential,rs))/potential.vcirc(potential.MWPotential,rs)) < 10.**-6.), 'RZPot interpolation of vcirc w/ interpRZPotential fails for vector input'
    return None

# Test evaluation outside the grid
def test_interpolation_potential_vcirc_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpvcirc=True,
                                       zsym=False)
    rs= [0.005,2.5]
    for r in rs:
        vcdiff= numpy.fabs((rzpot.vcirc(r)
                            -potential.vcirc(potential.MWPotential,r))/potential.vcirc(potential.MWPotential,r))
        assert vcdiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails outside the grid at R = %g by %g' % (r,vcdiff)
    return None

def test_interpolation_potential_vcirc_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpvcirc=False,
                                       zsym=True)
    rs= [0.5,1.5]
    for r in rs:
        vcdiff= numpy.fabs((rzpot.vcirc(r)
                               -potential.vcirc(potential.MWPotential,r))/potential.vcirc(potential.MWPotential,r))
        assert vcdiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails when the potential was not interpolated at R = %g by %g' % (r,vcdiff)
    return None

# Test dvcircdR
def test_interpolation_potential_dvcircdR():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpdvcircdr=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    for r in rs:
        assert numpy.fabs((rzpot.dvcircdR(r)
                           -potential.dvcircdR(potential.MWPotential,r))/potential.dvcircdR(potential.MWPotential,r)) < 10.**-10., 'RZPot interpolation of dvcircdR w/ interpRZPotential fails at R = %g' % (r)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    for r in rs:
        dvcdrdiff= numpy.fabs((rzpot.dvcircdR(r)
                            -potential.dvcircdR(potential.MWPotential,r))/potential.dvcircdR(potential.MWPotential,r))
        assert dvcdrdiff < 10.**-5., 'RZPot interpolation of dvcircdR w/ interpRZPotential fails at R = %g by %g' % (r,dvcdrdiff)
    #Test all at the same time to use vector evaluation
    assert numpy.all(numpy.fabs((rzpot.dvcircdR(rs)-potential.dvcircdR(potential.MWPotential,rs))/potential.dvcircdR(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of dvcircdR w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       interpdvcircdr=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    assert numpy.all(numpy.fabs((rzpot.dvcircdR(rs)-potential.dvcircdR(potential.MWPotential,rs))/potential.dvcircdR(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of dvcircdR w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, with numcores
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpdvcircdr=True,
                                       numcores=1,
                                       zsym=True)
    rs= numpy.linspace(0.01,2.,20)
    assert numpy.all(numpy.fabs((rzpot.dvcircdR(rs)-potential.dvcircdR(potential.MWPotential,rs))/potential.dvcircdR(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of dvcircdR w/ interpRZPotential fails for vector input'
    return None

# Test evaluation outside the grid
def test_interpolation_potential_dvcircdR_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpdvcircdr=True,
                                       zsym=False)
    rs= [0.005,2.5]
    for r in rs:
        dvcdrdiff= numpy.fabs((rzpot.dvcircdR(r)
                               -potential.dvcircdR(potential.MWPotential,r))/potential.dvcircdR(potential.MWPotential,r))
        assert dvcdrdiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails outside the grid at R = %g by %g' % (r,dvcdrdiff)
    return None

def test_interpolation_potential_dvcircdR_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpdvcircdr=False,
                                       zsym=True)
    rs= [0.5,1.5]
    for r in rs:
        dvcdrdiff= numpy.fabs((rzpot.dvcircdR(r)
                               -potential.dvcircdR(potential.MWPotential,r))/potential.dvcircdR(potential.MWPotential,r))
        assert dvcdrdiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails when the potential was not interpolated at R = %g by %g' % (r,dvcdrdiff)
    return None

# Test epifreq
def test_interpolation_potential_epifreq():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpepifreq=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    for r in rs:
        assert numpy.fabs((rzpot.epifreq(r)
                           -potential.epifreq(potential.MWPotential,r))/potential.epifreq(potential.MWPotential,r)) < 10.**-10., 'RZPot interpolation of epifreq w/ interpRZPotential fails at R = %g' % (r)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    for r in rs:
        epidiff= numpy.fabs((rzpot.epifreq(r)
                            -potential.epifreq(potential.MWPotential,r))/potential.epifreq(potential.MWPotential,r))
        assert epidiff < 10.**-5., 'RZPot interpolation of epifreq w/ interpRZPotential fails at R = %g by %g' % (r,epidiff)
    #Test all at the same time to use vector evaluation
    assert numpy.all(numpy.fabs((rzpot.epifreq(rs)-potential.epifreq(potential.MWPotential,rs))/potential.epifreq(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of epifreq w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       interpepifreq=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    assert numpy.all(numpy.fabs((rzpot.epifreq(rs)-potential.epifreq(potential.MWPotential,rs))/potential.epifreq(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of epifreq w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, with numcores
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpepifreq=True,
                                       numcores=1,
                                       zsym=True)
    rs= numpy.linspace(0.01,2.,20)
    assert numpy.all(numpy.fabs((rzpot.epifreq(rs)-potential.epifreq(potential.MWPotential,rs))/potential.epifreq(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of epifreq w/ interpRZPotential fails for vector input'
    return None

# Test epifreq setup when the number of r points is small
def test_interpolation_potential_epifreq_smalln():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(1.,1.3,3),
                                       logR=False,
                                       interpepifreq=True,
                                       zsym=False)
    rs= numpy.linspace(1.1,1.2,20)
    assert numpy.all(numpy.fabs((rzpot.epifreq(rs)-potential.epifreq(potential.MWPotential,rs))/potential.epifreq(potential.MWPotential,rs)) < 10.**-2.), 'RZPot interpolation of epifreq w/ interpRZPotential fails for vector input' #not as harsh, bc we don't have many points
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(1.),numpy.log(1.3),3),
                                       logR=True,
                                       interpepifreq=True,
                                       zsym=False)
    rs= numpy.linspace(1.1,1.2,20)
    assert numpy.all(numpy.fabs((rzpot.epifreq(rs)-potential.epifreq(potential.MWPotential,rs))/potential.epifreq(potential.MWPotential,rs)) < 10.**-2.), 'RZPot interpolation of epifreq w/ interpRZPotential fails for vector input' #not as harsh, bc we don't have many points
    return None

# Test evaluation outside the grid
def test_interpolation_potential_epifreq_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpepifreq=True,
                                       zsym=False)
    rs= [0.005,2.5]
    for r in rs:
        epidiff= numpy.fabs((rzpot.epifreq(r)
                               -potential.epifreq(potential.MWPotential,r))/potential.epifreq(potential.MWPotential,r))
        assert epidiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails outside the grid at R = %g by %g' % (r,epidiff)
    return None

def test_interpolation_potential_epifreq_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpepifreq=False,
                                       zsym=True)
    rs= [0.5,1.5]
    for r in rs:
        epidiff= numpy.fabs((rzpot.epifreq(r)
                               -potential.epifreq(potential.MWPotential,r))/potential.epifreq(potential.MWPotential,r))
        assert epidiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails when the potential was not interpolated at R = %g by %g' % (r,epidiff)
    return None

# Test verticalfreq
def test_interpolation_potential_verticalfreq():
    #Test the interpolation of the potential
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpverticalfreq=True,
                                       zsym=True)
    #This just tests on the grid
    rs= numpy.linspace(0.01,2.,21)
    for r in rs:
        assert numpy.fabs((rzpot.verticalfreq(r)
                           -potential.verticalfreq(potential.MWPotential,r))/potential.verticalfreq(potential.MWPotential,r)) < 10.**-10., 'RZPot interpolation of verticalfreq w/ interpRZPotential fails at R = %g' % (r)
    #This tests within the grid
    rs= numpy.linspace(0.01,2.,20)
    for r in rs:
        vfdiff= numpy.fabs((rzpot.verticalfreq(r)
                            -potential.verticalfreq(potential.MWPotential,r))/potential.verticalfreq(potential.MWPotential,r))
        assert vfdiff < 10.**-5., 'RZPot interpolation of verticalfreq w/ interpRZPotential fails at R = %g by %g' % (r,vfdiff)
    #Test all at the same time to use vector evaluation
    assert numpy.all(numpy.fabs((rzpot.verticalfreq(rs)-potential.verticalfreq(potential.MWPotential,rs))/potential.verticalfreq(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of verticalfreq w/ interpRZPotential fails for vector input'
    #Test the interpolation of the potential, now with logR
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(numpy.log(0.01),numpy.log(20.),
                                              201),
                                       logR=True,
                                       interpverticalfreq=True,
                                       zsym=True)
    rs= numpy.linspace(0.01,20.,20)
    assert numpy.all(numpy.fabs((rzpot.verticalfreq(rs)-potential.verticalfreq(potential.MWPotential,rs))/potential.verticalfreq(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of verticalfreq w/ interpRZPotential fails for vector input, w/ logR'
    #Test the interpolation of the potential, with numcores
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpverticalfreq=True,
                                       numcores=1,
                                       zsym=True)
    rs= numpy.linspace(0.01,2.,20)
    assert numpy.all(numpy.fabs((rzpot.verticalfreq(rs)-potential.verticalfreq(potential.MWPotential,rs))/potential.verticalfreq(potential.MWPotential,rs)) < 10.**-5.), 'RZPot interpolation of verticalfreq w/ interpRZPotential fails for vector input'
    return None

# Test evaluation outside the grid
def test_interpolation_potential_verticalfreq_outsidegrid():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpverticalfreq=True,
                                       zsym=False)
    rs= [0.005,2.5]
    for r in rs:
        vfdiff= numpy.fabs((rzpot.verticalfreq(r)
                               -potential.verticalfreq(potential.MWPotential,r))/potential.verticalfreq(potential.MWPotential,r))
        assert vfdiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails outside the grid at R = %g by %g' % (r,vfdiff)
    return None

def test_interpolation_potential_verticalfreq_notinterpolated():
    rzpot= potential.interpRZPotential(RZPot=potential.MWPotential,
                                       rgrid=(0.01,2.,201),
                                       logR=False,
                                       interpverticalfreq=False,
                                       zsym=True)
    rs= [0.5,1.5]
    for r in rs:
        vfdiff= numpy.fabs((rzpot.verticalfreq(r)
                               -potential.verticalfreq(potential.MWPotential,r))/potential.verticalfreq(potential.MWPotential,r))
        assert vfdiff < 10.**-10., 'RZPot interpolation w/ interpRZPotential fails when the potential was not interpolated at R = %g by %g' % (r,vfdiff)
    return None

max_stars_repo_name: fardal/galpy

max_issues_repo_name: fardal/galpy

max_forks_repo_name: fardal/galpy


text:
#!/usr/bin/env python3

import cv2
import numpy as np
import tensorflow as tf
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge
from scipy.special import softmax

def draw_text(text, bgcolor, plt_ax, text_plt):
    """
    Render the text
    :param str text: text to render
    :param str bgcolor: backgroundcolor used to render text
    :param matplotlib.axes.Axes plt_ax: figure sub plot instance
    :param matplotlib.text.Text text_plt: plot of text
    :return matplotlib.text.Text: updated plot of text
    """

    if text_plt is None:
        # render text with color
        text_plt = plt_ax.text(0.95, 0.95, text, backgroundcolor=bgcolor,
                        horizontalalignment='right', verticalalignment='top',
                        transform=plt_ax.transAxes, fontsize=10)
    else:
        # update existing text
        text_plt.set_text(text)

    return text_plt

def draw_floor_map(floor_map, map_shape, plt_ax, map_plt, cmap='gray'):
    """
    Render the scene floor map
    :param ndarray floor_map: environment scene floor map
    :param ndarray map_shape: (unpadded) map shape [H, W, C]
    :param matplotlib.axes.Axes plt_ax: figure sub plot instance
    :return matplotlib.image.AxesImage: updated plot of scene floor map
    """

    H, W = map_shape[:2]
    origin_x, origin_y = W/2, H/2
    if map_plt is None:
        # draw floor map
        map_plt = plt_ax.imshow(floor_map[:H, :W], cmap=cmap)
        plt.scatter(origin_x, origin_y, s=10, c='black', marker='x', alpha=1)
    else:
        map_plt.set_data(floor_map[:H, :W])
    return map_plt

def draw_particles_pose(particles, weights, map_shape, particles_plt, scale=1):
    """
    Render the particle poses on the scene floor map
    :param ndarray particles: estimates of particle pose
    :param ndarray weights: corresponding weights of particle pose estimates
    :param tuple map_shape: [height, width, channel] of the map the co-ordinated need to be transformed
    :param matplotlib.collections.PathCollection: plot of particle position color coded according to weights
    :param scale: integer rescaling value
    :return matplotlib.collections.PathCollection: updated plot of particles
    """

    part_col, part_row, part_th = tf.unstack(particles, axis=-1, num=3)   # (k, 3)
    height, width, channel = map_shape

    # HACK: display particles alpha proprtional to their weights
    lin_weights = softmax(weights)
    th = 0 # np.mean(lin_weights)
    alphas = np.where(lin_weights >= th, 1, 0) * lin_weights
    alphas = alphas/np.max(alphas)

    rgba_colors = cm.rainbow(weights-np.min(weights))
    rgba_colors[:, 3] = alphas

    if particles_plt is None:
        # render particles positions with color
        particles_plt = plt.scatter(part_col, part_row, s=10, c=rgba_colors)
    else:
        # update existing particles positions and color
        particles_plt.set_offsets(tf.stack([part_col, part_row], axis=-1))
        particles_plt.set_color(rgba_colors)

    return particles_plt

def draw_robot_pose(robot_pose, color, map_shape, plt_ax, position_plt, heading_plt, plt_path=False, scale=1):
    """
    Render the robot pose on the scene floor map
    :param ndarray robot_pose: ndarray representing robot position (x, y) and heading (theta)
    :param str color: color used to render robot position and heading
    :param tuple map_shape: [height, width, channel] of the map the co-ordinated need to be transformed
    :param matplotlib.axes.Axes plt_ax: figure sub plot instance
    :param matplotlib.patches.Wedge position_plt: plot of robot position
    :param matplotlib.lines.Line2D heading_plt: plot of robot heading
    :param scale: integer rescaling value
    :return tuple(matplotlib.patches.Wedge, matplotlib.lines.Line2D): updated position and heading plot of robot
    """

    col, row, heading = robot_pose
    height, width, channel = map_shape

    heading_len  = robot_radius = 10.0
    xdata = [col, col + (robot_radius + heading_len) * np.cos(heading)]
    ydata = [row, row + (robot_radius + heading_len) * np.sin(heading)]

    if position_plt == None:
        # render robot position and heading with color
        position_plt = Wedge((col, row), robot_radius, 0, 360, color=color, alpha=0.5)
        plt_ax.add_artist(position_plt)
        heading_plt, = plt_ax.plot(xdata, ydata, color=color, alpha=0.5)
    else:
        # update existing robot position and heading
        position_plt.update({'center': [col, row]})
        heading_plt.update({'xdata': xdata, 'ydata': ydata})
    if plt_path is True:
        plt_ax.arrow(xdata[0], ydata[0], (xdata[1]-xdata[0]), (ydata[1]-ydata[0]), head_width=0.5, head_length=0.7, fc='brown', ec='brown')

    return position_plt, heading_plt

reason: import numpy,from scipy


text:
import os
import glob
import math
import random

import numpy as np

import scann
import tensorflow as tf

random.seed(17)

# Build dict mapping image ids to their paths.
def load_image_id_paths_map(images_dir):
  dir_prefix = os.path.join(os.getcwd(), images_dir)
  image_paths = []
  for ext in ['*.png', '*.jpg', '*.jpeg', '*.JPEG', '*.PNG', '*.JPG']:
    image_paths.extend(glob.glob(os.path.join(dir_prefix, ext)))
  return {idx: path for idx, path in enumerate(image_paths)}

# Build dict mapping image ids to PIL image instances.
def load_image_id_pil_map(image_id_paths_map, image_size):
  map = dict()

  for k in sorted(image_id_paths_map.keys()):
    map.update({k: tf.keras.preprocessing.image.load_img(
                        path=image_id_paths_map[k],
                        target_size=image_size,
                        interpolation='bilinear'
                     )
               })

  return map

# Normalize an image array to the following range: [0, 1].
def normalize_img_arr(arr):
  return tf.keras.utils.normalize(arr, axis=-1, order=2)

# Build dict mapping image ids to image arrays.
def load_image_id_arr_map(image_id_pil_map):
  map = dict()

  for k in sorted(image_id_pil_map.keys()):
    img_arr = tf.keras.preprocessing.image.img_to_array(image_id_pil_map[k])
    norm_img_arr = normalize_img_arr(img_arr)
    map.update({k: norm_img_arr})

  return map

# Build dict mapping image ids to embeddings.
def load_image_id_embedding_map(model, image_id_arr_map):
  map = dict()
  inputs = []
  for k in sorted(image_id_arr_map.keys()):
    inputs.append(image_id_arr_map[k])

  batched_img_arrs = np.array(inputs)
  predictions = model.predict(batched_img_arrs)
  for idx, embedding in enumerate(predictions):
    map.update({idx: embedding})

  return map

# Build a ScaNN index for later ANN lookups.
def load_search_engine(corpus_image_embeddings, num_results, similarity_function="dot_product"):
  dataset = np.array(list(corpus_image_embeddings))
  num_leaves = int(math.sqrt(len(corpus_image_embeddings)))

  search_engine = scann.scann_ops_pybind.builder(dataset, num_results, similarity_function).score_brute_force().build()
  return search_engine

def image_path_to_arr(image_path, image_size):
  pil_image = tf.keras.preprocessing.image.load_img(
                    path=image_path,
                    target_size=image_size,
                    interpolation='bilinear'
                  )
  img_arr = tf.keras.preprocessing.image.img_to_array(pil_image)
  norm_img_arr = normalize_img_arr(img_arr)

  return norm_img_arr

def rand():
  return np.base_repr(int(str(random.random())[2:]), 36).lower()

def generate_token():
  return rand()+rand()

max_stars_repo_name: ashaltu/crier

max_issues_repo_name: ashaltu/crier

max_forks_repo_name: ashaltu/crier