diff --git a/.gitignore b/.gitignore index ba8dc4a2f44e..3e325b71ac5c 100644 --- a/.gitignore +++ b/.gitignore @@ -84,3 +84,5 @@ mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Output/* /mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HClanglogs /mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/ServerExeLogs /mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/ServerExeLogs +hexagon_target/* +Hexagon_Tools/* diff --git a/Dockerfile b/Dockerfile index e3d1ca0d29ec..f96218d608e4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,38 +1,61 @@ -# Use the official Ubuntu base image -FROM ubuntu:latest +# Use an official Ubuntu 22.04 as a base +FROM ubuntu:22.04 -# Install required packages +# Install dependencies RUN apt-get update && \ - apt-get install -y git cmake ninja-build clang - -# Set the working directory -WORKDIR /llvm-project - -# Clone the LLVM project repository -RUN git clone https://github.com/tridhapuku/DSP_MLIR.git . - -# Checkout latest Branch -RUN git checkout latestMain - -# Create the build directory -RUN mkdir build - -# Change to the build directory -WORKDIR /llvm-project/build - -# Download and install cmake -RUN apt-get install -y cmake - -# Configure and build LLVM projects -RUN cmake -S llvm -B build -G Ninja ../llvm -DLLVM_ENABLE_PROJECTS="mlir;clang;clang-tools-extra;lld" -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DLLVM_ENABLE_LLD=OFF - -# Configure and build MLIR project -RUN cmake ../llvm \ - -DLLVM_ENABLE_PROJECTS=mlir \ - -DLLVM_BUILD_EXAMPLES=ON \ - -DLLVM_TARGETS_TO_BUILD="Native" \ - -DCMAKE_BUILD_TYPE=Release \ - -DLLVM_ENABLE_ASSERTIONS=ON - -# Build and run MLIR tests -RUN cmake --build . --target check-mlir + DEBIAN_FRONTEND=noninteractive apt-get install -y \ + git \ + cmake \ + ninja-build \ + clang \ + build-essential \ + python3 \ + libedit2 \ + libedit-dev \ + libncurses6 \ + libtinfo5 \ + libncurses-dev \ + python3-pip \ + lld \ + wget \ + curl \ + vim \ + desktop-file-utils \ + gawk \ + sudo \ + systemd \ + xdg-utils && \ + ln -s /usr/bin/python3 /usr/bin/python && \ + rm -rf /var/lib/apt/lists/* + + +# Symlinks for older libraries +RUN ln -s /usr/lib/x86_64-linux-gnu/libedit.so.2 /usr/lib/x86_64-linux-gnu/libedit.so.0 && \ + ln -s /usr/lib/x86_64-linux-gnu/libncurses.so.6 /usr/lib/x86_64-linux-gnu/libncurses.so.5 + + + +# Set environment variables +ENV PATH=/usr/local/bin:$PATH + +# Clone your project (checkout docker branch directly) +RUN git clone https://github.com/MPSLab-ASU/DSP_MLIR.git /DSP_MLIR + +# Set working directory +WORKDIR /DSP_MLIR +RUN git checkout docker +# Build +RUN mkdir build && cd build && \ + cmake -G Ninja ../llvm \ + -DLLVM_ENABLE_PROJECTS="mlir;clang" \ + -DLLVM_BUILD_EXAMPLES=ON \ + -DLLVM_TARGETS_TO_BUILD="Native;Hexagon" \ + -DCMAKE_BUILD_TYPE=Release && \ + ninja + +# Copy additional files +# COPY hexagon_target/ /DSP_MLIR/build/bin/hexagon/ +# COPY Hexagon_Tools/ /DSP_MLIR/Hexagon_Tools/ + +# Default to bash +CMD ["/bin/bash"] diff --git a/LICENSE.TXT b/LICENSE.TXT index fa6ac5400070..3901fa02e64f 100644 --- a/LICENSE.TXT +++ b/LICENSE.TXT @@ -1,3 +1,219 @@ +============================================================================== +Dual License +============================================================================== + +The DSP-MLIR project is dual-licensed under: + +1. The DSP-MLIR Apache License, Version 2.0 +2. The standard LLVM Project License: Apache License v2.0 with LLVM Exceptions +============================================================================== +The DSP-MLIR Apache License, Version 2.0: + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + ============================================================================== The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: ============================================================================== diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/FIRFilterDesign.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/FIRFilterDesign.c index e2361143850d..459277473b91 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/FIRFilterDesign.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/FIRFilterDesign.c @@ -3,6 +3,7 @@ #include #define INPUT_LENGTH 101 +#define M_PI 3.14159265358979323846 #define PI M_PI #define FS 8000 #define FC1 500 @@ -76,10 +77,12 @@ int main() { double final1 = getElemAtIndx(hpf_w1, 6); double final2 = getElemAtIndx(hpf_w2, 7); double final3 = getElemAtIndx(hpf_w3, 8); + double final4 = getElemAtIndx(hpf_w3, 5); printf("%f\n", final1); printf("%f\n", final2); printf("%f\n", final3); + printf("%f\n", final4); free(hamming_window); free(hpf1); diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/HexagonClangResultScript.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/HexagonClangResultScript.py new file mode 100644 index 000000000000..a58b8e4a0d0a --- /dev/null +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/HexagonClangResultScript.py @@ -0,0 +1,452 @@ +import os +import subprocess +import time +import sys +import math +# The script does the following +# Input : filename.c +# Output : TimeOfExecution for different IP sizes : +# Steps to run: +# Open a terminal at the path of the script -- +# Run: python ScriptForCases.c #3.11 validated + +# Pseudo-code: +# Iterate for all the input-size & update the input value in file +# Update logic -- change the 2nd parameter of line: var c = getRangeOfVector(init , Count, StepSize) +# Run the respective commands on the file + +# Path to the input file +# Apps = "lowPassFIRFilterDesign.c", "noisecancelling.c" , "echocancelling.c", "hearingAid.c", "audioEqualizer.c", "vibrationAnalysis.c", "underWaterCommunication.c", "voiceActivityDetection.c", "signalSmoothing", "targetDetection", "biomedicalSignalProcessing", "periodogram2Conv", "spaceCommunication", "dtmfDetection", "speakerIdentification" +input_file_name = sys.argv[1] +full_path = os.path.abspath(__file__) + +# Find the path up to 'DSP_MLIR' +if 'DSP_MLIR' in full_path: + BasePathForLLVM = full_path.split('DSP_MLIR')[0] + 'DSP_MLIR/' +OutputScriptPath = "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/" +# OutputPath = BasePathForLLVM + "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/Results/TryResultScript/Output/" +input_file_path = BasePathForLLVM + OutputScriptPath + input_file_name + +print(f"Running Application {input_file_path}") +# Construct full output path +if sys.argv[2]: + OutputPath = os.path.join(BasePathForLLVM, OutputScriptPath, "Output", sys.argv[2]) + +else: + OutputPath = os.path.join(BasePathForLLVM, OutputScriptPath, "Output") + +# Check if the Output folder exists, create it if it doesn't +if not os.path.exists(OutputPath): + os.makedirs(OutputPath) + +# Now OutputPath is ready for use +print("InputPath:{}".format(BasePathForLLVM)) +print(f"OutputPath: {OutputPath}") +# exit() + +# ************ Don't change unless u required +# Define the values dictionary + +inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + + + #"10M": 10000000, + #"20M": 20000000, + #"30M": 30000000, + #"40M": 40000000, + #"50M": 50000000, + #"100M": 100000000, + # "1B": 1000000000 +} + +if sys.argv[1] == "noiseCancellation.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + } + +elif sys.argv[1] == "echoCancellation.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + } + +elif sys.argv[1] == "periodogram.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + } + +elif sys.argv[1] == "lowPassFiltering.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + + +elif sys.argv[1] == "hearingAid.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + +elif sys.argv[1] == "FIRFilterDesign.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + + +elif sys.argv[1] == "spectralAnalysis.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + } + + +elif sys.argv[1] == "audioEqualization.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + + +elif sys.argv[1] == "audioCompression.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + } + + +elif sys.argv[1] == "vibrationAnalysis.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + } + + +elif sys.argv[1] == "underWaterCommunication.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + } + +elif sys.argv[1] == "voiceActivityDetection.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + } + + +elif sys.argv[1] == "signalSmoothing.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + } + + + +elif sys.argv[1] == "targetDetection.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + } + + +elif sys.argv[1] == "biomedicalSignalProcessing.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + } + + +elif sys.argv[1] == "digitalModulation.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + } + + + +elif sys.argv[1] == "spaceCommunication.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + } + + +elif sys.argv[1] == "radarSignalProcessing.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + } + + +elif sys.argv[1] == "speakerIdentification.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + "5K": 5000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + + +elif sys.argv[1] == "dtmfDetection.c": + inputValues = { + "10": 10, + "100": 100, + "500": 500, + "1K": 1000, + "2K": 2000, + } +NoOfIterations = 1 + +# Define the cases +cases = [ + { + "hexagon-clang": True, + "llvm-clang": False, + "exe": "Clang-hexagon", + }, + { + "llvm-clang": True, + "hexagon-clang": False, + "exe": "Clang", + }, +] + + +with open(input_file_path, "r") as file: + lines = file.readlines() + +print("", end="\t") + +for case in cases: + print(f"{case['exe']}", end="\t") + +for key, value in inputValues.items(): + # Update the specific line in the file + # print("Updating for {}".format(value)) + print("\n{}".format(key), end="\t") + with open(input_file_path, "w") as file: + for line in lines: + if line.strip().startswith("#define INPUT_LENGTH"): + if sys.argv[1] == "speakerIdentification.c": + updated_line = f"#define INPUT_LENGTH {math.floor(value/8.192)}\n" + elif sys.argv[1] == "FIRFilterDesign.c": + updated_line = f"#define INPUT_LENGTH {value +1}\n" + else: + updated_line = f"#define INPUT_LENGTH {value}\n" + file.write(updated_line) + else: + file.write(line) + + for case in cases: + + if case["hexagon-clang"]: + command = f"/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-clang -O3 -o {OutputPath}/{case['exe']} {input_file_path} -lm", + if case["llvm-clang"]: + command = f"{BasePathForLLVM}/build/bin/clang-19 -O3 {input_file_path} -o {OutputPath}/{case['exe']} -lm --target=hexagon -mcpu=hexagonv68 -fuse-ld=/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-link", + + result = subprocess.run(command, shell=True, capture_output=True, text=True) + + sum_exe_time = 0 + for i in range(0, NoOfIterations): + command2 = f"{BasePathForLLVM}/Hexagon_Tools/bin/hexagon-sim --mv68 ./Output/{sys.argv[2]}/{case['exe']}" + + # Record the start time + #start_time = time.time() + + # Execute the command + try: + result2 = subprocess.run( + command2, + shell=True, + #stdout=subprocess.DEVNULL, + #stderr=subprocess.DEVNULL, + #check=True, + capture_output = True, + text = True, + check=True, + ) + # subprocess.run(command2, shell=True) + pcycle = int(result2.stderr.split("Pcycles=")[1].replace("\n","").replace(" ","").replace("\t","")) + except subprocess.CalledProcessError as exc: + print( + f"Process failed because did not return a successful return code. " + f"Returned {exc.returncode}\n{exc}" + ) + + #end_time = time.time() + + #execution_time = end_time - start_time + #sum_exe_time = sum_exe_time + execution_time + sum_exe_time = sum_exe_time + pcycle + avg_exe_time = sum_exe_time + print("{}".format(avg_exe_time), end="\t") diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/ResultScript.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/ResultScript.py index 9cd5fc3e02a7..e53ed67f58c2 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/ResultScript.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/ResultScript.py @@ -18,7 +18,11 @@ # Path to the input file # Apps = "lowPassFIRFilterDesign.c", "noisecancelling.c" , "echocancelling.c", "hearingAid.c", "audioEqualizer.c", "vibrationAnalysis.c", "underWaterCommunication.c", "voiceActivityDetection.c", "signalSmoothing", "targetDetection", "biomedicalSignalProcessing", "periodogram2Conv", "spaceCommunication", "dtmfDetection", "speakerIdentification" input_file_name = sys.argv[1] -BasePathForLLVM = "/home/local/ASURITE/apkhedka/ForLLVM/" +full_path = os.path.abspath(__file__) + +# Find the path up to 'DSP_MLIR' +if 'DSP_MLIR' in full_path: + BasePathForLLVM = full_path.split('DSP_MLIR')[0] + 'DSP_MLIR/' OutputScriptPath = "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/" # OutputPath = BasePathForLLVM + "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/Results/TryResultScript/Output/" input_file_path = BasePathForLLVM + OutputScriptPath + input_file_name @@ -182,6 +186,7 @@ "10K": 10000, "20K": 20000, "30K": 30000, + "40K": 40000 } elif sys.argv[1] == "audioEqualization.c": @@ -407,7 +412,7 @@ "1M": 1000000, } -NoOfIterations = 3 +NoOfIterations = 30 # Define the cases @@ -442,6 +447,8 @@ if line.strip().startswith("#define INPUT_LENGTH"): if sys.argv[1] == "speakerIdentification.c": updated_line = f"#define INPUT_LENGTH {math.floor(value/8.192)}\n" + elif sys.argv[1] == "FIRFilterDesign.c": + updated_line = f"#define INPUT_LENGTH {value +1}\n" else: updated_line = f"#define INPUT_LENGTH {value}\n" file.write(updated_line) @@ -461,7 +468,7 @@ for i in range(0, NoOfIterations): try: process = subprocess.run( - "sudo sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'", + "sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'", shell=True, check=True, ) diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/RunHexagon.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/RunHexagon.py new file mode 100644 index 000000000000..442aae67face --- /dev/null +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/RunHexagon.py @@ -0,0 +1,50 @@ +import subprocess +import os + +# Ensure the log directory exists +log_dir = "ServerExeLogs" +os.makedirs(log_dir, exist_ok=True) + +# Corrected list of application names (without non-application entries) +app_names = [ + "speakerIdentification", + "targetDetection", + "underWaterCommunication", + "voiceActivityDetection", + "spectralAnalysis", + "audioCompression", + "audioEqualization", + "biomedicalSignalProcessing", + "digitalModulation", + "dtmfDetection", + "echoCancellation", + "FIRFilterDesign", + "hearingAid", + "lowPassFiltering", + "noiseCancellation", + "periodogram", + "vibrationAnalysis", + "radarSignalProcessing", + "signalSmoothing", + "spaceCommunication" +] + +# Loop through each application and execute the script +for app_name in app_names: + app_script = f"{app_name}.c" + log_file = os.path.join(log_dir, f"{app_name}.log") + with open(log_file, "w") as log: + command = ["python", "HexagonClangResultScript.py", app_script, app_name] + print("") + print(f"Running command: {' '.join(command)}") + process = subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True + ) + for line in process.stdout: + print(line, end="") + log.write(line) + for line in process.stderr: + print(line, end="") + log.write(line) + process.wait() + diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/audioCompression.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/audioCompression.c index f8239d55d35b..5797d0ffca8d 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/audioCompression.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/audioCompression.c @@ -3,11 +3,13 @@ #include #include -#define INPUT_LENGTH 10 +#define INPUT_LENGTH 500 #define NLEVELS 16 #define MIN 0.0 #define MAX 8.0 #define THRESHOLD_VAL 4.0 +#define M_PI 3.14159265358979323846 + double *getRangeOfVector(double start, int noOfSamples, double increment) { double *output = malloc(noOfSamples * sizeof(double)); @@ -140,4 +142,4 @@ int main() { free(rLEOutImg); return 0; -} \ No newline at end of file +} diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/hearingAid.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/hearingAid.c index 21657587aec4..a35436ad7f42 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/hearingAid.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/hearingAid.c @@ -3,7 +3,7 @@ #include #define PI 3.14159265359 -#define INPUT_LENGTH 10 +#define INPUT_LENGTH 100000000 #define FILTER_LENGTH 32 // Function to generate a range of values @@ -58,47 +58,55 @@ int main() { int fs = 8000; double step = 1.0 / fs; - // Allocate memory for vectors - double input[INPUT_LENGTH]; - double getSinDuration[INPUT_LENGTH]; - double clean_sig[INPUT_LENGTH]; - double getNoiseSinDuration[INPUT_LENGTH]; - double noise[INPUT_LENGTH]; - double noise1[INPUT_LENGTH]; - double noisy_sig[INPUT_LENGTH]; - double y[INPUT_LENGTH]; - double sol[INPUT_LENGTH]; - - // Generate input range + // Allocate memory dynamically + double* input = malloc(INPUT_LENGTH * sizeof(double)); + double* getSinDuration = malloc(INPUT_LENGTH * sizeof(double)); + double* clean_sig = malloc(INPUT_LENGTH * sizeof(double)); + double* getNoiseSinDuration = malloc(INPUT_LENGTH * sizeof(double)); + double* noise = malloc(INPUT_LENGTH * sizeof(double)); + double* noise1 = malloc(INPUT_LENGTH * sizeof(double)); + double* noisy_sig = malloc(INPUT_LENGTH * sizeof(double)); + double* y = malloc(INPUT_LENGTH * sizeof(double)); + double* sol = malloc(INPUT_LENGTH * sizeof(double)); + + if (!input || !getSinDuration || !clean_sig || !getNoiseSinDuration || + !noise || !noise1 || !noisy_sig || !y || !sol) { + printf("Memory allocation failed!\n"); + return -1; + } + getRangeOfVector(input, 0.0, INPUT_LENGTH, step); - // Generate clean signal double f_sig = 500; gain(getSinDuration, input, 2 * PI * f_sig, INPUT_LENGTH); sine(clean_sig, getSinDuration, INPUT_LENGTH); - // Generate noise signal with frequency of 3000 Hz double f_noise = 3000; gain(getNoiseSinDuration, input, 2 * PI * f_noise, INPUT_LENGTH); sine(noise, getNoiseSinDuration, INPUT_LENGTH); - gain(noise1, noise, 0.5, INPUT_LENGTH); - // Create noisy signal by adding noise to clean signal add(noisy_sig, clean_sig, noise1, INPUT_LENGTH); - double mu = 0.01; lmsFilterResponse(y, noisy_sig, clean_sig, mu, FILTER_LENGTH, INPUT_LENGTH); - double G1 = 123; gain(sol, y, G1, INPUT_LENGTH); - printf("%f\n", sol[3]); + // Free allocated memory + free(input); + free(getSinDuration); + free(clean_sig); + free(getNoiseSinDuration); + free(noise); + free(noise1); + free(noisy_sig); + free(y); + free(sol); return 0; } \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/lowPassFiltering.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/lowPassFiltering.c index 3903a26caf13..61902bc57aa6 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/lowPassFiltering.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/lowPassFiltering.c @@ -1,71 +1,147 @@ #include -#include #include +#include #define PI 3.14159265359 -#define FS 8000 -#define N 101 -#define INPUT_LENGTH 100 -#define FILTER_LENGTH 200 +#define INPUT_LENGTH 10000 + +double* getRangeOfVector(double start, int noOfSamples, double increment) { + double* output = malloc(noOfSamples * sizeof(double)); + if (!output) { + perror("Memory allocation failed in getRangeOfVector"); + exit(EXIT_FAILURE); + } + + for (int i = 0; i < noOfSamples; i++) { + output[i] = start + i * increment; + } + + return output; +} + +void gain(double* output, double* input, double multiplier, int length) { + for (int i = 0; i < length; i++) { + output[i] = input[i] * multiplier; + } +} -void generate_signal(double *signal, double freq, int length) { +void elementWiseAdd(double* output, double* input1, double* input2, int length) { for (int i = 0; i < length; i++) { - signal[i] = sin(2 * PI * freq * i / FS); + output[i] = input1[i] + input2[i]; } } -void generate_lowpass_filter(double *filter, double cutoff_freq) { - double wc = 2 * PI * cutoff_freq / FS; - for (int i = 0; i < N; i++) { - int n = i - (N / 2); - if (n == 0) { - filter[i] = wc / PI; +void elementWiseMultiply(double* output, double* input1, double* input2, int length) { + for (int i = 0; i < length; i++) { + output[i] = input1[i] * input2[i]; + } +} + +void lowPassFIRFilter(double* lpf, double wc, int N) { + int mid = (N - 1) / 2; + for (int n = 0; n < N; n++) { + if (n == mid) { + lpf[n] = wc / PI; } else { - filter[i] = sin(wc * n) / (PI * n); + lpf[n] = (wc / PI) * sin(wc * (n - mid)) / (wc * (n - mid)); } - // Apply Hamming window - filter[i] *= (0.54 - 0.46 * cos(2 * PI * i / (N - 1))); } } -void apply_fir_filter(double *input, double *output, double *filter) { - for (int i = 0; i < FILTER_LENGTH; i++) { - double sum = 0.0; - for (int j = 0; j < N; j++) { - if (i - j >= 0 && i - j < INPUT_LENGTH) { - sum += input[i - j] * filter[j]; +void hammingWindow(double* hamming, int N) { + for (int n = 0; n < N; n++) { + hamming[n] = 0.54 - 0.46 * cos(2 * PI * n / (N - 1)); + } +} + +void FIRFilterResponse(double* output, double* input, double* filter, int input_length, int filter_length) { + int i, j; + for (i = 0; i < input_length; i++) { + output[i] = 0; + for (j = 0; j < filter_length; j++) { + if (i - j >= 0) { + output[i] += input[i - j] * filter[j]; } } - output[i] = sum; } } int main() { - double clean_signal[INPUT_LENGTH]; - double noise_signal[INPUT_LENGTH]; - double noisy_signal[INPUT_LENGTH]; - double fir_filter[N]; - double filtered_signal[FILTER_LENGTH] = {0}; - - // Generate clean signal with frequency 500Hz - generate_signal(clean_signal, 500, INPUT_LENGTH); + int fs = 8000; + + // Allocate memory dynamically + double* input = getRangeOfVector(0, INPUT_LENGTH, 0.000125); - // Generate noise signal with frequency 3000Hz and scale it - generate_signal(noise_signal, 3000, INPUT_LENGTH); + // Allocate other large arrays dynamically + double* getSinDuration = malloc(INPUT_LENGTH * sizeof(double)); + double* clean_sig = malloc(INPUT_LENGTH * sizeof(double)); + double* getNoiseSinDuration = malloc(INPUT_LENGTH * sizeof(double)); + double* noise = malloc(INPUT_LENGTH * sizeof(double)); + double* noisy_sig = malloc(INPUT_LENGTH * sizeof(double)); + double* scaled_noise = malloc(INPUT_LENGTH * sizeof(double)); + double* FIRfilterResponse = malloc(INPUT_LENGTH * sizeof(double)); + + // Check if memory allocation was successful + if (!getSinDuration || !clean_sig || !getNoiseSinDuration || !noise || !noisy_sig || !scaled_noise || !FIRfilterResponse) { + perror("Memory allocation failed"); + free(input); + free(getSinDuration); + free(clean_sig); + free(getNoiseSinDuration); + free(noise); + free(noisy_sig); + free(scaled_noise); + free(FIRfilterResponse); + exit(EXIT_FAILURE); + } + + // Signal processing steps + double f_sig = 500; + gain(getSinDuration, input, 2 * PI * f_sig, INPUT_LENGTH); + for (int i = 0; i < INPUT_LENGTH; i++) { - noise_signal[i] *= 0.5; - noisy_signal[i] = clean_signal[i] + noise_signal[i]; + clean_sig[i] = sin(getSinDuration[i]); } - // Design low-pass filter with cutoff frequency 1000Hz - generate_lowpass_filter(fir_filter, 1000); + double f_noise = 3000; + gain(getNoiseSinDuration, input, 2 * PI * f_noise, INPUT_LENGTH); - // Apply FIR filter - apply_fir_filter(noisy_signal, filtered_signal, fir_filter); + for (int i = 0; i < INPUT_LENGTH; i++) { + noise[i] = sin(getNoiseSinDuration[i]); + } - - printf("%f\n", filtered_signal[6]); + gain(scaled_noise, noise, 0.5, INPUT_LENGTH); + elementWiseAdd(noisy_sig, clean_sig, scaled_noise, INPUT_LENGTH); + // Filter design + double fc = 1000; + double wc = 2 * PI * fc / fs; + int N = 101; - return 0; -} + double lpf[N]; + lowPassFIRFilter(lpf, wc, N); + + double hamming[N]; + hammingWindow(hamming, N); + + double lpf_w[N]; + elementWiseMultiply(lpf_w, lpf, hamming, N); + + FIRFilterResponse(FIRfilterResponse, noisy_sig, lpf_w, INPUT_LENGTH, N); + + + printf("%f\n", FIRfilterResponse[6]); + + + // Free allocated memory at the end + free(input); + free(getSinDuration); + free(clean_sig); + free(getNoiseSinDuration); + free(noise); + free(noisy_sig); + free(scaled_noise); + free(FIRfilterResponse); + + return 0; +} \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/speakerIdentification.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/speakerIdentification.c index 1fb7ff58fc5c..6d86b9f6c3e3 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/speakerIdentification.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/speakerIdentification.c @@ -3,9 +3,11 @@ #include #define SAMPLE_RATE 1000 -#define INPUT_LENGTH 12207 +#define INPUT_LENGTH 61 #define DURATION ((double)INPUT_LENGTH / SAMPLE_RATE) #define CORRELATION_LENGTH (2 * INPUT_LENGTH - 1) +#define M_PI 3.14159265358979323846 + void generateVoiceSignature(double *signal, double freq1, double freq2) { for (int i = 0; i < INPUT_LENGTH; i++) { diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/targetDetection.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/targetDetection.c index 0235c5c5933d..305eb1c1241f 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/targetDetection.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/targetDetection.c @@ -4,7 +4,7 @@ #define PI 3.14159265359 #define FS 1000 -#define INPUT_LENGTH 1000 +#define INPUT_LENGTH 50000000 #define FILTER_SIZE 20 #define MAX_PEAKS 50 @@ -104,48 +104,62 @@ double getElemAtIndx(double* input, int index) { int main() { double pi = PI; - double input[INPUT_LENGTH]; - getRangeOfVector(input, 0, INPUT_LENGTH, 0.000125); + int len = INPUT_LENGTH; + + // Dynamically allocate memory + double *input = malloc(len * sizeof(double)); + double *getSinDuration = malloc(len * sizeof(double)); + double *sig1 = malloc(len * sizeof(double)); + double *getSinDuration2 = malloc(len * sizeof(double)); + double *sinsig2 = malloc(len * sizeof(double)); + double *sig2 = malloc(len * sizeof(double)); + double *signal = malloc(len * sizeof(double)); + double *noise = malloc(len * sizeof(double)); + double *noisy_sig = malloc(len * sizeof(double)); + double *y = malloc(len * sizeof(double)); + + // Check allocation + if (!input || !getSinDuration || !sig1 || !getSinDuration2 || !sinsig2 || + !sig2 || !signal || !noise || !noisy_sig || !y) { + printf("Memory allocation failed.\n"); + return -1; + } + getRangeOfVector(input, 0, len, 0.000125); double getMultiplier = 2 * pi * 10; - double getSinDuration[INPUT_LENGTH]; - gain(getSinDuration, input, getMultiplier, INPUT_LENGTH); - - double sig1[INPUT_LENGTH]; - sine(sig1, getSinDuration, INPUT_LENGTH); + gain(getSinDuration, input, getMultiplier, len); + sine(sig1, getSinDuration, len); double getMultiplier2 = 2 * pi * 20; - double getSinDuration2[INPUT_LENGTH]; - gain(getSinDuration2, input, getMultiplier2, INPUT_LENGTH); - - double sinsig2[INPUT_LENGTH]; - sine(sinsig2, getSinDuration2, INPUT_LENGTH); - - double sig2[INPUT_LENGTH]; - gain(sig2, sinsig2, 0.5, INPUT_LENGTH); - - double signal[INPUT_LENGTH]; - add(signal, sig1, sig2, INPUT_LENGTH); - - double noise[INPUT_LENGTH]; - delay(noise, signal, 5, INPUT_LENGTH); - - double noisy_sig[INPUT_LENGTH]; - add(noisy_sig, signal, noise, INPUT_LENGTH); + gain(getSinDuration2, input, getMultiplier2, len); + sine(sinsig2, getSinDuration2, len); + gain(sig2, sinsig2, 0.5, len); + add(signal, sig1, sig2, len); + delay(noise, signal, 5, len); + add(noisy_sig, signal, noise, len); double mu = 0.01; - double y[INPUT_LENGTH]; - lmsFilterResponse(y, noisy_sig, signal, mu, FILTER_SIZE, INPUT_LENGTH); + lmsFilterResponse(y, noisy_sig, signal, mu, FILTER_SIZE, len); double peaks[MAX_PEAKS]; - find_peaks(peaks, y, INPUT_LENGTH, 1.0, 50); + find_peaks(peaks, y, len, 1.0, 50); double final1 = getElemAtIndx(peaks, 1); double final2 = getElemAtIndx(peaks, 0); - - printf("%f\t", final1); - printf("%f", final2); - + printf("%f\t%f\n", final1, final2); + + // Free memory + free(input); + free(getSinDuration); + free(sig1); + free(getSinDuration2); + free(sinsig2); + free(sig2); + free(signal); + free(noise); + free(noisy_sig); + free(y); return 0; } + diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/underWaterCommunication.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/underWaterCommunication.c index 8aff517fa10e..6bc4edd47c73 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/underWaterCommunication.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/underWaterCommunication.c @@ -85,44 +85,51 @@ double getElemAtIndx(double* input, int index) { int main() { double pi = PI; - double input[INPUT_LENGTH]; + + double *input = malloc(INPUT_LENGTH * sizeof(double)); + double *getSinDuration = malloc(INPUT_LENGTH * sizeof(double)); + double *signal = malloc(INPUT_LENGTH * sizeof(double)); + double *noise = malloc(INPUT_LENGTH * sizeof(double)); + double *noisy_sig = malloc(INPUT_LENGTH * sizeof(double)); + double *FIRfilterResponseArray = malloc(INPUT_LENGTH * sizeof(double)); + double *GetThresholdReal = malloc(INPUT_LENGTH * sizeof(double)); + + // Always check for successful allocation + if (!input || !getSinDuration || !signal || !noise || !noisy_sig || + !FIRfilterResponseArray || !GetThresholdReal) { + printf("Memory allocation failed\n"); + return -1; + } + getRangeOfVector(input, 0, INPUT_LENGTH, 0.000125); double getMultiplier = 2 * pi * 5; - double getSinDuration[INPUT_LENGTH]; gain(getSinDuration, input, getMultiplier, INPUT_LENGTH); - - double signal[INPUT_LENGTH]; sine(signal, getSinDuration, INPUT_LENGTH); - - double noise[INPUT_LENGTH]; delay(noise, signal, 5, INPUT_LENGTH); - - double noisy_sig[INPUT_LENGTH]; add(noisy_sig, signal, noise, INPUT_LENGTH); - // Low-pass filter design double wc = 2 * pi * 1000 / 500; int N = 5; - double lpf = lowPassFIRFilter(wc, 1); - double hamming_window[N]; hamming(hamming_window, N); - - double lpf_w = lpf * hamming_window[0]; - - double FIRfilterResponseArray[INPUT_LENGTH]; FIRFilterResponse(FIRfilterResponseArray, noisy_sig, lpf_w, INPUT_LENGTH); - double threshold = 0.05; - double GetThresholdReal[INPUT_LENGTH]; thresholdUp(GetThresholdReal, FIRfilterResponseArray, threshold, 0, INPUT_LENGTH); double final1 = getElemAtIndx(GetThresholdReal, 3); + printf("%f\n", final1); - printf("%f", final1); + free(input); + free(getSinDuration); + free(signal); + free(noise); + free(noisy_sig); + free(FIRfilterResponseArray); + free(GetThresholdReal); return 0; } + diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/vibrationAnalysis.c b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/vibrationAnalysis.c index a30a3c4f5a13..50f1f176af2d 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/vibrationAnalysis.c +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/CCode/vibrationAnalysis.c @@ -4,7 +4,7 @@ #include #define PI 3.14159265359 -#define INPUT_LENGTH 10 +#define INPUT_LENGTH 100 // Function prototypes double *getRangeOfVector(double start, int length, double increment); diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/FIRFilterDesign.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/FIRFilterDesign.py index 40081eeefdf2..7cc6e9c9a704 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/FIRFilterDesign.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/FIRFilterDesign.py @@ -8,7 +8,7 @@ def main() { # var a10 = getRangeOfVector(0, 400, 0.000125); # var orig = sin(a10); - var N_input = 101; + var N_input = 10000001; # for cut-off freq var pi = 3.14159265359; @@ -44,11 +44,11 @@ def main() { var final2 = getElemAtIndx(hpf_w2 , [7]); var final3 = getElemAtIndx(hpf_w3 , [8]); # var final4 = getElemAtIndx(hpf_w4 , [500]); - # var final4 = getElemAtIndx(hpf_w4 , [5]); + var final4 = getElemAtIndx(hpf_w4 , [5]); print(final1); print(final2); print(final3); - # print(final4); + print(final4); # print(hpf_w); diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonClangResultScript.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonClangResultScript.py index 3f26f9ce3a79..bdd2c9ca6215 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonClangResultScript.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonClangResultScript.py @@ -20,10 +20,11 @@ # Apps = "hearingAid.py" , "lowPassFull.py" , " audioCompression.py", "lowPassFIRFilterDesign.py" , "EnergyOfSignal.py", "periodogram2Conv1.py", "audioEqualizer.py", "vibrationAnalysis.py", "signalSmoothing.py", "targetDetection.py", "biomedicalSignalProcessing.py", "spaceCommunication.py", "echocancelling", "noisecancelling.py", "digitalModulation", "underWaterCommunication", "voiceActivityDetection", "radarSignalProcessing", "speakerIdentification" # input_file_name = "speakerIdentification.py" input_file_name = sys.argv[1] +full_path = os.path.abspath(__file__) - - -BasePathForLLVM = "/home/local/ASURITE/apkhedka/ForLLVM/" +# Find the path up to 'DSP_MLIR' +if 'DSP_MLIR' in full_path: + BasePathForLLVM = full_path.split('DSP_MLIR')[0] + 'DSP_MLIR/' OutputScriptPath = ( "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/" ) @@ -379,9 +380,8 @@ # "clang-17 -O0 file.ll -o fileexe -lm", ] -# clang = f"{BasePathForLLVM}/build/bin/clang LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld=/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-link" -clang = f"/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-clang LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld=/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-link" +clang = f"{BasePathForLLVM}/Hexagon_Tools/bin/hexagon-clang LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld={BasePathForLLVM}/Hexagon_Tools/bin/hexagon-link" # Define the cases cases = [ @@ -404,7 +404,7 @@ "affineOpt": True, "canonOpt": False, "suffix": "fileAffineOpt.ll", - "exe": "fileAffineOptExe", + "exe": "AffineExe", }, # { # "affineOpt": False, @@ -416,7 +416,7 @@ "affineOpt": True, "canonOpt": True, "suffix": "fileAffineCanonOpt.ll", - "exe": "fileAffineCanonOptExe", + "exe": "DSP_MLIRExe", }, ] @@ -517,7 +517,7 @@ # command2 = f"taskset -c 0 ./{case['exe']}" #{OutputPath} # command2 = f"taskset -c 0 ./Output/{case['exe']}" - command2 = "/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-sim --mv68 OUT_FILE_PATH".replace("OUT_FILE_PATH", out_file_path) + command2 = f"{BasePathForLLVM}/Hexagon_Tools/bin/hexagon-sim --mv68 OUT_FILE_PATH".replace("OUT_FILE_PATH", out_file_path) diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonResultScript.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonResultScript.py index 0de93a9a3ac3..8e6d7c4c6907 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonResultScript.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/HexagonResultScript.py @@ -20,10 +20,11 @@ # Apps = "hearingAid.py" , "lowPassFull.py" , " audioCompression.py", "lowPassFIRFilterDesign.py" , "EnergyOfSignal.py", "periodogram2Conv1.py", "audioEqualizer.py", "vibrationAnalysis.py", "signalSmoothing.py", "targetDetection.py", "biomedicalSignalProcessing.py", "spaceCommunication.py", "echocancelling", "noisecancelling.py", "digitalModulation", "underWaterCommunication", "voiceActivityDetection", "radarSignalProcessing", "speakerIdentification" # input_file_name = "speakerIdentification.py" input_file_name = sys.argv[1] +full_path = os.path.abspath(__file__) - - -BasePathForLLVM = "/home/local/ASURITE/apkhedka/ForLLVM/" +# Find the path up to 'DSP_MLIR' +if 'DSP_MLIR' in full_path: + BasePathForLLVM = full_path.split('DSP_MLIR')[0] + 'DSP_MLIR/' OutputScriptPath = ( "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/" ) @@ -379,10 +380,14 @@ # "clang-17 -O0 file.ll -o fileexe -lm", ] -clang = f"{BasePathForLLVM}/build/bin/clang LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld=/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-link" +clang = f"{BasePathForLLVM}/build/bin/clang-19 LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld={BasePathForLLVM}/Hexagon_Tools/bin/hexagon-link" # clang = f"/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-clang LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld=/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-link" +# clang = f"{BasePathForLLVM}/build/bin/clang LL_FILE_PATH -O3 -o OUT_FILE_PATH --target=hexagon -mcpu=hexagonv68 -fuse-ld=/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-link" + + + # Define the cases cases = [ # { @@ -404,7 +409,7 @@ "affineOpt": True, "canonOpt": False, "suffix": "fileAffineOpt.ll", - "exe": "fileAffineOptExe", + "exe": "AffineExe", }, # { # "affineOpt": False, @@ -416,7 +421,7 @@ "affineOpt": True, "canonOpt": True, "suffix": "fileAffineCanonOpt.ll", - "exe": "fileAffineCanonOptExe", + "exe": "DSP_MLIRExe", }, ] @@ -517,7 +522,10 @@ # command2 = f"taskset -c 0 ./{case['exe']}" #{OutputPath} # command2 = f"taskset -c 0 ./Output/{case['exe']}" - command2 = "/local/mnt/workspace/Qualcomm/Hexagon_SDK/6.2.0.1/tools/HEXAGON_Tools/8.8.06/Tools/bin/hexagon-sim --mv68 OUT_FILE_PATH".replace("OUT_FILE_PATH", out_file_path) + # command2 = f"/{BasePathForLLVM}/build/bin/hexagon-sim --mv68 OUT_FILE_PATH".replace("OUT_FILE_PATH", out_file_path) + + command2 = f"{BasePathForLLVM}/Hexagon_Tools/bin/hexagon-sim --mv68 OUT_FILE_PATH".replace("OUT_FILE_PATH", out_file_path) + diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/ResultScript.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/ResultScript.py index 2a5cdeb9e708..2230d01160bb 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/ResultScript.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/ResultScript.py @@ -20,9 +20,11 @@ # Apps = "hearingAid.py" , "lowPassFull.py" , " audioCompression.py", "lowPassFIRFilterDesign.py" , "EnergyOfSignal.py", "periodogram2Conv1.py", "audioEqualizer.py", "vibrationAnalysis.py", "signalSmoothing.py", "targetDetection.py", "biomedicalSignalProcessing.py", "spaceCommunication.py", "echocancelling", "noisecancelling.py", "digitalModulation", "underWaterCommunication", "voiceActivityDetection", "radarSignalProcessing", "speakerIdentification" # input_file_name = "speakerIdentification.py" input_file_name = sys.argv[1] +full_path = os.path.abspath(__file__) - -BasePathForLLVM = "/home/local/ASURITE/apkhedka/ForLLVM/" +# Find the path up to 'DSP_MLIR' +if 'DSP_MLIR' in full_path: + BasePathForLLVM = full_path.split('DSP_MLIR')[0] + 'DSP_MLIR/' OutputScriptPath = ( "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/" ) @@ -44,7 +46,7 @@ # Now OutputPath is ready for use -print("InputPath:{}".format(BasePathForLLVM)) +# print("InputPath:{}".format(BasePathForLLVM)) print(f"OutputPath: {OutputPath}") # ************ Don't change unless u required @@ -183,12 +185,13 @@ elif sys.argv[1] == "spectralAnalysis.py": inputValues = { - "10": 10, + # "10": 10, "100": 100, "1K": 1000, "10K": 10000, "20K": 20000, "30K": 30000, + "40K": 40000, } elif sys.argv[1] == "audioEqualization.py": @@ -414,7 +417,7 @@ "1M": 1000000, } -NoOfIterations = 3 +NoOfIterations = 30 # -------------------------------------------------- commands_base = [ @@ -436,13 +439,13 @@ "affineOpt": True, "canonOpt": False, "suffix": "fileAffineOpt.ll", - "exe": "fileAffineOptExe", + "exe": "AffineExe", }, { "affineOpt": True, "canonOpt": True, "suffix": "fileAffineCanonOpt.ll", - "exe": "fileAffineCanonOptExe", + "exe": "DSP_MLIRExe", }, ] @@ -465,14 +468,14 @@ with open(input_file_path, "w") as file: for line in lines: if line.strip().startswith("var input = getRangeOfVector("): - if input_file_name in [ + if sys.argv[1] in [ "audioCompression.py", "audioEqualization.py", "periodogram.py", "spectralAnalysis.py", ]: updated_line = f"\tvar input = getRangeOfVector(0, {value}, 1);\n" - if input_file_name in ["voiceActivityDetection.py"]: + elif sys.argv[1] in ["voiceActivityDetection.py"]: updated_line = ( f"\tvar input = getRangeOfVector(0, {value}, 0.125);\n" ) @@ -528,7 +531,7 @@ # subprocess.run("sync; echo 3 > /proc/sys/vm/drop_caches", shell=True) try: process = subprocess.run( - "sudo sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'", + "sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'", shell=True, check=True, ) diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunHexagon.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunHexagon.py index f58f706418ce..26d0545a4364 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunHexagon.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunHexagon.py @@ -7,10 +7,9 @@ # Corrected list of application names (without non-application entries) app_names = [ - "spectralAnalysis", + "biomedicalSignalProcessing", "audioCompression", "audioEqualization", - "biomedicalSignalProcessing", "digitalModulation", "dtmfDetection", "echoCancellation", @@ -26,15 +25,23 @@ "speakerIdentification", "targetDetection", "underWaterCommunication", - "voiceActivityDetection" + "voiceActivityDetection", + "spectralAnalysis" ] # Loop through each application and execute the HexagonResultScript.py script + + +log_dir2 = "HClanglogs" +os.makedirs(log_dir2, exist_ok=True) + + + for app_name in app_names: app_script = f"{app_name}.py" - log_file = os.path.join(log_dir, f"{app_name}.log") - with open(log_file, "w") as log: - command = ["python", "HexagonResultScript.py", app_script, app_name] + log_file2 = os.path.join(log_dir2, f"{app_name}.log") + with open(log_file2, "w") as log: + command = ["python", "HexagonClangResultScript.py", app_script, app_name] print(f"Running command: {' '.join(command)}") process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True @@ -47,17 +54,11 @@ log.write(line) process.wait() - -log_dir2 = "HClanglogs" -os.makedirs(log_dir2, exist_ok=True) - - - for app_name in app_names: app_script = f"{app_name}.py" - log_file2 = os.path.join(log_dir2, f"{app_name}.log") - with open(log_file2, "w") as log: - command = ["python", "HexagonClangResultScript.py", app_script, app_name] + log_file = os.path.join(log_dir, f"{app_name}.log") + with open(log_file, "w") as log: + command = ["python", "HexagonResultScript.py", app_script, app_name] print(f"Running command: {' '.join(command)}") process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunResults.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunResults.py index 82f82c941ae9..594e3394a3ca 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunResults.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/DSP-DSL/RunResults.py @@ -7,6 +7,10 @@ # Corrected list of application names (without non-application entries) app_names = [ + "speakerIdentification", + "targetDetection", + "underWaterCommunication", + "voiceActivityDetection", "spectralAnalysis", "audioCompression", "audioEqualization", @@ -22,11 +26,7 @@ "vibrationAnalysis", "radarSignalProcessing", "signalSmoothing", - "spaceCommunication", - "speakerIdentification", - "targetDetection", - "underWaterCommunication", - "voiceActivityDetection" + "spaceCommunication" ] # Loop through each application and execute the script diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/FIRFilterDesign.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/FIRFilterDesign.m index 0b364f0d3e89..62397fac8a93 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/FIRFilterDesign.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/FIRFilterDesign.m @@ -1,48 +1,56 @@ -% Constants -INPUT_LENGTH = 100000000; -FS = 8000; -FC1 = 500; -FC2 = 600; -FC3 = 1000; - -% Calculate normalized frequencies -wc1 = 2 * pi * FC1 / FS; -wc2 = 2 * pi * FC2 / FS; -wc3 = 2 * pi * FC3 / FS; - -% Create Hamming window -hamming_window = hamming(INPUT_LENGTH); - -% Create high-pass filters +INPUT_LENGTH = 101; +fs = 8000; +fc1 = 500; +fc2 = 600; +fc3 = 1000; +fc4 = 1200; + +wc1 = 2 * pi * fc1 / fs; +wc2 = 2 * pi * fc2 / fs; +wc3 = 2 * pi * fc3 / fs; +wc4 = 2 * pi * fc4 / fs; + +hamming_window = hammingWindow(INPUT_LENGTH); + hpf1 = highPassFIRFilter(wc1, INPUT_LENGTH); hpf2 = highPassFIRFilter(wc2, INPUT_LENGTH); hpf3 = highPassFIRFilter(wc3, INPUT_LENGTH); +hpf4 = highPassFIRFilter(wc4, INPUT_LENGTH); + +hpf_w1 = elementWiseMultiply(hpf1, hamming_window); +hpf_w2 = elementWiseMultiply(hpf2, hamming_window); +hpf_w3 = elementWiseMultiply(hpf3, hamming_window); +hpf_w4 = elementWiseMultiply(hpf4, hamming_window); + +final1 = getElemAtIndex(hpf_w1, 6); +final2 = getElemAtIndex(hpf_w2, 7); +final3 = getElemAtIndex(hpf_w3, 8); + +fprintf('%.6f\n', final1); +fprintf('%.6f\n', final2); +fprintf('%.6f\n', final3); + +function window = hammingWindow(length) + n = 0:length-1; + window = 0.54 - 0.46 * cos(2 * pi * n / (length - 1)); +end + +function filter = highPassFIRFilter(wc, length) + mid = (length - 1) / 2; + filter = zeros(1, length); + for n = 0:length-1 + if n == mid + filter(n+1) = 1 - (wc / pi); + else + filter(n+1) = -sin(wc * (n - mid)) / (pi * (n - mid)); + end + end +end + +function output = elementWiseMultiply(array1, array2) + output = array1 .* array2; +end -% Element-wise multiplication with Hamming window -hpf_w1 = hpf1 .* hamming_window'; -hpf_w2 = hpf2 .* hamming_window'; -hpf_w3 = hpf3 .* hamming_window'; - -% Get specific elements -final1 = hpf_w1(7); -final2 = hpf_w2(8); -final3 = hpf_w3(9); - -% Display results -fprintf('%f\n', final1); -fprintf('%f\n', final2); -fprintf('%f\n', final3); - -% High-pass FIR filter function -function h = highPassFIRFilter(wc, filterLength) - n = 0:(filterLength-1); - mid = (filterLength-1) / 2; - h = zeros(1, filterLength); - - % Use logical indexing to avoid issues with non-integer indices - midIndex = (n ~= mid); - h(midIndex) = -sin(wc * (n(midIndex) - mid)) ./ (pi * (n(midIndex) - mid)); - - % Handle the middle point separately - h(floor(mid)+1) = 1 - (wc / pi); +function value = getElemAtIndex(array, index) + value = array(index + 1); end \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/ResultScript.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/ResultScript.py index 8da6b86da1fa..3bb6ec31724a 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/ResultScript.py +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/ResultScript.py @@ -2,6 +2,7 @@ import subprocess import time import re +import sys # The script does the following # Input : filename.py # Output : TimeOfExecution for different IP sizes : @@ -16,16 +17,26 @@ # Path to the input file # Apps = "noiseCancelling.m" , "echoCancelling.m", "periodogram.m", "lowPassFull.m", "hearingAid.m", "lowPassFIRFilterDesign", "energyOfSignal", "audioEqualizer", "audioCompression","vibrationAnalysis", "underWaterCommunication", "voiceActivityDetection", "signalSmoothing", "targetDetection", "biomedicalSignalProcessing", "digitalModulation", "spaceCommunication", "radarSignalProcessing" -input_file = "speakerIdentification" -input_file_path = input_file + ".m" -BasePathForLLVM = "/home/local/ASURITE/apkhedka/ForLLVM/" -OutputScriptPath = "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/" mcc_path ="/home/local/ASURITE/apkhedka/Matlab_Installation/bin/mcc" mrt_path ="/home/local/ASURITE/apkhedka/Matlab_Runtime/R2024b/" # OutputPath = BasePathForLLVM + "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/Results/TryResultScript/Output/" +input_file_name = sys.argv[1] +full_path = os.path.abspath(__file__) + +# Find the path up to 'DSP_MLIR' +if 'DSP_MLIR' in full_path: + BasePathForLLVM = full_path.split('DSP_MLIR')[0] + 'DSP_MLIR/' +OutputScriptPath = "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/" +# OutputPath = BasePathForLLVM + "mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/Results/TryResultScript/Output/" +input_file_path = BasePathForLLVM + OutputScriptPath + input_file_name + print(f"Running Application {input_file_path}") # Construct full output path -OutputPath = os.path.join(BasePathForLLVM, OutputScriptPath, "Output") +if sys.argv[2]: + OutputPath = os.path.join(BasePathForLLVM, OutputScriptPath, "Output", sys.argv[2]) + +else: + OutputPath = os.path.join(BasePathForLLVM, OutputScriptPath, "Output") # Check if the Output folder exists, create it if it doesn't if not os.path.exists(OutputPath): @@ -38,26 +49,373 @@ # ************ Don't change unless u required # Define the values dictionary + inputValues = { - # "10": 10, + "10": 10, "100": 100, + "500": 500, "1K": 1000, + "2K": 2000, + "5K": 5000, "10K": 10000, "20K": 20000, "30K": 30000, "40K": 40000, "50K": 50000, "100K": 100000, - "1M": 1000000, - "10M": 10000000, - "20M": 20000000, - "30M": 30000000, - "40M": 40000000, - "50M": 50000000, - "100M": 100000000, + "1M": 1000000, + # "10M": 10000000, + # "20M": 20000000, + # "30M": 30000000, + # "40M": 40000000, + # "50M": 50000000, + # "100M": 100000000, # "1B": 1000000000 } -NoOfIterations = 3 + +if sys.argv[1] == "noiseCancellation.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "echoCancellation.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "periodogram.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + } + +elif sys.argv[1] == "lowPassFiltering.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "hearingAid.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "FIRFilterDesign.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "spectralAnalysis.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000 + } + +elif sys.argv[1] == "audioEqualization.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "audioCompression.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + } + +elif sys.argv[1] == "vibrationAnalysis.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + +elif sys.argv[1] == "underWaterCommunication.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "voiceActivityDetection.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "signalSmoothing.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "targetDetection.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "biomedicalSignalProcessing.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "digitalModulation.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "spaceCommunication.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "radarSignalProcessing.m": + inputValues = { + "10": 10, + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + "10M": 10000000, + "20M": 20000000, + "30M": 30000000, + "40M": 40000000, + "50M": 50000000, + "100M": 100000000, + } + +elif sys.argv[1] == "dtmfDetection.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + } + +elif sys.argv[1] == "speakerIdentification.m": + inputValues = { + "100": 100, + "1K": 1000, + "10K": 10000, + "20K": 20000, + "30K": 30000, + "40K": 40000, + "50K": 50000, + "100K": 100000, + "1M": 1000000, + } + +NoOfIterations = 5 def delete_folder_contents(folder_path): for filename in os.listdir(folder_path): @@ -89,13 +447,13 @@ def delete_folder_contents(folder_path): else: file.write(line) - command = f"{mcc_path} -m {input_file_path} -d 'Output/' -o {input_file}{key}" + command = f"{mcc_path} -m {input_file_path} -d 'Output/' -o {sys.argv[2]}{key}" result = subprocess.run(command, shell=True, capture_output=True, text=True) # Modify the generated shell script - script_path = f"./Output/run_{input_file}{key}.sh" + script_path = f"./Output/run_{sys.argv[2]}{key}.sh" # Modify the generated shell script - script_path = f"./Output/run_{input_file}{key}.sh" + script_path = f"./Output/run_{sys.argv[2]}{key}.sh" with open(script_path, 'r') as file: script_content = file.readlines() @@ -122,7 +480,7 @@ def delete_folder_contents(folder_path): except subprocess.CalledProcessError as exc: print(exc) - command2 = f"taskset -c 0 ./Output/run_{input_file}{key}.sh {mrt_path}" + command2 = f"taskset -c 0 ./Output/run_{sys.argv[2]}{key}.sh {mrt_path}" try: result = subprocess.run(command2, shell=True, capture_output=True, text=True, check=True) diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/RunResults.py b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/RunResults.py new file mode 100644 index 000000000000..3cd2a32ddb3a --- /dev/null +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/RunResults.py @@ -0,0 +1,51 @@ +import subprocess +import os + +# Ensure the log directory exists +log_dir = "ServerExeLogs" +os.makedirs(log_dir, exist_ok=True) + +# Corrected list of application names (without non-application entries) +app_names = [ + "speakerIdentification", + "targetDetection", + "underWaterCommunication", + "voiceActivityDetection", + "spectralAnalysis", + "audioCompression", + "audioEqualization", + "biomedicalSignalProcessing", + "digitalModulation", + "dtmfDetection", + "echoCancellation", + "FIRFilterDesign", + "hearingAid", + "lowPassFiltering", + "noiseCancellation", + "periodogram", + "vibrationAnalysis", + "radarSignalProcessing", + "signalSmoothing", + "spaceCommunication" +] + + + +# Loop through each application and execute the script +for app_name in app_names: + app_script = f"{app_name}.m" + log_file = os.path.join(log_dir, f"{app_name}.log") + with open(log_file, "w") as log: + command = ["python", "ResultScript.py", app_script, app_name] + print(f"Running command: {' '.join(command)}") + process = subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True + ) + for line in process.stdout: + print(line, end="") + log.write(line) + for line in process.stderr: + print(line, end="") + log.write(line) + process.wait() + diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioCompression.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioCompression.m index c388ce8f13fa..67df7ace74e0 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioCompression.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioCompression.m @@ -1,71 +1,97 @@ % Constants -INPUT_LENGTH = 100000000; +INPUT_LENGTH = 1000; NLEVELS = 16; MIN = 0.0; MAX = 8.0; THRESHOLD_VAL = 4.0; -% Function to get range of vector + function output = getRangeOfVector(start, noOfSamples, increment) - output = start + (0:noOfSamples-1) * increment; + output = zeros(1, noOfSamples); + for i = 1:noOfSamples + output(i) = start + (i - 1) * increment; + end end -% DFT function -function output = dft(input) - N = length(input); - n = 0:N-1; - k = n'; - M = exp(-1j * 2 * pi * k * n / N); - output = M * input(:); + +function output = dft(input, length) + output = zeros(1, length); + for k = 0:length-1 + sum = 0; + for n = 0:length-1 + angle = 2 * pi * k * n / length; + sum = sum + input(n+1) * exp(-1j * angle); + end + output(k+1) = sum; + end end -% Threshold function -function output = threshold(input, thresh) - output = input .* (abs(input) >= thresh); +function output = threshold(input, thresh, length) + output = zeros(1, length); + for i = 1:length + if abs(input(i)) >= thresh + output(i) = input(i); + else + output(i) = 0; + end + end end -% Quantization function -function output = quantization(input, nlevels, max, min) - step = (max - min) / nlevels; - output = round((input - min) / step) * step + min; +function output = quantization(input, nlevels, max, min, length) + stepSize = (max - min) / nlevels; + output = zeros(1, length); + for i = 1:length + level = (input(i) - min) / stepSize; + roundedLevel = floor(level); + output(i) = roundedLevel * stepSize + min; + end end -% Run Length Encoding function -function [rle, rleLength] = runLenEncoding(input) - diffs = diff([input(:); NaN]); - runs = find(diffs ~= 0); - lengths = diff([0; runs]); - values = input(runs); - rle = [values, lengths]; - rle = rle'; - rle = rle(:); - rleLength = length(rle); + +function output = runLenEncoding(input, length) + output = zeros(1, 2 * length); + k = 1; % MATLAB index starts at 1 + count = 1; + output(k) = input(1); + half_len = length; + for i = 2:length + if input(i) == input(i-1) + count = count + 1; + else + output(k + half_len) = count; + k = k + 1; + output(k) = input(i); + count = 1; + end + end + output(k + half_len) = count; end -% Get element at index function + function elem = getElemAtIndx(rle, indx) elem = rle(indx); end -% Main script + input = getRangeOfVector(0, INPUT_LENGTH, 1); -fft_result = dft(input); +fft = dft(input, INPUT_LENGTH); + +GetThresholdReal = real(fft); +GetThresholdImg = imag(fft); -GetThresholdReal = real(fft_result); -GetThresholdImg = imag(fft_result); +GetThresholdReal = threshold(GetThresholdReal, THRESHOLD_VAL, INPUT_LENGTH); +GetThresholdImg = threshold(GetThresholdImg, THRESHOLD_VAL, INPUT_LENGTH); -GetThresholdReal = threshold(GetThresholdReal, THRESHOLD_VAL); -GetThresholdImg = threshold(GetThresholdImg, THRESHOLD_VAL); +QuantOutReal = quantization(GetThresholdReal, NLEVELS, MAX, MIN, INPUT_LENGTH); +QuantOutImg = quantization(GetThresholdImg, NLEVELS, MAX, MIN, INPUT_LENGTH); -QuantOutReal = quantization(GetThresholdReal, NLEVELS, MAX, MIN); -QuantOutImg = quantization(GetThresholdImg, NLEVELS, MAX, MIN); +rLEOutReal = runLenEncoding(QuantOutReal, INPUT_LENGTH); +rLEOutImg = runLenEncoding(QuantOutImg, INPUT_LENGTH); -[rLEOutReal, rleLengthReal] = runLenEncoding(QuantOutReal); -[rLEOutImg, rleLengthImg] = runLenEncoding(QuantOutImg); +final1 = getElemAtIndx(rLEOutReal, 1); +final2 = getElemAtIndx(rLEOutImg, 2); -final1 = getElemAtIndx(rLEOutReal, 2); -final2 = getElemAtIndx(rLEOutImg, 1); +fprintf('%f\t', final1); +fprintf('%f\n', final2); -fprintf('%f\n', final1); -fprintf('%f\n', final2); \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioEqualization.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioEqualization.m index 8b3f85c42e18..3cf3cac1f29c 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioEqualization.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/audioEqualization.m @@ -1,57 +1,66 @@ -% Constants -INPUT_LENGTH = 100000000; +INPUT_LENGTH = 100; +FILTER_LENGTH = 101; +input = 0:INPUT_LENGTH-1; + pi = 3.14159265359; -fc = 300; Fs = 8000; -gainForBass = 2; -gainForMid = 1.5; -gainForTreble = 0.8; -wc = 2 * pi * fc / Fs; -N = 101; - -% Input signal -input = 0:(INPUT_LENGTH-1); - -% Low-pass filter -lpf = lowPassFIRFilter(wc, N); -hamming_window = hamming(N)'; -lpf_w = lpf .* hamming_window; -FIRfilterResponseForLpf = conv(input, lpf_w, 'same'); -gainWithLpf = FIRfilterResponseForLpf * gainForBass; - -% High-pass filter -fc2 = 1500; -wc2 = 2 * pi * fc2 / Fs; -hpf = highPassFIRFilter(wc2, N); -hpf_w = hpf .* hamming_window; -FIRfilterResponseForHpf = conv(input, hpf_w, 'same'); -gainWithHpf = FIRfilterResponseForHpf * gainForTreble; - -% Band-pass filter -lpf2 = lowPassFIRFilter(wc2, N); -lpf2_w = lpf2 .* hamming_window; -bpf_w = lpf2_w - lpf_w; -FIRfilterResponseForBpf = conv(input, bpf_w, 'same'); -gainWithBpf = FIRfilterResponseForBpf * gainForMid; - -% Final audio -final_audio = gainWithLpf + gainWithHpf + gainWithBpf; - -% Print results -fprintf('Element at index 4: %f\n', final_audio(4)); -disp(final_audio); - -% Helper functions -function h = lowPassFIRFilter(wc, length) - n = 0:(length-1); +gainBass = 2; +gainMid = 0.8; +gainTreble = 0.8; + +mid = (FILTER_LENGTH - 1) / 2; + +hamming_window = hamming(FILTER_LENGTH); + +wc1 = 2 * pi * 300 / Fs; +lpf = lowPassFIRFilter(wc1, FILTER_LENGTH); +lpf_w = elementWiseMultiply(lpf, hamming_window); + +wc2 = 2 * pi * 1500 / Fs; +lpf2 = lowPassFIRFilter(wc2, FILTER_LENGTH); +hpf = -lpf2; +hpf(mid+1) = hpf(mid+1) + 1; +hpf_w = elementWiseMultiply(hpf, hamming_window); + +bpf_w = elementWiseSubtract(elementWiseMultiply(lpf2, hamming_window), lpf_w); + +resp_lpf = conv(input, lpf_w); +resp_hpf = conv(input, hpf_w); +resp_bpf = conv(input, bpf_w); + +gain_lpf = applyGain(resp_lpf, gainBass); +gain_hpf = applyGain(resp_hpf, gainTreble); +gain_bpf = applyGain(resp_bpf, gainMid); + +final_audio = gain_lpf + gain_hpf + gain_bpf; + +fprintf('%.6f\n', final_audio(4)); + +function window = hamming(length) + n = 0:length-1; + window = 0.54 - 0.46 * cos(2 * pi * n / (length - 1)); +end + +function filter = lowPassFIRFilter(wc, length) mid = (length - 1) / 2; - h = zeros(1, length); - h(n ~= mid) = sin(wc * (n(n ~= mid) - mid)) ./ (pi * (n(n ~= mid) - mid)); - h(mid+1) = wc / pi; + filter = zeros(1, length); + for n = 0:length-1 + if n == mid + filter(n+1) = wc / pi; + else + filter(n+1) = sin(wc * (n - mid)) / (pi * (n - mid)); + end + end end -function h = highPassFIRFilter(wc, length) - lpf = lowPassFIRFilter(wc, length); - h = -lpf; - h((length+1)/2) = h((length+1)/2) + 1; -end \ No newline at end of file +function output = elementWiseMultiply(array1, array2) + output = array1 .* array2; +end + +function output = elementWiseSubtract(array1, array2) + output = array1 - array2; +end + +function output = applyGain(input, gainFactor) + output = input * gainFactor; +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/biomedicalSignalProcessing.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/biomedicalSignalProcessing.m index 9212913001f2..4d87710fef07 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/biomedicalSignalProcessing.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/biomedicalSignalProcessing.m @@ -1,60 +1,87 @@ -% Constants -INPUT_LENGTH = 20000000; -MAX_PEAKS = 1000; -N = 101; +FS = 8000; +INPUT_LENGTH = 2000; +FILTER_SIZE = 101; +MAX_PEAKS = 950; + +input = (0:INPUT_LENGTH-1) * 0.000125; -% Signal parameters -fc1 = 1000; -fc2 = 7500; -Fs = 8000; -distance = 950; f_sig = 500; +clean_sig = sin(2 * pi * f_sig * input); + f_noise = 3000; +noise = 0.5 * sin(2 * pi * f_noise * input); + +noisy_sig = clean_sig + noise; -% Generate input signal -t = (0:0.000125:(INPUT_LENGTH-1)*0.000125)'; +fc1 = 1000; +fc2 = 7500; -% Generate clean signal -clean_sig = sin(2*pi*f_sig*t); +wc1 = 2 * pi * fc1 / FS; +wc2 = 2 * pi * fc2 / FS; -% Generate noise -noise = 0.5 * sin(2*pi*f_noise*t); +hamming_window = hamming(FILTER_SIZE); -% Create noisy signal -noisy_sig = clean_sig + noise; +lpf1 = lowPassFIRFilter(wc1, FILTER_SIZE); +lpf2 = lowPassFIRFilter(wc2, FILTER_SIZE); + +lpf1_w = elementWiseMultiply(lpf1, hamming_window); +lpf2_w = elementWiseMultiply(lpf2, hamming_window); + +bpf_w = elementWiseSubtract(lpf2_w, lpf1_w); + +FIRfilterResponseForBpf = conv(noisy_sig, bpf_w); -% Step 1: FIR Bandpass Filter -wc1 = 2 * pi * fc1 / Fs; -wc2 = 2 * pi * fc2 / Fs; +height = 0.3 * max(FIRfilterResponseForBpf); +r_peaks = findPeaks(FIRfilterResponseForBpf, height, 950, MAX_PEAKS); -% Design lowpass filters -n = 0:N-1; -mid = (N-1)/2; -lpf1 = (wc1/pi) * sinc(wc1*(n-mid)/pi); -lpf2 = (wc2/pi) * sinc(wc2*(n-mid)/pi); +len_r_peaks = r_peaks(end); +valid_peaks = r_peaks(1:len_r_peaks); -% Apply Hamming window -hamming_window = hamming(N)'; -lpf1_w = lpf1 .* hamming_window; -lpf2_w = lpf2 .* hamming_window; +peak_intervals = diff(valid_peaks); +diff_mean = mean(peak_intervals); -% Create bandpass filter -bpf_w = lpf2_w - lpf1_w; +avg_hr = (60 * FS) / diff_mean; -% Apply bandpass filter -FIRfilterResponseForBpf = filter(bpf_w, 1, noisy_sig); +fprintf('%.6f\n', avg_hr); -% Step 2: Artifact Removal (R-peak detection) -max_val = max(FIRfilterResponseForBpf); -height = 0.3 * max_val; +function window = hamming(length) + n = 0:length-1; + window = 0.54 - 0.46 * cos(2 * pi * n / (length - 1)); +end -% Find peaks -[~, r_peaks] = findpeaks(FIRfilterResponseForBpf, 'MinPeakHeight', height, 'MinPeakDistance', distance); +function filter = lowPassFIRFilter(wc, length) + mid = (length - 1) / 2; + filter = zeros(1, length); + for n = 0:length-1 + if n == mid + filter(n+1) = wc / pi; + else + filter(n+1) = sin(wc * (n - mid)) / (pi * (n - mid)); + end + end +end -% Calculate heart rate -diff_val = diff(r_peaks); -diff_mean = mean(diff_val); +function output = elementWiseMultiply(array1, array2) + output = array1 .* array2; +end -avg_hr = (60 * Fs) / diff_mean; +function output = elementWiseSubtract(array1, array2) + output = array1 - array2; +end -fprintf('%f\n', avg_hr); +function r_peaks = findPeaks(signal, threshold, min_distance, max_peaks) + r_peaks = -ones(1, max_peaks); + count = 0; + for i = 2:length(signal)-1 + if signal(i) > signal(i-1) && signal(i) > signal(i+1) && signal(i) >= threshold + if count == 0 || (i - r_peaks(count)) >= min_distance + count = count + 1; + r_peaks(count) = i; + if count >= max_peaks - 1 + break; + end + end + end + end + r_peaks(max_peaks) = count; +end \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/digitalModulation.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/digitalModulation.m index 656fee46c2f3..74d13488cb68 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/digitalModulation.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/digitalModulation.m @@ -1,58 +1,72 @@ -% Define constants -INPUT_LENGTH = 100000000; - -% Generate random input data -data = randi([0 1], 1, INPUT_LENGTH); - -% QAM Modulation -function symbols = qam_modulate(data) - symbols = zeros(1, length(data)/2); - for i = 1:2:length(data) - bit1 = data(i); - bit2 = data(i+1); - - if bit1 == 0 && bit2 == 0 - symbols((i+1)/2) = -1 - 1i; - elseif bit1 == 0 && bit2 == 1 - symbols((i+1)/2) = -1 + 1i; - elseif bit1 == 1 && bit2 == 0 - symbols((i+1)/2) = 1 - 1i; - elseif bit1 == 1 && bit2 == 1 - symbols((i+1)/2) = 1 + 1i; +INPUT_LENGTH = 100; + +input = getRangeOfVector(0, INPUT_LENGTH, 0.000125); + +f_sig = 500; +getMultiplier = 2 * pi * f_sig; +getSinDuration = gain(input, getMultiplier); + +clean_sig = sin(getSinDuration); + +binary_sig = thresholdUp(clean_sig, 0.4, 0); + +modulate_symbol_real = qamModulateReal(binary_sig); +modulate_symbol_imag = qamModulateImag(binary_sig); + +decode_data = qamDemodulate(modulate_symbol_real, modulate_symbol_imag); + +fprintf('%.6f\n', decode_data(3)); + +function vector = getRangeOfVector(start, length, increment) + vector = start + (0:length-1) * increment; +end + +function output = gain(input, multiplier) + output = input * multiplier; +end + +function output = thresholdUp(input, threshold, low_value) + output = double(input >= threshold); + output(output < 1) = low_value; +end + +function real = qamModulateReal(binary_sig) + real = zeros(1, length(binary_sig)/2); + for i = 1:2:length(binary_sig) + bit1 = binary_sig(i); + bit2 = binary_sig(i+1); + if (bit1 == 0 && bit2 == 0) || (bit1 == 0 && bit2 == 1) + real((i+1)/2) = -1; + else + real((i+1)/2) = 1; end end end -% QAM Demodulation -function bits = qam_demodulate(symbols) - bits = zeros(1, length(symbols)*2); - for i = 1:length(symbols) - symbol = symbols(i); - - if symbol == -1 - 1i - bits(2*i-1) = 0; - bits(2*i) = 0; - elseif symbol == -1 + 1i - bits(2*i-1) = 0; - bits(2*i) = 1; - elseif symbol == 1 - 1i - bits(2*i-1) = 1; - bits(2*i) = 0; - elseif symbol == 1 + 1i - bits(2*i-1) = 1; - bits(2*i) = 1; +function imag = qamModulateImag(binary_sig) + imag = zeros(1, length(binary_sig)/2); + for i = 1:2:length(binary_sig) + bit1 = binary_sig(i); + bit2 = binary_sig(i+1); + if (bit1 == 0 && bit2 == 0) || (bit1 == 1 && bit2 == 0) + imag((i+1)/2) = -1; + else + imag((i+1)/2) = 1; end end end -% Main script -rng('shuffle'); % Seed random number generator - -% Perform QAM modulation -symbols = qam_modulate(data); - -% Perform QAM demodulation -bits = qam_demodulate(symbols); - -% Print the 6th bit (equivalent to bits[5] in C, as MATLAB uses 1-based indexing) -disp(bits(6)); \ No newline at end of file +function decoded = qamDemodulate(real, imag) + decoded = zeros(1, length(real)*2); + for i = 1:length(real) + if real(i) == -1 && imag(i) == -1 + decoded(2*i-1:2*i) = [0 0]; + elseif real(i) == -1 && imag(i) == 1 + decoded(2*i-1:2*i) = [0 1]; + elseif real(i) == 1 && imag(i) == -1 + decoded(2*i-1:2*i) = [1 0]; + elseif real(i) == 1 && imag(i) == 1 + decoded(2*i-1:2*i) = [1 1]; + end + end +end \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/dtmfDetection.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/dtmfDetection.m index 20f4c3517247..a4cf698b95fe 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/dtmfDetection.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/dtmfDetection.m @@ -1,71 +1,68 @@ -% DTMF Detection in MATLAB using DFT +INPUT_LENGTH = 1000; +digit = 8; +fs = 8192; +duration = INPUT_LENGTH / fs; +N = round(fs * duration); + +dtmf_tone = generateDtmf(digit, fs, duration); + +fft_real = dftReal(dtmf_tone); +fft_imag = dftImag(dtmf_tone); + +magnitudes = sqrt(fft_real.^2 + fft_imag.^2); +frequencies = zeros(1, N); +for i = 1:N + if i <= N/2 + frequencies(i) = (i-1) * fs / N; + else + frequencies(i) = (i-1 - N) * fs / N; + end +end -% Constants -SAMPLING_FREQUENCY = 8192; % Sampling frequency -DURATION = 0.5; % Duration of the DTMF signal -N_SAMPLES = SAMPLING_FREQUENCY * DURATION; % Number of samples for the DTMF signal +peaks = findDominantPeaks(frequencies, magnitudes); + +fprintf('%.6f %.6f\t', peaks(1), peaks(2)); -% DTMF frequencies freqPairs = [ - 941, 1336; % 0 - 697, 1209; % 1 - 697, 1336; % 2 - 697, 1477; % 3 - 770, 1209; % 4 - 770, 1336; % 5 - 770, 1477; % 6 - 852, 1209; % 7 - 852, 1336; % 8 - 852, 1477 % 9 + 941, 1336; 697, 1209; 697, 1336; 697, 1477; + 770, 1209; 770, 1336; 770, 1477; 852, 1209; + 852, 1336; 852, 1477 ]; -% Main script -digit = 0; % DTMF digit to be generated -fs = SAMPLING_FREQUENCY; -duration = DURATION; - -% Generate the DTMF tone -dtmf_tone = generateDtmf(digit, fs, duration, freqPairs); - -% Perform DFT -[real_out, imag_out] = dft(dtmf_tone); - -% Calculate magnitudes and frequencies -N = length(dtmf_tone); -magnitudes = sqrt(real_out.^2 + imag_out.^2); -frequencies = (0:N-1)' * fs / N; -frequencies(frequencies > fs/2) = frequencies(frequencies > fs/2) - fs; - -% Find dominant frequency peaks -peaks = findDominantPeaks(frequencies, magnitudes); - -% Recover the DTMF digit -recovered_digit = recoverDtmfDigit(peaks, freqPairs); - -% Display results -if recovered_digit >= 0 - fprintf('Recovered DTMF digit: %d\n', recovered_digit); -else - fprintf('No DTMF digit detected.\n'); -end +recovered_digit = recoverDTMFDigit(peaks, freqPairs); +fprintf('%.6f\n', recovered_digit); -% Function definitions -function dtmf_tone = generateDtmf(digit, fs, duration, freqPairs) +function tone = generateDtmf(digit, fs, duration) + freqPairs = [ + 941, 1336; 697, 1209; 697, 1336; 697, 1477; + 770, 1209; 770, 1336; 770, 1477; 852, 1209; + 852, 1336; 852, 1477 + ]; f1 = freqPairs(digit + 1, 1); f2 = freqPairs(digit + 1, 2); - t = (0:1/fs:duration-1/fs)'; - dtmf_tone = 10 * (sin(2 * pi * f1 * t) + sin(2 * pi * f2 * t)); + N = fs * duration; + t = (0:N-1) / fs; + tone = 10 * sin(2 * pi * f1 * t) + sin(2 * pi * f2 * t); end -function [real_out, imag_out] = dft(signal) - N = length(signal); - real_out = zeros(N, 1); - imag_out = zeros(N, 1); +function real = dftReal(input) + N = length(input); + real = zeros(1, N); for k = 0:N-1 for n = 0:N-1 angle = 2 * pi * k * n / N; - real_out(k+1) = real_out(k+1) + signal(n+1) * cos(angle); - imag_out(k+1) = imag_out(k+1) - signal(n+1) * sin(angle); + real(k+1) = real(k+1) + input(n+1) * cos(angle); + end + end +end + +function imag = dftImag(input) + N = length(input); + imag = zeros(1, N); + for k = 0:N-1 + for n = 0:N-1 + angle = 2 * pi * k * n / N; + imag(k+1) = imag(k+1) - input(n+1) * sin(angle); end end end @@ -73,30 +70,21 @@ function peaks = findDominantPeaks(frequencies, magnitudes) max1 = 0; max2 = 0; freq1 = 0; freq2 = 0; - for i = 1:length(frequencies) currentFreq = frequencies(i); currentMag = magnitudes(i); - - % Check if frequency is positive if currentFreq >= 0 - % Compare current magnitude with max1 if currentMag > max1 - % Update max2 and freq2 with previous max1 and freq1 max2 = max1; freq2 = freq1; - % Update max1 and freq1 with current values max1 = currentMag; freq1 = currentFreq; elseif currentMag > max2 - % Update max2 and freq2 with current values max2 = currentMag; freq2 = currentFreq; end end end - - % Compare freq1 and freq2 to determine the order if freq1 < freq2 peaks = [freq1, freq2]; else @@ -104,16 +92,15 @@ end end -function digit = recoverDtmfDigit(peaks, freqPairs) +function digit = recoverDTMFDigit(peaks, freqPairs) + digit = -1; for i = 1:size(freqPairs, 1) f1 = freqPairs(i, 1); f2 = freqPairs(i, 2); - if (abs(peaks(1) - f1) < 10 && abs(peaks(2) - f2) < 10) || ... (abs(peaks(1) - f2) < 10 && abs(peaks(2) - f1) < 10) - digit = i - 1; % Digit found (subtract 1 because MATLAB is 1-indexed) + digit = i - 1; return; end end - digit = -1; % No match found -end \ No newline at end of file +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/echoCancellation.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/echoCancellation.m index 2fae6b58462e..f5ae45ba953c 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/echoCancellation.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/echoCancellation.m @@ -1,36 +1,55 @@ -% Constants -INPUT_LENGTH = 100000000; -PI = pi; % MATLAB has pi built-in +INPUT_LENGTH = 1000; fs = 8000; step = 1 / fs; +t = (0:INPUT_LENGTH-1) * step; -% Generate input range -input = (0:step:(INPUT_LENGTH-1)*step)'; - -% Generate clean signal f_sig = 500; -clean_sig = sin(2 * PI * f_sig * input); - -% Generate noise signal with a delay of 2 samples -noise = [zeros(2, 1); clean_sig(1:end-2)]; +getSinDuration = gain(t, 2 * pi * f_sig); +clean_sig = sin(getSinDuration); -% Create noisy signal by adding noise to clean signal +noise = delaySignal(clean_sig, 2); noisy_sig = clean_sig + noise; -% LMS filter parameters mu = 0.01; filterSize = 32; +y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize); + +normalized_sol = normalizeSignal(y); + +fprintf('%.6f\n', normalized_sol(6)); -% LMS filter implementation -w = zeros(filterSize, 1); -y = zeros(INPUT_LENGTH, 1); +function output = gain(input, multiplier) + output = input * multiplier; +end + +function output = delaySignal(input, delaySamples) + output = zeros(size(input)); + output((delaySamples+1):end) = input(1:end-delaySamples); +end -for n = filterSize:INPUT_LENGTH - x = noisy_sig(n:-1:n-filterSize+1); - y(n) = w' * x; - e = clean_sig(n) - y(n); - w = w + mu * e * x; +function y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize) + N = length(noisy_sig); + y = zeros(1, N); + w = zeros(1, filterSize); + for n = 1:N + y_n = 0; + for i = 1:filterSize + if n - i + 1 > 0 + y_n = y_n + w(i) * noisy_sig(n - i + 1); + end + end + e = clean_sig(n) - y_n; + for i = 1:filterSize + if n - i + 1 > 0 + w(i) = w(i) + mu * e * noisy_sig(n - i + 1); + end + end + y(n) = y_n; + end end -% Print result -fprintf('%f\n', y); +function output = normalizeSignal(input) + min_val = min(input); + max_val = max(input); + output = (input - min_val) / (max_val - min_val); +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/hearingAid.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/hearingAid.m index 47208238ddc7..0fe8bf77f0f0 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/hearingAid.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/hearingAid.m @@ -1,45 +1,49 @@ -% Define constants -INPUT_LENGTH = 100000000; +INPUT_LENGTH = 100; fs = 8000; step = 1 / fs; +t = (0:INPUT_LENGTH-1) * step; -% Generate input range -input = (0:step:(INPUT_LENGTH-1)*step)'; - -% Generate clean signal f_sig = 500; -clean_sig = sin(2 * pi * f_sig * input); +getSinDuration = gain(t, 2 * pi * f_sig); +clean_sig = sin(getSinDuration); -% Generate noise signal with frequency of 3000 Hz f_noise = 3000; -noise = 0.5 * sin(2 * pi * f_noise * input); - -% Create noisy signal by adding noise to clean signal -noisy_sig = clean_sig + noise; +getNoiseSinDuration = gain(t, 2 * pi * f_noise); +noise = sin(getNoiseSinDuration); +noise1 = gain(noise, 0.5); -% LMS filter response function -function y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize) - w = zeros(filterSize, 1); - y = zeros(size(noisy_sig)); - - for n = 1:length(noisy_sig) - x = noisy_sig(max(1, n-filterSize+1):n); - x = [zeros(filterSize - length(x), 1); x]; - y(n) = w' * x; - e = clean_sig(n) - y(n); - w = w + mu * e * x; - y(n) = e; - end -end +noisy_sig = clean_sig + noise1; -% Apply LMS filter mu = 0.01; filterSize = 32; y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize); -% Apply final gain factor G1 to the LMS filter output -G1 = 1002300; -sol = G1 * y; +G1 = 123; +sol = gain(y, G1); + +fprintf('%.6f\n', sol(4)); -% Display -disp(sol); \ No newline at end of file +function output = gain(input, multiplier) + output = input * multiplier; +end + +function y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize) + N = length(noisy_sig); + y = zeros(1, N); + w = zeros(1, filterSize); + for n = 1:N + y_n = 0; + for i = 1:filterSize + if n - i + 1 > 0 + y_n = y_n + w(i) * noisy_sig(n - i + 1); + end + end + e = clean_sig(n) - y_n; + for i = 1:filterSize + if n - i + 1 > 0 + w(i) = w(i) + mu * e * noisy_sig(n - i + 1); + end + end + y(n) = y_n; + end +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/lowPassFiltering.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/lowPassFiltering.m index 4b5348e6641f..d565c0a4d8e0 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/lowPassFiltering.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/lowPassFiltering.m @@ -1,40 +1,49 @@ -% Define constants -PI = pi; -INPUT_LENGTH = 100000000; -fs = 8000; - -% Generate input vector -input = (0:0.000125:(INPUT_LENGTH-1)*0.000125)'; - -% Signal processing steps -f_sig = 500; -getSinDuration = 2 * PI * f_sig * input; -clean_sig = sin(getSinDuration); - -f_noise = 3000; -getNoiseSinDuration = 2 * PI * f_noise * input; -noise = sin(getNoiseSinDuration); - -scaled_noise = 0.5 * noise; -noisy_sig = clean_sig + scaled_noise; - -% Filter design -fc = 1000; -wc = 2 * PI * fc / fs; +INPUT_LENGTH = 100; +FILTER_LENGTH = 200; N = 101; +fs = 8000; -% Low-pass FIR filter -n = -(N-1)/2:(N-1)/2; -lpf = (wc / PI) * sinc(wc * n / PI); - -% Hamming window -hamming = 0.54 - 0.46 * cos(2 * PI * (0:N-1) / (N-1)); - -% Apply window to filter -lpf_w = lpf .* hamming; - -% Apply FIR filter -FIRfilterResponse = filter(lpf_w, 1, noisy_sig); - -% Display results -disp(FIRfilterResponse(2)); \ No newline at end of file +clean_signal = generateSignal(500, INPUT_LENGTH, fs); +noise_signal = generateSignal(3000, INPUT_LENGTH, fs); +noise_signal = noise_signal * 0.5; + +noisy_signal = clean_signal + noise_signal; + +fir_filter = generateLowpassFilter(1000, N, fs); +filtered_signal = applyFIRFilter(noisy_signal, fir_filter, FILTER_LENGTH, INPUT_LENGTH); + +fprintf('%.6f\n', filtered_signal(7)); + +function signal = generateSignal(freq, length, fs) + t = (0:length-1) / fs; + signal = sin(2 * pi * freq * t); +end + +function filter = generateLowpassFilter(cutoff_freq, N, fs) + wc = 2 * pi * cutoff_freq / fs; + mid = floor(N / 2); + filter = zeros(1, N); + for i = 1:N + n = i - mid - 1; + if n == 0 + filter(i) = wc / pi; + else + filter(i) = sin(wc * n) / (pi * n); + end + filter(i) = filter(i) * (0.54 - 0.46 * cos(2 * pi * (i-1) / (N - 1))); + end +end + +function output = applyFIRFilter(input, filter, out_length, input_length) + N = length(filter); + output = zeros(1, out_length); + for i = 1:out_length + sum = 0; + for j = 1:N + if i - j + 1 > 0 && i - j + 1 <= input_length + sum = sum + input(i - j + 1) * filter(j); + end + end + output(i) = sum; + end +end \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/noiseCancellation.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/noiseCancellation.m index be40a7369d23..1339875626f8 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/noiseCancellation.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/noiseCancellation.m @@ -1,32 +1,56 @@ -% Constants -INPUT_LENGTH = 100000000; +INPUT_LENGTH = 1000; +fs = 8000; -% Main script -t = linspace(0, INPUT_LENGTH * 0.000125, INPUT_LENGTH); +t = getRangeOfVector(0, INPUT_LENGTH, 0.000125); f_sig = 500; -clean_sig = sin(2 * pi * f_sig * t); +getSinDuration = gain(t, 2 * pi * f_sig); +clean_sig = sin(getSinDuration); f_noise = 3000; -noise = 0.5 * sin(2 * pi * f_noise * t); +getNoiseSinDuration = gain(t, 2 * pi * f_noise); +noise = sin(getNoiseSinDuration); +noise1 = gain(noise, 0.5); -noisy_sig = clean_sig + noise; +noisy_sig = clean_sig + noise1; -% LMS filter response -mu = 0.01; -filterSize = 32; +y = lmsFilterResponse(noisy_sig, clean_sig, 0.01, 32); +sol = gain(y, 10); +normalized_sol = normalizeSignal(sol); -% Preallocate arrays -w = zeros(1, filterSize); -y = zeros(1, INPUT_LENGTH); +fprintf('%.6f\n', normalized_sol(6)); -% Implement LMS filter -for n = filterSize:INPUT_LENGTH - x = noisy_sig(n:-1:n-filterSize+1); - y(n) = w * x'; - e = clean_sig(n) - y(n); - w = w + mu * e * x; +function vector = getRangeOfVector(start, length, increment) + vector = start + (0:length-1) * increment; end -sol = 10 * y; -fprintf('%f\n', sol); +function output = gain(input, multiplier) + output = input * multiplier; +end + +function y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize) + N = length(noisy_sig); + y = zeros(1, N); + w = zeros(1, filterSize); + for n = 1:N + y_n = 0; + for i = 1:filterSize + if n - i + 1 > 0 + y_n = y_n + w(i) * noisy_sig(n - i + 1); + end + end + e = clean_sig(n) - y_n; + for i = 1:filterSize + if n - i + 1 > 0 + w(i) = w(i) + mu * e * noisy_sig(n - i + 1); + end + end + y(n) = y_n; + end +end + +function output = normalizeSignal(input) + min_val = min(input); + max_val = max(input); + output = (input - min_val) / (max_val - min_val); +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/periodogram.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/periodogram.m index 8484900de377..d1b0b16d2b78 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/periodogram.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/periodogram.m @@ -1,20 +1,60 @@ -% Define INPUT_LENGTH globally -INPUT_LENGTH = 10; +INPUT_LENGTH = 100; +input = getRangeOfVector(0, INPUT_LENGTH, 1.0); -% Generate input range -input = 0:1:(INPUT_LENGTH-1); +reverse_input = reverseSignal(input); -% Reverse input -reverse_input = flip(input); +conv_length = 2 * INPUT_LENGTH - 1; +conv1d = firFilterResponse(input, reverse_input, INPUT_LENGTH); -% FIR Filter Response (Convolution) -conv1d = conv(input, reverse_input, 'same'); +fft_real = dftReal(conv1d); +fft_img = dftImag(conv1d); -% Compute DFT using FFT -fft_result = fft(conv1d); +sq = squareMagnitude(fft_real, fft_img); -% Compute square magnitude -sq = abs(fft_result).^2; +fprintf('%.6f\n', sq(3)); -% Display results -fprintf('%f\n', sq); +function vector = getRangeOfVector(start, length, increment) + vector = start + (0:length-1) * increment; +end + +function reversed = reverseSignal(input) + reversed = input(end:-1:1); +end + +function conv_out = firFilterResponse(input, filter, L) + conv_length = 2 * L - 1; + conv_out = zeros(1, conv_length); + for n = 1:conv_length + for k = 1:L + if n - k + 1 > 0 && n - k + 1 <= L + conv_out(n) = conv_out(n) + input(n - k + 1) * filter(k); + end + end + end +end + +function real = dftReal(signal) + N = length(signal); + real = zeros(1, N); + for k = 0:N-1 + for n = 0:N-1 + angle = 2 * pi * k * n / N; + real(k+1) = real(k+1) + signal(n+1) * cos(angle); + end + end +end + +function imag = dftImag(signal) + N = length(signal); + imag = zeros(1, N); + for k = 0:N-1 + for n = 0:N-1 + angle = 2 * pi * k * n / N; + imag(k+1) = imag(k+1) - signal(n+1) * sin(angle); + end + end +end + +function output = squareMagnitude(real, imag) + output = real.^2 + imag.^2; +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/radarSignalProcessing.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/radarSignalProcessing.m index 3874976f3833..b6bc71056baa 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/radarSignalProcessing.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/radarSignalProcessing.m @@ -1,79 +1,83 @@ -% Constants -PI = pi; -INPUT_LENGTH = 10000; - -% Function prototypes -input = linspace(0, (INPUT_LENGTH - 1) * 0.000125, INPUT_LENGTH); % Using linspace instead of getrangeofvector -weights = linspace(-90, 180, 4); % Example antenna weights -antennas = 4; -input_fc = 5; -N = 101; +INPUT_LENGTH = 10; +fs = 8000; fc1 = 1000; fc2 = 7500; -Fs = 8000; +N = 101; -% Generate beamformed signal -signal = beamForm(antennas, input_fc, input, weights); +input = getRangeOfVector(0, INPUT_LENGTH, 0.000125); +weights = getRangeOfVector(-90, 180, 1); +signal = beamForm(4, 5, input, weights); -% Compute absolute values and power profile b1 = abs(signal); -power = b1 .^ 2; % element-wise square instead of power_profile +power = b1.^2; -% Low-pass and high-pass FIR filters with Hamming window -wc1 = 2 * PI * fc1 / Fs; -filter1 = lowPassFIRFilter(wc1, N); -filter_hamming_1 = filter1 .* hamming(N, 'symmetric')'; % Using 'symmetric' Hamming window +wc1 = 2 * pi * fc1 / fs; +wc2 = 2 * pi * fc2 / fs; -wc2 = 2 * PI * fc2 / Fs; +filter1 = lowPassFIRFilter(wc1, N); filter2 = highPassFIRFilter(wc2, N); -filter_hamming_2 = filter2 .* hamming(N, 'symmetric')'; % Using 'symmetric' Hamming window -% Band-pass filter by subtracting the filters -bpf = filter_hamming_2 - filter_hamming_1; - -% Apply FIR filter to the power profile (use full convolution) -firFilterResponse = conv(power, bpf, 'full'); % Use 'full' to match C code +filter_hamming_1 = filter1 .* hammingWindow(N); +filter_hamming_2 = filter2 .* hammingWindow(N); -% Output final value at the 10000th index (adjust if necessary) -final = firFilterResponse(2); % Adjust to match desired index in C code -fprintf('final: %f\n', final); +bpf = filter_hamming_2 - filter_hamming_1; +firResponse = firFilterResponse(power, bpf); -% Functions +fprintf('%.6f\n', firResponse(11)); -function output = beamForm(antennas, frequency, time, weights) - phase_var = 2 * pi * frequency; - signal = zeros(antennas, length(time)); +function vector = getRangeOfVector(first, N, step) + vector = first + (0:N-1) * step; +end +function signal = beamForm(antennas, freq, time, weights) + timeDim = length(time); + signalMat = zeros(antennas, timeDim); for i = 1:antennas - iter_args = (i - 1) * pi / 4.0; - signal(i, :) = sin(time * phase_var + iter_args); + phase_shift = (i-1) * pi / 4; + signalMat(i, :) = sin(2 * pi * freq * time + phase_shift); end - - output = sum(signal .* weights', 1); % Beamforming by weighted summation + signal = sum(signalMat(1:antennas, :) .* weights(1:antennas)', 1); end -function output = lowPassFIRFilter(wc, N) - midIndex = (N - 1) / 2; - output = zeros(1, N); - +function filter = lowPassFIRFilter(wc, N) + mid = floor(N/2); + filter = zeros(1, N); for i = 1:N - if i == midIndex + 1 - output(i) = wc / pi; + n = i - mid - 1; + if n == 0 + filter(i) = wc / pi; else - output(i) = sin(wc * (i - midIndex - 1)) / (pi * (i - midIndex - 1)); + filter(i) = sin(wc * n) / (pi * n); end end end -function output = highPassFIRFilter(wc, N) - midIndex = (N - 1) / 2; - output = zeros(1, N); - +function filter = highPassFIRFilter(wc, N) + mid = floor(N/2); + filter = zeros(1, N); for i = 1:N - if i == midIndex + 1 - output(i) = 1 - wc / pi; + n = i - mid - 1; + if n == 0 + filter(i) = 1 - wc / pi; else - output(i) = -sin(wc * (i - midIndex - 1)) / (pi * (i - midIndex - 1)); + filter(i) = -sin(wc * n) / (pi * n); + end + end +end + +function window = hammingWindow(N) + n = 0:N-1; + window = 0.54 - 0.46 * cos(2 * pi * n / (N - 1)); +end + +function output = firFilterResponse(input, filter) + outputLen = length(input) + length(filter) - 1; + output = zeros(1, outputLen); + for i = 1:outputLen + for k = 1:length(filter) + if i - k + 1 > 0 && i - k + 1 <= length(input) + output(i) = output(i) + filter(k) * input(i - k + 1); + end end end end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/signalSmoothing.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/signalSmoothing.m index 0753b6e78ef9..c4b35ef452e3 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/signalSmoothing.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/signalSmoothing.m @@ -1,30 +1,44 @@ -% Define constants -INPUT_LENGTH = 1000; -SAMPLE_RATE = 8000; -step = 0.000125; +INPUT_LENGTH = 10; +fs = 8000; +dt = 1 / fs; WINDOW_SIZE = 3; -% Generate input range -input = (0:step:(INPUT_LENGTH-1)*step)'; - -% Signal parameters -f_sig = 500; -f_noise = 3000; - -% Generate clean signal -clean_sig = sin(2*pi*f_sig*input); - -% Generate noise -noise = 0.5 * sin(2*pi*f_noise*input); - -% Create noisy signal -noisy_sig = clean_sig + noise; - -% Apply median filter -median_filtered = medfilt1(noisy_sig, WINDOW_SIZE); - -% Apply moving average filter -avg_filtered = movmean(median_filtered, WINDOW_SIZE); - -% Print the 4th element of the final result -disp(avg_filtered(4)); +input = getRangeOfVector(0, INPUT_LENGTH, dt); +getMultiplier = 2 * pi * 500; +getSinDuration = gain(input, getMultiplier); +clean_sig = sin(getSinDuration); + +getNoiseSinDuration = gain(input, 2 * pi * 3000); +noise = sin(getNoiseSinDuration); +noise1 = gain(noise, 0.5); + +noisy_sig = clean_sig + noise1; +median = slidingMedianFilter(noisy_sig); +average = slidingAvgFilter(median); + +fprintf('%.6f\n', average(4)); + +function vector = getRangeOfVector(start, len, increment) + vector = start + (0:len-1) * increment; +end + +function output = gain(input, multiplier) + output = input * multiplier; +end + +function avg_out = slidingAvgFilter(input) + len = length(input) - 2; + avg_out = zeros(1, len); + for i = 1:len + avg_out(i) = mean(input(i:i+2)); + end +end + +function med_out = slidingMedianFilter(input) + len = length(input) - 2; + med_out = zeros(1, len); + for i = 1:len + window = input(i:i+2); + med_out(i) = median(window); + end +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spaceCommunication.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spaceCommunication.m index 6dbc04445c1e..b8d5fa31cceb 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spaceCommunication.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spaceCommunication.m @@ -1,95 +1,64 @@ +INPUT_LENGTH = 40000; +fs = 8000; +dt = 1 / fs; +input = getRangeOfVector(0, INPUT_LENGTH, dt); +p = 2 * pi; +f_sig = 500; +getMultiplier = p * f_sig; +thresh = 0.4; -function main() - % Define constants - INPUT_LENGTH = 100000000; - - % Generate input vector - input = getRangeOfVector(0, INPUT_LENGTH, 1); - - % Threshold - binary_sig = thresholdUp(input, INPUT_LENGTH, 50); - - % Modulate - modulated_signal = space_modulate(binary_sig, INPUT_LENGTH); - - % Transmit and receive (add noise) - received_signal = transmit_and_receive(modulated_signal, INPUT_LENGTH, 1.0); - - % Demodulate - demodulated_data = demodulate(received_signal, INPUT_LENGTH); - - % Error correction - corrected_data = error_correction(demodulated_data); - - % Decode data - decoded_data = decode_data(corrected_data); - - % Display first corrected byte (equivalent to printing corrected_data[8] in C) - fprintf('%c\n', corrected_data(9)); +getSinDuration = gain(input, getMultiplier); +clean_sig = sin(getSinDuration); +binary_sig = thresholdUp(clean_sig, thresh, 0); +a = spaceModulate(binary_sig); +noisy_signal = addNoise(a); +b = spaceDemodulate(noisy_signal); +e = errorCorrection(b); + +fprintf('%.6f\n', e(9)); + +function vec = getRangeOfVector(start, len, step) + vec = start + (0:len-1) * step; end -% Function to generate a vector with a given range and increment -function vector = getRangeOfVector(start, length, increment) - vector = start:increment:(start + (length - 1) * increment); +function out = gain(input, factor) + out = input * factor; end -% Thresholding function (creates a binary string from a vector) -function output = thresholdUp(input, length, threshold) - output = char(zeros(1, length)); % Preallocate output - output(input > threshold) = '1'; - output(input <= threshold) = '0'; +function out = thresholdUp(input, threshold, returnOriginal) + if returnOriginal == 0 + out = double(input >= threshold); + else + out = input; + out(input < threshold) = 0; + end end -% Space modulation: convert binary string to modulated signal -function output = space_modulate(input, length) - output = zeros(1, length); - output(input == '1') = 1; - output(input == '0') = -1; +function out = spaceModulate(input) + out = ones(1, length(input)); + out(input ~= 1) = -1; end -% Transmit and receive (add noise based on sine of the signal) -function received_signal = transmit_and_receive(signal, length, noise_level) - received_signal = signal + sin(signal); % Add noise (sine-based in this case) +function out = addNoise(input) + out = input + sin(input); end -% Demodulate: convert received signal back into binary data -function demodulated_data = demodulate(signal, length) - demodulated_data = char(zeros(1, length)); - demodulated_data(signal > 0) = '1'; - demodulated_data(signal <= 0) = '0'; +function out = spaceDemodulate(input) + out = double(input > 0); end -% Error correction function -function corrected = error_correction(data) - length = numel(data); - corrected = char(zeros(1, length)); % Preallocate corrected array - corrected_index = 1; - - for i = 1:8:length - segment = data(i:i+7); - count = sum(segment == '1'); - - if mod(count, 2) == 0 - corrected(corrected_index:corrected_index+7) = segment; +function corrected = errorCorrection(data) + corrected = zeros(1, length(data)); + idx = 1; + for i = 1:8:length(data) + chunk = data(i:min(i+7, end)); + if mod(sum(chunk), 2) == 0 + corrected(idx:idx+length(chunk)-1) = chunk; else - corrected(corrected_index) = '0'; - corrected(corrected_index+1:corrected_index+7) = segment(2:8); + chunk(1) = 0; + corrected(idx:idx+length(chunk)-1) = chunk; end - - corrected_index = corrected_index + 8; - end -end - -% Decode binary data to ASCII characters -function decoded = decode_data(binary) - length = numel(binary); - decoded = char(zeros(1, length / 8)); % Preallocate decoded data array - decoded_index = 1; - - for i = 1:8:length - byte = binary(i:i+7); - decoded(decoded_index) = char(bin2dec(byte)); - decoded_index = decoded_index + 1; + idx = idx + 8; end end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/speakerIdentification.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/speakerIdentification.m index bf7e9a18991b..11ee448dab5d 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/speakerIdentification.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/speakerIdentification.m @@ -1,46 +1,47 @@ -% Function to generate voice signature (sinusoidal wave with two frequencies) -function signal = generateVoiceSignature(freq1, freq2, duration, sample_rate) - t = linspace(0, duration, sample_rate * duration); - signal = sin(2 * pi * freq1 * t) + cos(2 * pi * freq2 * t); -end +SAMPLE_RATE = 1000; +INPUT_LENGTH = 61; +DURATION = INPUT_LENGTH / SAMPLE_RATE; +CORRELATION_LENGTH = 2 * INPUT_LENGTH - 1; -% Function to compute the dot product (correlation) between two signals -function result = correlate(signal1, signal2) - result = sum(signal1 .* signal2); -end +person1 = generateVoiceSignature(100, 200, INPUT_LENGTH, SAMPLE_RATE); +person2 = generateVoiceSignature(150, 250, INPUT_LENGTH, SAMPLE_RATE); +person3 = generateVoiceSignature(120, 180, INPUT_LENGTH, SAMPLE_RATE); +unknown_signal = generateVoiceSignature(150, 250, INPUT_LENGTH, SAMPLE_RATE); + +correlation1 = correlate(person1, unknown_signal); +correlation2 = correlate(person2, unknown_signal); +correlation3 = correlate(person3, unknown_signal); + +total_maxes = [max(correlation1), max(correlation2), max(correlation3)]; -% Main function -function main() - % Sample rate and duration - sample_rate = 1000; - duration = 1; - - % Generate voice signatures for Alice, Bob, Charlie - person1 = generateVoiceSignature(100, 200, duration, sample_rate); % Alice - person2 = generateVoiceSignature(150, 250, duration, sample_rate); % Bob - person3 = generateVoiceSignature(120, 180, duration, sample_rate); % Charlie - - % Generate an unknown signal (Bob's signature in this case) - unknown_signal = generateVoiceSignature(150, 250, duration, sample_rate); % Change this to test - - % Correlate unknown signal with each person's signature - max1 = correlate(person1, unknown_signal); - max2 = correlate(person2, unknown_signal); - max3 = correlate(person3, unknown_signal); - - % Store correlation results - total_maxes = [max1, max2, max3]; - - % Find the index of the maximum correlation result - [max_value, max_index] = max(total_maxes); - - % Output results - fprintf('Max Index: %d\n', max_index); - fprintf('Max Value: %f\n', max_value); - fprintf('Correlation with Alice: %f\n', max1); - fprintf('Correlation with Bob: %f\n', max2); - fprintf('Correlation with Charlie: %f\n', max3); +[max_value, max_index] = max(total_maxes); + +temp2 = total_maxes(1); +temp3 = total_maxes(2); +temp4 = total_maxes(3); + +fprintf('%d\t', max_index - 1); +fprintf('%.6f\t', temp2); +fprintf('%.6f\t', max_value); +fprintf('%.6f\t', temp3); +fprintf('%.6f %.6f %.6f\t', total_maxes); +fprintf('%.6f\n', temp4); + +function signal = generateVoiceSignature(freq1, freq2, len, fs) + t = (0:len-1) / fs; + signal = sin(2 * pi * freq1 * t) + sin(2 * pi * freq2 * t); end -% Call the main function -main(); +function result = correlate(signal1, signal2) + len = length(signal1); + corr_len = 2 * len - 1; + result = zeros(1, corr_len); + for lag = 0:corr_len-1 + for i = 1:len + j = lag - len + i; + if j >= 1 && j <= len + result(lag+1) = result(lag+1) + signal1(i) * signal2(j); + end + end + end +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spectralAnalysis.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spectralAnalysis.m index 787269371ac3..5c8c4a73e186 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spectralAnalysis.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/spectralAnalysis.m @@ -1,22 +1,24 @@ -% Constants -INPUT_LENGTH = 100000000; - -% getRange function +INPUT_LENGTH = 400; input = getRange(0, INPUT_LENGTH, 1); -% DFT function (using built-in FFT) -fft_result = fft(input); - -% Square of absolute values -sq_abs = abs(fft_result).^2; +fft = dft(input); +sq_abs = abs(fft).^2; +sum_result = sum(sq_abs); +res = sum_result / INPUT_LENGTH; -% Sum and average -res = mean(sq_abs); +fprintf('%.6f\n', res); -% Display result -fprintf('%f\n', res); +function vector = getRange(start, len, step) + vector = start + (0:len-1) * step; +end -% getRange function -function output = getRange(start, noOfSamples, increment) - output = start + (0:noOfSamples-1) * increment; -end \ No newline at end of file +function output = dft(input) + N = length(input); + output = zeros(1, N); + for k = 1:N + for n = 1:N + angle = 2 * pi * (k-1) * (n-1) / N; + output(k) = output(k) + input(n) * exp(-1i * angle); + end + end +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/targetDetection.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/targetDetection.m index fda717133060..8e2038bcdc45 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/targetDetection.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/targetDetection.m @@ -1,51 +1,65 @@ % Constants -INPUT_LENGTH = 100000000; -MAX_PEAKS = 100; +PI = pi; +INPUT_LENGTH = 500; +FILTER_SIZE = 20; +MAX_PEAKS = 50; -% Generate input range -input = (0:0.000125:(INPUT_LENGTH-1)*0.000125)'; +% Generate input time vector +input = 0:0.000125:(INPUT_LENGTH - 1) * 0.000125; -% Generate signals -getMultiplier = 2 * pi * 10; -getSinDuration = input * getMultiplier; +% Signal 1: 10 Hz sine +getMultiplier = 2 * PI * 10; +getSinDuration = getMultiplier * input; sig1 = sin(getSinDuration); -getMultiplier2 = 2 * pi * 20; -getSinDuration2 = input * getMultiplier2; +% Signal 2: 20 Hz sine with 0.5 amplitude +getMultiplier2 = 2 * PI * 20; +getSinDuration2 = getMultiplier2 * input; sinsig2 = sin(getSinDuration2); sig2 = 0.5 * sinsig2; % Combine signals signal = sig1 + sig2; -% Add delayed noise -noise = [zeros(5, 1); signal(1:end-5)]; +% Create delayed noise (5-sample delay) +delaySamples = 5; +noise = [zeros(1, delaySamples), signal(1:end - delaySamples)]; + +% Add noise to signal noisy_sig = signal + noise; -% LMS Filter +% LMS filtering using function mu = 0.01; -filterSize = 20; -y = lmsFilterResponse(noisy_sig, signal, mu, filterSize); - -% Find peaks -[peaks, ~] = findpeaks(signal, 'MinPeakHeight', 1, 'MinPeakDistance', 50); - -% Display results -fprintf('%d %d\n', peaks(2), peaks(3)); - - -% LMS Filter Response Function -function output = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize) - length = numel(noisy_sig); - w = zeros(filterSize, 1); - output = zeros(length, 1); - - for n = 1:length - x = noisy_sig(max(1, n-filterSize+1):n); - x = [zeros(filterSize - numel(x), 1); x]; - y = w' * x; - e = clean_sig(n) - y; - w = w + mu * e * x; - output(n) = e; +y = lmsFilterResponse(noisy_sig, signal, mu, FILTER_SIZE); + +% Peak detection +[~, peakLocs] = findpeaks(y, 'MinPeakHeight', 1.0, 'MinPeakDistance', 50); +numPeaks = min(length(peakLocs), MAX_PEAKS - 1); +peaks = -1 * ones(1, MAX_PEAKS); +peaks(1:numPeaks) = peakLocs(1:numPeaks); +peaks(end) = numPeaks; + +% Extract two peak indices +final1 = peaks(2); +final2 = peaks(1); + +fprintf('%f\t%f\n', final1, final2); +function y = lmsFilterResponse(noisy_sig, clean_sig, mu, filterSize) + len = length(noisy_sig); + y = zeros(1, len); + w = zeros(1, filterSize); % Initialize weights to zero + + for n = 1:len + for i = 1:filterSize + if (n - i + 1) > 0 + y(n) = y(n) + w(i) * noisy_sig(n - i + 1); + end + end + e = clean_sig(n) - y(n); + for i = 1:filterSize + if (n - i + 1) > 0 + w(i) = w(i) + mu * e * noisy_sig(n - i + 1); + end + end end -end \ No newline at end of file +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/underWaterCommunication.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/underWaterCommunication.m index bd4e3f04fe17..154356aee330 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/underWaterCommunication.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/underWaterCommunication.m @@ -1,79 +1,45 @@ % Constants -INPUT_LENGTH = 100000000; +PI = 3.14159265359; +FS = 1000; +INPUT_LENGTH = 40; FILTER_ORDER = 5; -% Sampling frequency -fs = 1000; +% Generate input time vector +input = (0:INPUT_LENGTH-1)' * 0.000125; -% Generate input vector -input = getRangeOfVector(0, INPUT_LENGTH, 1); +% Generate base sinusoid +getMultiplier = 2 * PI * 5; +getSinDuration = input * getMultiplier; +signal = sin(getSinDuration); -% Gain calculation -getMultiplier = 2 * pi * 5; -getSinDuration = gain(input, getMultiplier); +% Create delayed noise and add to signal +noise = [zeros(5,1); signal(1:end-5)]; +noisy_sig = signal + noise; -% Sine wave generation -signal = sine(getSinDuration); - -% Adding delay (noise) -noise = delay(signal, 5); - -% Adding signal and noise -noisy_sig = add(signal, noise); - -% Low-pass filter parameters -fc = 1000; -wc = 2 * pi * fc / 500; % wc should vary from 0 to pi - -% Low-pass FIR filter design -lpf = lowPassFIRFilter(wc, FILTER_ORDER); +% Filter configuration +wc = 2 * PI * 1000 / 500; +lpf = lowPassFIRFilter(wc); hamming_window = hamming(FILTER_ORDER); -% Apply Hamming window to the filter -lpf_w = lpf .* hamming_window; - -% FIR filter response -FIRfilterResponse = FIRFilterResponse(noisy_sig, lpf_w); +% Use first coefficient of Hamming window as in C +lpf_w = lpf * hamming_window(1); -% Thresholding operation -threshold = 0.5; -GetThresholdReal = thresholdUp(FIRfilterResponse, threshold, 0); +% Apply scalar FIR filter +FIRfilterResponseArray = noisy_sig * lpf_w; -% Display the result -disp(GetThresholdReal(3)); +% Apply threshold +threshold = 0.05; +GetThresholdReal = thresholdUp(FIRfilterResponseArray, threshold, 0); -% Function implementations - -function vector = getRangeOfVector(start, length, increment) - vector = (start : increment : start + (length-1)*increment)'; -end - -function output = gain(input, multiplier) - output = input * multiplier; +% Extract final result +final1 = GetThresholdReal(4); % MATLAB is 1-indexed +fprintf('%.6f\n', final1); +function out = lowPassFIRFilter(wc) + PI = 3.14159265359; + out = wc / PI; end -function output = sine(input) - output = sin(input); +function out = thresholdUp(input, threshold, defaultValue) + out = double(input >= threshold); + out(out < 1) = defaultValue; end - -function output = delay(input, delaySamples) - output = [zeros(delaySamples, 1); input(1:end-delaySamples)]; -end - -function output = add(input1, input2) - output = input1 + input2; -end - -function filter = lowPassFIRFilter(wc, length) - n = (-(length-1)/2:(length-1)/2)'; - filter = wc/pi * sinc(wc/pi * n); -end - -function output = FIRFilterResponse(input, filter) - output = conv(input, filter, 'same'); -end - -function output = thresholdUp(input, threshold, defaultValue) - output = max(input, threshold); - output(output == threshold) = defaultValue; -end \ No newline at end of file diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/vibrationAnalysis.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/vibrationAnalysis.m index 934c4e9501a2..1ef619fb0b84 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/vibrationAnalysis.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/vibrationAnalysis.m @@ -1,39 +1,51 @@ -% Constants -INPUT_LENGTH = 10000000; -fs = 1000; +function main + PI = 3.14159265359; + INPUT_LENGTH = 100; -% Generate input signal -input = 0:(INPUT_LENGTH-1); + fs = 1000; + input = getRangeOfVector(0, INPUT_LENGTH, 0.000125); -% Generate first sinusoidal signal -getMultiplier = 2 * pi * 50; -getSinDuration = input * getMultiplier; -sig1 = sin(getSinDuration); + getMultiplier = 2 * PI * 50; + getSinDuration = input * getMultiplier; -% Generate second sinusoidal signal -getMultiplier2 = 2 * pi * 120; -getSinDuration2 = input * getMultiplier2; -sig2 = 0.5 * sin(getSinDuration2); + sig1 = sin(getSinDuration); -% Combine signals -signal = sig1 + sig2; + getMultiplier2 = 2 * PI * 120; + getSinDuration2 = input * getMultiplier2; -% Add delayed noise -noise = [zeros(1, 5), signal(1:end-5)]; -noisy_sig = signal + noise; + sinsig2 = sin(getSinDuration2); + sig2 = sinsig2 * 0.5; -% Perform DFT -dft_output = fft(noisy_sig); + signal = sig1 + sig2; -% Calculate squared magnitude -sq_abs = abs(dft_output).^2; + noise = delay(signal, 5); -% Calculate mean -res = mean(sq_abs); + noisy_sig = signal + noise; -% Apply threshold -threshold_value = 0.2; -GetThresholdReal = sq_abs .* (sq_abs >= threshold_value); + threshold_value = 2; -% Display results -disp(GetThresholdReal); + dft_output = fft(noisy_sig); + + fft_real = real(dft_output); + fft_img = imag(dft_output); + + sq_abs = fft_real.^2 + fft_img.^2; + magnitude = sqrt(sq_abs); + GetThresholdReal = threshold(magnitude, threshold_value); + + disp(GetThresholdReal(1)); +end + +function vector = getRangeOfVector(start, len, increment) + vector = start + (0:len-1) * increment; +end + +function output = delay(input, delaySamples) + output = zeros(size(input)); + output(delaySamples+1:end) = input(1:end-delaySamples); +end + +function output = threshold(input, thresholdValue) + output = input; + output(input < thresholdValue) = 0; +end diff --git a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/voiceActivityDetection.m b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/voiceActivityDetection.m index a3cc47b620c8..49d2d8e254bd 100644 --- a/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/voiceActivityDetection.m +++ b/mlir/examples/dsp/SimpleBlocks/Output/TryDSPApps/BenchmarkTest/Matlab/voiceActivityDetection.m @@ -1,57 +1,36 @@ -% Constants -INPUT_LENGTH = 100000000; +function main + PI = 3.14159265359; + SAMPLE_RATE = 1000; + INPUT_LENGTH = 100; + THRESHOLD = 0.01; -% Main script -fs = 1000; -input = getRangeOfVector(0, INPUT_LENGTH, 1); + input = (0:INPUT_LENGTH-1)' * 0.0125; -getMultiplier = 2 * pi * 5; -getSinDuration = gain(input, getMultiplier); + getMultiplier = 2 * PI * 5; + getSinDuration = input * getMultiplier; + signal = sin(getSinDuration); -signal = sine(getSinDuration); + delay_steps = 5; + noise = [zeros(delay_steps,1); signal(1:end-delay_steps)]; + noisy_sig = signal + noise; -noise = delay(signal, 5); + GetThresholdReal = applyThreshold(noisy_sig, THRESHOLD); + zcr = zeroCrossCount(GetThresholdReal); -noisy_sig = add(signal, noise); - -threshold_value = 0.8; -GetThresholdReal = threshold(noisy_sig, threshold_value); - -zcr = zeroCrossCount(GetThresholdReal); - -% Display results -disp(GetThresholdReal(4)); - -% Print zero-crossing count -fprintf('Zero-crossing count: %d\n', zcr); - -% Function implementations -function vector = getRangeOfVector(start, length, increment) - vector = (start : increment : start + (length-1)*increment)'; -end - -function output = gain(input, multiplier) - output = input * multiplier; + fprintf('%.6f\n', zcr); end -function output = sine(input) - output = sin(input); -end - -function output = delay(input, delaySamples) - output = [zeros(delaySamples, 1); input(1:end-delaySamples)]; -end - -function output = add(input1, input2) - output = input1 + input2; -end - -function output = threshold(input, thresholdValue) +function output = applyThreshold(input, threshold) output = input; - output(abs(input) < thresholdValue) = 0; + output(abs(input) <= threshold) = 0; end -function count = zeroCrossCount(input) - signs = sign(input); - count = sum(abs(diff(signs)) == 2); -end \ No newline at end of file +function count = zeroCrossCount(signal) + count = 0; + for i = 2:length(signal) + if (signal(i-1) > 0 && signal(i) < 0) || ... + (signal(i-1) < 0 && signal(i) > 0) + count = count + 1; + end + end +end