Implementation of a threshold detection function in Python











up vote
2
down vote

favorite












I want to implement following trigger function in Python:



Input:




  • time vector t [n dimensional numpy vector]

  • data vector y [n dimensional numpy vector] (values correspond to t vector)

  • threshold tr [float]

  • Threshold type vector tr_type [m dimensional list of int values]


Output:




  • Threshold time vector tr_time [m dimensional list of float values]


Function:



I would like to return tr_time which consists of the exact (preffered also interpolated which is not yet in code below) time values at which y is crossing tr (crossing means going from less then to greater then or the other way around). The different values in tr_time correspond to the tr_type vector: the elements of tr_type indicate the number of the crossing and if this is an upgoing or a downgoing crossing. For example 1 means first time y goes from less then tr to greater than tr, -3 means the third time y goes from greater then tr to less then tr (third time means along the time vector t)



For the moment I have next code:



import numpy as np
import matplotlib.pyplot as plt


def trigger(t, y, tr, tr_type):
triggermarker = np.diff(1 * (y > tr))
positiveindices = [i for i, x in enumerate(triggermarker) if x == 1]
negativeindices = [i for i, x in enumerate(triggermarker) if x == -1]
triggertime =
for i in tr_type:
if i >= 0:
triggertime.append(t[positiveindices[i - 1]])
elif i < 0:
triggertime.append(t[negativeindices[i - 1]])
return triggertime


t = np.linspace(0, 20, 1000)
y = np.sin(t)
tr = 0.5
tr_type = [1, 2, -2]
print(trigger(t, y, tr, tr_type))
plt.plot(t, y)
plt.grid()


Now I'm pretty new to Python so I was wondering if there is a more Pythonic and more efficient way to implement this. For example whitout for loops or without the need to write seperate code for upgoing or downgoing crossings.



thanks!










share|improve this question







New contributor




StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    2
    down vote

    favorite












    I want to implement following trigger function in Python:



    Input:




    • time vector t [n dimensional numpy vector]

    • data vector y [n dimensional numpy vector] (values correspond to t vector)

    • threshold tr [float]

    • Threshold type vector tr_type [m dimensional list of int values]


    Output:




    • Threshold time vector tr_time [m dimensional list of float values]


    Function:



    I would like to return tr_time which consists of the exact (preffered also interpolated which is not yet in code below) time values at which y is crossing tr (crossing means going from less then to greater then or the other way around). The different values in tr_time correspond to the tr_type vector: the elements of tr_type indicate the number of the crossing and if this is an upgoing or a downgoing crossing. For example 1 means first time y goes from less then tr to greater than tr, -3 means the third time y goes from greater then tr to less then tr (third time means along the time vector t)



    For the moment I have next code:



    import numpy as np
    import matplotlib.pyplot as plt


    def trigger(t, y, tr, tr_type):
    triggermarker = np.diff(1 * (y > tr))
    positiveindices = [i for i, x in enumerate(triggermarker) if x == 1]
    negativeindices = [i for i, x in enumerate(triggermarker) if x == -1]
    triggertime =
    for i in tr_type:
    if i >= 0:
    triggertime.append(t[positiveindices[i - 1]])
    elif i < 0:
    triggertime.append(t[negativeindices[i - 1]])
    return triggertime


    t = np.linspace(0, 20, 1000)
    y = np.sin(t)
    tr = 0.5
    tr_type = [1, 2, -2]
    print(trigger(t, y, tr, tr_type))
    plt.plot(t, y)
    plt.grid()


    Now I'm pretty new to Python so I was wondering if there is a more Pythonic and more efficient way to implement this. For example whitout for loops or without the need to write seperate code for upgoing or downgoing crossings.



    thanks!










    share|improve this question







    New contributor




    StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I want to implement following trigger function in Python:



      Input:




      • time vector t [n dimensional numpy vector]

      • data vector y [n dimensional numpy vector] (values correspond to t vector)

      • threshold tr [float]

      • Threshold type vector tr_type [m dimensional list of int values]


      Output:




      • Threshold time vector tr_time [m dimensional list of float values]


      Function:



      I would like to return tr_time which consists of the exact (preffered also interpolated which is not yet in code below) time values at which y is crossing tr (crossing means going from less then to greater then or the other way around). The different values in tr_time correspond to the tr_type vector: the elements of tr_type indicate the number of the crossing and if this is an upgoing or a downgoing crossing. For example 1 means first time y goes from less then tr to greater than tr, -3 means the third time y goes from greater then tr to less then tr (third time means along the time vector t)



      For the moment I have next code:



      import numpy as np
      import matplotlib.pyplot as plt


      def trigger(t, y, tr, tr_type):
      triggermarker = np.diff(1 * (y > tr))
      positiveindices = [i for i, x in enumerate(triggermarker) if x == 1]
      negativeindices = [i for i, x in enumerate(triggermarker) if x == -1]
      triggertime =
      for i in tr_type:
      if i >= 0:
      triggertime.append(t[positiveindices[i - 1]])
      elif i < 0:
      triggertime.append(t[negativeindices[i - 1]])
      return triggertime


      t = np.linspace(0, 20, 1000)
      y = np.sin(t)
      tr = 0.5
      tr_type = [1, 2, -2]
      print(trigger(t, y, tr, tr_type))
      plt.plot(t, y)
      plt.grid()


      Now I'm pretty new to Python so I was wondering if there is a more Pythonic and more efficient way to implement this. For example whitout for loops or without the need to write seperate code for upgoing or downgoing crossings.



      thanks!










      share|improve this question







      New contributor




      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I want to implement following trigger function in Python:



      Input:




      • time vector t [n dimensional numpy vector]

      • data vector y [n dimensional numpy vector] (values correspond to t vector)

      • threshold tr [float]

      • Threshold type vector tr_type [m dimensional list of int values]


      Output:




      • Threshold time vector tr_time [m dimensional list of float values]


      Function:



      I would like to return tr_time which consists of the exact (preffered also interpolated which is not yet in code below) time values at which y is crossing tr (crossing means going from less then to greater then or the other way around). The different values in tr_time correspond to the tr_type vector: the elements of tr_type indicate the number of the crossing and if this is an upgoing or a downgoing crossing. For example 1 means first time y goes from less then tr to greater than tr, -3 means the third time y goes from greater then tr to less then tr (third time means along the time vector t)



      For the moment I have next code:



      import numpy as np
      import matplotlib.pyplot as plt


      def trigger(t, y, tr, tr_type):
      triggermarker = np.diff(1 * (y > tr))
      positiveindices = [i for i, x in enumerate(triggermarker) if x == 1]
      negativeindices = [i for i, x in enumerate(triggermarker) if x == -1]
      triggertime =
      for i in tr_type:
      if i >= 0:
      triggertime.append(t[positiveindices[i - 1]])
      elif i < 0:
      triggertime.append(t[negativeindices[i - 1]])
      return triggertime


      t = np.linspace(0, 20, 1000)
      y = np.sin(t)
      tr = 0.5
      tr_type = [1, 2, -2]
      print(trigger(t, y, tr, tr_type))
      plt.plot(t, y)
      plt.grid()


      Now I'm pretty new to Python so I was wondering if there is a more Pythonic and more efficient way to implement this. For example whitout for loops or without the need to write seperate code for upgoing or downgoing crossings.



      thanks!







      python numpy matplotlib






      share|improve this question







      New contributor




      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 days ago









      StefanVR

      111




      111




      New contributor




      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      StefanVR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote













          If y will always be a sine wave, then you're going about this the wrong way. Rather than calculating trigger_marker based on whether y exceeds tr, you should be calling asin(tr) to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.






          share|improve this answer





















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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',
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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
            });


            }
            });






            StefanVR is a new contributor. Be nice, and check out our Code of Conduct.










             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208279%2fimplementation-of-a-threshold-detection-function-in-python%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








            up vote
            1
            down vote













            If y will always be a sine wave, then you're going about this the wrong way. Rather than calculating trigger_marker based on whether y exceeds tr, you should be calling asin(tr) to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.






            share|improve this answer

























              up vote
              1
              down vote













              If y will always be a sine wave, then you're going about this the wrong way. Rather than calculating trigger_marker based on whether y exceeds tr, you should be calling asin(tr) to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.






              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote









                If y will always be a sine wave, then you're going about this the wrong way. Rather than calculating trigger_marker based on whether y exceeds tr, you should be calling asin(tr) to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.






                share|improve this answer












                If y will always be a sine wave, then you're going about this the wrong way. Rather than calculating trigger_marker based on whether y exceeds tr, you should be calling asin(tr) to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 days ago









                Reinderien

                1,392516




                1,392516






















                    StefanVR is a new contributor. Be nice, and check out our Code of Conduct.










                     

                    draft saved


                    draft discarded


















                    StefanVR is a new contributor. Be nice, and check out our Code of Conduct.













                    StefanVR is a new contributor. Be nice, and check out our Code of Conduct.












                    StefanVR is a new contributor. Be nice, and check out our Code of Conduct.















                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208279%2fimplementation-of-a-threshold-detection-function-in-python%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

                    Mont Emei

                    Province de Neuquén

                    Journaliste