Calculating area under a curve - trapezium rule

Hi,
I'm trying to calculate the 'area under the curve' using the trapezium rule for a set of data points. i.e. I have a set of values, sampled at irregular intervals.
create table measurements (
  measurement_value integer,
  measurement_time timestamp
insert into measurements (measurement_value,measurement_time) values (50,TIMESTAMP'2011-01-01 00:00:00');
insert into measurements (measurement_value,measurement_time) values (40,TIMESTAMP'2011-01-01 01:00:00');
insert into measurements (measurement_value,measurement_time) values (40,TIMESTAMP'2011-01-01 03:00:00');
insert into measurements (measurement_value,measurement_time) values (50,TIMESTAMP'2011-01-01 03:30:00');
insert into measurements (measurement_value,measurement_time) values (40,TIMESTAMP'2011-01-01 05:00:00');
insert into measurements (measurement_value,measurement_time) values (40,TIMESTAMP'2011-01-01 06:00:00');
insert into measurements (measurement_value,measurement_time) values (60,TIMESTAMP'2011-01-01 07:00:00');I'd like to calculate the area of the 'curve' where the value was below a threshold of, e.g. 45.
I can use the trapezium rule and assume a straight line between subsequent measurement, i.e. for the first 2 data points, the value drops from 50 to 40 linearly over the hour, and so the area for those measurements is (30min * 5)/2. For the 2nd and 3rd data points, the area is (120min * 5), for the 3rd and 4th, the area is (15min * 5)/2. And so on. The values are not necessarily round numbers, almost any value is possible.
I've started by using 'lead' to obtain the subsequent measurement value and time, but I'm getting stuck dealing with the end points and non-trivial interpolation. Does anyone have any pointers to get me going?
Thanks,
Dan Scott

Maybe this will do it:
SELECT SUM(CASE
            WHEN curr_value > :threshold AND next_value < :threshold
            THEN -- Area of rectangle specified by threshold
                 (new_measurement_time_sec-curr_measurement_time_sec)*:threshold
               + -- Area of remaining trapezoid
                 ABS((next_measurement_time_sec - new_measurement_time_sec)*((next_value - :threshold)/2))
            WHEN next_value > :threshold AND curr_value < :threshold
            THEN -- Area of rectangle specified by threshold
                 (next_measurement_time_sec-new_measurement_time_sec)*:threshold
               + -- Area of remaining trapezoid
                 (new_measurement_time_sec - curr_measurement_time_sec)*((:threshold - curr_value)/2)
            WHEN (:threshold < curr_value AND :threshold < next_value)
              OR (:threshold > curr_value AND :threshold > next_value)
            THEN (next_measurement_time_sec-curr_measurement_time_sec)*:threshold
            ELSE -- Area of trapezoid
                 ABS((next_measurement_time_sec - curr_measurement_time_sec)*((next_value - curr_value)/2))
       END)  AS area
FROM   (
         SELECT measurement_time
              , curr_measurement_time_sec
              , next_measurement_time_sec
              , curr_value
              , next_value
              , (:threshold - LEAD(intercept) OVER (ORDER BY measurement_time))/LEAD(slope) OVER (ORDER BY measurement_time) AS new_measurement_time_sec
         FROM   ( SELECT measurement_time        
                       , TO_CHAR(measurement_time,'J')*24*60*60 + TO_CHAR(measurement_time,'SSSSS') AS curr_measurement_time_sec
                       , TO_CHAR(LEAD(measurement_time) OVER (ORDER BY measurement_time),'J')*24*60*60 + TO_CHAR(LEAD(measurement_time) OVER (ORDER BY measurement_time),'SSSSS') AS next_measurement_time_sec
                       , measurement_value                                        AS curr_value
                       , LEAD(measurement_value) OVER (ORDER BY measurement_time) AS next_value
                       , REGR_SLOPE(measurement_value, TO_CHAR(measurement_time,'J')*24*60*60 + TO_CHAR(measurement_time,'SSSSS')) OVER (ORDER BY measurement_time) AS slope
                       , REGR_INTERCEPT(measurement_value, TO_CHAR(measurement_time,'J')*24*60*60 + TO_CHAR(measurement_time,'SSSSS')) OVER (ORDER BY measurement_time) AS intercept
                  FROM   measurements
       )Results:
SQL> var threshold NUMBER;
SQL> exec :threshold := 45;
SQL> /
      AREA
1191437.2The units are the time values were converted to seconds since January 1, 4712 BC (roughly).
Edited by: Centinul on Jul 7, 2011 10:39 AM

Similar Messages

  • How can I calculate area under a curve?

    I would like to use an integral equation to obtain positive and negative areas from graphed data. For example, I have a graph representing power for a 24 hour period and want to integrate the curve to obtain daily energy.

    One common way to approximate the area under a curve is to divide it into a series of trapezoids, with the area of each calculated as avg height x width. Then sum the areas.
    So with this table:
    x     

    trapezoid
    1
    0
    3
    2
    6
    11
    3
    16
    23
    4
    30
    39
    5
    48
    59
    6
    70
    83
    7
    96
    218
    You could use this formula in C2, filled down through the rest of the body cells in that column:
    =IFERROR((B3+B2)÷2×(A3−A2),"")
    This calculates the area of each trapezoid.
    The first row is defined as a Header Row, the last row as a Footer Row.  It's important not to have blank row(s) before the Footer Row. The sum formula in the Footer Row in C9 is:
    =SUM(C)
    Of course, the greater the number of x-y data points the better the estimate of the area under the curve.
    SG

  • Regression area under the curve

    hello
    i was trying to get the area under the curve. mathematically the
    integration can b done directly from 'numeric integration' vi. but what
    my problem is i cant define the time t1 to t3( as i need to set the
    threshold level to eliminate noise). what i previously did was defining
    the threshold level, find the 2 point of t1 and t2. but i left out the
    coloured portion. using regression will it help to get t3?if yes. how
    this will b done?
    thanks
    regards
    Attachments:
    graph(dt)1.PNG ‏8 KB

    This has been going on for a while:
    http://forums.ni.com/ni/board/message?board.id=170&message.id=226483#M226483
    http://forums.ni.com/ni/board/message?board.id=MathScript&message.id=145#M145
    http://forums.ni.com/ni/board/message?board.id=170&message.id=227008#M227008
    If I understand this correctly, you use a threshold to find the peak, but then you want the entire area, including the "wings".
    As I said before, if you pick the baseline right, your integration boundary does not need to be exact and can be significantly outside because the areas outside the peak will average to zero.
    If you have a mathematical model for the peak (e.g. gaussian), you can fit it and calculate the area from the fit.
    LabVIEW Champion . Do more with less code and in less time .

  • Integrate area under multiple curves

    I have a VI that will detect peaks (centroid) and their amplitudes from waveform data. I would like to also integrate the areas under each peak. I used the trigger/gate vi and the numeric integration vi to integrate the area under the first peak, but cannot get integration of later peaks. I am also wondering why I get the message: NaN when I try to use Simpson's integration rule (I am using trapezoid rule). The VI "read voltage make table" is attached.
    Attachments:
    read voltage make table.vi ‏601 KB

    I took a quick look at your VI. The reason you are only integrating the first peak is that the Trigger and Gate Express VI only triggers once. You need to put you data into a loop with a shift register and extract the section containing each peak. Then integrate each section separately (possibly in the same loop).
    I like to put the data acquisition and data processing (peak detection and integration) in separate, parallel loops. This can help avoid missed data and is easier to maintain. Look at the examples for State Machines.
    NaN often comes from dividing by zero. I do not recall the Simpson's rule algorithm, but if your data can have vertical segments you might see an infinite slope which could produce a divide by zero error.
    Lynn

  • Area under normal curve

    I need to calculate the area under a normal (gaussian) curve between two given limits. Is there some algorithm or freely usable library which I could use to calculate this? I've searched around but so far have come up with nothing.

    , i.e., something relatively close to
    the precision of 'double'. Why do you need it to be so precise? After all, when you're dealing with statistics there's always a level of probability. Even if you had double precision, would that make the final result more accurate?
    I expect there's
    probably some asymptotic approach that approaches the
    desired precision in some fixed number of
    iterations.
    Probably so. Just out of curiosity I wanted to measure the change in area as the number of points grew by a factor of 10. here are the results:
    0.9746011459589066 numPoints: 80
    0.9803552459545505 numPoints: 800 area - oldArea: 0.005754099995643913
    0.9808610053578404 numPoints: 8000 area - oldArea: 5.05759403289896E-4
    0.9809109343345651 numPoints: 80000 area - oldArea: 4.992897672473351E-5
    0.9809159208101573 numPoints: 800000 area - oldArea: 4.986475592216877E-6
    0.9809164193936031 numPoints: 8000000 area - oldArea: 4.985834457515992E-7
    0.980916469248969 numPoints: 80000000 area - oldArea: 4.985536594670492E-8
    Basically, if you use 10 times as many points from one to the next, you get an extra decimal place of accuracy. So if you can live with 4 decimal places of accuracy, then maybe this method is ok, otherwise the computation becomes expensive.
    Here is the code:
    public class ATest {
         public static void main(String[] args) {
         double oldArea = -1;
         for (int k = 0; k < 6; k++) {
              double dx = 0.1 / Math.pow(10, k);
              double x1 = -4.0;
              double x2 = 4.0;
              int numPoints = (int) Math.round((x2 - x1) / dx);
              double area = 0;
              for (int i = 0; i < numPoints; i++) {
                   int j = (i + 1) % numPoints;
                   double xi = x1 + i * dx;
                   double xj = x1 + j * dx;
                   double yi = calcFunction(xi);
                   double yj = calcFunction(xj);
                   area += xi * yj - xj * yi;
              if (area < 0) area = -area;
              area = area / 2;
              if (oldArea != -1) {
                   double dif = area - oldArea;
                   System.out.println(area + " numPoints: " + numPoints + " area - oldArea: " + dif);
              else
                   System.out.println(area + " numPoints: " + numPoints);
              oldArea = area;
         private static double calcFunction(double X) {
              double SIGMA = 1.0;
              double SIGMA_SQ_2 = SIGMA * SIGMA * 2;
              double C = 1.0 / Math.sqrt(Math.PI * SIGMA_SQ_2);
              double MU = 1.0;
              double xmu = X - MU;
              return C * Math.exp(-1 * xmu * xmu / SIGMA_SQ_2);
    }

  • How do I calculate areas under the curves above and below the x axis at 0?

    The xy graph generated is similar to a sinusoidal representing the magnetic intensity of the poles of a motor. For each of the four areas above and below the x axis at 0 I would like to calculate the area then do a variance analysis on the 8 areas. Can anyone suggest a method to calculate each of the 8 areas. See the attached vi to understand better what I'm trying to do.
    Thank you.
    Attachments:
    MIN MAX A.vi ‏16 KB

    Hi all,
    If you are simply looking to do numeric integration, there is built in functionality to do that.  The help file is here:
    http://zone.ni.com/reference/en-XX/help/371361H-01/gmath/numeric_integration/
    You will may have to do some edge checking if you want to break this down into individual components.
    Let us know if you need any more assistance
    Applications Engineer
    National Instruments

  • Area under Curve -- ROC-- Classification

    Dear All,
    I had applied classification technique and plot the ROC curve, the Oracle Data miner calculates the Area under Curve of that ROC, anyone please tell me on which formula does the Area under curve is calculated....

    which formula is used to calculate the area under ROC curve in oracle data miner

  • Area under curve

    i am having the hardest time calculating area under a closed curve using basic maths. I have tried the integrate function (by splitting the curve in two and then adding the two). I am not susre of the answer so i am using basic math functions to code the thing in. So far i have:
    L1 = globusedchn
    CALL FORMULACALC("CH(L1):=CH('D')*CH('F')")
    CC(L1)="MULTIPLIED POINTS"
    CN(L1)="MULTPTS"
    R4 = 0
    R1 = CHDX(1, L1)
    R2 = CHDX(2, L1)
    R3 = R2 - R1
    R4 = R3 + R1
    A = R4
    FOR I = 2 TO CL(L1)
    L2 = I
    R5 = CHDX(L2, L1)
    R6 = CHDX(L2+1, L1)
    R7 = R6 - R5
    R8 = R7 + A
    A = R8
    NEXT
    CALL MSGBOXDISP(R8 & " = new area")
    maybe its my data but i keep getting R8 as 0. Any pointers will be greatly appreciated. Thanks ~sn

    Hi shefalika,
    It looks to me like the ChnIntegrate() function is the one to use. Note that the entire area under the curve is just the last value of the integrated curve. I included your original data in the ZIP file attached below, along with a quick VBScript which loads the data, creates 2 new channels which are the integral of channels 2 and 3 vs. channel 1, respectively, and loads a REPORT layout to show the results.
    The REPORT layout shows the raw data curves twice, once as a thick red line and then again as vertical blue spikes. This gives you the visual respresentation of the area under each curve being blue. I then included on each of the 2 graphs a text box which displays the last value of the integrated channel for that raw data curve. This is not a static value but an embedded @ function in the REPORT layout, specifically:
    Area Under Curve = @str(ChDX(CL('Area1'), 'Area1'), 'd')@
    for the 1st graph. Note that the area under the curve value is pulled explicitly from the channel named "Area1", so if you rename the integrated channel, you will need to change the channel reference in each of these 2 embedded @ formulas in the REPORT layout. The str() function formats the string result to not show any decimal points in the results (you could use 'd.ddd" instead, for instance). The ChDX(row, channel) function returns the value from the "row-th" data row of the "channel" data channel.
    Also note that several items in this example are built with DIAdem 9.1 features. If you need an earlier version of the example, let me know and I can build it again in DIAdem 8.1.
    Ask if you have further questions,
    Brad Turpin
    DIAdem Product Support Engineer
    National Instruments
    Attachments:
    Area Under Curve.zip ‏12 KB

  • Calculate area under XY graph

    Hello to all, I am plotting the data acquired from the system as amplitude v/s time on XY graph. My task is to calculate are under the graph and am using integrator tool to achieve this. However, feel that am not using correctly as answer is not matching with expected value. For example, I have plotted y=x function and as per the definition area is equal to 0.5*height*base for area under the graph. It is not matching, kindly help as I want to find out area under the curve for any two points of X-axis.
    Attachments:
    xy-graph.vi ‏22 KB

    The integration gets accurate in your case if you change the integration method to 'trapezoidal' instead of the default 'Simpson's Rule'.
    Simpson's Rule probably doesnt work because you don't provide suitable Initial and Final conditions. This method needs an assumption about the borders of the integration interval.
    Cheers
    Edgar

  • How to calculate area under the waveform

    I need to calculate absolute energy of the waveform. Do you have a math function to do this? I used Integrate funtion but the return value is 0.

    You didn't say much about what you are doing. The CNiMath::Integrate function should be able to do this for you. Maybe you don't understand the function. You would input your waveform as a vector (say 1000 elements), then the delta time between each element (1/sampling rate), then the first and last value of the discrete integral (waveform[-1] and waveform[n]). Then, on output, the vector would contain the integrated data. You could get the sum of the elements to get the total area under the curve.
    Best Regards,
    Chris Matthews
    National Instruments

  • Integral of waveform graph to calculate area under curve over time

    Hello ,
    Please find my attached VI and please help me for integration to get area undercut for my waveform graph.
    I would like to find total  Energy output from my wind power  waveform graph oever one month period of time.
    I believe i have to integrate to get area under curve and so i m now using integral tool in labview as attached. 
    As I don't have expected ans for my result and so i want to make sure the tool that i m using is correct.
    Please advise me which method of integration shall i use for my graph.
    Solved!
    Go to Solution.
    Attachments:
    Wind data only.vi ‏134 KB
    wind data.txt ‏1253 KB

    I don't know about your calculations to get the Wattage.  But as far as integration, you really should supply a dt (sample rate) in order to get a proper energy measurement.  I would use your second integration method (the one with "Result" as the indicator) and give it the dt as well.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How can i find area under a closed curve

    I am having set of Y-values w.r.t X-values.When i am using numerical integration.vi to measure area, it is showing wrong answer.Is there any other vi to find the area under a closed curve.

    Is the dt constant between your values? The numerical integration.vi needs them to be...
    What's the correct answer depends on how you are to interpolate between the points. The numerical integration.vi allows you to select between a number of approaches (Simpson's rule, trapezoidal etc..). It does not allow integrating the values as if it were a histogram...If that is what you want to do then all you need to do is to add the values and then multiply the result by dt...
    When you say that the answer is incorrect, could you give an example array, dt and correct result?
    If the curve is supposed to be a special function you could use regression analysis to find the formula of the curve and then integrate that...
    MTO

  • I am using a 5D Mark II and I am getting a series of three curved lines on the photos that are under

    I am using a 5D Mark II and I am getting a series of three curved lines on the photos that are under exposed only.  Can anyone help me figure out why it is doing this?

    Everything on the sensor is going to be organized in rows and columns. You can get a bad pixel or a column of bad pixels... or perhaps even a block ... but not a curve. If you're seeing a curve then certainly there must be something else causing this.
    The camera does have two internal filters in front of the sensor, but those are flat and would probably not be the source of a curved reflection.
    If you are confident this happens with more than one lens, then I might remove the lens and use the menu system to put the camera into manual "sensor cleaning" mode. This really just causes the mirror to swing clear (to the roof the chamber) and also causes the shutter door to open and expose the sensor (although the sensor is actually powered down when in "cleaning" mode). This would allow you to visually check to make sure nothing is hanging in the light path.
    I would normally suspect the problem is caused either by the lens or possibly by a filter mounted on the front of the lens (do you use any type of UV filter or other filter when this happens?) The lens itself is curved glass... but since a "filter" would be flat glass in front of the curved glass, a reflection off the curved glass can bounce back off the filter and into the camera. Many "ghosting" problems are caused by the use of filters (and these can be eliminated by removing the filter or reduced by using filters with anti-reflective coatings.)
    Hopefully you can the solution -- but I would probably be looking at the optics as I suspect this is not related to the camera body.
    Tim Campbell
    5D II, 5D III, 60Da

  • Calulate area under curve: Hystresis

    I have a force and dispacement values in excel. I want to calulate the hystresis of this.
    How can i do this through VBS?? I dont have time channel in that, How can i create it and find the hystresis?
    Rsh
    Solved!
    Go to Solution.
    Attachments:
    data points.xls ‏67 KB

    Hi RSH,
    Ignore the above, I wasn't thinking clearly.  I banged out a quick data set and tried it out, and it turns out to be much simpler-- you just need to calculated the integral channel and look at the last value in the channel, like this:
    i = 1 ' GroupIndex
    Call GroupDefaultSet(i)
    DispCh = CNo("[" & i & "]/Displacement")
    ForceCh = CNo("[" & i & "]/Force")
    IntCh = CNo("[" & i & "]/Integral")
    IF IntCh > 0 THEN Call ChnDel(IntCh)
    Call GroupDefaultSet(i)
    Call ChnIntegrate(DispCh, ForceCh, "/Integral")
    IntCh = CNo("[" & "]/Integral")
    Integral = ChDX(ChnLength(IntCh), IntCh)
    Call ChnPropValSet(IntCh, "Integral", Integral)
    The calculated area is put in the "Integral" property of the "Integral" channel in the same group as the "Displacement" and "Force" channels.  In the example I'm attaching, I split the raw hysteresis curve (both forward and return) into its two components and calculated the integral of each, just to make sure that the different in their integrals really was the same as the net integral of the raw data curve-- and it was.
    Brad Turpin
    DIAdem Product Support Engineer
    National Instruments
    Attachments:
    Hysteresis.zip ‏3 KB

  • Regarding Area Under Curve of ROC-ODM

    Which method is used by Oracle Data Miner to calculate the Area Under Curve(AUC) of ROC? either trapezoidal or other ? Please reply me

    Using the trapezoid method, the numerical integration is rather direct.
    See the attached vi.
    You can't get the function described by the X and Y arrays. You need to know the function from start ! However, you can always fit a function to the data. Polynomial curve fitting is quite popular. Of course this is something you could have done : fit a polynomial, then integrate it. With a large number of points (such as yours), the result will not be better than the trapezoid method.
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Area.vi ‏30 KB

Maybe you are looking for

  • Help?  Beginning Student--error msgs

    Hi, I'm a college student taking Java with the 3rd edition Deitel and Deitel Text. In Chapter 5, problem 5.11 is killing me. I've tried moving things around, and it just changes the error messages from "type expected" to "variable may not have been i

  • How can i create emca form the operating system

    Hi, I am new to java, ran the script and i got the following response....... emca -config dbcontrol -repos recreate java.lang.IllegalArgumentException: -config at oracle.sysman.vto.vtoe.repmgr.Arguments.getOperationCode(Arguments.java:424) at oracle.

  • How do I authorize another computer to use iTunes?

    how do I authorize another computer to use iTunes?

  • SAP-BPC Faq's

    Hi Experts,        This is Arjun i am new to BPC Could you please help me to provide some BPC Documents and BPC Faq's ,as soon as possible Thanks in advance, Arjun.

  • Question about queries

    I am using several ways to build queries : mySession.readObject mySession.readAllObjects mySession.executeQuery and classes ReadObjectQuery, readAllQuery and readQuery What are the differences between all this classes and methods ??? I also used quer