blob: ca060be9a34ff3fd60b69697eebc548056da58eb [file] [log] [blame]
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.lib.math;
import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.annotation.InputPortFieldAnnotation;
import com.datatorrent.api.annotation.OutputPortFieldAnnotation;
import com.datatorrent.lib.util.BaseNumberValueOperator;
/**
*
* Emits the average of values at the end of window.
* <p>
* This is an end window operator. This can not be partitioned. Partitioning
* this will yield incorrect result.<br>
* <b>Ports</b>:<br>
* <b>data</b>: expects V extends Number<br>
* <b>average</b>: emits V extends Number<br>
* <br>
* <br>
* <b>Properties</b>: None<br>
* <b>Specific compile time checks</b>: None<br>
* <b>Specific run time checks</b>: None<br>
* <p>
* @displayname: Average
* @category: math
* @tags: average, numeric, end window
* @since 0.3.3
*/
public class Average<V extends Number> extends BaseNumberValueOperator<V>
{
/**
* Input port that takes a number.
*/
@InputPortFieldAnnotation(name = "data")
public final transient DefaultInputPort<V> data = new DefaultInputPort<V>()
{
/**
* Computes sum and count with each tuple
*/
@Override
public void process(V tuple)
{
sums += tuple.doubleValue();
counts++;
}
};
/**
* Output port that emits average as a number.
*/
@OutputPortFieldAnnotation(name = "average")
public final transient DefaultOutputPort<V> average = new DefaultOutputPort<V>();
protected double sums = 0;
protected long counts = 0;
/**
* Emit average.
*/
@Override
public void endWindow()
{
// May want to send out only if count != 0
if (counts != 0) {
average.emit(getAverage());
}
sums = 0;
counts = 0;
}
/**
* Calculate average based on number type.
*/
@SuppressWarnings("unchecked")
public V getAverage()
{
if (counts == 0) {
return null;
}
V num = getValue(sums);
Number val;
switch (getType()) {
case DOUBLE:
val = new Double(num.doubleValue() / counts);
break;
case INTEGER:
int icount = (int) (num.intValue() / counts);
val = new Integer(icount);
break;
case FLOAT:
val = new Float(num.floatValue() / counts);
break;
case LONG:
val = new Long(num.longValue() / counts);
break;
case SHORT:
short scount = (short) (num.shortValue() / counts);
val = new Short(scount);
break;
default:
val = new Double(num.doubleValue() / counts);
break;
}
return (V) val;
}
}