Finding minimual spatial distance












1















The task is to find such a dot with a (x,0) coordinates, that the distance from it to the most distant point from the original set (distance is Euclidean) is minimal.
My idea is to find the minimum of the function that finds an euclidean distance like this:



import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import minimize

def function_3(points_x, points_y):
dots = np.array([points_x,points_y])
ans = minimize(cdist(dots,points1),x0=0)
return(ans)


But it seems like that I'm doing something wrong... Can somebody give an advice?










share|improve this question




















  • 1





    Why do you think something is wrong? ("Because it does not work" may seem a valid answer but we need a bit more than that. Please do not answer in comments; edit your question to add all missing information.)

    – usr2564301
    Nov 25 '18 at 9:56











  • You're mostly on the right track, but your basic problem is down to syntax/formulation of the arguments for minimize (and possibly also cdist as well). The first argument to minimize needs to be a function that meets a few specific requirements. See my answer below for details

    – tel
    Nov 25 '18 at 10:34
















1















The task is to find such a dot with a (x,0) coordinates, that the distance from it to the most distant point from the original set (distance is Euclidean) is minimal.
My idea is to find the minimum of the function that finds an euclidean distance like this:



import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import minimize

def function_3(points_x, points_y):
dots = np.array([points_x,points_y])
ans = minimize(cdist(dots,points1),x0=0)
return(ans)


But it seems like that I'm doing something wrong... Can somebody give an advice?










share|improve this question




















  • 1





    Why do you think something is wrong? ("Because it does not work" may seem a valid answer but we need a bit more than that. Please do not answer in comments; edit your question to add all missing information.)

    – usr2564301
    Nov 25 '18 at 9:56











  • You're mostly on the right track, but your basic problem is down to syntax/formulation of the arguments for minimize (and possibly also cdist as well). The first argument to minimize needs to be a function that meets a few specific requirements. See my answer below for details

    – tel
    Nov 25 '18 at 10:34














1












1








1


0






The task is to find such a dot with a (x,0) coordinates, that the distance from it to the most distant point from the original set (distance is Euclidean) is minimal.
My idea is to find the minimum of the function that finds an euclidean distance like this:



import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import minimize

def function_3(points_x, points_y):
dots = np.array([points_x,points_y])
ans = minimize(cdist(dots,points1),x0=0)
return(ans)


But it seems like that I'm doing something wrong... Can somebody give an advice?










share|improve this question
















The task is to find such a dot with a (x,0) coordinates, that the distance from it to the most distant point from the original set (distance is Euclidean) is minimal.
My idea is to find the minimum of the function that finds an euclidean distance like this:



import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import minimize

def function_3(points_x, points_y):
dots = np.array([points_x,points_y])
ans = minimize(cdist(dots,points1),x0=0)
return(ans)


But it seems like that I'm doing something wrong... Can somebody give an advice?







python numpy scipy minimize scipy-spatial






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 9:55









usr2564301

17.8k73370




17.8k73370










asked Nov 25 '18 at 9:40









nutcrackernutcracker

133




133








  • 1





    Why do you think something is wrong? ("Because it does not work" may seem a valid answer but we need a bit more than that. Please do not answer in comments; edit your question to add all missing information.)

    – usr2564301
    Nov 25 '18 at 9:56











  • You're mostly on the right track, but your basic problem is down to syntax/formulation of the arguments for minimize (and possibly also cdist as well). The first argument to minimize needs to be a function that meets a few specific requirements. See my answer below for details

    – tel
    Nov 25 '18 at 10:34














  • 1





    Why do you think something is wrong? ("Because it does not work" may seem a valid answer but we need a bit more than that. Please do not answer in comments; edit your question to add all missing information.)

    – usr2564301
    Nov 25 '18 at 9:56











  • You're mostly on the right track, but your basic problem is down to syntax/formulation of the arguments for minimize (and possibly also cdist as well). The first argument to minimize needs to be a function that meets a few specific requirements. See my answer below for details

    – tel
    Nov 25 '18 at 10:34








1




1





Why do you think something is wrong? ("Because it does not work" may seem a valid answer but we need a bit more than that. Please do not answer in comments; edit your question to add all missing information.)

– usr2564301
Nov 25 '18 at 9:56





Why do you think something is wrong? ("Because it does not work" may seem a valid answer but we need a bit more than that. Please do not answer in comments; edit your question to add all missing information.)

– usr2564301
Nov 25 '18 at 9:56













You're mostly on the right track, but your basic problem is down to syntax/formulation of the arguments for minimize (and possibly also cdist as well). The first argument to minimize needs to be a function that meets a few specific requirements. See my answer below for details

– tel
Nov 25 '18 at 10:34





You're mostly on the right track, but your basic problem is down to syntax/formulation of the arguments for minimize (and possibly also cdist as well). The first argument to minimize needs to be a function that meets a few specific requirements. See my answer below for details

– tel
Nov 25 '18 at 10:34












1 Answer
1






active

oldest

votes


















2














Solution



Here's a complete working example for fitting points of the form (x, 0):



from scipy.spatial.distance import cdist
from scipy.optimize import minimize

# set up a test set of 100 points to fit against
n = 100
xyTestset = np.random.rand(n,2)*10

def fun(x, xycomp):
# x is a vector, assumed to be of size 1
# cdist expects a 2D array, so we reshape xy into a 1x2 array
xy = np.array((x[0], 0)).reshape(1, -1)
return cdist(xy, xycomp).max()

fit = minimize(fun, x0=0, args=xyTestset)
print(fit.x)


which outputs:



[5.06807808]


This means, roughly speaking, that the minimization is finding the centroid of the set of random test points, as expected. If you wanted to do a 2D fitting to points of the form (x, y) instead, you can do:



from scipy.spatial.distance import cdist
from scipy.optimize import minimize

# set up a test set of 100 points to fit against
n = 100
xyTestset = np.random.rand(n,2)*10

def fun(x, xycomp):
# x is a vector, assumed to be of size 2
return cdist(x.reshape(1, -1), xycomp).max()

fit = minimize(fun, x0=(0, 0), args=xyTestset)
print(fit.x)


which outputs:



[5.21292828 5.01491085]


which, again, is roughly the centroid of the 100 random points in xyTestset, as you'd expect.



Complete explanation



The problem that you're running into is that scipy.optimize.minimize has very specific expectations about the form of its first argument fun. fun is supposed to be a function that takes x as its first argument, where x is a 1D vector of the values to be minimized over. fun can also take additional arguments. These have to be passed into minimize via the args parameter, and their values are constant (ie they won't change over the course of the minimization).



Also, you should be aware that your case of fitting (x, 0) can be simplified. It's effectively a 1D problem, so you all you need to do is calculate the x distances between the points. You can completely ignore the y distances and still get the same results.



Additionally, you don't need a minimization to solve the problem you stated. The point that minimizes the distance to the farthest point (which is the same as saying "minimizing the distance to all points") is the centroid. The coordinates of the centroid are the means of each coordinate in your set of points, so if your points are stored in an Nx2 array xydata you can calculate the centroid by just doing:



xydata.mean(axis=1)





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466262%2ffinding-minimual-spatial-distance%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Solution



    Here's a complete working example for fitting points of the form (x, 0):



    from scipy.spatial.distance import cdist
    from scipy.optimize import minimize

    # set up a test set of 100 points to fit against
    n = 100
    xyTestset = np.random.rand(n,2)*10

    def fun(x, xycomp):
    # x is a vector, assumed to be of size 1
    # cdist expects a 2D array, so we reshape xy into a 1x2 array
    xy = np.array((x[0], 0)).reshape(1, -1)
    return cdist(xy, xycomp).max()

    fit = minimize(fun, x0=0, args=xyTestset)
    print(fit.x)


    which outputs:



    [5.06807808]


    This means, roughly speaking, that the minimization is finding the centroid of the set of random test points, as expected. If you wanted to do a 2D fitting to points of the form (x, y) instead, you can do:



    from scipy.spatial.distance import cdist
    from scipy.optimize import minimize

    # set up a test set of 100 points to fit against
    n = 100
    xyTestset = np.random.rand(n,2)*10

    def fun(x, xycomp):
    # x is a vector, assumed to be of size 2
    return cdist(x.reshape(1, -1), xycomp).max()

    fit = minimize(fun, x0=(0, 0), args=xyTestset)
    print(fit.x)


    which outputs:



    [5.21292828 5.01491085]


    which, again, is roughly the centroid of the 100 random points in xyTestset, as you'd expect.



    Complete explanation



    The problem that you're running into is that scipy.optimize.minimize has very specific expectations about the form of its first argument fun. fun is supposed to be a function that takes x as its first argument, where x is a 1D vector of the values to be minimized over. fun can also take additional arguments. These have to be passed into minimize via the args parameter, and their values are constant (ie they won't change over the course of the minimization).



    Also, you should be aware that your case of fitting (x, 0) can be simplified. It's effectively a 1D problem, so you all you need to do is calculate the x distances between the points. You can completely ignore the y distances and still get the same results.



    Additionally, you don't need a minimization to solve the problem you stated. The point that minimizes the distance to the farthest point (which is the same as saying "minimizing the distance to all points") is the centroid. The coordinates of the centroid are the means of each coordinate in your set of points, so if your points are stored in an Nx2 array xydata you can calculate the centroid by just doing:



    xydata.mean(axis=1)





    share|improve this answer






























      2














      Solution



      Here's a complete working example for fitting points of the form (x, 0):



      from scipy.spatial.distance import cdist
      from scipy.optimize import minimize

      # set up a test set of 100 points to fit against
      n = 100
      xyTestset = np.random.rand(n,2)*10

      def fun(x, xycomp):
      # x is a vector, assumed to be of size 1
      # cdist expects a 2D array, so we reshape xy into a 1x2 array
      xy = np.array((x[0], 0)).reshape(1, -1)
      return cdist(xy, xycomp).max()

      fit = minimize(fun, x0=0, args=xyTestset)
      print(fit.x)


      which outputs:



      [5.06807808]


      This means, roughly speaking, that the minimization is finding the centroid of the set of random test points, as expected. If you wanted to do a 2D fitting to points of the form (x, y) instead, you can do:



      from scipy.spatial.distance import cdist
      from scipy.optimize import minimize

      # set up a test set of 100 points to fit against
      n = 100
      xyTestset = np.random.rand(n,2)*10

      def fun(x, xycomp):
      # x is a vector, assumed to be of size 2
      return cdist(x.reshape(1, -1), xycomp).max()

      fit = minimize(fun, x0=(0, 0), args=xyTestset)
      print(fit.x)


      which outputs:



      [5.21292828 5.01491085]


      which, again, is roughly the centroid of the 100 random points in xyTestset, as you'd expect.



      Complete explanation



      The problem that you're running into is that scipy.optimize.minimize has very specific expectations about the form of its first argument fun. fun is supposed to be a function that takes x as its first argument, where x is a 1D vector of the values to be minimized over. fun can also take additional arguments. These have to be passed into minimize via the args parameter, and their values are constant (ie they won't change over the course of the minimization).



      Also, you should be aware that your case of fitting (x, 0) can be simplified. It's effectively a 1D problem, so you all you need to do is calculate the x distances between the points. You can completely ignore the y distances and still get the same results.



      Additionally, you don't need a minimization to solve the problem you stated. The point that minimizes the distance to the farthest point (which is the same as saying "minimizing the distance to all points") is the centroid. The coordinates of the centroid are the means of each coordinate in your set of points, so if your points are stored in an Nx2 array xydata you can calculate the centroid by just doing:



      xydata.mean(axis=1)





      share|improve this answer




























        2












        2








        2







        Solution



        Here's a complete working example for fitting points of the form (x, 0):



        from scipy.spatial.distance import cdist
        from scipy.optimize import minimize

        # set up a test set of 100 points to fit against
        n = 100
        xyTestset = np.random.rand(n,2)*10

        def fun(x, xycomp):
        # x is a vector, assumed to be of size 1
        # cdist expects a 2D array, so we reshape xy into a 1x2 array
        xy = np.array((x[0], 0)).reshape(1, -1)
        return cdist(xy, xycomp).max()

        fit = minimize(fun, x0=0, args=xyTestset)
        print(fit.x)


        which outputs:



        [5.06807808]


        This means, roughly speaking, that the minimization is finding the centroid of the set of random test points, as expected. If you wanted to do a 2D fitting to points of the form (x, y) instead, you can do:



        from scipy.spatial.distance import cdist
        from scipy.optimize import minimize

        # set up a test set of 100 points to fit against
        n = 100
        xyTestset = np.random.rand(n,2)*10

        def fun(x, xycomp):
        # x is a vector, assumed to be of size 2
        return cdist(x.reshape(1, -1), xycomp).max()

        fit = minimize(fun, x0=(0, 0), args=xyTestset)
        print(fit.x)


        which outputs:



        [5.21292828 5.01491085]


        which, again, is roughly the centroid of the 100 random points in xyTestset, as you'd expect.



        Complete explanation



        The problem that you're running into is that scipy.optimize.minimize has very specific expectations about the form of its first argument fun. fun is supposed to be a function that takes x as its first argument, where x is a 1D vector of the values to be minimized over. fun can also take additional arguments. These have to be passed into minimize via the args parameter, and their values are constant (ie they won't change over the course of the minimization).



        Also, you should be aware that your case of fitting (x, 0) can be simplified. It's effectively a 1D problem, so you all you need to do is calculate the x distances between the points. You can completely ignore the y distances and still get the same results.



        Additionally, you don't need a minimization to solve the problem you stated. The point that minimizes the distance to the farthest point (which is the same as saying "minimizing the distance to all points") is the centroid. The coordinates of the centroid are the means of each coordinate in your set of points, so if your points are stored in an Nx2 array xydata you can calculate the centroid by just doing:



        xydata.mean(axis=1)





        share|improve this answer















        Solution



        Here's a complete working example for fitting points of the form (x, 0):



        from scipy.spatial.distance import cdist
        from scipy.optimize import minimize

        # set up a test set of 100 points to fit against
        n = 100
        xyTestset = np.random.rand(n,2)*10

        def fun(x, xycomp):
        # x is a vector, assumed to be of size 1
        # cdist expects a 2D array, so we reshape xy into a 1x2 array
        xy = np.array((x[0], 0)).reshape(1, -1)
        return cdist(xy, xycomp).max()

        fit = minimize(fun, x0=0, args=xyTestset)
        print(fit.x)


        which outputs:



        [5.06807808]


        This means, roughly speaking, that the minimization is finding the centroid of the set of random test points, as expected. If you wanted to do a 2D fitting to points of the form (x, y) instead, you can do:



        from scipy.spatial.distance import cdist
        from scipy.optimize import minimize

        # set up a test set of 100 points to fit against
        n = 100
        xyTestset = np.random.rand(n,2)*10

        def fun(x, xycomp):
        # x is a vector, assumed to be of size 2
        return cdist(x.reshape(1, -1), xycomp).max()

        fit = minimize(fun, x0=(0, 0), args=xyTestset)
        print(fit.x)


        which outputs:



        [5.21292828 5.01491085]


        which, again, is roughly the centroid of the 100 random points in xyTestset, as you'd expect.



        Complete explanation



        The problem that you're running into is that scipy.optimize.minimize has very specific expectations about the form of its first argument fun. fun is supposed to be a function that takes x as its first argument, where x is a 1D vector of the values to be minimized over. fun can also take additional arguments. These have to be passed into minimize via the args parameter, and their values are constant (ie they won't change over the course of the minimization).



        Also, you should be aware that your case of fitting (x, 0) can be simplified. It's effectively a 1D problem, so you all you need to do is calculate the x distances between the points. You can completely ignore the y distances and still get the same results.



        Additionally, you don't need a minimization to solve the problem you stated. The point that minimizes the distance to the farthest point (which is the same as saying "minimizing the distance to all points") is the centroid. The coordinates of the centroid are the means of each coordinate in your set of points, so if your points are stored in an Nx2 array xydata you can calculate the centroid by just doing:



        xydata.mean(axis=1)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 25 '18 at 10:50

























        answered Nov 25 '18 at 10:09









        teltel

        7,41621431




        7,41621431
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466262%2ffinding-minimual-spatial-distance%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            Refactoring coordinates for Minecraft Pi buildings written in Python