Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zerocross Threshold optimize #35

Open
wants to merge 4 commits into
base: latestMain
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
#include <math.h>

#define PI 3.14159265359
#define INPUT_LENGTH 100000000
#define INPUT_LENGTH 1000000000
#define INCREMENT 0.000137

double* getRangeOfVector(double start, int length, double increment);
void gain(double* output, const double* input, double multiplier, int length);
Expand Down Expand Up @@ -64,19 +65,32 @@ void threshold(double* output, const double* input, double thresholdValue, int l
}
}

inline int sign(int x) {
return (x > 0) - (x < 0);
}

// Function to count zero crossings
int zeroCrossCount(const double* input, int length) {
int count = 0;
for (int i = 1; i < length; i++) {
if ((input[i-1] > 0 && input[i] <= 0) || (input[i-1] < 0 && input[i] >= 0)) {
count++;
int previous_sign = 0;

for (int i = 0; i < length; i++) {
int current_sign = sign(input[i]);

if (current_sign != 0) {
if (previous_sign != 0 && current_sign != previous_sign) {
count++;
}
previous_sign = current_sign;
}
}

return count;
}

int main() {
int fs = 1000;
double* input = getRangeOfVector(0, INPUT_LENGTH, 1);
double* input = getRangeOfVector(0, INPUT_LENGTH, INCREMENT);

double getMultiplier = 2 * PI * 5;
double* getSinDuration = malloc(INPUT_LENGTH * sizeof(double));
Expand All @@ -97,10 +111,10 @@ int main() {

int zcr = zeroCrossCount(GetThresholdReal, INPUT_LENGTH);

for (int i = 0; i < INPUT_LENGTH; i++) {
printf("%f ", GetThresholdReal[i]);
}
printf("\n");
// for (int i = 0; i < INPUT_LENGTH; i++) {
// printf("%f ", GetThresholdReal[i]);
// }
// printf("\n");

// Print zero-crossing count
printf("Zero-crossing count: %d\n", zcr);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
def main() {
var fs = 1000;
var input = getRangeOfVector(0, 10000, 0.000125);
var sep = getRangeOfVector(0, 1, 0.5);
var pi = 3.14159265359;
var getMultiplier = 2 * pi * 5;
var getSinDuration = gain(input, getMultiplier);
var signal = sin(getSinDuration );

var noise = delay(signal, 5);
var noisy_sig = signal + noise;
var threshold = 0.8;
var zeroOpt = zero_cross_threshold_opt(noisy_sig, threshold);
print(noisy_sig);
print(zeroOpt);
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
def main() {
var fs = 1000;
# var step = 1/fs;
# print(step);
var input = getRangeOfVector(0, 100000000, 1);
var pi = 3.14159265359;
var getMultiplier = 2 * pi * 5;
# print(getMultiplier);
var getSinDuration = gain(input, getMultiplier);
var signal = sin(getSinDuration );
var fs = 1000;
var input = getRangeOfVector(0, 100000000, 0.000137);
var sep = getRangeOfVector(0, 1, 0.5);
var pi = 3.14159265359;
var getMultiplier = 2 * pi * 5;
var getSinDuration = gain(input, getMultiplier);
var signal = sin(getSinDuration );

var noise = delay(signal, 5);
var noisy_sig = signal + noise;
var threshold = 0.8;
var GetThresholdReal = threshold( noisy_sig , threshold);
var zcr = zeroCrossCount(GetThresholdReal);
print(GetThresholdReal);
print(zcr);
}
var noise = delay(signal, 5);
var noisy_sig = signal + noise;
var threshold = 0.8;
# print(sep);
var GetThresholdReal = threshold( noisy_sig , threshold);
# print(GetThresholdReal);
var zcr = zeroCrossCount(GetThresholdReal);
print(zcr);
# print(noisy_sig);
}
33 changes: 20 additions & 13 deletions mlir/examples/dsp/SimpleBlocks/include/toy/Ops.td
Original file line number Diff line number Diff line change
Expand Up @@ -643,25 +643,13 @@ def zeroCrossCountOp : Dsp_Op<"zeroCrossCount" ,

let arguments = (ins F64Tensor:$lhs); //working -- F64
let results = (outs F64Tensor);
// let results = (outs I64);

// Indicate that the operation has a custom parser and printer method.
// let hasCustomAssemblyFormat = 1;
// let assemblyFormat = [{
// `(` $input `:` type($input1 , $input2) `)` attr-dict `to` type(results)
// }];
// Allow building a zeroCrossCountOp with from the one input operands.
let builders = [
OpBuilder<(ins "Value":$lhs)>
];

// Indicate that the operation has a custom parser and printer method.
// let hasCustomAssemblyFormat = 1;

// Enable registering canonicalization patterns with this operation.
//let hasCanonicalizer = 1;
let hasCanonicalizer = 1;

// let hasVerifier = 1;
}


Expand Down Expand Up @@ -2679,6 +2667,25 @@ def FIRFilterResSymmThresholdUpOptimizedOp : Dsp_Op<"FIRFilterResSymmThresholdUp

}

//===----------------------------------------------------------------------===//
// zeroCntOptimizeOp
//===----------------------------------------------------------------------===//

def zeroCntOptimizeOp : Dsp_Op<"zero_cross_threshold_opt",
[Pure, DeclareOpInterfaceMethods<ShapeInferenceOpInterface>]> {
let summary = "optimze op for zero cross count + threshold op";
let description = [{
val between given threshold are bound to 0, otherwise count + 1 if consecutive 2 elements have different sign.
}];

let arguments = (ins F64Tensor:$input, F64Tensor:$threshold);
let results = (outs F64Tensor);

let builders = [
OpBuilder<(ins "Value":$input, "Value":$threshold)>
];
}

#endif // TOY_OPS


Expand Down
22 changes: 19 additions & 3 deletions mlir/examples/dsp/SimpleBlocks/mlir/Dialect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -879,15 +879,17 @@ mlir::LogicalResult PowOp::verify() {
void zeroCrossCountOp::build(mlir::OpBuilder &builder,
mlir::OperationState &state, mlir::Value lhs) {
state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
// state.addTypes(builder.getF64Type()));
// state.addTypes(builder.getI64Type());
state.addOperands({lhs});
}

/// Infer the output shape of the zeroCrossCountOp, this is required by the
/// shape inference interface.
void zeroCrossCountOp::inferShapes() {
getResult().setType(getLhs().getType());
auto tensorInput = getLhs().getType();
std::vector<int64_t> shapeForOutput;
mlir::TensorType manipulatedType = mlir::RankedTensorType::get(
shapeForOutput, tensorInput.getElementType());
getResult().setType(manipulatedType);
}

//===----------------------------------------------------------------------===//
Expand Down Expand Up @@ -3400,6 +3402,20 @@ void FIRFilterResSymmThresholdUpOptimizedOp::inferShapes() {
getResult().setType(manipulatedType);
}

//===----------------------------------------------------------------------===//
// zeroCntOptimizeOp
//===----------------------------------------------------------------------===//

void zeroCntOptimizeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
mlir::Value input, mlir::Value threshold) {
state.addTypes({UnrankedTensorType::get(builder.getF64Type())});
state.addOperands({input, threshold});
}

void zeroCntOptimizeOp::inferShapes() {
getResult().setType(getThreshold().getType());
}

//===----------------------------------------------------------------------===//
// TableGen'd op method definitions
//===----------------------------------------------------------------------===//
Expand Down
115 changes: 106 additions & 9 deletions mlir/examples/dsp/SimpleBlocks/mlir/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6873,7 +6873,7 @@ struct BitwiseAndOpLowering : public ConversionPattern {
};

//===----------------------------------------------------------------------===//
// ToyToAffine RewritePatterns: BitwiseAndOp operations
// ToyToAffine RewritePatterns: zeroCrossCountOpLowering operations
//===----------------------------------------------------------------------===//

struct zeroCrossCountOpLowering : public ConversionPattern {
Expand All @@ -6897,15 +6897,15 @@ struct zeroCrossCountOpLowering : public ConversionPattern {
// output for result type
auto tensorType = llvm::cast<RankedTensorType>((*op->result_type_begin()));
Type integerType = rewriter.getI64Type();
auto memrefType = convertTensorToMemRef(tensorType);

zeroCrossCountOpAdaptor zeroCrossCountOpAdaptor(operands);
auto inputType = llvm::cast<RankedTensorType>(zeroCrossCountOpAdaptor.getLhs().getType());

// allocation & deallocation for the result of this operation
// auto memRefType = convertTensorToMemRef(tensorType);
// Force the result to be a tensor of size 1
auto alloc = insertAllocAndDealloc(
MemRefType::get(ArrayRef<int64_t>(1), tensorType.getElementType()), loc,
rewriter);
zeroCrossCountOpAdaptor zeroCrossCountOpAdaptor(operands);
DEBUG_PRINT_NO_ARGS();
auto alloc = insertAllocAndDealloc(memrefType, loc, rewriter);

// Define constants
Value constant0 = rewriter.create<arith::ConstantOp>(
Expand All @@ -6923,7 +6923,7 @@ struct zeroCrossCountOpLowering : public ConversionPattern {
Value ub = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(),
tensorType.getShape()[0]));
inputType.getShape()[0]));
Value step = rewriter.create<arith::ConstantIndexOp>(loc, 1);

// Set up for loop
Expand Down Expand Up @@ -7002,13 +7002,14 @@ struct zeroCrossCountOpLowering : public ConversionPattern {
Value finalCountArgFloat = rewriter.create<arith::SIToFPOp>(
loc, rewriter.getF64Type(), finalCountArg);

rewriter.create<AffineStoreOp>(loc, finalCountArgFloat, alloc, Indx0);
rewriter.create<AffineStoreOp>(loc, finalCountArgFloat, alloc, ValueRange{});
rewriter.replaceOp(op, alloc);

return success();
};
};


//===----------------------------------------------------------------------===//
// ToyToAffine RewritePatterns: Binary operations
//===----------------------------------------------------------------------===//
Expand Down Expand Up @@ -10367,6 +10368,102 @@ Value constant00 = rewriter.create<arith::ConstantOp>(
}
};

//===----------------------------------------------------------------------===//
// ToyToAffine RewritePatterns: zeroCntOptimize operations
//===----------------------------------------------------------------------===//

struct zeroCntOptimizeOpLowering : public ConversionPattern {
zeroCntOptimizeOpLowering(MLIRContext *ctx)
: ConversionPattern(dsp::zeroCntOptimizeOp::getOperationName(), 1,
ctx) {}
#define DUMP(x) llvm::errs() << "here " << x << "\n";
LogicalResult
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc();

auto tensorType = llvm::dyn_cast<RankedTensorType>(*op->result_type_begin());
auto memrefType = convertTensorToMemRef(tensorType);
auto alloc = insertAllocAndDealloc(memrefType, loc, rewriter);
// DUMP("alloc");

// acumulator and threshold
Value zero = rewriter.create<arith::ConstantOp>(loc, rewriter.getF64Type(), rewriter.getF64FloatAttr(0));
Value one = rewriter.create<arith::ConstantOp>(loc, rewriter.getF64Type(), rewriter.getF64FloatAttr(1));
Value negOne = rewriter.create<arith::NegFOp>(loc, one);
// DUMP("constant");

zeroCntOptimizeOpAdaptor adaptor(operands);
auto inputType = llvm::cast<RankedTensorType>(adaptor.getInput().getType());
auto thresholdMem = adaptor.getThreshold();
auto threshold = rewriter.create<AffineLoadOp>(loc, thresholdMem, ValueRange{});
auto negThreshold = rewriter.create<arith::NegFOp>(loc, threshold);

int64_t lb=0, ub=inputType.getShape()[0], step=1;
affine::AffineForOp forOp = rewriter.create<AffineForOp>(loc, lb, ub, step, ValueRange{zero, zero});
auto iv = forOp.getInductionVar();
rewriter.setInsertionPointToStart(forOp.getBody());


auto ele = rewriter.create<AffineLoadOp>(loc, adaptor.getInput(), ValueRange{iv});
auto prev_sign = forOp.getBody()->getArgument(1);
auto zero_cnt = forOp.getBody()->getArgument(2);

// lt threshold
auto lt = rewriter.create<arith::CmpFOp>(loc, arith::CmpFPredicate::OLE, ele, threshold);
// gt threshold
auto gt = rewriter.create<arith::CmpFOp>(loc, arith::CmpFPredicate::OGE, ele, negThreshold);

auto cmp = rewriter.create<arith::AndIOp>(loc, lt, gt);
// DUMP("cmp");

auto ifOp = rewriter.create<scf::IfOp>(loc, TypeRange{rewriter.getF64Type(), rewriter.getF64Type()}, cmp, true);
// if ele in range, yield stored cnt out
rewriter.setInsertionPointToStart(ifOp.thenBlock());
// DUMP("1st if");
rewriter.create<scf::YieldOp>(loc, ValueRange{prev_sign, zero_cnt});

// else if prev_sign !=0 and cur_sign != prev_sign
rewriter.setInsertionPointToStart(ifOp.elseBlock());
// DUMP("1st else");

auto cur_sign_cmp = rewriter.create<arith::SelectOp>(loc, lt, negOne, one);
auto sign_add = rewriter.create<arith::AddFOp>(loc, cur_sign_cmp, prev_sign);
auto sign_diff = rewriter.create<arith::CmpFOp>(loc, arith::CmpFPredicate::OEQ, sign_add, zero);
// DUMP("sign diff");

auto valid = rewriter.create<scf::IfOp>(loc, TypeRange{rewriter.getF64Type()}, sign_diff, true);
// DUMP("2nd if");
rewriter.setInsertionPointToStart(valid.thenBlock());
auto incre_cnt = rewriter.create<arith::AddFOp>(loc, zero_cnt, one);
rewriter.create<scf::YieldOp>(loc, ValueRange{incre_cnt});
rewriter.setInsertionPointToStart(valid.elseBlock());
// DUMP("2nd else");
rewriter.create<scf::YieldOp>(loc, ValueRange{zero_cnt});
rewriter.setInsertionPointAfter(valid);

// DUMP("get result");
auto cntResult = valid.getResults()[0];

rewriter.create<scf::YieldOp>(loc, ValueRange{cur_sign_cmp, cntResult});
rewriter.setInsertionPointAfter(ifOp);

auto new_sign = ifOp.getResults()[0];
auto new_cnt = ifOp.getResults()[1];

rewriter.create<AffineYieldOp>(loc, ValueRange{new_sign, new_cnt});
rewriter.setInsertionPointAfter(forOp);
// DUMP("get answer");

auto result = forOp.getResult(1);
rewriter.create<AffineStoreOp>(loc, result, alloc, ValueRange{});

rewriter.replaceOp(op, alloc);
return mlir::success();
}

};

} // namespace

//===----------------------------------------------------------------------===//
Expand Down Expand Up @@ -10448,7 +10545,7 @@ void ToyToAffineLoweringPass::runOnOperation() {
NormalizeOpLowering, AbsOpLowering, MedianFilterOpLowering,
LMS2FindPeaksOptimizedOpLowering, FindPeaks2Diff2MeanOptimizedOpLowering,
NormLMSFilterResponseOptimizeOpLowering,
FIRFilterResSymmThresholdUpOptimizedOpLowering>(&getContext());
FIRFilterResSymmThresholdUpOptimizedOpLowering, zeroCntOptimizeOpLowering>(&getContext());

// With the target and rewrite patterns defined, we can now attempt the
// conversion. The conversion will signal failure if any of our `illegal`
Expand Down
Loading