diff options
| author | Clément Zrounba <6691770+clement-z@users.noreply.github.com> | 2023-09-30 23:06:01 +0200 |
|---|---|---|
| committer | Clément Zrounba <6691770+clement-z@users.noreply.github.com> | 2023-09-30 23:26:46 +0200 |
| commit | ff9b8bb838ecdfbfc1dc81038fcf3b2a87636982 (patch) | |
| tree | 21f27be782ce11c6d00b96ce100a2bff88141b2e | |
| download | specs-ff9b8bb838ecdfbfc1dc81038fcf3b2a87636982.tar.gz specs-ff9b8bb838ecdfbfc1dc81038fcf3b2a87636982.zip | |
Initial release
145 files changed, 23801 insertions, 0 deletions
diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..b586a0e --- /dev/null +++ b/.clang-format @@ -0,0 +1,121 @@ +--- +Language: Cpp +# BasedOnStyle: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: false +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: InlineOnly +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: false +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: All +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 88 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentPPDirectives: None +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseTab: Never +... + diff --git a/.config.gitlab-ci.mk b/.config.gitlab-ci.mk new file mode 100644 index 0000000..d59f3d0 --- /dev/null +++ b/.config.gitlab-ci.mk @@ -0,0 +1,28 @@ +#### PROJECT SETTINGS #### +# The name of the executable to be created +BIN_NAME = specs +LIB_NAME = libspecs.so + +# Compiler used +CXX = g++ +CCACHE = + +BUILD_TB ?= 1 + +# Path to the source directory, relative to the makefile +SRC_PATH = src + +# General compiler flags +CXXFLAGS = -std=c++17 -Wall -Wextra +CXXFLAGS += -O2 -march=native + +# Add additional include paths (SRC_PATH and subdirectories are automatically added) +INCLUDES += -isystem thirdparty/args + +# General linker settings +LDFLAGS += -lsystemc -lm + +# Destination directory +BUILD_PATH = build + +#### END PROJECT SETTINGS #### diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa7b2f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +*~ +*.vcd +*.o +*.d +**/__pycache__/ +build/ +sim +src.old/ +compile_commands.json +README.html +resources/out/ +doc/html +doc/*.tar.xz +bitstream.txt +Pout.png +Pout.obj +detector_trace.txt +.cache +.vscode/** +**/.vscode/** +**/.clangd/** +detector_traces/** +.vimrc.local +config.local.mk +specs +libspecs.so +gmon.out +**/main +**/a.out +*.exe +*.cir +tmp/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..f41da7d --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,79 @@ +# Currently using alpine as base +#image: alpine:latest +image: alpine:latest +# TODO: Migrate to another base including all the dependencies +# in order to avoid fetching and installing everything each time + +stages: + - build + - test + - deploy + +variables: + # Recursive submodule update + GIT_SUBMODULE_STRATEGY: recursive + +before_script: + # Add the testing repo for SystemC + - echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories + # Install all dependencies + - apk update + - apk add --no-cache + bash findutils + build-base bison flex + doxygen graphviz + systemc-dev + - cp .config.gitlab-ci.mk config.local.mk + +build: + stage: build + script: + - make -j$(nproc) bin V=1 + - make -j$(nproc) lib V=1 + artifacts: + paths: + - "./specs" + - "./libspecs.so" + +test: + stage: test + script: + # Only running a few tests manually for now + - ./specs -t wg + #- ./specs -t dc + #- ./specs -t splitter + #- ./specs -t merger + #- ./specs -t detector + #- ./specs -t phaseshifter + # TODO: add other tests (both from -t and the circuit test files) + dependencies: + - build + artifacts: + paths: + - "traces/*.vcd" + +doc: + stage: build + script: + - make doc + artifacts: + paths: + - doc/pcm-doc.tar.xz + - doc/html/ + only: + - master + + +pages: + stage: deploy + script: + - mkdir public + - cp -R doc/html/* public + dependencies: + - doc + artifacts: + paths: + - public + only: + - master + diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..a469512 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "deps/args"] + path = thirdparty/args + url = https://github.com/Taywee/args +[submodule "thirdparty/systemc"] + path = thirdparty/systemc + url = https://github.com/accellera-official/systemc diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..5357f69 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,166 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1975007 --- /dev/null +++ b/Makefile @@ -0,0 +1,299 @@ +# Use bash as the shell +SHELL = /bin/bash + +LOCAL_CONFIG_EXISTS = $(shell (test -e config.local.mk && echo 1) || echo 0) +ifeq "${LOCAL_CONFIG_EXISTS}" "1" + CONFIG_MK_FILE = config.local.mk + #CONFIG_MK_FILE = config.windows.mk +else + CONFIG_MK_FILE = config.mk +endif + +include $(CONFIG_MK_FILE) + +BUILD_TB ?= 0 +BUILD_PATH_LIB ?= $(BUILD_PATH)-lib + +CXX_LD ?= $(CXX) + +CXXFLAGS += -MMD -MP +CXXFLAGS_LIB = $(CXXFLAGS) -fpic +LDFLAGS_LIB = $(LDFLAGS) -shared -Wl,-soname,libspecs.so +BISONFLAGS += --warnings -Wall #-Wcex + +# Find all source files in the source directory +SOURCES_BIN = $(shell find $(SRC_PATH) -name '*.cpp' -not -ipath '*/tb/*') +SOURCES_LIB = $(shell find $(SRC_PATH) -name '*.cpp' -not -ipath '*/tb/*' -not -name 'main.cpp' -not -ipath '*/parser/*.cpp') +SOURCES_TB = $(shell find $(SRC_PATH) -name '*.cpp' -ipath '*/tb/*') +SOURCES_TB_MAIN = $(shell find $(SRC_PATH) -name 'alltestbenches.cpp' -ipath '*/tb/*') +SOURCES_ALLFILES = $(shell find $(SRC_PATH) -name '*.cpp' -or -name '*.h') + +# Add the whole source directory tree to INCLUDES +INCLUDES += $(addprefix -I,$(shell find $(SRC_PATH) -type d)) + +# Find all bison/flex source files +# - Note: bison/flex sources must have a matching filename +FLEX_SOURCES = $(shell find $(SRC_PATH) -name '*.l') +BISON_SOURCES = $(shell find $(SRC_PATH) -name '*.y') + +# Set the object filenames from the cpp sources +OBJECTS_BIN = $(SOURCES_BIN:$(SRC_PATH)/%.cpp=$(BUILD_PATH)/%.o) +ifeq ($(BUILD_TB), 1) + OBJECTS_BIN += $(SOURCES_TB:$(SRC_PATH)/%.cpp=$(BUILD_PATH)/%.o) + CXXFLAGS += -DBUILD_TB +else + OBJECTS_BIN += $(SOURCES_TB_MAIN:$(SRC_PATH)/%.cpp=$(BUILD_PATH)/%.o) +endif + +# Add the objects filenames from the bison/flex sources +OBJECTS_PARSE = $(FLEX_SOURCES:$(SRC_PATH)/%.l=$(BUILD_PATH)/%.yy.o) +OBJECTS_PARSE += $(BISON_SOURCES:$(SRC_PATH)/%.y=$(BUILD_PATH)/%.tab.o) + +# Same without main (without testbenches) +OBJECTS_LIB = $(SOURCES_LIB:$(SRC_PATH)/%.cpp=$(BUILD_PATH_LIB)/%.o) + +# Set the dependency files that will be used to add header dependencies +DEPS = $(OBJECTS_BIN:.o=.d) +DEPS_PARSE = $(OBJECTS_PARSE:.o=.d) +DEPS_LIB = $(OBJECTS_LIB:.o=.d) + +# Set other dependencies that should trigger rebuilding .o files +ADDITIONAL_DEPS = Makefile $(CONFIG_MK_FILE) + +# Find the latest trace according to modification time +LATEST_TRACE_NAME = $(shell ls -1rt --group-directories-first traces | tail -1) + +# Be verbose +V ?= 0 + +# Set/Unset the Q flag according to the V flag +ifeq ($(V),1) + Q = + QQ = @ +else + Q = @ + QQ = @ +endif + +# Clear known suffixes rules +.SUFFIXES: + +# Define phony targets +.PHONY: todos format waves newwaves print-% help cleandoc cleanoldtraces \ + cleantraces cleanall clean compiledb view-doc upload-doc doc readme \ + all bin lib + +# Instruct make not to remove intermediate files from bison/flex compilation +.SECONDARY: $(FLEX_SOURCES:$(SRC_PATH)/%.l=$(BUILD_PATH)/%.yy.h) +.SECONDARY: $(FLEX_SOURCES:$(SRC_PATH)/%.l=$(BUILD_PATH)/%.yy.cpp) +.SECONDARY: $(FLEX_SOURCES:$(SRC_PATH)/%.l=$(BUILD_PATH)/%.tab.h) +.SECONDARY: $(BISON_SOURCES:$(SRC_PATH)/%.y=$(BUILD_PATH)/%.tab.cpp) + +# Default rule +all: bin + +# Build executable +bin: $(BIN_NAME) + +# Build shared library +lib: $(LIB_NAME) + +# Link all objects together into executable +$(BIN_NAME): $(OBJECTS_BIN) $(OBJECTS_PARSE) + @echo "Linking binary" + $(Q)$(CCACHE) $(CXX_LD) $(OBJECTS_BIN) $(OBJECTS_PARSE) $(LDFLAGS) -o $@ + @echo "Done" + +# Link all objects together into library +$(LIB_NAME): $(OBJECTS_LIB) + @echo "Linking library" + $(Q)$(CCACHE) $(CXX_LD) $(OBJECTS_LIB) $(LDFLAGS_LIB) -o $@ + @echo "Done" + +# Objects depend on their directories +$(OBJECTS_PARSE): $(ADDITIONAL_DEPS) | $(dir $(OBJECTS_PARSE)) + +# Objects depend on their directories +$(OBJECTS_BIN): $(ADDITIONAL_DEPS) | $(dir $(OBJECTS_BIN)) $(OBJECTS_PARSE) + +# Objects depend on their directories +$(OBJECTS_LIB): $(ADDITIONAL_DEPS) | $(dir $(OBJECTS_LIB)) + +# Rule to create the $(BUILD_PATH) directory +$(BUILD_PATH)/: + $(Q)mkdir -p $@ + +# Rule to create a subdirectory in $(BUILD_PATH) +$(BUILD_PATH)/%/: + $(Q)mkdir -p $@ + +# Rule to create the $(BUILD_PATH_LIB) directory +$(BUILD_PATH_LIB)/: + $(Q)mkdir -p $@ + +# Rule to create a subdirectory in $(BUILD_PATH_LIB) +$(BUILD_PATH_LIB)/%/: + $(Q)mkdir -p $@ + +# Default .cpp → .o compilation rule +$(BUILD_PATH)/%.o: $(SRC_PATH)/%.cpp + @echo "Compiling $<" + $(Q)$(CCACHE) $(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ + +# Default .cpp → .o compilation rule for library +$(BUILD_PATH_LIB)/%.o: $(SRC_PATH)/%.cpp + @echo "Compiling $<" + $(Q)$(CCACHE) $(CXX) $(CXXFLAGS_LIB) $(INCLUDES) -MMD -MP -c $< -o $@ + +# Special .cpp compilation rule for flex generated sources +%.yy.o: %.yy.cpp %.tab.h + @echo "Compiling $<" + $(Q)$(CCACHE) $(CXX) $(CXXFLAGS) $(INCLUDES) -iquote"$(dir $@)" -c $< -o $@ + +# Special .cpp compilation rule for bison generated sources +%.tab.o: %.tab.cpp %.yy.h + @echo "Compiling $<" + $(Q)$(CCACHE) $(CXX) $(CXXFLAGS) $(INCLUDES) -iquote"$(dir $@)" -c $< -o $@ + +# Default .l → .yy.cpp compilation rule +$(BUILD_PATH)/%.yy.cpp: $(SRC_PATH)/%.l | $(dir $($@)) + @echo "Lexing $<" + $(Q)flex --header-file="$(@:.cpp=.h)" -o $@ $< + +# Default .y → .tab.{h,cpp} compilation rule +$(BUILD_PATH)/%.tab.cpp: $(SRC_PATH)/%.y $(BUILD_PATH)/%.yy.cpp | $(dir $($@)) + @echo "Bisoning $<" + $(Q)bison $(BISONFLAGS) --defines="$(@:.cpp=.h)" -o $@ -d $< + +# Dependency rule for .tab.h (bison output, needed to compile flex output) +%.tab.h: | %.tab.cpp + @: + +# Dependency rule for .yy.h (bison output, needed to compile flex output) +%.yy.h: | %.yy.cpp + @: + +#$(ADDITIONAL_DEPS): +#@: + +# Add dependency files, if they exist +-include $(DEPS) +-include $(DEPS_LIB) +-include $(DEPS_PARSE) + +# Generation of documentation using Doxygen +doc: + @echo "Generating documentation" + @mkdir -p doc/html + @cp -r doc/resources/ doc/html/ + $(Q)doxygen doc/Doxyfile + #$(Q)tar -c -f doc/pcm-doc.tar.xz -C doc/html . + +# Regenerate compile_commands.json for YouCompleteMe +compiledb: compile_commands.json + +# Regenerate compile_commands.json for YouCompleteMe +compile_commands.json: clean + @echo "Generating compile_commands.json" + $(Q)compiledb --verbose make -j8 + $(Q)sed -i '/"-MMD"\|"-MP"/d' $@ + +# Clean build artifacts +clean: + @echo "Removing build artifacts" + $(QQ)#[ ! -d 'build' ] || rm -rf build/ + $(QQ)#[ ! -d 'build-lib' ] || rm -rf build-lib/ + $(Q)[ ! -d "$(BUILD_PATH)" ] || rm -rf "$(BUILD_PATH)" + $(Q)[ ! -d "$(BUILD_PATH_LIB)" ] || rm -rf "$(BUILD_PATH_LIB)" + +# Remove any product of the build (build, trace, doc, bin) +cleanall: clean cleantraces cleandoc + @echo "Removing binary" + $(Q)rm -f Pout.obj Pout.png detector_trace.txt + $(Q)rm -f sim specs libspecs.so + +# Clean all traces +cleantraces: + @echo "Removing all traces" + $(Q)find traces/ -maxdepth 1 -type f -and -iname '*.vcd' -delete + +# Clean all traces but the newest +cleanoldtraces: + @echo "Removing all traces but newest" + $(Q)find traces/ -maxdepth 1 -iname '*.vcd' -and -type f -and ! -iname "$(LATEST_TRACE_NAME)" -delete + +# Clean documentation output +cleandoc: + @echo "Removing generated documentation" + $(Q)rm -rf doc/html doc/pcm-doc.tar.xz + +# Show the latest trace with a blank GTKWave config +newwaves: + @echo "Opening latest trace file" + @mkdir -p traces/configs + @bash utils/openwave.sh "traces/$(LATEST_TRACE_NAME)" + +# Show the latest trace with a menu to select which GTKWave config to use +waves: + @echo "Opening latest trace file" + @mkdir -p traces/configs + @bash utils/openwave.sh "traces/$(LATEST_TRACE_NAME)" traces/configs + +test: + @echo "Running all tests" + $(Q)./specs -t waveguide + $(Q)./specs -t splitter + $(Q)./specs -t merger + $(Q)./specs -t detector + $(Q)./specs -t directional_coupler + $(Q)./specs -t phaseshifter + $(Q)./specs -t mzi + $(Q)./specs -t pcm + $(Q)#./specs -t ring + $(Q)#./specs -t ac_add_drop + $(Q)#./specs -t ac_crow + $(Q)#./specs -t mesh + +rc: all + ./${BIN_NAME} -fcircuits/rc_mohab.cir + + +# TODO: add a gate so we don't accidentally "mess up" the working +# directory by shadowing real changes. Maybe do a commit or something +# like this ? or check the git status whether there are changes ? +# Automatic formatting should be automatically run on write, but if +# modifying a file with a different format and re-formatting, changes +# seen by git could be far from obvious to re-read later +# Run clang-format on the source (in place) +format: + @echo "Formatting source" + @clang-format -i $(SOURCES_ALLFILES) + +# Print all TODOs found in the source and other files +todos: + @echo "TODO (from code):" + @find $(SRC_PATH) -type f | xargs awk '/TODO:/ {split($$0, arr, "TODO:"); content = arr[2]; print "- " content, "("FILENAME":"FNR")"}' || true + @#find module_definitions/ -type f | xargs awk '/TODO:/ {split($$0, arr, "TODO:"); content = arr[2]; print "- " content, "("FILENAME":"FNR")"}' || true + @find utils/ -type f | xargs awk '/TODO:/ {split($$0, arr, "TODO:"); content = arr[2]; print "- " content, "("FILENAME":"FNR")"}' || true + @cat todo.txt || true + +# Print a given variable +print-%: + $(Q)echo $* = $($*) + +# FIXME: cannot have ":" in rule descriptions +# Show this help prompt +help: + @ echo + @ echo ' Usage:' + @ echo '' + @ echo ' make <target> [flags...]' + @ echo '' + @ echo ' Targets:' + @ echo '' + @ awk '/^#/{ comment = substr($$0,3) } comment && /^[a-zA-Z][a-zA-Z0-9_-]+ ?:/{ print " ", $$1, comment }' $(MAKEFILE_LIST) | column -t -s ':' | sort + @ echo '' + @ echo ' Flags:' + @ echo '' + @awk '/^#/{ comment = substr($$0,3) } comment && /^[a-zA-Z][a-zA-Z0-9_-]*/ && /\??=/ && /[01]$$/{ print " " $$1 " (default = " $$3 ")",":",comment }' $(MAKEFILE_LIST) | column -t -s ':' | sort + @ echo '' diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 0000000..70509ec --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,102 @@ +# Quickstart guide {#quickstart} + +[TOC] + +# Dependencies + +## Building toolchain + +* `git` +* `bash` +* `find` +* `make` +* a c++ compiler that supports c++14 or c++17 (`g++` or `clang++`) +* GNU `flex` (`lex` is untested) +* GNU `bison` (`yacc` is untested) + +Optional: + +* `python3` for generating the sources using the module definitions +* ... + +## External build dependencies + +* `systemc` (v2.3.3) + +## Documentation generation + +* `doxygen` +* `dot` (via `graphviz` for example) + +## Traces visualization + +* GTKWave +* `python3` +* `python3-matplotlib` +* ... + +# Building + +* First, make sure to install all the dependencies on your system, either locally or globally. +* Then, fetch the code: + + % git clone git@gitlab.inl90.ec-lyon.fr:czrounba/systemc-pcm-matrix-multiplication-simulator.git + % git submodule update --init --recursive + +* Copy `config.mk` to `config.local.mk` and update the compiler/library information there +* If you installed systemc in a non-default path, you might need to update the +`INCLUDES` and `LD_FLAGS` make variables in `config.mk`. +* Finally, build `specs` + % make -j$(nproc) +* Run a test circuits + % ./sim -t {waveguide,splitter,pcm,...} + +# Running + +Simulating a circuit from a netlist is straightforward: + + % ./sim -f <my-circuit>.cir + +Look at the [cheatsheet](doc/resources/cheatsheet.pdf) for more information on the syntax to use. +[](TODO: add a page for info on syntax of circuit files) + +After running, you can find results in the VCD tracefile (the file name can be specified in the circuit file with option `-o`). + +# Generating documentation (OUTDATED) + +First make sure `doxygen` and `graphviz` are installed, then: + +* To generate the doc, run: + + % make doc + +* To open it in your default browser, run: + + % make view-doc + +The generated documentation is available as HTML under `doc/html/` and compressed +into a `tar.xz` archive under `doc/`. Other ouput formats are supported by `doxygen`. + +# Troubleshooting + +<!-- +If you cannot manage to build the simulator, you can check the `.gitlab-ci.yml` +file which contains all the instructions to run to successfully build the code +in a docker: + +* Install docker ([docker.io](https://docker.io)) and start it +* Start an alpine container: + + % docker run -it alpine:latest + +* Run all commands from the `before_script` section +* Clone the git repo and update submodules: + + % git clone <url> <local-folder> + % cd <local-folder> + % git submodule update --init --recursive + +* Run all commands from the `build:script` section +* Run all commands from the `test:script` section +* Optional: Run all commands from the `doc:script` section +--> diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a2644d --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Scalable Photonic Event-driven Circuit Simulator (SPECS) + +For the moment, refer to our user guide to see how to download and use SPECS + +https://demo.zrounba.fr/specs/doc/index.html diff --git a/circuits/add_drop.cir b/circuits/add_drop.cir new file mode 100644 index 0000000..bc0ee01 --- /dev/null +++ b/circuits/add_drop.cir @@ -0,0 +1,41 @@ +* An Add-drop filter + +* Circuit parameters +.assign lambda0 = 1.55e-6 +.assign neff = 2.3 +.assign length_2pi = {lambda0}/{neff} +.assign k = 0.85 + +.subckt test p1 p2 length=100e-6 att=1 neff=2.2 ng=4.3 +wg1 p1 0 length={length} att={att} neff={neff} ng={ng} +wg2 0 p2 length={length} att={att} neff={neff} ng={ng} +.ends + +* Circuit definition +cwsrc1 in_ wl=1.55e-6 power=1 +x1 in_ in test length=1e-3 neff=1 ng=4 att=0 +;wg_access in_ in length={length_2pi} neff={neff} ng=4 + +coupler1 in ring_bl out ring_br k={k} +coupler2 add ring_tr drop ring_tl k={k} + +wg_ring_l ring_tl ring_bl att=2 length=101*{length_2pi} neff={neff} ng=4.3 +wg_ring_r ring_br ring_tr att=2 length=101*{length_2pi} neff={neff} ng=4.3 + +* Simulator options +.options abstol=1e-12 reltol=1e-6 timescale=-15 + +* DC analysis (CW sweep) parameters +.assign lambda_min = {lambda0} - 15e-9 +.assign lambda_max = 2*{lambda0}-{lambda_min} +.assign dlambda = 1*1e-9 + +* Analysis +;.dc WL(cwsrc1) {lambda_min} {lambda_max} {dlambda} P(cwsrc1) 0 1 0.01 +.dc /cwsrc1/WL {lambda_min} {lambda_max} {dlambda} +;.dc P(cwsrc1) 0 1 0.1 +;.dc FREQ(cwsrc1) 192e12 194e12 1e9 +;.dc WL(cwsrc1) +;.op +;.tran +;.dc wl(osrc1)=[{lambda_min},{lambda_max},{npoints}] diff --git a/circuits/add_drop_pyspecs.cir b/circuits/add_drop_pyspecs.cir new file mode 100644 index 0000000..cc724d4 --- /dev/null +++ b/circuits/add_drop_pyspecs.cir @@ -0,0 +1,28 @@ +* An Add-drop filter + +* Circuit parameters +.assign lambda0 = 1.55e-6 + +* Circuit definition +;cwsrc1 in wl=1.55e-6 power=1 +vlsrc1 in values=[[0.5e-9,1,{lambda0}],[2e-9,0,{lambda0}]] + +coupler1 in 1 out 2 k=0.15 +coupler2 add 3 drop 4 k=0.15 + +wg_ring_l 4 1 length=300e-6 neff=3.999 +wg_ring_r 2 3 length=300e-6 neff=3.999 + +probe1 out +probe2 drop +probe3 in + +* Simulator options +.options abstol=1e-6 reltol=1e-8 timescale=-12 traceall=1 + +* Analysis parameter +.assign dlambda = 1e-12 + +* Analysis +;.dc /cwsrc1/WL 1549.9e-9 1550.1e-9 {dlambda} +.tran 3e-9 diff --git a/circuits/add_drop_sub.cir b/circuits/add_drop_sub.cir new file mode 100644 index 0000000..1d96aed --- /dev/null +++ b/circuits/add_drop_sub.cir @@ -0,0 +1,15 @@ +* An Add-drop filter subcircuit + +.subckt add_drop_filter in drop out add radius_ring=50e-6 k1=0.85 k2=0.85 att_wg=2 neff_wg=2.2 ng_wg=4.3 + +* Circuit parameters +.assign length_wg = {pi}*{radius_ring} + +* Circuit definition +coupler1 in ring_bl out ring_br k={k1} +coupler2 add ring_tr drop ring_tl k={k2} + +wg_ring_l ring_tl ring_bl att={att_wg} length={length_wg} neff={neff_wg} ng={ng_wg} +wg_ring_r ring_br ring_tr att={att_wg} length={length_wg} neff={neff_wg} ng={ng_wg} + +.ends diff --git a/circuits/common_definitions.def b/circuits/common_definitions.def new file mode 100644 index 0000000..9c25105 --- /dev/null +++ b/circuits/common_definitions.def @@ -0,0 +1,5 @@ +.assign lambda0 = 1.55e-6 ; m +.assign neff = 2.3 +.assign ng = 4.3 +.assign att_wg = 2 ; db/cm +.assign length_2pi = {lambda0}/{neff} diff --git a/circuits/double_ring.cir b/circuits/double_ring.cir new file mode 100644 index 0000000..0e4addb --- /dev/null +++ b/circuits/double_ring.cir @@ -0,0 +1,57 @@ +* Show bitstream source + +* Initialize the sources +one 0 +clk 1 100p + +*bsrc 0 1 2 {0, 0, 0} +bsrc 0 1 2 {0, 252, 15, 0} 1550.0e-9 +*bsrc 0 1 2 {0, 252, 15, 0} 1545.0e-9 + +* split +dc 2 3 4 5 +dc 6 7 8 9 +dc 12 13 10 11 +dc 16 17 14 15 + +wg 10 3 350.85477427u +*wg 5 18 350.85477427u +wg 5 12 350.85477427u + +* resonance at 1545 +*wg 14 7 351.08113608611u +*wg 9 16 351.08113608611u +* resonance at 1550 +wg 14 7 350.85477427u +wg 9 16 350.85477427u + +wg 4 6 701.12011675u +wg 15 13 701.12011675u + + +* feed into detector +* Input +pdet 2 35 24 + +* Inside ring1 +pdet 12 36 23 + +* Through 1 port +*pdet 4 37 25 + +* Through 2 port +pdet 8 38 26 + +* Drop port +pdet 11 39 27 + +* Inside ring2 +pdet 13 40 28 + +*tracefile "traces/double_ring" +*tracenet 20 "SIG_IN" +*tracenet 2 "SIG_IN_1" +*tracenet 4 "SIG_ADD_1" +*tracenet 11 "SIG_DROP_1" +*tracenet 8 "SIG_ADD_2" +*tracenet 15 "SIG_DROP_2" diff --git a/circuits/paul_3ring_puf.cir b/circuits/paul_3ring_puf.cir new file mode 100644 index 0000000..0854975 --- /dev/null +++ b/circuits/paul_3ring_puf.cir @@ -0,0 +1,58 @@ +* Paul 3 ring PUF + +.assign wl0=1.55e-6 +.assign neff=2.44 ng=4.3 att=3 +.assign R=10e-6 dR=10e-9 k=0.22360679774997896 +.assign L_r2r=3e-6 L_access=0e-6 +.assign R1={R} R2=({R}+{dR}) R3={R}+(2*{dR}) +.assign tau=1e-12 +.assign filename="inputstream.csv" +.assign filename="inputstream_25wl.csv" +.assign filename="paul_puf_bitstream_16bit_25wl.csv" +.assign filename="paul_puf_bitstream_158b_3wl.csv" +;.assign filename="paul_puf_bitstream_temp.csv" + +.include circuits/add_drop_sub.cir + +;CWSRC1 in wl={wl0} power=1 +VLSRC1 in values={filename} +;VLSRC_bot in_top values={filename} +;VLSRC_bot in_bot values={filename} +;VLSRC_top in_top values=[[0,0,{wl0}],[{tau},1,],[2*{tau},0,],[3*{tau},1,],[4*{tau},0,]] +;VLSRC_bot in_bot values=[[0,0,{wl0}],[{tau},1,],[2*{tau},0,],[3*{tau},1,],[4*{tau},0,]] + +SPLITTER1 in in_top in_bot +MERGER1 drop_top_1 drop_bot_1 out_drop +MLPROBE1 in [1.55e-6, 1.5599999999999999e-06, 1.57e-6] +;PDETin in _ 1e-15 +PDET1 out_drop _ 1e-15 +PROBE1 out_drop + +WG1 in_top in_top_1 L={L_access} att={att} neff={neff} ng={ng} +WG2 in_bot in_bot_1 L={L_access} att={att} neff={neff} ng={ng} + +WG3 through_bot_1 in_bot_2 L={L_r2r} att={att} neff={neff} ng={ng} +WG4 through_bot_2 in_bot_3 L={L_r2r} att={att} neff={neff} ng={ng} +WG5 through_top_2 in_top_3 L={L_r2r} att={att} neff={neff} ng={ng} +WG6 through_top_1 in_top_2 L={L_r2r} att={att} neff={neff} ng={ng} + +XAD_top_1 in_top_1 drop_top_1 through_top_1 add_top_1 add_drop_filter radius_ring={R1} k1={k} k2={k} neff_wg={neff} ng_wg={ng} att_wg={att} +XAD_top_2 in_top_2 drop_top_2 through_top_2 add_top_2 add_drop_filter radius_ring={R2} k1={k} k2={k} neff_wg={neff} ng_wg={ng} att_wg={att} +XAD_top_3 in_top_3 drop_top_3 through_top_3 nothing add_drop_filter radius_ring={R3} k1={k} k2={k} neff_wg={neff} ng_wg={ng} att_wg={att} + +XAD_bot_1 in_bot_1 drop_bot_1 through_bot_1 add_bot_1 add_drop_filter radius_ring={R1} k1={k} k2={k} neff_wg={neff} ng_wg={ng} att_wg={att} +XAD_bot_2 in_bot_2 drop_bot_2 through_bot_2 add_bot_2 add_drop_filter radius_ring={R2} k1={k} k2={k} neff_wg={neff} ng_wg={ng} att_wg={att} +XAD_bot_3 in_bot_3 drop_bot_3 through_bot_3 nothing add_drop_filter radius_ring={R3} k1={k} k2={k} neff_wg={neff} ng_wg={ng} att_wg={att} + +WG13 drop_bot_3 add_bot_2 L={L_r2r} att={att} neff={neff} ng={ng} +WG14 drop_bot_2 add_bot_1 L={L_r2r} att={att} neff={neff} ng={ng} +WG16 drop_top_3 add_top_2 L={L_r2r} att={att} neff={neff} ng={ng} +WG17 drop_top_2 add_top_1 L={L_r2r} att={att} neff={neff} ng={ng} + +WG18 through_top_3 out_top L={L_access} att={att} neff={neff} ng={ng} +WG15 through_bot_3 out_bot L={L_access} att={att} neff={neff} ng={ng} + +.options abstol=1e-5 reltol=1e-4 traceall=0 timescale=-14 resolution=1 +.tran 8e-9 +;.dc WL(CWSRC1) 1.54e-6 1.56e-6 1e-11 +;.tran 300e-12 diff --git a/circuits/paul_simple_ring.cir b/circuits/paul_simple_ring.cir new file mode 100644 index 0000000..a6e6b2f --- /dev/null +++ b/circuits/paul_simple_ring.cir @@ -0,0 +1,28 @@ +* Show bitstream source + +* Initialize the sources +one 0 +clk 1 100p + +*bsrc 0 1 13 {0, 0, 0} +bsrc 0 1 2 {0, 252, 15, 0, 0, 0} + +* split +dc 2 3 4 5 +dc 12 13 10 11 + +wg 10 3 350.85477427u +wg 5 12 350.85477427u + +* feed into detector +* Input +pdet 2 35 24 + +* Inside ring +pdet 12 36 23 + +* Through 1 port +pdet 4 37 25 + +* Drop port +pdet 11 39 27 diff --git a/circuits/subckt_test.cir b/circuits/subckt_test.cir new file mode 100644 index 0000000..fd3eec0 --- /dev/null +++ b/circuits/subckt_test.cir @@ -0,0 +1,10 @@ +.subckt AAA 1 2 len=3 +WG 1 2 length={len} neff=1 ng=1 att=0 +.ends + +cwsrc in pow=1 wl=1.55e-6 +X1 in out AAA +;probe out type=power + +.op + diff --git a/circuits/subckt_tests.cir b/circuits/subckt_tests.cir new file mode 100644 index 0000000..98f8e7b --- /dev/null +++ b/circuits/subckt_tests.cir @@ -0,0 +1,51 @@ +* An Add-drop filter + +** Circuit parameters +.assign lambda0 = 1.55e-6 +.assign neff = 2.3 +.assign length_2pi = {lambda0}/{neff} +.assign k = 0.85 + +** Include definition of add-drop subcircuit +.include circuits/add_drop_sub.cir + +.subckt test p1 p2 +.assign L=3e-3 + +.subckt test 1 p2 L={L} +wg1 1 p2 length={L} +.ends + +x1 p1 1 test +x2 1 2 test L=0 +wg1 2 p2 L=1e-3 + +.ends + +** Circuit definition +vlsrc1 in values=[[1e-9,1,{lambda0}], [2e-9,2,], [3e-9, -2,], [4e-9, 0,]] + +;cwsrc1 in wl=1.55e-6 power=1 + +x1 in drop out add add_drop_filter radius_ring={length_2pi}*109.5 +x2 out out_ test + +** Simulator options +.options abstol=1e-12 reltol=1e-6 timescale=-15 + +* DC analysis (CW sweep) parameters +.assign lambda_min = {lambda0} - 15e-9 +.assign lambda_max = 2*{lambda0}-{lambda_min} +.assign dlambda = 0.1*1e-9 + +** Analysis +;.dc WL(cwsrc1) {lambda_min} {lambda_max} {dlambda} P(cwsrc1) 0 1 0.01 +;.dc WL(cwsrc1) {lambda_min} {lambda_max} {dlambda} +;.dc P(cwsrc1) 0 1 0.1 +;.dc FREQ(cwsrc1) 192e12 194e12 1e9 +;.dc WL(cwsrc1) +;.op +.tran +;.dc wl(osrc1)=[{lambda_min},{lambda_max},{npoints}] + + diff --git a/circuits/test_include.cir b/circuits/test_include.cir new file mode 100644 index 0000000..d40e7de --- /dev/null +++ b/circuits/test_include.cir @@ -0,0 +1 @@ +include circuits/double_ring.cir diff --git a/circuits/triple_ring.cir b/circuits/triple_ring.cir new file mode 100644 index 0000000..2642f34 --- /dev/null +++ b/circuits/triple_ring.cir @@ -0,0 +1,76 @@ +* Show bitstream source + +* Initialize the sources +one 0 +clk 1 100p + +*bsrc 0 1 2 {0, 0, 0} +bsrc 0 1 2 {0, 252, 15, 0} 1550.0e-9 +*bsrc 0 1 2 {0, 252, 15, 0} 1545.0e-9 + +* split +dc 2 3 4 5 +dc 6 7 8 9 + +dc 12 13 10 11 +dc 16 17 14 15 + +dc 18 19 20 21 +dc 24 25 22 23 + +* ring 1 +wg 10 3 350.85477427u +wg 5 12 350.85477427u + +* ring 2 +* resonance at 1545 +*wg 14 7 351.08113608611u +*wg 9 16 351.08113608611u +* resonance at 1550 +wg 14 7 350.85477427u +wg 9 16 350.85477427u + +* ring 1 to ring 2 +wg 4 6 701.12011675u +wg 15 13 701.12011675u + +* ring 2 to ring 3 +wg 8 18 1701.12011675u +wg 23 17 1701.12011675u + +* ring 3 +wg 22 19 350.85477427u +wg 21 24 350.85477427u + +* feed into detector +* Input +pdet 2 100 200 + +* Inside ring1 +pdet 5 101 201 + +* Inside ring2 +pdet 9 102 202 + +* Inside ring3 +pdet 21 103 203 + +* Through 1 port +*pdet 4 104 204 + +* Through 2 port +pdet 8 105 205 + +* Through 3 port +pdet 20 106 206 + +* Drop port +pdet 11 107 207 + +*tracefile "traces/double_ring" +*tracenet 20 "SIG_IN" +*tracenet 2 "SIG_IN_1" +*tracenet 4 "SIG_ADD_1" +*tracenet 11 "SIG_DROP_1" +*tracenet 8 "SIG_ADD_2" +*tracenet 15 "SIG_DROP_2" diff --git a/config.mk b/config.mk new file mode 100644 index 0000000..c866e63 --- /dev/null +++ b/config.mk @@ -0,0 +1,35 @@ +#### PROJECT SETTINGS #### +# The name of the executable to be created +BIN_NAME = specs +LIB_NAME = libspecs.so + +SYSTEMC_PATH_ROOT = $(abspath ./thirdparty/systemc/sc_install) +SYSTEMC_PATH_LIBS = ${SYSTEMC_PATH_ROOT}/lib +SYSTEMC_PATH_INCLUDE = ${SYSTEMC_PATH_ROOT}/include + +# Compiler used +CXX = g++ +#CXX = clang++ +CCACHE = +#CCACHE = ccache + +# Path to the source directory, relative to the makefile +SRC_PATH = src + +# General compiler flags +CXXFLAGS = -std=c++17 -Wall -Wextra +CXXFLAGS += -O2 -march=native +#CXXFLAGS += -DYYDEBUG=1 +CXXFLAGS += -g + +# Add additional include paths (SRC_PATH and subdirectories are automatically added) +INCLUDES = -I${SYSTEMC_PATH_INCLUDE} -isystem thirdparty/args + +# General linker settings +LDFLAGS += -L${SYSTEMC_PATH_LIBS} -lsystemc -lm +LDFLAGS += -Wl,-rpath -Wl,${SYSTEMC_PATH_LIBS} + +# Destination directory +BUILD_PATH = build +BUILD_TB ?= 1 +#### END PROJECT SETTINGS #### diff --git a/doc/Doxyfile b/doc/Doxyfile new file mode 100644 index 0000000..c135f5e --- /dev/null +++ b/doc/Doxyfile @@ -0,0 +1,2543 @@ +# Doxyfile 1.8.16 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "SPECS" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = doc + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all generated output in the proper direction. +# Possible values are: None, LTR, RTL and Context. +# The default value is: None. + +OUTPUT_TEXT_DIRECTION = None + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = YES + +# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line +# such as +# /*************** +# as being the beginning of a Javadoc-style comment "banner". If set to NO, the +# Javadoc-style will behave just like regular comments and it will not be +# interpreted by doxygen. +# The default value is: NO. + +JAVADOC_BANNER = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines (in the resulting output). You can put ^^ in the value part of an +# alias to insert a newline as if a physical newline was in the original file. +# When you need a literal { or } or , in the value part of an alias you have to +# escape them by means of a backslash (\), this can lead to conflicts with the +# commands \{ and \} for these it is advised to use the version @{ and @} or use +# a double escape (\\{ and \\}) + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, +# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is +# Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 5. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 5 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = YES + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = YES + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual +# methods of a class will be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIV_VIRTUAL = YES + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# (including Cygwin) ands Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = YES + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if <section_label> ... \endif and \cond <section_label> +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. If +# EXTRACT_ALL is set to YES then this flag will automatically be disabled. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = src/ \ + doc/mainpage.md \ + README.md \ + QUICKSTART.md + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: https://www.gnu.org/software/libiconv/) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, +# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice. + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.m \ + *.markdown \ + *.md \ + *.mm \ + *.dox \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf \ + *.ice \ + *.y \ + *.l + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# <filter> <input-file> +# +# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = doc/mainpage.md + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = doc/custom.css + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 198 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 139 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 194 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = YES + +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via Javascript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have Javascript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_MENUS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: https://developer.apple.com/xcode/), introduced with OSX +# 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = YES + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANSPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. +# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/ + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use <access key> + S +# (what the <access key> is depends on the OS and browser, but it is typically +# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down +# key> to jump into the search results window, the results can be navigated +# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel +# the search. The filter options can be selected when the cursor is inside the +# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys> +# to select a filter and <Enter> or <escape> to activate or cancel the filter +# option. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a web server instead of a web client using Javascript. There +# are two flavors of web server based searching depending on the EXTERNAL_SEARCH +# setting. When disabled, doxygen will generate a PHP script for searching and +# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing +# and searching needs to be provided by external tools. See the section +# "External Indexing and Searching" for details. +# The default value is: NO. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SERVER_BASED_SEARCH = NO + +# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain the +# search results. +# +# Doxygen ships with an example indexer (doxyindexer) and search engine +# (doxysearch.cgi) which are based on the open source search engine library +# Xapian (see: https://xapian.org/). +# +# See the section "External Indexing and Searching" for details. +# The default value is: NO. +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will return the search results when EXTERNAL_SEARCH is enabled. +# +# Doxygen ships with an example indexer (doxyindexer) and search engine +# (doxysearch.cgi) which are based on the open source search engine library +# Xapian (see: https://xapian.org/). See the section "External Indexing and +# Searching" for details. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. +# The default file is: searchdata.xml. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of +# to a relative location where the documentation can be found. The format is: +# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTRA_SEARCH_MAPPINGS = + +#--------------------------------------------------------------------------- +# Configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. +# The default value is: YES. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: latex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. +# +# Note that when not enabling USE_PDFLATEX the default is latex when enabling +# USE_PDFLATEX the default is pdflatex and when in the later case latex is +# chosen this is overwritten by pdflatex. For specific output languages the +# default can have been set differently, this depends on the implementation of +# the output language. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_CMD_NAME = + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate +# index for LaTeX. +# Note: This tag is used in the Makefile / make.bat. +# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file +# (.tex). +# The default file is: makeindex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +MAKEINDEX_CMD_NAME = makeindex + +# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to +# generate index for LaTeX. In case there is no backslash (\) as first character +# it will be automatically added in the LaTeX code. +# Note: This tag is used in the generated output file (.tex). +# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat. +# The default value is: makeindex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_MAKEINDEX_CMD = makeindex + +# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX +# documents. This may be useful for small projects and may help to save some +# trees in general. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used by the +# printer. +# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x +# 14 inches) and executive (7.25 x 10.5 inches). +# The default value is: a4. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +PAPER_TYPE = a4 + +# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names +# that should be included in the LaTeX output. The package can be specified just +# by its name or with the correct syntax as to be used with the LaTeX +# \usepackage command. To get the times font for instance you can specify : +# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times} +# To use the option intlimits with the amsmath package you can specify: +# EXTRA_PACKAGES=[intlimits]{amsmath} +# If left blank no extra packages will be included. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the +# generated LaTeX document. The header should contain everything until the first +# chapter. If it is left blank doxygen will generate a standard header. See +# section "Doxygen usage" for information on how to let doxygen write the +# default header to a separate file. +# +# Note: Only use a user-defined header if you know what you are doing! The +# following commands have a special meaning inside the header: $title, +# $datetime, $date, $doxygenversion, $projectname, $projectnumber, +# $projectbrief, $projectlogo. Doxygen will replace $title with the empty +# string, for the replacement values of the other commands the user is referred +# to HTML_HEADER. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the +# generated LaTeX document. The footer should contain everything after the last +# chapter. If it is left blank doxygen will generate a standard footer. See +# LATEX_HEADER for more information on how to generate a default footer and what +# special commands can be used inside the footer. +# +# Note: Only use a user-defined footer if you know what you are doing! +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_FOOTER = + +# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# LaTeX style sheets that are included after the standard style sheets created +# by doxygen. Using this option one can overrule certain style aspects. Doxygen +# will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EXTRA_STYLESHEET = + +# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the LATEX_OUTPUT output +# directory. Note that the files will be copied as-is; there are no commands or +# markers available. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EXTRA_FILES = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is +# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will +# contain links (just like the HTML output) instead of page references. This +# makes the output suitable for online browsing using a PDF viewer. +# The default value is: YES. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate +# the PDF file directly from the LaTeX files. Set this option to YES, to get a +# higher quality PDF documentation. +# The default value is: YES. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode +# command to the generated LaTeX files. This will instruct LaTeX to keep running +# if errors occur, instead of asking the user for help. This option is also used +# when generating formulas in HTML. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_BATCHMODE = NO + +# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the +# index chapters (such as File Index, Compound Index, etc.) in the output. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_HIDE_INDICES = NO + +# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source +# code with syntax highlighting in the LaTeX output. +# +# Note that which sources are shown also depends on other settings such as +# SOURCE_BROWSER. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_SOURCE_CODE = NO + +# The LATEX_BIB_STYLE tag can be used to specify the style to use for the +# bibliography, e.g. plainnat, or ieeetr. See +# https://en.wikipedia.org/wiki/BibTeX and \cite for more info. +# The default value is: plain. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_BIB_STYLE = plain + +# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated +# page will contain the date and time when the page was generated. Setting this +# to NO can help when comparing the output of multiple runs. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_TIMESTAMP = NO + +# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute) +# path from which the emoji images will be read. If a relative path is entered, +# it will be relative to the LATEX_OUTPUT directory. If left blank the +# LATEX_OUTPUT directory will be used. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EMOJI_DIRECTORY = + +#--------------------------------------------------------------------------- +# Configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The +# RTF output is optimized for Word 97 and may not look too pretty with other RTF +# readers/editors. +# The default value is: NO. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: rtf. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF +# documents. This may be useful for small projects and may help to save some +# trees in general. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will +# contain hyperlink fields. The RTF file will contain links (just like the HTML +# output) instead of page references. This makes the output suitable for online +# browsing using Word or some other Word compatible readers that support those +# fields. +# +# Note: WordPad (write) and others do not support links. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# configuration file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. +# +# See also section "Doxygen usage" for information on how to generate the +# default style sheet that doxygen normally uses. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an RTF document. Syntax is +# similar to doxygen's configuration file. A template extensions file can be +# generated using doxygen -e rtf extensionFile. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_EXTENSIONS_FILE = + +# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code +# with syntax highlighting in the RTF output. +# +# Note that which sources are shown also depends on other settings such as +# SOURCE_BROWSER. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for +# classes and files. +# The default value is: NO. + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. A directory man3 will be created inside the directory specified by +# MAN_OUTPUT. +# The default directory is: man. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to the generated +# man pages. In case the manual section does not start with a number, the number +# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is +# optional. +# The default value is: .3. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_EXTENSION = .3 + +# The MAN_SUBDIR tag determines the name of the directory created within +# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by +# MAN_EXTENSION with the initial . removed. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_SUBDIR = + +# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it +# will generate one additional man file for each entity documented in the real +# man page(s). These additional files only source the real man page, but without +# them the man command would be unable to find the correct page. +# The default value is: NO. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that +# captures the structure of the code including all documentation. +# The default value is: NO. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: xml. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_OUTPUT = xml + +# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program +# listings (including syntax highlighting and cross-referencing information) to +# the XML output. Note that enabling this will significantly increase the size +# of the XML output. +# The default value is: YES. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_PROGRAMLISTING = YES + +# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include +# namespace members in file scope as well, matching the HTML output. +# The default value is: NO. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_NS_MEMB_FILE_SCOPE = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the DOCBOOK output +#--------------------------------------------------------------------------- + +# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files +# that can be used to generate PDF. +# The default value is: NO. + +GENERATE_DOCBOOK = NO + +# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in +# front of it. +# The default directory is: docbook. +# This tag requires that the tag GENERATE_DOCBOOK is set to YES. + +DOCBOOK_OUTPUT = docbook + +# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the +# program listings (including syntax highlighting and cross-referencing +# information) to the DOCBOOK output. Note that enabling this will significantly +# increase the size of the DOCBOOK output. +# The default value is: NO. +# This tag requires that the tag GENERATE_DOCBOOK is set to YES. + +DOCBOOK_PROGRAMLISTING = NO + +#--------------------------------------------------------------------------- +# Configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an +# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures +# the structure of the code including all documentation. Note that this feature +# is still experimental and incomplete at the moment. +# The default value is: NO. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module +# file that captures the structure of the code including all documentation. +# +# Note that this feature is still experimental and incomplete at the moment. +# The default value is: NO. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary +# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI +# output from the Perl module output. +# The default value is: NO. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely +# formatted so it can be parsed by a human reader. This is useful if you want to +# understand what is going on. On the other hand, if this tag is set to NO, the +# size of the Perl module output will be much smaller and Perl will parse it +# just the same. +# The default value is: YES. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file are +# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful +# so different doxyrules.make files included by the same Makefile don't +# overwrite each other's variables. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all +# C-preprocessor directives found in the sources and include files. +# The default value is: YES. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names +# in the source code. If set to NO, only conditional compilation will be +# performed. Macro expansion can be done in a controlled way by setting +# EXPAND_ONLY_PREDEF to YES. +# The default value is: NO. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then +# the macro expansion is limited to the macros specified with the PREDEFINED and +# EXPAND_AS_DEFINED tags. +# The default value is: NO. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES, the include files in the +# INCLUDE_PATH will be searched if a #include is found. +# The default value is: YES. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by the +# preprocessor. +# This tag requires that the tag SEARCH_INCLUDES is set to YES. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will be +# used. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that are +# defined before the preprocessor is started (similar to the -D option of e.g. +# gcc). The argument of the tag is a list of macros of the form: name or +# name=definition (no spaces). If the definition and the "=" are omitted, "=1" +# is assumed. To prevent a macro definition from being undefined via #undef or +# recursively expanded use the := operator instead of the = operator. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this +# tag can be used to specify a list of macro names that should be expanded. The +# macro definition that is found in the sources will be used. Use the PREDEFINED +# tag if you want to use a different macro definition that overrules the +# definition found in the source code. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will +# remove all references to function-like macros that are alone on a line, have +# an all uppercase name, and do not end with a semicolon. Such function macros +# are typically used for boiler-plate code, and will confuse the parser if not +# removed. +# The default value is: YES. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES tag can be used to specify one or more tag files. For each tag +# file the location of the external documentation should be added. The format of +# a tag file without this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where loc1 and loc2 can be relative or absolute paths or URLs. See the +# section "Linking to external documentation" for more information about the use +# of tag files. +# Note: Each tag file must have a unique name (where the name does NOT include +# the path). If a tag file is not located in the directory in which doxygen is +# run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create a +# tag file that is based on the input files it reads. See section "Linking to +# external documentation" for more information about the usage of tag files. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES, all external class will be listed in +# the class index. If set to NO, only the inherited external classes will be +# listed. +# The default value is: NO. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will be +# listed. +# The default value is: YES. + +EXTERNAL_GROUPS = YES + +# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in +# the related pages index. If set to NO, only the current project's pages will +# be listed. +# The default value is: YES. + +EXTERNAL_PAGES = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram +# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to +# NO turns the diagrams off. Note that this option also works with HAVE_DOT +# disabled, but it is recommended to install and use dot, since it yields more +# powerful graphs. +# The default value is: YES. + +CLASS_DIAGRAMS = YES + +# You can include diagrams made with dia in doxygen documentation. Doxygen will +# then run dia to produce the diagram and insert it in the documentation. The +# DIA_PATH tag allows you to specify the directory where the dia binary resides. +# If left empty dia is assumed to be found in the default search path. + +DIA_PATH = + +# If set to YES the inheritance and collaboration graphs will hide inheritance +# and usage relations if the target is undocumented or is not a class. +# The default value is: YES. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz (see: +# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent +# Bell Labs. The other options in this section have no effect if this option is +# set to NO +# The default value is: NO. + +HAVE_DOT = YES + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed +# to run in parallel. When set to 0 doxygen will base this on the number of +# processors available in the system. You can set it explicitly to a value +# larger than 0 to get control over the balance between CPU load and processing +# speed. +# Minimum value: 0, maximum value: 32, default value: 0. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_NUM_THREADS = 0 + +# When you want a differently looking font in the dot files that doxygen +# generates you can specify the font name using DOT_FONTNAME. You need to make +# sure dot is able to find the font, which can be done by putting it in a +# standard location or by setting the DOTFONTPATH environment variable or by +# setting DOT_FONTPATH to the directory containing the font. +# The default value is: Helvetica. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTNAME = Helvetica + +# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of +# dot graphs. +# Minimum value: 4, maximum value: 24, default value: 10. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTSIZE = 11 + +# By default doxygen will tell dot to use the default font as specified with +# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set +# the path where dot can find it using this tag. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTPATH = + +# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for +# each documented class showing the direct and indirect inheritance relations. +# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a +# graph for each documented class showing the direct and indirect implementation +# dependencies (inheritance, containment, and class references variables) of the +# class with other documented classes. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for +# groups, showing the direct groups dependencies. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +UML_LOOK = NO + +# If the UML_LOOK tag is enabled, the fields and methods are shown inside the +# class node. If there are many fields or methods and many nodes the graph may +# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the +# number of items for each type to make the size more manageable. Set this to 0 +# for no limit. Note that the threshold may be exceeded by 50% before the limit +# is enforced. So when you set the threshold to 10, up to 15 fields may appear, +# but if the number exceeds 15, the total amount of fields shown is limited to +# 10. +# Minimum value: 0, maximum value: 100, default value: 10. +# This tag requires that the tag HAVE_DOT is set to YES. + +UML_LIMIT_NUM_FIELDS = 10 + +# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and +# collaboration graphs will show the relations between templates and their +# instances. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +TEMPLATE_RELATIONS = NO + +# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to +# YES then doxygen will generate a graph for each documented file showing the +# direct and indirect include dependencies of the file with other documented +# files. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +INCLUDE_GRAPH = YES + +# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are +# set to YES then doxygen will generate a graph for each documented file showing +# the direct and indirect include dependencies of the file with other documented +# files. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH tag is set to YES then doxygen will generate a call +# dependency graph for every global function or class method. +# +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. Disabling a call graph can be +# accomplished by means of the command \hidecallgraph. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller +# dependency graph for every global function or class method. +# +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. Disabling a caller graph can be +# accomplished by means of the command \hidecallergraph. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical +# hierarchy of all classes instead of a textual one. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the +# dependencies a directory has on other directories in a graphical way. The +# dependency relations are determined by the #include relations between the +# files in the directories. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. For an explanation of the image formats see the section +# output formats in the documentation of the dot tool (Graphviz (see: +# http://www.graphviz.org/)). +# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order +# to make the SVG files visible in IE 9+ (other browsers do not have this +# requirement). +# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo, +# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and +# png:gdiplus:gdiplus. +# The default value is: png. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_IMAGE_FORMAT = png + +# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to +# enable generation of interactive SVG images that allow zooming and panning. +# +# Note that this requires a modern browser other than Internet Explorer. Tested +# and working are Firefox, Chrome, Safari, and Opera. +# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make +# the SVG files visible. Older versions of IE do not have SVG support. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +INTERACTIVE_SVG = NO + +# The DOT_PATH tag can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the \dotfile +# command). +# This tag requires that the tag HAVE_DOT is set to YES. + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the \mscfile +# command). + +MSCFILE_DIRS = + +# The DIAFILE_DIRS tag can be used to specify one or more directories that +# contain dia files that are included in the documentation (see the \diafile +# command). + +DIAFILE_DIRS = + +# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the +# path where java can find the plantuml.jar file. If left blank, it is assumed +# PlantUML is not used or called during a preprocessing step. Doxygen will +# generate a warning when it encounters a \startuml command in this case and +# will not generate output for the diagram. + +PLANTUML_JAR_PATH = + +# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a +# configuration file for plantuml. + +PLANTUML_CFG_FILE = + +# When using plantuml, the specified paths are searched for files specified by +# the !include statement in a plantuml block. + +PLANTUML_INCLUDE_PATH = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes +# that will be shown in the graph. If the number of nodes in a graph becomes +# larger than this value, doxygen will truncate the graph, which is visualized +# by representing a node as a red box. Note that doxygen if the number of direct +# children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that +# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. +# Minimum value: 0, maximum value: 10000, default value: 50. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs +# generated by dot. A depth value of 3 means that only nodes reachable from the +# root by following a path via at most 3 edges will be shown. Nodes that lay +# further from the root node will be omitted. Note that setting this option to 1 +# or 2 may greatly reduce the computation time needed for large code bases. Also +# note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. +# Minimum value: 0, maximum value: 1000, default value: 0. +# This tag requires that the tag HAVE_DOT is set to YES. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not seem +# to support this out of the box. +# +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) support +# this, this feature is disabled by default. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page +# explaining the meaning of the various boxes and arrows in the dot generated +# graphs. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot +# files that are used to generate the various graphs. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_CLEANUP = YES diff --git a/doc/custom.css b/doc/custom.css new file mode 100644 index 0000000..4a256a9 --- /dev/null +++ b/doc/custom.css @@ -0,0 +1,13 @@ +tt, code, kbd, samp { + display: inline-block; + direction: ltr; + color: darkblue; +} + +pre.fragment { + color: darkblue; +} + +a { + text-decoration: underline; +} diff --git a/doc/mainpage.md b/doc/mainpage.md new file mode 100644 index 0000000..f980c5c --- /dev/null +++ b/doc/mainpage.md @@ -0,0 +1,14 @@ +# SPECS + +## Introduction + +TODO + +## This documentation + +For now, you can have a look at: + +* [**Readme**](readme.html) to get some general information about the project +* [**Quickstart**](quickstart.html) to get started (building and running the code) + +And refer the auto-generated code documentation. diff --git a/doc/resources/cheatsheet.pdf b/doc/resources/cheatsheet.pdf Binary files differnew file mode 100644 index 0000000..8e2bf3a --- /dev/null +++ b/doc/resources/cheatsheet.pdf diff --git a/doc/resources/delayedwriter.svg b/doc/resources/delayedwriter.svg new file mode 100644 index 0000000..996c26b --- /dev/null +++ b/doc/resources/delayedwriter.svg @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentScriptType="application/ecmascript" contentStyleType="text/css" height="325px" preserveAspectRatio="none" style="width:291px;height:325px;" version="1.1" viewBox="0 0 291 325" width="291px" zoomAndPan="magnify"><defs><filter height="300%" id="fj3cfvzyv2q3n" width="300%" x="-1" y="-1"><feGaussianBlur result="blurOut" stdDeviation="2.0"/><feColorMatrix in="blurOut" result="blurOut2" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .4 0"/><feOffset dx="4.0" dy="4.0" in="blurOut2" result="blurOut3"/><feBlend in="SourceGraphic" in2="blurOut3" mode="normal"/></filter></defs><g><!--class DelayedWriter--><rect fill="#FEFECE" filter="url(#fj3cfvzyv2q3n)" height="306.4844" id="DelayedWriter" style="stroke: #A80036; stroke-width: 1.5;" width="271" x="6" y="8"/><ellipse cx="71.25" cy="24" fill="#ADD1B2" rx="11" ry="11" style="stroke: #A80036; stroke-width: 1.0;"/><path d="M74.2188,29.6406 Q73.6406,29.9375 73,30.0781 Q72.3594,30.2344 71.6563,30.2344 Q69.1563,30.2344 67.8281,28.5938 Q66.5156,26.9375 66.5156,23.8125 Q66.5156,20.6875 67.8281,19.0313 Q69.1563,17.375 71.6563,17.375 Q72.3594,17.375 73,17.5313 Q73.6563,17.6875 74.2188,17.9844 L74.2188,20.7031 Q73.5938,20.125 73,19.8594 Q72.4063,19.5781 71.7813,19.5781 Q70.4375,19.5781 69.75,20.6563 Q69.0625,21.7188 69.0625,23.8125 Q69.0625,25.9063 69.75,26.9844 Q70.4375,28.0469 71.7813,28.0469 Q72.4063,28.0469 73,27.7813 Q73.5938,27.5 74.2188,26.9219 L74.2188,29.6406 Z "/><text fill="#000000" font-family="sans-serif" font-size="12" lengthAdjust="spacingAndGlyphs" textLength="87" x="91.75" y="28.1543">DelayedWriter</text><rect fill="#FFFFFF" height="15.9688" style="stroke: #000000; stroke-width: 1.0; stroke-dasharray: 2.0,2.0;" width="43" x="237" y="5"/><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacingAndGlyphs" textLength="41" x="238" y="17.1387">class T</text><line style="stroke: #A80036; stroke-width: 1.5;" x1="7" x2="276" y1="40" y2="40"/><polygon fill="none" points="17,64.707,13,70.707,21,70.707" style="stroke: #1963A0; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="245" x="26" y="71.0151">port_type = sc_port<sc_signal_out_if<T>></text><polygon fill="none" points="17,77.5117,13,83.5117,21,83.5117" style="stroke: #1963A0; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="194" x="26" y="83.8198">pair_type = std::pair<sc_time, T></text><polygon fill="none" points="17,90.3164,13,96.3164,21,96.3164" style="stroke: #1963A0; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="213" x="26" y="96.6245">queue_type = std::deque<pair_type></text><line style="stroke: #A80036; stroke-width: 1.0; stroke-dasharray: 1.0,2.0;" x1="7" x2="102.5" y1="54.4023" y2="54.4023"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="78" x="102.5" y="57.7104">internal types</text><line style="stroke: #A80036; stroke-width: 1.0; stroke-dasharray: 1.0,2.0;" x1="180.5" x2="276" y1="54.4023" y2="54.4023"/><line style="stroke: #A80036; stroke-width: 1.0;" x1="7" x2="276" y1="103.2188" y2="103.2188"/><polygon fill="none" points="17,110.1211,21,114.1211,17,118.1211,13,114.1211" style="stroke: #B38D22; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="98" x="26" y="117.4292">port : port_type&</text><ellipse cx="17" cy="127.9258" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="64" x="26" y="130.2339">curr_val : T</text><ellipse cx="17" cy="140.7305" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="112" x="26" y="143.0386">queue : queue_type</text><rect fill="none" height="6" style="stroke: #C82930; stroke-width: 1.0;" width="6" x="14" y="150.5352"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="175" x="26" y="155.8433">event_queue : sc_event_queue</text><line style="stroke: #A80036; stroke-width: 1.0; stroke-dasharray: 1.0,2.0;" x1="7" x2="276" y1="162.4375" y2="162.4375"/><ellipse cx="17" cy="174.3398" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="137" x="26" y="176.6479">actAsAccumulator : bool</text><ellipse cx="17" cy="187.1445" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="77" x="26" y="189.4526">acc_val : bool</text><line style="stroke: #A80036; stroke-width: 1.0;" x1="7" x2="276" y1="196.0469" y2="196.0469"/><rect fill="#F24D5C" height="6" style="stroke: #C82930; stroke-width: 1.0;" width="6" x="14" y="204.9492"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="126" x="26" y="210.2573">on_data_ready() : void</text><ellipse cx="17" cy="220.7539" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="174" x="26" y="223.062">delayedWrite(T, sc_time) : void</text><ellipse cx="17" cy="233.5586" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="122" x="26" y="235.8667">writeNow_nb(T) : void</text><ellipse cx="17" cy="246.3633" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="102" x="26" y="248.6714">writeNow(T) : void</text><ellipse cx="17" cy="259.168" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="119" x="26" y="261.4761">getCurrentValue() : T</text><line style="stroke: #A80036; stroke-width: 1.0; stroke-dasharray: 1.0,2.0;" x1="7" x2="276" y1="268.0703" y2="268.0703"/><ellipse cx="17" cy="279.9727" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="144" x="26" y="282.2808">actAsAccumulator() : void</text><ellipse cx="17" cy="292.7773" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="99" x="26" y="295.0854">resetAcc(T) : void</text><ellipse cx="17" cy="305.582" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="95" x="26" y="307.8901">getAccValue() : T</text><!-- +@startuml delayedwriter
+class DelayedWriter <class T> {
+ ..internal types..
+ ~port_type = sc_port<sc_signal_out_if<T>>
+ ~pair_type = std::pair<sc_time, T>
+ ~queue_type = std::deque<pair_type>
+ - -
+ #port : port_type&
+ +curr_val : T
+ +queue : queue_type
+ -event_queue : sc_event_queue
+ ..
+ +actAsAccumulator : bool
+ +acc_val : bool
+ - -
+ -on_data_ready() : void
+ +delayedWrite(T, sc_time) : void
+ +writeNow_nb(T) : void
+ +writeNow(T) : void
+ +getCurrentValue() : T
+ ..
+ +actAsAccumulator() : void
+ +resetAcc(T) : void
+ +getAccValue() : T
+}
+@enduml
+ +PlantUML version 1.2018.01(Sun Jan 28 19:08:22 CET 2018) +(GPL source distribution) +Java Runtime: OpenJDK Runtime Environment +JVM: OpenJDK 64-Bit Server VM +Java Version: 13.0.1+9 +Operating System: Linux +OS Version: 4.19.95-1-lts +Default Encoding: UTF-8 +Language: en +Country: US +--></g></svg>
\ No newline at end of file diff --git a/doc/resources/gdrsoc_poster.pdf b/doc/resources/gdrsoc_poster.pdf Binary files differnew file mode 100644 index 0000000..e71c200 --- /dev/null +++ b/doc/resources/gdrsoc_poster.pdf diff --git a/doc/resources/signals.svg b/doc/resources/signals.svg new file mode 100644 index 0000000..3671d35 --- /dev/null +++ b/doc/resources/signals.svg @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentScriptType="application/ecmascript" contentStyleType="text/css" height="212px" preserveAspectRatio="none" style="width:479px;height:212px;" version="1.1" viewBox="0 0 479 212" width="479px" zoomAndPan="magnify"><defs><filter height="300%" id="f1ah9w5ca8awd5" width="300%" x="-1" y="-1"><feGaussianBlur result="blurOut" stdDeviation="2.0"/><feColorMatrix in="blurOut" result="blurOut2" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .4 0"/><feOffset dx="4.0" dy="4.0" in="blurOut2" result="blurOut3"/><feBlend in="SourceGraphic" in2="blurOut3" mode="normal"/></filter></defs><g><!--cluster Signals--><polygon fill="#FFFFFF" filter="url(#f1ah9w5ca8awd5)" points="22,24,84,24,91,46.2969,457,46.2969,457,200,22,200,22,24" style="stroke: #000000; stroke-width: 1.5;"/><line style="stroke: #000000; stroke-width: 1.5;" x1="22" x2="91" y1="46.2969" y2="46.2969"/><text fill="#000000" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacingAndGlyphs" textLength="56" x="26" y="38.9951">Signals</text><!--class OpticalSignal::Type--><rect fill="#FEFECE" filter="url(#f1ah9w5ca8awd5)" height="99.2188" id="OpticalSignal::Type" style="stroke: #A80036; stroke-width: 1.5;" width="150" x="38" y="72"/><ellipse cx="53" cy="88" fill="#EB937F" rx="11" ry="11" style="stroke: #A80036; stroke-width: 1.0;"/><path d="M57.1094,94 L49.3906,94 L49.3906,81.6094 L57.1094,81.6094 L57.1094,83.7656 L51.8438,83.7656 L51.8438,86.4375 L56.6094,86.4375 L56.6094,88.5938 L51.8438,88.5938 L51.8438,91.8438 L57.1094,91.8438 L57.1094,94 Z "/><text fill="#000000" font-family="sans-serif" font-size="12" lengthAdjust="spacingAndGlyphs" textLength="118" x="67" y="92.1543">OpticalSignal::Type</text><line style="stroke: #A80036; stroke-width: 1.5;" x1="39" x2="187" y1="104" y2="104"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="32" x="44" y="118.2104">NONE</text><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="33" x="44" y="131.0151">WRITE</text><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="36" x="44" y="143.8198">ERASE</text><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="53" x="44" y="156.6245">READOUT</text><line style="stroke: #A80036; stroke-width: 1.5;" x1="39" x2="187" y1="163.2188" y2="163.2188"/><!--class OpticalSignal--><rect fill="#FEFECE" filter="url(#f1ah9w5ca8awd5)" height="124.8281" id="OpticalSignal" style="stroke: #A80036; stroke-width: 1.5;" width="218" x="223" y="59"/><ellipse cx="287.25" cy="75" fill="#ADD1B2" rx="11" ry="11" style="stroke: #A80036; stroke-width: 1.0;"/><path d="M290.2188,80.6406 Q289.6406,80.9375 289,81.0781 Q288.3594,81.2344 287.6563,81.2344 Q285.1563,81.2344 283.8281,79.5938 Q282.5156,77.9375 282.5156,74.8125 Q282.5156,71.6875 283.8281,70.0313 Q285.1563,68.375 287.6563,68.375 Q288.3594,68.375 289,68.5313 Q289.6563,68.6875 290.2188,68.9844 L290.2188,71.7031 Q289.5938,71.125 289,70.8594 Q288.4063,70.5781 287.7813,70.5781 Q286.4375,70.5781 285.75,71.6563 Q285.0625,72.7188 285.0625,74.8125 Q285.0625,76.9063 285.75,77.9844 Q286.4375,79.0469 287.7813,79.0469 Q288.4063,79.0469 289,78.7813 Q289.5938,78.5 290.2188,77.9219 L290.2188,80.6406 Z "/><text fill="#000000" font-family="sans-serif" font-size="12" lengthAdjust="spacingAndGlyphs" textLength="81" x="307.75" y="79.1543">OpticalSignal</text><line style="stroke: #A80036; stroke-width: 1.5;" x1="224" x2="440" y1="91" y2="91"/><ellipse cx="234" cy="102.9023" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="36" x="243" y="105.2104">id : int</text><ellipse cx="234" cy="115.707" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="63" x="243" y="118.0151">type : Type</text><ellipse cx="234" cy="128.5117" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="192" x="243" y="130.8198">parameter : union{double, void*}</text><ellipse cx="234" cy="141.3164" fill="none" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="114" x="243" y="143.6245">wavelength : double</text><line style="stroke: #A80036; stroke-width: 1.0;" x1="224" x2="440" y1="150.2188" y2="150.2188"/><ellipse cx="234" cy="162.1211" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="86" x="243" y="164.4292">getNewId() : int</text><ellipse cx="234" cy="174.9258" fill="#84BE84" rx="3" ry="3" style="stroke: #038048; stroke-width: 1.0;"/><text fill="#000000" font-family="sans-serif" font-size="11" lengthAdjust="spacingAndGlyphs" textLength="135" x="243" y="177.2339">attenuate(double) : void</text><!--link OpticalSignal::Type to OpticalSignal--><path d="M203.39,121.5 C209.86,121.5 216.33,121.5 222.81,121.5 " fill="none" id="OpticalSignal::Type-OpticalSignal" style="stroke: #A80036; stroke-width: 1.0;"/><ellipse cx="196.28" cy="121.5" fill="#FFFFFF" rx="8" ry="8" style="stroke: #A80036; stroke-width: 1.0;"/><line style="stroke: #A80036; stroke-width: 1.0;" x1="204.28" x2="188.28" y1="121.5" y2="121.5"/><line style="stroke: #A80036; stroke-width: 1.0;" x1="196.28" x2="196.28" y1="129.5" y2="113.5"/><!-- +@startuml signals
+package Signals {
+
+ enum OpticalSignal::Type {
+ NONE
+ WRITE
+ ERASE
+ READOUT
+ }
+
+ class OpticalSignal {
+ + id : int
+ + type : Type
+ + parameter : union{double, void*}
+ + wavelength : double
+ - -
+ + getNewId() : int
+ + attenuate(double) : void
+ }
+ OpticalSignal::Type +- OpticalSignal
+}
+@enduml
+ +PlantUML version 1.2018.01(Sun Jan 28 19:08:22 CET 2018) +(GPL source distribution) +Java Runtime: OpenJDK Runtime Environment +JVM: OpenJDK 64-Bit Server VM +Java Version: 13.0.1+9 +Operating System: Linux +OS Version: 4.19.95-1-lts +Default Encoding: UTF-8 +Language: en +Country: US +--></g></svg>
\ No newline at end of file diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..d51e835 --- /dev/null +++ b/install.sh @@ -0,0 +1,46 @@ +#! /bin/sh + +set -e + +# Download required submodules +echo ------------------------------ +echo Dowloading required submodules +echo ------------------------------ +git submodule update --init --recursive + +# Compiling the systemc submodule + +echo ------------------------------ +echo Changing into SystemC folder +echo ------------------------------ +cd ./thirdparty/systemc + +if [ -d "./objdir" ] +then + echo "objdir already exists, not recreating." +else + mkdir objdir +fi + + +cd objdir + +echo ------------------------------ +echo Configuring SystemC +echo ------------------------------ +cmake .. -DCMAKE_CXX_STANDARD=17 -DCMAKE_INSTALL_PREFIX=../sc_install -DCMAKE_INSTALL_DOCDIR=../sc_doc +make -j2 +make install + + + +echo ------------------------------ +echo Compiling SPECS +echo ------------------------------ +cd ../../.. +specs_dir=$(pwd) +make -j2 + +echo ------------------------------ +echo Finished! +echo ------------------------------
\ No newline at end of file diff --git a/pyspecs/__init__.py b/pyspecs/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/pyspecs/__init__.py diff --git a/pyspecs/draw_graph_from_json.py b/pyspecs/draw_graph_from_json.py new file mode 100644 index 0000000..78a3c64 --- /dev/null +++ b/pyspecs/draw_graph_from_json.py @@ -0,0 +1,145 @@ +import sys +import json +import html +import graphviz + +def shorten(s, length=8): + if type(s) == list: + return "[...]" + s = str(s) + if len(s) > length: + return s[:length-3] + else: + return s + +def edge_label(name, net): + bgcolors = { + "default": "white", + "OANALOG": "turquoise", + "EANALOG": "orange", + } + try: + bgcolor = bgcolors[net["type"]] + except: + bgcolor = bgcolors["default"] + + short_name = name + if short_name.startswith('ROOT/'): + short_name = short_name[5:] + + attributes = [f'<table style="rounded" border="0" cellborder="1" cellspacing="10" bgcolor="{bgcolor}" cellpadding="4" align="center">'] + attributes.append(f'<tr><td bgcolor="grey91" port="head"><b>{html.escape(short_name)}</b></td></tr>') + + attributes.append(f'<tr><td bgcolor="{bgcolor}" port="middle" border="0"><table border="0" cellborder="1" cellspacing="0">') + # attributes.append(f'<tr><td bgcolor="{bgcolor}"><table border="0" cellborder="1" cellspacing="0" cellpadding="0">') + attributes.append(f'<tr><td bgcolor="grey91">Type</td><td bgcolor="white">{net["type"]}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Bidirectional</td><td bgcolor="white">{"true" if net["bidirectional"] else "false"}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Size</td><td bgcolor="white">{net["size"]}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Readers</td><td bgcolor="white">{net["readers"]}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Writers</td><td bgcolor="white">{net["writers"]}</td></tr>') + attributes.append(f'</table></td></tr>') + + attributes.append('</table>') + return f'"{name}" [label=<{"".join(attributes)}> shape=none fillcolor="{bgcolor}" margin="0.05"]' + + + +def node_label(element): + attributes = ['<table border="0" cellborder="1" cellspacing="0" cellpadding="4" align="center">'] + + short_name = element["name"] + if short_name.startswith('ROOT/'): + short_name = short_name[5:] + # Header + attributes.append(f'<tr><td bgcolor="grey91"><b>{html.escape(short_name)}</b></td></tr>') + + # Nets + attributes.append(f'<tr><td bgcolor="darkslategray2"><table border="0" cellborder="1" cellspacing="8">') + if 'nets' in element and element['nets']: + nets = ''.join(f'<tr><td bgcolor="white" cellpadding="4" port="{html.escape(str(i))}">{str(i)}</td></tr>' for i,net in enumerate(element['nets'])) + attributes.append(f'{nets}') + else: + attributes.append('<tr><td border="0" cellpadding="0">∅</td></tr>') + attributes.append(f'</table></td></tr>') + + # Args + attributes.append(f'<tr><td bgcolor="palegreen"><table border="0" cellborder="1" cellpadding="2" cellspacing="0">') + if 'args' in element and element['args']: + args = ''.join(f'<tr><td bgcolor="white" cellpadding="4">{html.escape(shorten(v["value"]))}</td></tr>' for v in element['args']) + attributes.append(f'{args}') + else: + attributes.append('<tr><td border="0" cellpadding="0">∅</td></tr>') + attributes.append(f'</table></td></tr>') + + # Kwargs + attributes.append(f'<tr><td bgcolor="wheat"><table border="0" cellborder="1" cellpadding="2" cellspacing="0">') + if 'kwargs' in element and element['kwargs']: + kwargs = ''.join(f'<tr><td bgcolor="grey91">{html.escape(k)}</td><td bgcolor="white">{html.escape(shorten(v["value"]))}</td></tr>' for k, v in element['kwargs'].items()) + attributes.append(f'{kwargs}') + else: + attributes.append('<tr><td border="0" cellpadding="0">∅</td></tr>') + attributes.append(f'</table></td></tr>') + + attributes.append('</table>') + return f'"{element["name"]}" [label=<{"".join(attributes)}> shape=none margin="0"]' + +def edge(element): + if 'nets' in element: + for i,net in enumerate(element['nets']): + # yield f'"{element["name"]}":"{str(i)}" -- "{net}":"head"' + yield f'"{element["name"]}":"{str(i)}" -> "{net}":"middle"[ arrowhead = none ]' + +def generate_graph(description): + result = [] + result.append('digraph G {') + # result.append(' fontname="Helvetica,Arial,sans-serif"') + # result.append(' node [fontname="Helvetica,Arial,sans-serif"]') + # result.append(' edge [fontname="Helvetica,Arial,sans-serif"]') + result.append(' fontname="Cascadia,Courrier,mono"') + result.append(' node [fontname="Cascadia,Courrier,mono"]') + result.append(' edge [fontname="Cascadia,Courrier,mono"]') + result.append(' layout="sfdp"') + result.append(' overlap=false') + result.append(' splines=curved') + + for name, net in description["nets"].items(): + result.append(' ' + edge_label(name, net)) + + for element in description["elements"]: + result.append(' ' + node_label(element)) + result.extend(' ' + e for e in edge(element)) + + result.append('}') + return '\n'.join(result) + +def draw_graph(json_file, out_file): + with open(json_file) as f: + description = json.load(f) + + dot_src = generate_graph(description) + # print(dot_src) + graph = graphviz.Source(dot_src) + graph.render(outfile=out_file) + print(f'Results written to {out_file}') + +def main(): + try: + json_file = sys.argv[1] + except IndexError: + print('First and only argument should be a JSON description of the circuit') + try: + out_file = sys.argv[2] + except IndexError: + out_file = json_file + ".png" + + with open(json_file) as f: + description = json.load(f) + + dot_src = generate_graph(description) + # print(dot_src) + graph = graphviz.Source(dot_src) + graph.render(outfile=out_file) + print(f'Results written to {out_file}') + +if __name__ == '__main__': + main() diff --git a/pyspecs/pyspecs_example.ipynb b/pyspecs/pyspecs_example.ipynb new file mode 100644 index 0000000..1ca337d --- /dev/null +++ b/pyspecs/pyspecs_example.ipynb @@ -0,0 +1,682 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "fdfbe616-3959-44bb-a62e-cccb87a8bee7", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import sys\n", + "path_to_specs = \"../\" # This needs to change if the notebook is used somewhere else\n", + "sys.path.insert(0, os.path.realpath(path_to_specs))\n", + "\n", + "from pyspecs import specs\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Dependencies:\n", + "# pyDigitalWaveTools 1.2 (https://pypi.org/project/pyDigitalWaveTools/)\n", + "# pandas\n", + "# numpy" + ] + }, + { + "cell_type": "markdown", + "id": "2bf6e3a5-ef41-4ae1-bc90-50eb142ef0dd", + "metadata": {}, + "source": [ + "### Calling the simulation\n", + "\n", + "There are two ways of doing it. The first one is the default, with the arguments shown in the function call.\n", + "\n", + "The second way uses custom_arguments as a dictionary of arguments. All arguments there are the same that can be passed to specs, with the same syntax except the - or -- before commands.\n", + "\n", + "You can put the verbose variable as True to see the full SPECS output" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "b5a1dc45-58ae-4892-92ce-3e0a54b57a23", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Executing SPECS from python. . .\n", + "Command: ../specs -f ../circuits/add_drop_pyspecs.cir -o ../traces/delete_me --abstol 1e-08 --reltol 0.0001\n", + "Execution finished with code: 0\n", + "Time in ms: 43.5395\n" + ] + } + ], + "source": [ + "# Simulating in the basic way\n", + "netlist_file = \"../circuits/add_drop_pyspecs.cir\"\n", + "output_file = \"../traces/delete_me\"\n", + "time_ms, std_out = specs.simulate(netlist_file=netlist_file, simulator_directory=path_to_specs, abstol=1e-8, reltol=1e-4, output_file=output_file, verbose=False)\n", + "print(\"Time in ms: \", time_ms)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "2143ab2e-f911-49db-a8dd-f6efb264bae6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Executing SPECS from python. . .\n", + "Command: ../specs -o ../traces/delete_me --abstol 1e-08 --reltol 0.0001 -f ../circuits/add_drop_pyspecs.cir\n", + "Execution finished with code: 0\n", + "Time in ms: 87.333\n" + ] + } + ], + "source": [ + "# Simulating in the custom way. This can be used for more advanced use-cases or for \n", + "# new features that weren't completely implemented in the wrapper yet\n", + "\n", + "test_dict = {\"f\":\"../circuits/add_drop_pyspecs.cir\", \"o\":\"../traces/delete_me\", \"abstol\":1e-8, \"reltol\":1e-4}\n", + "time_ms, std_out = specs.simulate(custom_arguments=test_dict, simulator_directory=path_to_specs, verbose=False)\n", + "print(\"Time in ms: \", time_ms)" + ] + }, + { + "cell_type": "markdown", + "id": "6ea09e11-30b8-474e-9d20-4197201e74d0", + "metadata": {}, + "source": [ + "### Having a non-hierarchical dataframe as output\n", + "\n", + "This data structure has everything in the same table directly. We chose to separate the data in two dataframes:\n", + "- df_probes: contains the probe data (optical power, field, phase, wavelength)\n", + "- df_pdet: contains the photodetector data (electric current and time)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "1987d33f-6b5a-4ce5-8151-19086d691bca", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "--- Contents of simulation ---\n", + "In df_pdet\n", + "In df_probes\n", + "\t time\n", + "\t PROBE{ROOT/N00001}/power\n", + "\t PROBE{ROOT/N00001}/abs\n", + "\t PROBE{ROOT/N00001}/phase\n", + "\t PROBE{ROOT/N00002}/power\n", + "\t PROBE{ROOT/N00002}/abs\n", + "\t PROBE{ROOT/N00002}/phase\n", + "\t PROBE{ROOT/N00003}/power\n", + "\t PROBE{ROOT/N00003}/abs\n", + "\t PROBE{ROOT/N00003}/phase\n", + "\t PROBE{ROOT/N00004}/power\n", + "\t PROBE{ROOT/N00004}/abs\n", + "\t PROBE{ROOT/N00004}/phase\n", + "\t PROBE{ROOT/add}/power\n", + "\t PROBE{ROOT/add}/abs\n", + "\t PROBE{ROOT/add}/phase\n", + "\t PROBE{ROOT/drop}/power\n", + "\t PROBE{ROOT/drop}/abs\n", + "\t PROBE{ROOT/drop}/phase\n", + "\t PROBE{ROOT/in}/power\n", + "\t PROBE{ROOT/in}/abs\n", + "\t PROBE{ROOT/in}/phase\n", + "\t PROBE{ROOT/out}/power\n", + "\t PROBE{ROOT/out}/abs\n", + "\t PROBE{ROOT/out}/phase\n", + "\t ROOT/PROBE1/power\n", + "\t ROOT/PROBE1/abs\n", + "\t ROOT/PROBE1/phase\n", + "\t ROOT/PROBE2/power\n", + "\t ROOT/PROBE2/abs\n", + "\t ROOT/PROBE2/phase\n", + "\t ROOT/PROBE3/power\n", + "\t ROOT/PROBE3/abs\n", + "\t ROOT/PROBE3/phase\n", + "Type of simulation: TD\n", + "------------------------------\n" + ] + } + ], + "source": [ + "(df_probes,df_pdet) = specs.parse_vcd_dataframe(output_file + '.vcd')" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "0e91dc0f-8e8c-4e25-921b-fe1e7a46f687", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAEFCAYAAADzHRw3AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAAe3ElEQVR4nO3deXRc9X338fd3Fkm2JcvYlhe8CYONMTuYLYStEOKQ1D5JmwLNvpHkCXnSZjmlaUIJPUmbtk/Ok4UmdRJCSMLeNo8DJmSBxGG3HMBgjIlsjC3jRd5tydq/zx93ZGQhocG+4zv3p8/rHB3P3PnNzPfqjj6+c+/v/n7m7oiISPplki5ARETioUAXEQmEAl1EJBAKdBGRQCjQRUQCkUvqjcePH+/19fVJvb2ISCotX758m7vXDfRYYoFeX19PQ0NDUm8vIpJKZvbyYI/pkIuISCCGDHQzu9nMtprZc4M8bmb2LTNrNLMVZnZG/GWKiMhQitlDvwWY/zqPvw2YVfi5Bvju4ZclIiJv1JCB7u5LgR2v02QhcKtHHgfGmNnkuAoUEZHixHEMfQqwoc/9psKy1zCza8yswcwampubY3hrERHpdURPirr7Inef5+7z6uoG7HUjIiKHKI5A3whM63N/amGZiIgcQXEE+mLg/YXeLucCu919UwyvG7wVTbv4/tK1dHX3JF2KBGhPWye3P7me7fvaky5FjpAhLywys9uBi4HxZtYE/COQB3D37wFLgCuARqAV+FCpig3Ntbc9xfodrZw7cxwnT61NuhwJzL3PbOKL//Ms63e08nfz5yRdjhwBQwa6u189xOMOfCq2ioaRjbv2A9CtSUakBDoL3/xa2rsSrkSOFF0pKiISCAW6iEggFOgiIoFQoIuIBEKBLiISCAW6iEggFOhl4JHGbUmXIAG7d4Wu8xsuFOgJmjOpBoCXtrUkXImEyCz6d0dLR7KFyBGjQE/Q5NoqACzhOiRMvZ+rbEafsOFCgS4iEggFuohIIBToIiKBUKCLiARCgS4iEggFehlYvWVv0iVIwLp7HNcQzcOCAr0MrGjarVmLpKQeX7sj6RLkCFCgl4ke7UBJCe3TJBfDggJdRCQQCnQRkUAo0EVEAqFAFxEJhAJdRCQQCvQy0alui1JCrR3q5TIcKNDLxOJnXkm6BAnYrY+9nHQJcgQo0BM2aXQ0JnpbZ3fClUjIaqpySZcgR4ACPWGafEBKbcqYEUmXIEeIAl1EJBAKdBGRQCjQRUQCoUAXEQmEAr1M/GbVlqRLkID9bnWzxkQfBooKdDObb2arzazRzK4b4PHpZvaQmT1lZivM7Ir4Sw1TdWXUnWzTrraEK5FQtXdFXWI379FnLHRDBrqZZYGbgLcBc4GrzWxuv2ZfAu5y99OBq4D/iLvQUOWyxttPnkxG3RelRD785mMAjbk/HBSzh3420Ojua929A7gDWNivjQOjC7drAV32KCJyhBUT6FOADX3uNxWW9XUD8F4zawKWAJ8e6IXM7BozazCzhubm5kMoV0REBhPXSdGrgVvcfSpwBfATM3vNa7v7Inef5+7z6urqYnprERGB4gJ9IzCtz/2phWV9fQS4C8DdHwOqgPFxFCgiIsUpJtCXAbPM7BgzqyA66bm4X5v1wKUAZnYCUaDrmMob0Lh1n7qVSUl1aYjm4A0Z6O7eBVwLPACsIurNstLMbjSzBYVmnwM+ZmbPALcDH3SlU9FaCmNVr3xlT8KVSIhG5rMA3LlswxAtJe2KGlPT3ZcQnezsu+z6PrefB86Pt7Th4z3nzOB3q5tpadckBBK/+SdN5oZfPJ90GXIE6ErRMjCqIpt0CRKwXNbIZ3Wdw3CgQBcRCYQCXUQkEAp0EZFAKNDLyJ42nRSV0ujsdpr3tiddhpSYAr0MVBcm8L2rQd3KpHTuXt6UdAlSYgr0MnDylFqyGWNEXr1dpDQumDVevamGAQV6GTAzpo8dmXQZErBj66rJZfXnHjptYRGRQCjQRUQCoUAXEQmEAr1M9Lhz37Obki5DArZ7fyd72jqTLkNKSIFeJto6u+nucfZpgC4pgd7JyB/+07aEK5FSUqCXiY9dMBNAY6JLSSw87Wgg+iYo4VKgi4gEQoEuIhIIBbqISCAU6GWmR4c4pYS6uvUBC5kCvUzkMtGMMj9/amPClUiIKnLRn/qipWsTrkRKSYFeJhacNgWA/Z3dCVciIZo+diQZg9oR+aRLkRJSoJcJjbQopWRmzJsxNukypMQU6CIigVCgi4gEIpd0AXKwbnVzkRJxXL2oAqc99DJhUScXbnqoMdlCJFid3c4TL+1gd6sG6AqVAr1MVOWzTBxdydhRFUmXIoE6bdoYALa3aLLoUCnQy8ibjh1PpndXXSRmp08fk3QJUmIKdBGRQCjQRUQCoUAvM+t3tGpMdCkp9aQKlwK9jOzviC77f3rDrmQLkSBV5qKrkW97cn3ClUipFBXoZjbfzFabWaOZXTdIm78ys+fNbKWZ3RZvmcPDlWdNA9A0dFISl54wAUAn3gM25IVFZpYFbgLeAjQBy8xssbs/36fNLODvgfPdfaeZTShVwSGrqdJ1XlI6+WzmwNyiEqZi9tDPBhrdfa27dwB3AAv7tfkYcJO77wRw963xlikiIkMpJtCnABv63G8qLOtrNjDbzB4xs8fNbH5cBYqISHHiOimaA2YBFwNXA983szH9G5nZNWbWYGYNzc3NMb11eB5u3JZ0CRKozu4e7luxKekypESKCfSNwLQ+96cWlvXVBCx29053fwl4kSjgD+Lui9x9nrvPq6urO9SagzVj3CgA1m1rSbgSCVV7Vw9b9rYlXYaUSDGBvgyYZWbHmFkFcBWwuF+bnxPtnWNm44kOwWiuqzeorqaS4yfWYKgXgpTGxy+cSWVOvZVDNeSWdfcu4FrgAWAVcJe7rzSzG81sQaHZA8B2M3seeAj4grtvL1XRIiLyWkX1YXL3JcCSfsuu73Pbgc8WfkREJAH67lVmHGflpt1JlyEBa+vsoau7J+kypAQU6GVmR0snG3bsZ0+bJiGQ+PUUxgn6zaotCVcipaBALzMfOr8egM4u7UFJ/K48azoALe3dCVcipaBALzO6/F9KqSKrP/mQaeuKiARCgV6mujRmtZRQa4dG9AyRAr3MVOWjMavvWd6UcCUSoqp89Cf/o0fWJVuIlIQCvcwsOPVoQLPKSGlMGF3F2FEV1I7MJ12KlIACvczkddJKSuzEo0drcIlAKT1ERAKhQC9TqzbtSboECdjKV/T5CpECvcz0fhV++E8aE11KY/f+Ttq7enhJwzQHR4FeZjIZ44qTJ1FZ6O0iErfeq5HbOnW1aGgU6GVodFUenRuVUhmhnYVgKTZERAKhQC9TW/a0s1VThUkJNby8M+kSJGYK9DI0uXYEACs2aFx0id+cSaMBeEE9qYKjQC9DfzZnQtIlSMDqx49i3KgKTFcXBUeBLiISCAV6GdvZ2pF0CRKorh7nlV06RxMaBXoZGlUZdSu7q2FDwpVIqPa1d/HgC1uTLkNipkAvQzPrqqkdkae6UrMXSWn8+SmTky5BSkCBXqZmjBuZdAkSsOljR+qkaIAU6GXKHTQkuoi8EQr0MtXZ3cPvX2ympV1ThUn8ejzaaXh0jQaBC4kCvUydMrUWiEbGE4nbJXPqAFi3rTXhSiROCvQydeaMo5IuQQI29SidowmRAl1EJBAK9DJlhS4ID6zcnHAlEqLeDi4/euSlROuQeCnQy9SlhfFctu1rT7gSCVFdTSWgSclDo61ZpsZVV5LLqKOwlIaZcdkJE9QXPTAK9DLW1eN0dqszupROZ3dP0iVIjIoKdDObb2arzazRzK57nXZ/YWZuZvPiK3F4W7R0bdIlSKDau3p4ccs+Nu7an3QpEpMhA93MssBNwNuAucDVZjZ3gHY1wGeAJ+Iucrg6YfJoajSei5TIm48bD0DzXp2nCUUxe+hnA43uvtbdO4A7gIUDtPsn4OuAxuSMydn1R5HN6iCnlMbsiTVJlyAxKybQpwB9x3FtKiw7wMzOAKa5+32v90Jmdo2ZNZhZQ3Nz8xsudjja1dpJe1d30mVIwLZpDz0Yh31S1MwywDeAzw3V1t0Xufs8d59XV1d3uG8dvN7ToUtf1HgbEr8xI/MALH7mlYQrkbgUE+gbgWl97k8tLOtVA5wE/M7M1gHnAot1YvTwveecGQB0dKkngsTv9OlHUZnLUJlTZ7dQFLMllwGzzOwYM6sArgIW9z7o7rvdfby717t7PfA4sMDdG0pS8TCiPsJSauNGVSRdgsRoyEB39y7gWuABYBVwl7uvNLMbzWxBqQsUuGe5pqKT0uh25+7lTbjreocQFNUnzt2XAEv6Lbt+kLYXH35ZAlA/bhQQ9RcWKYWaqjxb9rTT2e1U5PSVMO108KyMVeQynFWvYXSldN55+pShG0lqKNDLXDSrzHZ9JZaS2tOmiVRCoEAvc/sKU9A17dTl2RK/0SOirov3P7sp4UokDgr0Mvfxi2YC0UBdInF7x8mTAejW5ysICvQyZ4WpCNQXXUpp935NRh4CBXqZG1GRBeCOZesTrkRClC9cVHTrY+uSLURioaH8ylzvzEVZXWUkJVBdmWPm+FFkNJlKELSHXuZy2QwVucyBk6MicZszuYZ9bfp8hUCBngIdXT3csUxXi0pptHX2sHlPG41b9yVdihwmBXoKnDdznOYXlZJ564kTAdjR0pFwJXK4FOgpcPLUWrp6XBcXSUlMPWokAF2aXzT1FOgp0NtH+LertiZciYSoKh/FwC2Prku2EDlsCvQU6B1vQ5dnSymcNi0aL6i3i6yklwI9BWqqot6la5tbEq5EQpTNGNPHjmRF0+6kS5HDpEBPgZqqaLyN376gQy5SGjtaOnhpWwttnZq/Ns0U6CkwdlQFJ0+pZURem0tK46MXHANozKC0U0KkRO2IPH9cv4v2Lu1BSfxGVUSH9daoL3qqKdBToveE1UvbdBxd4nf8pBoAHlu7PeFK5HAo0FPiXYWeLuqKLqUwrzAzlobRTTcFekrks9Gmuu0Jjboo8csUBn/7zoONCVcih0OjLabEBbPHJ12CBKwqn2VybRVZDTGRatpDT4nKXJbRVTn+56mNSZcigTp35jiadu5nry5gSy0Feop097iG0ZWSGV24gO3pDbuSLUQOmQI9RT785qivsKajk1L481OPBmBXq/bQ00qBniJWOHF1/3OaoV3iV13YQ7+rQWPvp5UCPUX+at5UAB12kZI4fmINI/JZqvIapCutFOgpUpmL/tC+9/s1CVciITIzJtVW8evnt2hMl5RSoKdIXU0lFdkMowuDdYnE7eQptQC06FtgKinQU+b848ax8pU9bNvXnnQpEqDeK0YfbtyWcCVyKBToKTNrYjTmxsad+xOuREJ08ewJALy8vTXhSuRQKNBT5tyZYwH45crNCVciIZpy1AgAfqzp6FKpqEA3s/lmttrMGs3sugEe/6yZPW9mK8zst2Y2I/5SBeCM6dFX4h37NEO7xC+bMXIZO9BFVtJlyEA3syxwE/A2YC5wtZnN7dfsKWCeu58C3AP8a9yFSmTMyArGV1dwZ8MGXEMvSgm864wpbNvXrqGaU6iYPfSzgUZ3X+vuHcAdwMK+Ddz9IXfvPej2ODA13jKlrwk1VYCGOpXSOKnQ00WTXaRPMYE+Beh76VhTYdlgPgLcP9ADZnaNmTWYWUNzc3PxVcpB5p80CYCHVut3KPE7c0Z0WO8WHUdPnVhPiprZe4F5wL8N9Li7L3L3ee4+r66uLs63HlYuP3EiAM827Uq2EAnSnEmjAdiypy3hSuSNKibQNwLT+tyfWlh2EDO7DPgHYIG7q5N0CU09aiQAty/TmBsSv2zGqB83kj9t3ceuVp18T5NiAn0ZMMvMjjGzCuAqYHHfBmZ2OvCfRGG+Nf4ypa/qyhzHT6yheW+7Jo2Wknjn6dFpsBe36Dh6mgwZ6O7eBVwLPACsAu5y95VmdqOZLSg0+zegGrjbzJ42s8WDvJzE5LiJ1QA8t3F3wpVIiM4pXO/w4AvaP0uToo6hu/sSd5/t7se6+1cLy65398WF25e5+0R3P63ws+D1X1EO11+fPR1AMxhJSZw7cxwANz/yUsKVyBuhK0VT6tRpYwB4bM32ZAuRYI0Zmaejq4fObk2okhYK9JSqrswxqiLLmuYWDXUqJfH2kycDsPRFdY9NCwV6in2kMCXd42u1ly7xe8850QgeP3tifcKVSLEU6Cl22dyoP/rdDU0JVyIhOm5CdOL9d6t1YjQtFOgpdsLk6AKQR9do7GqJX0Uuw+yJ1fQ4NO3UcLppoEBPsXw2w6VzJrCztZMXt+xNuhwJ0KcuOQ6AO3URWyoo0FOud1yXnz7+csKVSIguPSE6rHfzw+q+mAYK9JS7fG4U6LfpxJWUQHVljurKHC0d3eze35l0OTIEBXrK1Y7MM7m2iq4e55VdmpZO4veJi2YC8LMn9C2w3CnQA/CFtx4PwA/1tVhK4OrCVcnfX7o24UpkKAr0ACw8LRqeXoEupTCuupIpY0aws7VT3wLLnAI9ANmMMbfQhfGp9TsTrkZC9ImLjwXg2w82JlyJvB4FeiC+MD867HLDL55PuBIJ0bvPjIbTvf1JnXwvZwr0QFw0K5oB6pkNu9jbpt4IEq+qfJaz6qOp6R5YuTnhamQwCvRAZDLGRwtju3xtyaqEq5EQffWdJwPw8Z8sT7gSGYwCPSCfL/R2uf3JDXR0achTidfsiTXkswbAExoQriwp0ANSlc9ywazxAPyfX61OuBoJ0aL3zQPgw7csS7gSGYgCPTDfvOp0AP5z6VrNNyqxu2TOBABaOro1/WEZUqAHZuyoCi4rjL9x3X89m3A1EqIff/hsAN7x7Ydx94Srkb4U6AH6xpWnAtF8o9v2tSdcjYTmotl1B27/VGMIlRUFeoBGV+X5+IXR+Bvn/8uDCVcjIfrV314IwJd//hwt7V0JVyO9FOiB+rv5cwBo7+rhR5q5XWI2e2INlxwf7am/7Zt/SLga6aVAD1QmYzzwN9Fe1Fd+8TybdmsMDonXDz5wFgDrd7Rq4K4yoUAP2PGTavjAedFEv+f984Pqmy6xymaM//ep8wH46pJVrHxFvV6SpkAP3FcWnsToqhwAs790Pz096pUg8Tl12pgDwze//VsPs3l3W8IVDW8K9GFg2ZcuO3B7zpd/qVCXWH3qkuMOXNB27j//lua96lmVFAX6MFCZy7LyK28FoKO7h5lfXEJbpy46kvjc+uGzmT2xGoCzvvobXti8J+GKhicF+jAxqjLHqhvnH7g/58u/1B+dxMbM+NXfXsS8GdGIjPP/7x9YtHRNwlUNPwr0YWRERZY1X7uCMSPzQPRH98mfLtchGInNPZ9804FrIL625AXqr7uPfeqnfsQo0IeZbMZ4+vrLD5zIuv+5zcz84hL1VZfY/P0VJ3Dvp9984P5J//gA77/5Sbq61cuq1BTow9SnLjmOZ2+4nJEVWSDqq15/3X189s6ndXxdDttJU2pZ+7UreMcpkwFY+mIzx/3D/fzZv/+ODTtaE64uXAr0YaymKs/zN87nwc9dRDYTjXP9309tZM6Xf0n9dfdxw+KV7N6v2Y/k0GQyxnf++gxe+Kf5B2Y7WruthQv+9SHqr7uP9/zgcRq37ku4yrDkimlkZvOBbwJZ4Afu/i/9Hq8EbgXOBLYDV7r7unhLlVKZWVfNmq9dQUt7F5+/+xnufy6aYuyWR9dxy6PrqMpnOHlKLSceXcubjh3HqdPGMKGmEjNLuHJJg6p8lrs/8SbcnR/84SW+WphR65HG7Vz2jd8DMGdSDWfOOIq5R4/m3JnjmDF2JLms9jffqCED3cyywE3AW4AmYJmZLXb3vrMRfwTY6e7HmdlVwNeBK0tRsJTOqMoc333vmQDsbevk509t5NE122l4eSfL1kU/tzy67kD78dUVjK+uZMzIPHU1VcyaUI071I8fCcDE0VVU5bNUZDPUVOWoyGWoyGaoyGXIZY1cJnPgm4GEz8z42IUz+diFM+npcX7/YjO/eOYVlq/fyQub9/LC5r0Hta/IZhhXXcHE0VWcMLmGfDbD6Ko8M+tG4Q6Txwz8+arMZ8lljFzGyGZsWO14FLOHfjbQ6O5rAczsDmAh0DfQFwI3FG7fA3zHzMxLMFjyXcs28P0/hDFuxCu79lM/flTSZQyopirP+86r533n1QPQ0+Osad7HsnU72birlU272nhpewsbdrSyfkcrrR07Dul9zCBX+KPr6OqhprLPR9IGvHnQH6gV02aA9xzoWYO/Vt/lA7d/vfcf7L2Led3X1j7Ieg3wnN37y7d3SSZjXDJnwoEJM9yd5r3tBz5fqzbt5eXtLWzZ086Olg5uf3LDIb9X9PmCzm5nVEWWTObV37ZZ9Jjx6u82uh3d6v119y6z1ywrPKd3WZ82B71H4Qm9yz5z2WwWnHr0Ia/ToOtaRJspQN/fZhNwzmBt3L3LzHYD44BtfRuZ2TXANQDTp08/pILHjMwzq3ABQ9rNmljNJcdPSLqMomQyxqyJNcyaWDNom7bObna1drKjpYP9nd20d3azeU8buWyGjq4e2jq72by7jZqqHF09Tle3093TQ2ePs3HnfsZVVxwINufVfYHBdgv67i/4Qcv73B7kdQZrz2DtD+M1+7Yf5GbhOcWsz9Dt+96ZOLqKcaMqKHdmxoTRVby9cBJ1IF3dPexs7WRfexc7Wtrp7I7+E/DCY+1dPbyya/9Bn6/o3x627+sglzUqcpl+2zXaOr3LHMedg5bRu8xf3ZZ92xzYvgeWvbrFfYBlOIwZkT/s39lAijqGHhd3XwQsApg3b94h7b1ffuIkLj9xUqx1STyq8lkm1WaZVFuVdCkSoFw2Q11NJXU1lRxTpt9sk1bMWYeNwLQ+96cWlg3YxsxyQC3RyVERETlCign0ZcAsMzvGzCqAq4DF/dosBj5QuP2XwIOlOH4uIiKDG/KQS+GY+LXAA0TdFm9295VmdiPQ4O6LgR8CPzGzRmAHUeiLiMgRVNQxdHdfAizpt+z6PrfbgHfHW5qIiLwR6rkvIhIIBbqISCAU6CIigVCgi4gEwpLqXWhmzcDLh/j08fS7CjXFtC7lKZR1CWU9QOvSa4a71w30QGKBfjjMrMHd5yVdRxy0LuUplHUJZT1A61IMHXIREQmEAl1EJBBpDfRFSRcQI61LeQplXUJZD9C6DCmVx9BFROS10rqHLiIi/SjQRUQCUdaBbmbzzWy1mTWa2XUDPF5pZncWHn/CzOoTKLMoRazLB82s2cyeLvx8NIk6h2JmN5vZVjN7bpDHzcy+VVjPFWZ2xpGusVhFrMvFZra7zza5fqB2STOzaWb2kJk9b2YrzewzA7RJxXYpcl3Ssl2qzOxJM3umsC5fGaBNvBnm7mX5QzRU7xpgJlABPAPM7dfmfwHfK9y+Crgz6boPY10+CHwn6VqLWJcLgTOA5wZ5/ArgfqLpE88Fnki65sNYl4uBe5Ous4j1mAycUbhdA7w4wOcrFdulyHVJy3YxoLpwOw88AZzbr02sGVbOe+gHJqd29w6gd3LqvhYCPy7cvge41Mpziu9i1iUV3H0p0Zj3g1kI3OqRx4ExZjb4RJEJKmJdUsHdN7n7Hwu39wKriOb57SsV26XIdUmFwu96X+FuvvDTvxdKrBlWzoE+0OTU/TfsQZNTA72TU5ebYtYF4C8KX4fvMbNpAzyeBsWua1qcV/jKfL+ZnZh0MUMpfGU/nWhvsK/UbZfXWRdIyXYxs6yZPQ1sBX7t7oNulzgyrJwDfbj5BVDv7qcAv+bV/7UlOX8kGjfjVODbwM+TLef1mVk18F/A37j7nqTrORxDrEtqtou7d7v7aURzMZ9tZieV8v3KOdBDmpx6yHVx9+3u3l64+wPgzCNUW9yK2W6p4O57er8yezRrV97Mxidc1oDMLE8UgD9z9/8eoElqtstQ65Km7dLL3XcBDwHz+z0Ua4aVc6CHNDn1kOvS73jmAqJjh2m0GHh/oVfFucBud9+UdFGHwswm9R7PNLOzif5eym6HoVDjD4FV7v6NQZqlYrsUsy4p2i51ZjamcHsE8BbghX7NYs2wouYUTYIHNDl1kevyv81sAdBFtC4fTKzg12FmtxP1MhhvZk3APxKd7MHdv0c09+wVQCPQCnwomUqHVsS6/CXwSTPrAvYDV5XpDsP5wPuAZwvHawG+CEyH1G2XYtYlLdtlMvBjM8sS/adzl7vfW8oM06X/IiKBKOdDLiIi8gYo0EVEAqFAFxEJhAJdRCQQCnQRkRgMNdjbIbze183sucLPlcU8R4EuIhKPW3jthUOHxMzeTjRw3GnAOcDnzWz0UM9ToIuIxGCgwd7M7Fgz+6WZLTezP5jZnCJfbi6w1N273L0FWEER/1ko0EVESmcR8Gl3PxP4PPAfRT7vGWC+mY0sDGtwCQcP3TCgsr1SVEQkzQoDjL0JuLvPiLiVhcfeBdw4wNM2uvtb3f1XZnYW8CjQDDwGdA/5nrpSVEQkHoUhf+9195MKx7xXu/thjztvZrcBPy0MRjYoHXIRESmBwrC/L5nZu+HANICnFvPcwjjq4wq3TwFOAX415PO0hy4icvj6DvYGbCEa7O1B4LtEA3XlgTvcfaBDLf1fq4po3HeAPcAn3P3pIZ+nQBcRCYMOuYiIBEKBLiISCAW6iEggFOgiIoFQoIuIBEKBLiISCAW6iEgg/j/PCGS71tAX9AAAAABJRU5ErkJggg==\n", + "text/plain": [ + "<Figure size 432x288 with 1 Axes>" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "y = df_probes['PROBE{ROOT/out}/power']\n", + "if specs.verify_wl_sweep(df_probes):\n", + " x = df_probes['wavelength']\n", + "else:\n", + " x = df_probes['time']\n", + "\n", + "if not specs.verify_wl_sweep(df_probes):\n", + " plt.step(x,y,where='post')\n", + "else:\n", + " plt.plot(x,y)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "1cc73fee", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "<div>\n", + "<style scoped>\n", + " .dataframe tbody tr th:only-of-type {\n", + " vertical-align: middle;\n", + " }\n", + "\n", + " .dataframe tbody tr th {\n", + " vertical-align: top;\n", + " }\n", + "\n", + " .dataframe thead th {\n", + " text-align: right;\n", + " }\n", + "</style>\n", + "<table border=\"1\" class=\"dataframe\">\n", + " <thead>\n", + " <tr style=\"text-align: right;\">\n", + " <th></th>\n", + " <th>time</th>\n", + " <th>PROBE{ROOT/N00001}/power</th>\n", + " <th>PROBE{ROOT/N00001}/abs</th>\n", + " <th>PROBE{ROOT/N00001}/phase</th>\n", + " <th>PROBE{ROOT/N00002}/power</th>\n", + " <th>PROBE{ROOT/N00002}/abs</th>\n", + " <th>PROBE{ROOT/N00002}/phase</th>\n", + " <th>PROBE{ROOT/N00003}/power</th>\n", + " <th>PROBE{ROOT/N00003}/abs</th>\n", + " <th>PROBE{ROOT/N00003}/phase</th>\n", + " <th>...</th>\n", + " <th>PROBE{ROOT/out}/phase</th>\n", + " <th>ROOT/PROBE1/power</th>\n", + " <th>ROOT/PROBE1/abs</th>\n", + " <th>ROOT/PROBE1/phase</th>\n", + " <th>ROOT/PROBE2/power</th>\n", + " <th>ROOT/PROBE2/abs</th>\n", + " <th>ROOT/PROBE2/phase</th>\n", + " <th>ROOT/PROBE3/power</th>\n", + " <th>ROOT/PROBE3/abs</th>\n", + " <th>ROOT/PROBE3/phase</th>\n", + " </tr>\n", + " </thead>\n", + " <tbody>\n", + " <tr>\n", + " <th>0</th>\n", + " <td>0.000000e+00</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>...</td>\n", + " <td>0.000000e+00</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000e+00</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1</th>\n", + " <td>5.000000e-10</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.022500</td>\n", + " <td>0.150000</td>\n", + " <td>1.570796</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>...</td>\n", + " <td>0.000000e+00</td>\n", + " <td>0.977500</td>\n", + " <td>0.988686</td>\n", + " <td>0.000000e+00</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>1.0</td>\n", + " <td>1.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>2</th>\n", + " <td>5.020000e-10</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.000000</td>\n", + " <td>0.022500</td>\n", + " <td>0.150000</td>\n", + " <td>1.570796</td>\n", + " <td>0.022500</td>\n", + " <td>0.150000</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>0.000000e+00</td>\n", + " <td>0.977500</td>\n", + " <td>0.988686</td>\n", + " <td>0.000000e+00</td>\n", + " <td>0.000506</td>\n", + " <td>0.022500</td>\n", + " <td>-3.141593</td>\n", + " <td>1.0</td>\n", + " <td>1.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>3</th>\n", + " <td>5.040000e-10</td>\n", + " <td>0.021994</td>\n", + " <td>0.148303</td>\n", + " <td>1.570796</td>\n", + " <td>0.087986</td>\n", + " <td>0.296625</td>\n", + " <td>1.570796</td>\n", + " <td>0.022500</td>\n", + " <td>0.150000</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-6.316716e-15</td>\n", + " <td>0.934007</td>\n", + " <td>0.966441</td>\n", + " <td>-6.316716e-15</td>\n", + " <td>0.000506</td>\n", + " <td>0.022500</td>\n", + " <td>-3.141593</td>\n", + " <td>1.0</td>\n", + " <td>1.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>4</th>\n", + " <td>5.060000e-10</td>\n", + " <td>0.021994</td>\n", + " <td>0.148303</td>\n", + " <td>1.570796</td>\n", + " <td>0.087986</td>\n", + " <td>0.296625</td>\n", + " <td>1.570796</td>\n", + " <td>0.087986</td>\n", + " <td>0.296625</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-6.316716e-15</td>\n", + " <td>0.934007</td>\n", + " <td>0.966441</td>\n", + " <td>-6.316716e-15</td>\n", + " <td>0.001980</td>\n", + " <td>0.044494</td>\n", + " <td>-3.141593</td>\n", + " <td>1.0</td>\n", + " <td>1.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>...</th>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " <td>...</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1246</th>\n", + " <td>2.990000e-09</td>\n", + " <td>0.000569</td>\n", + " <td>0.023863</td>\n", + " <td>1.570796</td>\n", + " <td>0.000557</td>\n", + " <td>0.023593</td>\n", + " <td>1.570796</td>\n", + " <td>0.000557</td>\n", + " <td>0.023593</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000013</td>\n", + " <td>0.003579</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000013</td>\n", + " <td>0.003539</td>\n", + " <td>-3.141593</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1247</th>\n", + " <td>2.992000e-09</td>\n", + " <td>0.000544</td>\n", + " <td>0.023326</td>\n", + " <td>1.570796</td>\n", + " <td>0.000532</td>\n", + " <td>0.023062</td>\n", + " <td>1.570796</td>\n", + " <td>0.000557</td>\n", + " <td>0.023593</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000012</td>\n", + " <td>0.003499</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000013</td>\n", + " <td>0.003539</td>\n", + " <td>-3.141593</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1248</th>\n", + " <td>2.994000e-09</td>\n", + " <td>0.000544</td>\n", + " <td>0.023326</td>\n", + " <td>1.570796</td>\n", + " <td>0.000532</td>\n", + " <td>0.023062</td>\n", + " <td>1.570796</td>\n", + " <td>0.000532</td>\n", + " <td>0.023062</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000012</td>\n", + " <td>0.003499</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000012</td>\n", + " <td>0.003459</td>\n", + " <td>-3.141593</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1249</th>\n", + " <td>2.996000e-09</td>\n", + " <td>0.000520</td>\n", + " <td>0.022801</td>\n", + " <td>1.570796</td>\n", + " <td>0.000508</td>\n", + " <td>0.022543</td>\n", + " <td>1.570796</td>\n", + " <td>0.000532</td>\n", + " <td>0.023062</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000012</td>\n", + " <td>0.003420</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000012</td>\n", + " <td>0.003459</td>\n", + " <td>-3.141593</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1250</th>\n", + " <td>2.998000e-09</td>\n", + " <td>0.000520</td>\n", + " <td>0.022801</td>\n", + " <td>1.570796</td>\n", + " <td>0.000508</td>\n", + " <td>0.022543</td>\n", + " <td>1.570796</td>\n", + " <td>0.000508</td>\n", + " <td>0.022543</td>\n", + " <td>1.570796</td>\n", + " <td>...</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000012</td>\n", + " <td>0.003420</td>\n", + " <td>-3.141593e+00</td>\n", + " <td>0.000011</td>\n", + " <td>0.003381</td>\n", + " <td>-3.141593</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " <td>0.0</td>\n", + " </tr>\n", + " </tbody>\n", + "</table>\n", + "<p>1251 rows × 34 columns</p>\n", + "</div>" + ], + "text/plain": [ + " time PROBE{ROOT/N00001}/power PROBE{ROOT/N00001}/abs \\\n", + "0 0.000000e+00 0.000000 0.000000 \n", + "1 5.000000e-10 0.000000 0.000000 \n", + "2 5.020000e-10 0.000000 0.000000 \n", + "3 5.040000e-10 0.021994 0.148303 \n", + "4 5.060000e-10 0.021994 0.148303 \n", + "... ... ... ... \n", + "1246 2.990000e-09 0.000569 0.023863 \n", + "1247 2.992000e-09 0.000544 0.023326 \n", + "1248 2.994000e-09 0.000544 0.023326 \n", + "1249 2.996000e-09 0.000520 0.022801 \n", + "1250 2.998000e-09 0.000520 0.022801 \n", + "\n", + " PROBE{ROOT/N00001}/phase PROBE{ROOT/N00002}/power \\\n", + "0 0.000000 0.000000 \n", + "1 0.000000 0.022500 \n", + "2 0.000000 0.022500 \n", + "3 1.570796 0.087986 \n", + "4 1.570796 0.087986 \n", + "... ... ... \n", + "1246 1.570796 0.000557 \n", + "1247 1.570796 0.000532 \n", + "1248 1.570796 0.000532 \n", + "1249 1.570796 0.000508 \n", + "1250 1.570796 0.000508 \n", + "\n", + " PROBE{ROOT/N00002}/abs PROBE{ROOT/N00002}/phase \\\n", + "0 0.000000 0.000000 \n", + "1 0.150000 1.570796 \n", + "2 0.150000 1.570796 \n", + "3 0.296625 1.570796 \n", + "4 0.296625 1.570796 \n", + "... ... ... \n", + "1246 0.023593 1.570796 \n", + "1247 0.023062 1.570796 \n", + "1248 0.023062 1.570796 \n", + "1249 0.022543 1.570796 \n", + "1250 0.022543 1.570796 \n", + "\n", + " PROBE{ROOT/N00003}/power PROBE{ROOT/N00003}/abs \\\n", + "0 0.000000 0.000000 \n", + "1 0.000000 0.000000 \n", + "2 0.022500 0.150000 \n", + "3 0.022500 0.150000 \n", + "4 0.087986 0.296625 \n", + "... ... ... \n", + "1246 0.000557 0.023593 \n", + "1247 0.000557 0.023593 \n", + "1248 0.000532 0.023062 \n", + "1249 0.000532 0.023062 \n", + "1250 0.000508 0.022543 \n", + "\n", + " PROBE{ROOT/N00003}/phase ... PROBE{ROOT/out}/phase ROOT/PROBE1/power \\\n", + "0 0.000000 ... 0.000000e+00 0.000000 \n", + "1 0.000000 ... 0.000000e+00 0.977500 \n", + "2 1.570796 ... 0.000000e+00 0.977500 \n", + "3 1.570796 ... -6.316716e-15 0.934007 \n", + "4 1.570796 ... -6.316716e-15 0.934007 \n", + "... ... ... ... ... \n", + "1246 1.570796 ... -3.141593e+00 0.000013 \n", + "1247 1.570796 ... -3.141593e+00 0.000012 \n", + "1248 1.570796 ... -3.141593e+00 0.000012 \n", + "1249 1.570796 ... -3.141593e+00 0.000012 \n", + "1250 1.570796 ... -3.141593e+00 0.000012 \n", + "\n", + " ROOT/PROBE1/abs ROOT/PROBE1/phase ROOT/PROBE2/power ROOT/PROBE2/abs \\\n", + "0 0.000000 0.000000e+00 0.000000 0.000000 \n", + "1 0.988686 0.000000e+00 0.000000 0.000000 \n", + "2 0.988686 0.000000e+00 0.000506 0.022500 \n", + "3 0.966441 -6.316716e-15 0.000506 0.022500 \n", + "4 0.966441 -6.316716e-15 0.001980 0.044494 \n", + "... ... ... ... ... \n", + "1246 0.003579 -3.141593e+00 0.000013 0.003539 \n", + "1247 0.003499 -3.141593e+00 0.000013 0.003539 \n", + "1248 0.003499 -3.141593e+00 0.000012 0.003459 \n", + "1249 0.003420 -3.141593e+00 0.000012 0.003459 \n", + "1250 0.003420 -3.141593e+00 0.000011 0.003381 \n", + "\n", + " ROOT/PROBE2/phase ROOT/PROBE3/power ROOT/PROBE3/abs ROOT/PROBE3/phase \n", + "0 0.000000 0.0 0.0 0.0 \n", + "1 0.000000 1.0 1.0 0.0 \n", + "2 -3.141593 1.0 1.0 0.0 \n", + "3 -3.141593 1.0 1.0 0.0 \n", + "4 -3.141593 1.0 1.0 0.0 \n", + "... ... ... ... ... \n", + "1246 -3.141593 0.0 0.0 0.0 \n", + "1247 -3.141593 0.0 0.0 0.0 \n", + "1248 -3.141593 0.0 0.0 0.0 \n", + "1249 -3.141593 0.0 0.0 0.0 \n", + "1250 -3.141593 0.0 0.0 0.0 \n", + "\n", + "[1251 rows x 34 columns]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "df_probes" + ] + }, + { + "cell_type": "markdown", + "id": "64c2170f-f879-43d2-ae1f-850ebf667601", + "metadata": {}, + "source": [ + "### Helper to recover data\n", + "\n", + "As SPECS is not a sampled simulator, but rather event-driven, unchanged values will not appear in the dataframe.\n", + "\n", + "To make it a bit easier to recover a value by time, we created the 'find_by_time' function that automates\n", + "some of the recovery for you. \n", + "\n", + "NOTE: if you want to do it for multiple values, it is better to implement it using the Pandas framework in your own way. Check the Pandas dataframe.ffill() function. Using find_by_time in loops will result in very slow python code." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "d042f4a5-de7d-425d-b772-f245e6346871", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.07090737655723536" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "target_time = 2.5668e-9\n", + "specs.find_by_time(df_probes,'PROBE{ROOT/N00001}/power',target_time)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75ede147-1232-46f5-b3b1-4a9dc75a28b7", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.10" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyspecs/specs.py b/pyspecs/specs.py new file mode 100644 index 0000000..ca0d6f9 --- /dev/null +++ b/pyspecs/specs.py @@ -0,0 +1,236 @@ +import numpy as np +import matplotlib.pyplot as plt +import pandas as pd +import subprocess +import time +from .specsparse import * + +""" +Ideas: + - generate value files + - generate netlists based on graph representations + - simulate + - paralel run + - others? + +""" + +default_settings = { + "o": "traces/delete_me.vcd", + "abstol": 1e-8, + "reltol": 1e-4 +} + + + +def create_arguments_netlist(netlist_file, output_file, abstol, reltol): + """ Function called by specs.simulate(), generates + the argument string for the command-line tool. + + Returns: + arguments (list of str): + Formatted list of arguments required by SPECS + """ + + arguments_dictionary = { "f":netlist_file, + "o":output_file, + "abstol":abstol, + "reltol":reltol + } + + arguments = create_arguments_dictionary(arguments_dictionary) + + return arguments + + +def create_arguments_dictionary(arguments_dictionary:dict): + """ Function called by specs.simulate(), generates + the argument string for the command-line tool. + + Args: + arguments_dictionary (dict): + The keys of this dictionary are keywords expected + by SPECS, while their contents hold their value. + + Example: {"f":"circuit.txt", "o":"data.vcd"," + "abstol":1e-8, "reltol":1e-4 + } + + Returns: + arguments (list of str): + Formatted list of arguments required by SPECS + """ + + arguments = [] + + for keyword_string in arguments_dictionary: + value = arguments_dictionary[keyword_string] + + # Long keywords are prepended with double dash + if len(keyword_string) > 1: + keyword_string = "--" + keyword_string + else: + keyword_string = "-" + keyword_string + + arguments.append(keyword_string) + if value is not None: + arguments.append(str(value)) + + return arguments + +def run_and_time(simulator_command, arguments, verbose): + """Function that runs SPECS and times it. + + This is BLOCKING execution, so not intended for paralel + usage. For this case, use par_run(). + + Args: + simulator_command (str): + The command to call SPECS comprised of + its directory and simulator name. Ex: ./specs + arguments (str): + Command-line arguments passed to SPECS + verbose (bool): + If true, will print SPECS output to the Python shell + Returns: + time_ms: + Execution time of SPECS for that run, in miliseconds (ms) + """ + + print("Executing SPECS from python. . .") + + #spec_env = {"SC_COPYRIGHT_MESSAGE":"DISABLE"} + + process_call = simulator_command + arguments + + tic_ns = time.perf_counter_ns() + print("Command: ", ' '.join(process_call)) + #p = subprocess.Popen(process_call, env=spec_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + p = subprocess.Popen(process_call, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + specs_stdout, specs_stderr = p.communicate() + p.wait() + toc_ns = time.perf_counter_ns() + + time_ms = (toc_ns - tic_ns)*1e-6 + + specs_return_code = p.returncode + print("Execution finished with code: ", specs_return_code) + + if (not specs_return_code == 0) or (verbose): + print("SPECS had an error. Here is the full output: ") + for line in specs_stdout.splitlines(): + print(line.decode(encoding='utf-8', errors='ignore')) + + return time_ms, (specs_return_code, specs_stdout) + +def simulate(netlist_file=None, + custom_arguments=None, + simulator_directory="", + verbose=False, + **kwargs): + """Function that call SPECS from the Python shell + + Args: + netlist_file (str): + File containing the netlist description + of the circuit to simulate. Should contain + a simulation directive within it (.tran, .dc, .op). + + The netlist is a text file that can be: + - Created using the KiCAD library of components in + its schematic editor (eeschema) + - Created and edited by hand by knowing the syntax + - Generated proceduraly using scripts. It's a basic .txt + + It can be achieved with custom arguments by defining + {"f": "path/to/file"} in the dict custom_arguments. + + Defaults to "". + + output_file (str, optional): + VCD file containing all the recorded events. + Can be read with GTKWAVE or parsed with parse_vcd() + Defaults to "traces/delete_me.vcd". + + abstol (double, optional): + Field absolute tolerance for propagating events in the simulator. + Is relevant when running circuits with feedback. + + It can be achieved with custom arguments by defining + {"abstol": 1e-8} in the dict custom_arguments. + + Defaults to 1e-8. + + reltol (double, optional): + Field relative tolerance for propagating events in the simulator. + Is relevant when running circuits with feedback. + + It can be achieved with custom arguments by defining + {"reltol": 1e-4} in the dict custom_arguments. + + Defaults to 1e-4. + + custom_arguments (dict, optional): + <<< ADVANCED USE >>> + It is possible to call SPECS with many other arguments. + You can consult them by running specs without arguments + in the command line interface. + + If custom_arguments is defined, you need to specify + the netlist as a part of the dictionary. + + There is no specific order that the arguments must follow. + + simulator_directory (str, optional): + SPECS can either be included in the PATH variable + or exist as a standalone executable. In the latter case, + it is necessary to define its location. + + Examples: + simulator_directory = "./" + Means that the executable is in the same + directory as this script." + simulator_directory = "/home/user/Documents/" + Means that the SPECS executable is in that + specific path. + + Defaults to "". + + verbose (bool, optional): + If true, will print all the outputs generated by SPECS + to the Python shell. + """ + + assert((netlist_file is not None) or (custom_arguments is not None)) + + + if 'abstol' in kwargs: + abstol = kwargs['abstol'] + else: + abstol = default_settings['abstol'] + + if 'reltol' in kwargs: + reltol = kwargs['reltol'] + else: + reltol = default_settings['reltol'] + + if 'output_file' in kwargs: + output_file = kwargs['output_file'] + else: + output_file = default_settings['o'] + + arguments = [] + if (netlist_file is not None): + arguments = create_arguments_netlist(netlist_file, output_file, abstol, reltol) + + if (custom_arguments is not None): + current_settings = default_settings.copy() + current_settings.update(custom_arguments) # overwrites defaults with the user input where needed + arguments += create_arguments_dictionary(current_settings) + + simulator_name = "specs" + simulator_command = [simulator_directory + simulator_name] + + outputs = run_and_time(simulator_command, arguments, verbose) + + return outputs diff --git a/pyspecs/specsparse.py b/pyspecs/specsparse.py new file mode 100644 index 0000000..91f4f4f --- /dev/null +++ b/pyspecs/specsparse.py @@ -0,0 +1,301 @@ +from pyDigitalWaveTools.vcd.parser import VcdParser +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +import json + +def parse_vcd_dataframe(filename): + """Parses a SPECS VCD file and returns simulation data as a DataFrame. + + Args: + filename (str): + The path to the VCD file. + + Returns: + simulation_data_df: + The simulation data with signals as columns and time/wavelength as rows. + """ + with open(filename) as vcd_file: + vcd = VcdParser() + vcd.parse(vcd_file) + data = vcd.scope.toJson() + + # print(json.dumps(data, indent=4, sort_keys=True)) + simulation_data_df = pd.DataFrame() # initialize empty dataframe + + top_level_name = 'SystemC' + top_scope = None + for child in data['children']: + if is_scope(child) and child['name'] == top_level_name: + top_scope = child + break + if top_scope is None: + raise RuntimeError(f'Top level scope not found in {filename}') + + assert('name' in top_scope.keys()) + assert('type' in top_scope.keys()) + assert('children' in top_scope.keys()) + assert(top_scope['type']['name'] == 'struct') + + scopes = [] + probes = [] + pdets = [] + values = [] + for child in top_scope['children']: + if is_scope(child): + scopes.append(child) + if is_probe(child): + probes.append(child) + if is_pdet(child): + pdets.append(child) + else: + values.append(child) + + # print(f'top level values: {[x["name"] for x in values]}') + # print(f'top level scopes: {[x["name"] for x in scopes]}') + # print(f'top level probes: {[x["name"] for x in probes]}') + + is_wl_sweep = check_wl_sweep(probes) + has_wl = False + save_wl = False + + df_probes = pd.DataFrame() + if len(probes) > 0: + for i,probe in enumerate(probes): + probe_name = probe['name'] + for j,signal in enumerate(probe['children']): + signal_name = signal['name'] + full_name = probe_name + '/' + signal_name + + save_wl = is_wl_sweep and not has_wl + if (not signal_name=='wavelength' or (signal_name=='wavelength' and save_wl)): + current_signal_df = pd.DataFrame() + current_signal_df['tick'] = vcd_get_ticks_vector(signal) + + if signal_name=='wavelength': + has_wl = False # this variable set to true will save WL vector only once + full_name = signal_name # wavelength should be saved independent of probe + + current_signal_df[full_name] = vcd_get_data_vector(signal) + + if i==0 and j==0: + df_probes = current_signal_df + else: + df_probes = df_probes.merge(current_signal_df, how='outer') + + df_probes = df_probes.sort_values('tick') + df_probes = df_probes.reset_index(drop=True) + + if not is_wl_sweep: # making sure that time goes first + df_probes.insert(0, 'time', df_probes['tick'] * vcd_get_multiplier(vcd)) + else: # making sure that wl goes first + first_column = df_probes.pop('wavelength') + df_probes.insert(0, 'wavelength', first_column) + + # we don't need ticks anymore + df_probes = df_probes.drop(columns=['tick']) + + # getting rid of the NaNs: for time domain we repeat the last valid value, + # for freq domain we interpolate linearly + if is_wl_sweep: + df_probes = df_probes.drop(df_probes.loc[df_probes['wavelength']== 0].index.values) + df_probes = df_probes.interpolate() + else: + df_probes = df_probes.fillna(method='ffill') + + # Same with pdetectors + df_pdet = pd.DataFrame() + if not is_wl_sweep and len(pdets) > 0: + for i,pdet in enumerate(pdets): + pdet_name = pdet['name'] + for j,signal in enumerate(pdet['children']): + if signal["type"]["name"] == "struct": + continue + signal_name = signal['name'] + full_name = pdet_name + '/' + signal_name + + # Add data to a temporary DF + current_signal_df = pd.DataFrame() + current_signal_df['tick'] = vcd_get_ticks_vector(signal) + current_signal_df[full_name] = vcd_get_data_vector(signal) + + if df_pdet.empty: + df_pdet = current_signal_df + else: + df_pdet = df_pdet.merge(current_signal_df, how='outer') + + df_pdet = df_pdet.sort_values('tick') + df_pdet = df_pdet.reset_index(drop=True) + if False: + # Add a point next to first value from photodetector + # to ensure 'step' appearance (as its more correct) + print(df_pdet.head()) + df_pdet.loc[-1] = df_pdet.loc[0] + df_pdet.loc[0, 'tick'] = df_pdet.loc[1]['tick'] + df_pdet = df_pdet.sort_values('tick') + df_pdet = df_pdet.reset_index(drop=True) + print(df_pdet.head()) + + # making sure that time goes first + df_pdet.insert(0, 'time', df_pdet['tick'] * vcd_get_multiplier(vcd)) + + # we don't need ticks anymore + df_pdet = df_pdet.drop(columns=['tick']) + + # getting rid of the NaNs: for time domain we repeat the last valid value, + df_pdet = df_pdet.fillna(method='ffill') + + + print('--- Contents of simulation ---') + print ('In df_pdet') + for col in list(df_pdet.columns): + print('\t',col) + print ('In df_probes') + for col in list(df_probes.columns): + print('\t',col) + if is_wl_sweep: + print('Type of simulation: FD') + else: + print('Type of simulation: TD') + + print('------------------------------') + + return df_probes, df_pdet + +def verify_wl_sweep(simulation_data): + """Checks the type of simulation based on the processed data. + + Args: + simulation_data (DataFrame): + Data recovered using parse_vcd_xxxx methods. + + Returns: + is_wl_sweep(bool): + True if it is a wavelength sweep, False otherwise. + """ + is_wl_sweep = False + + if isinstance(simulation_data,pd.DataFrame): + is_wl_sweep = list(simulation_data.columns)[0] == 'wavelength' + else: + print('Error: Invalid simulation data') + + return is_wl_sweep + +def find_by_time(simulation_data,colname,time): + """Finds specific time values from the processed data + Useful when you want to a datapoint of a specific moment + but there was no transition there so it is not necessarily + contained in the data frame. + + As it is an event-based simulator, it means that if + the exact time that you want is not there, the closest + previous value is the correct one, and this function gets it + automatically for you. + + Args: + simulation_data (DataFrame): + Data recovered using parse_vcd_xxxx methods. + colname (string): + Name of the column that you want to extract data from. + time (float): + Time that you want to get your sample. + + Returns: + value(float): + Sample value at the specified time.. + """ + # first check if exact match is present + # else, gets most recent value smaller than + # the specified time + + value = None + + exact_match_df = simulation_data.loc[simulation_data['time'] == time] + if exact_match_df.empty: + previous_match_df = simulation_data.loc[simulation_data['time'] <= time] + previous_match_df = previous_match_df.tail(1) + value = previous_match_df[colname].values[0] + else: + value = exact_match_df[colname].values[0] + + return value + +######### The next functions are intended for internal use ######### + +def is_scope(data): + return data['type']['name'] == 'struct' + +def is_pdet(data): + if not is_scope(data): + return False + + allowed_attrs = ["readout", "readout_no_interference"] + for child in data['children']: + if child['name'] not in allowed_attrs: + return False + return True + +def is_probe(data): + if not is_scope(data): + return False + + allowed_attrs = ["wavelength", "power", "abs", "phase", "real", "imag"] + for child in data['children']: + if is_scope(child): + # Probe contains only values + return False + base_name = child['name'] + # For MLprobe ignore what's after the "@" + # If there is no "@", it remains the full name + i_last_at = base_name.rfind('@') + if i_last_at > 0: + base_name = base_name[0:i_last_at] + if base_name not in allowed_attrs: + return False + return True + +def check_wl_sweep(probes): + for probe in probes: + # see if wavelength is part of probe attributes + attrs = ["wavelength", "power", "abs", "phase"] + lengths = {a:-1 for a in attrs} + for signal in probe['children']: + for a in attrs: + if signal['name'] == a: + lengths[a] = len( signal['data'] ) + + match = False + if lengths[attrs[1]] != -1: + match = lengths[attrs[0]] == lengths[attrs[1]] + if lengths[attrs[2]] != -1: + match = lengths[attrs[0]] == lengths[attrs[2]] + + if match and lengths[attrs[0]] != 1: + return True + return False + +def vcd_get_data_vector(signal): + data = np.array([float(tup[1][1::]) for tup in signal['data']]) + return data + +def vcd_get_ticks_vector(signal): + ticks = np.array([tup[0] for tup in signal['data']]) + return ticks + +def vcd_get_multiplier(vcd): + timescale_list = vcd.timescale.split() + base_scale = float(timescale_list[0]) + unit = timescale_list[1][0] + + multipliers = { + 's': 1.0, + 'm': 1e-3, + 'u': 1e-6, + 'n': 1e-9, + 'p': 1e-12, + 'f': 1e-15, + } + + # returns value in seconds + return base_scale * multipliers[unit] diff --git a/src/devices/alldevices.h b/src/devices/alldevices.h new file mode 100644 index 0000000..daa7ee1 --- /dev/null +++ b/src/devices/alldevices.h @@ -0,0 +1,44 @@ +#pragma once + +/** ******************************************* **/ +/** Elementary passive devices **/ +/** ******************************************* **/ +#include <waveguide.h> +#include <directional_coupler.h> +#include <merger.h> +#include <splitter.h> +#include <crossing.h> +#include <pcm_device.h> + +/** ******************************************* **/ +/** Active devices **/ +/** ******************************************* **/ +#include <detector.h> +#include <phaseshifter.h> +#include <mzi_active.h> +#include <mzi.h> + +/** ******************************************* **/ +/** Sources **/ +/** ******************************************* **/ +//#include <bitstream_source.h> +#include <cw_source.h> +#include <value_list_source.h> +#include <electrical_value_list_source.h> + +/** ******************************************* **/ +/** Utilities **/ +/** ******************************************* **/ +#include <probe.h> +//#include <ring.h> +#include <time_monitor.h> + +/** ******************************************* **/ +/** Circuits **/ +/** ******************************************* **/ +#include <crow.h> +#include <octane_cell.h> +#include <octane_segment.h> +#include <octane_matrix.h> +#include <mesh_col.h> +#include <clements.h> diff --git a/src/devices/bitstream_source.cpp b/src/devices/bitstream_source.cpp new file mode 100644 index 0000000..f2e38a6 --- /dev/null +++ b/src/devices/bitstream_source.cpp @@ -0,0 +1,76 @@ +#include <bitstream_source.h> + +#include <random> +#include <cstdlib> + +using std::cout; +using std::endl; + +unsigned int BitstreamSource::m_bits_per_value = 8; +//double BitstreamSource::m_output_jitter = 0.0; + +void BitstreamSource::runner() +{ + // Initialize random number generator + //mt19937 gen(m_seed); + //uniform_int_distribution<> dis(1, m_max_value); // uniform in [1, max] + //int operation_mode = 0; // 0: modulated source , 1: independent pulses + + auto max_val = pow(2.0, m_bits_per_value) - 1; + + cout << name() << ":" << endl; + cout << "signal on: " << m_signal_on << endl; + cout << "signal off: " << m_signal_off << endl; + cout << "bits: "; + cout << endl; + + for(const auto &val : m_values) { + auto val_saturated = val; + if (m_current_value > max_val) + val_saturated = max_val; + + for (unsigned int iBit = 0; iBit < m_bits_per_value; ++iBit) { + bool bit = val_saturated & (1 << iBit); + cout << bit; + } + } + cout << " --> " << (dynamic_cast<sc_signal<OpticalSignal> *>(p_out.get_interface()))->name(); + cout << endl; + cout << endl; + + // Loop over all values + for (unsigned int iVal = 0; iVal < m_values.size(); ++iVal) { + m_current_value = m_values[iVal]; + + if (m_current_value > max_val) + m_current_value = max_val; + + for (unsigned int iBit = 0; iBit < m_bits_per_value; ++iBit) { + // Wait at least one clk cycle, and for enable to be high + do { + // Wait next clk edge + wait(); + cout << "CLK tick (" << this->name() << ")" << endl; + } while (!p_enable->read()); + + // Deduce bit "value" from binary representation + // iBit = 0 represents LSB + bool bit = m_current_value & (1 << iBit); + + // Initialize corresponding signal + auto s = (bit ? OpticalSignal(m_signal_on) : + OpticalSignal(m_signal_off)); + + s.getNewId(); // New Id is necessary to notify signal change + + // Send signal to output with no delay + m_out_writer.delayedWrite(s, SC_ZERO_TIME); + } + } + + // Wait for end of simulation + while (true) { + // Do nothing + wait(); + } +} diff --git a/src/devices/bitstream_source.h b/src/devices/bitstream_source.h new file mode 100644 index 0000000..a7c8715 --- /dev/null +++ b/src/devices/bitstream_source.h @@ -0,0 +1,105 @@ +#pragma once + +#include <systemc.h> +#include <fstream> + +#include <optical_output_port.h> +#include <optical_signal.h> + +using namespace std; + +class BitstreamSource : public sc_module { +public: + // Set it as typedef for now (we may very well never need to change it) + typedef unsigned long operand_type; + +public: + // Ports + sc_port<sc_signal_in_if<bool>> p_enable; + sc_in<bool> p_clk; + sc_port<sc_signal_out_if<OpticalSignal>> p_out; + + // Timed ports writers + OpticalOutputPort m_out_writer; + + // Member variables + static unsigned int m_bits_per_value; + + vector<operand_type> m_values; + operand_type m_current_value = 0; + + OpticalSignal m_signal_on; + OpticalSignal m_signal_off; + + // Processes + void runner(); + + // + inline void setWavelength(const double &wl) + { + m_signal_on.m_wavelength_id = m_signal_on.getIDFromWavelength(wl); + m_signal_off.m_wavelength_id = m_signal_off.getIDFromWavelength(wl); + } + + // + inline void setPower(const double &on, const double &off = 0.0) + { + m_signal_on.m_field = sqrt(on); + m_signal_off.m_field = sqrt(off); + } + + // Constructor + BitstreamSource(sc_module_name name) + : sc_module(name) + , m_out_writer("out_delayed_writer", p_out) + { + SC_HAS_PROCESS(BitstreamSource); + + SC_THREAD(runner); + sensitive << p_clk.pos() << p_clk.neg(); + } + + BitstreamSource(sc_module_name name, + const vector<operand_type> &values, + const OpticalSignal &signal_on, + const OpticalSignal &signal_off = OpticalSignal(0)) + : sc_module(name) + , m_out_writer("out_delayed_writer", p_out) + , m_values(values) + , m_current_value(values.empty() ? 0 : values[0]) + , m_signal_on(signal_on) + , m_signal_off(signal_off) + { + SC_HAS_PROCESS(BitstreamSource); + + SC_THREAD(runner); + sensitive << p_clk.pos() << p_clk.neg(); + } + + BitstreamSource(sc_module_name name, + const std::string &values_file, + const OpticalSignal &signal_on, + const OpticalSignal &signal_off = OpticalSignal(0)) + : sc_module(name) + , m_out_writer("out_delayed_writer", p_out) + , m_signal_on(signal_on) + , m_signal_off(signal_off) + { + // Read values from file + std::ifstream i(values_file); + + int value; + m_values.clear(); + while ( i.good() ) { + i >> value; + m_values.push_back(value); + } + + m_current_value = (m_values.empty() ? 0 : m_values[0]); + + SC_HAS_PROCESS(BitstreamSource); + + SC_THREAD(runner); + sensitive << p_clk.pos() << p_clk.neg(); + } +}; diff --git a/src/devices/clements.cpp b/src/devices/clements.cpp new file mode 100644 index 0000000..a99bfb3 --- /dev/null +++ b/src/devices/clements.cpp @@ -0,0 +1,137 @@ +#include "clements.h" + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + +void Clements::init_ports() +{ + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing optical ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + p_in.clear(); + p_out.clear(); + for(size_t i = 0; i < m_N; i++) + { + p_in.push_back(make_unique<spx::oa_port_in_type>(__modname("IN_", i))); + p_out.push_back(make_unique<spx::oa_port_out_type>(__modname("OUT_", i))); + } + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing electrical input ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + p_vphi.clear(); + p_vtheta.clear(); + + size_t num_of_electrical_ports = (m_N * (m_N - 1) / 2); + for(size_t i = 0; i < num_of_electrical_ports; i++) + { + p_vphi.push_back(make_unique<sc_in<double>>(__modname("VPHI_", i))); + p_vtheta.push_back(make_unique<sc_in<double>>(__modname("VTHETA_", i))); + } +} + +void Clements::init() +{ + m_optical_connect.clear(); + m_mesh_cols.clear(); + + size_t num_cols = (m_N != 2) ? m_N : 1; + size_t num_wires = m_N * (num_cols - 1); + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Instantiating submodules + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + for(size_t j = 0; j < num_cols; j++) + { + m_mesh_cols.push_back(make_unique<MeshCol>(__modname("COL_", j), + m_N, j, m_length_cm, m_attenuation_wg_dB_cm, + m_attenuation_coupler_dB, m_attenuation_ps_dB, + m_neff, m_ng)); + m_mesh_cols[j]->init(); + } + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Instantiating optical wires + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + for(size_t i = 0; i < num_wires; i++) + m_optical_connect.push_back(make_unique<spx::oa_signal_type>(__modname("W_", i))); + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Connecting modules (optical) + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + if (m_N == 2) + { + m_mesh_cols[0]->p_in[0]->bind(*p_in[0]); + m_mesh_cols[0]->p_in[1]->bind(*p_in[1]); + m_mesh_cols[0]->p_out[0]->bind(*p_out[0]); + m_mesh_cols[0]->p_out[1]->bind(*p_out[1]); + } + else + { + // first col has inputs that go to ports, + // and outputs going to the first m_N wires + for(size_t i = 0; i < m_N; i++) + { + m_mesh_cols[0]->p_in[i]->bind(*p_in[i]); + m_mesh_cols[0]->p_out[i]->bind(*m_optical_connect[i]); + } + + size_t in_index; + size_t out_index; + for(size_t j = 1; j < num_cols - 1; j++) + { + in_index = (j - 1) * m_N; + out_index = j * m_N; + for(size_t i = 0; i < m_N; i++) + { + m_mesh_cols[j]->p_in[i]->bind(*m_optical_connect[in_index + i]); + m_mesh_cols[j]->p_out[i]->bind(*m_optical_connect[out_index + i]); + } + } + + // last col has outputs that go to ports, + // and inputs coming from the last m_N wires + in_index = (num_cols - 2) * m_N; + for(size_t i = 0; i < m_N; i++) + { + m_mesh_cols[num_cols - 1]->p_in[i]->bind(*m_optical_connect[in_index + i]); + m_mesh_cols[num_cols - 1]->p_out[i]->bind(*p_out[i]); + } + } + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Connecting modules (electrical) + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + // The index of the electrical port advances top to bottom, and + // then moves to the next column + + size_t ports_in_col; + size_t cur_port = 0; + for(size_t j = 0; j < num_cols; j++) + { + ports_in_col = m_N/2; + if ((m_N % 2 == 0) && !(j % 2 == 0)) // if even-odd, there is one less MZI + ports_in_col = m_N/2 - 1; + + for(size_t i = 0; i < ports_in_col; i++) + { + m_mesh_cols[j]->p_vphi[i]->bind(*p_vphi[cur_port]); + m_mesh_cols[j]->p_vtheta[i]->bind(*p_vtheta[cur_port]); + + cur_port ++; + } + } +}
\ No newline at end of file diff --git a/src/devices/clements.h b/src/devices/clements.h new file mode 100644 index 0000000..78de99f --- /dev/null +++ b/src/devices/clements.h @@ -0,0 +1,66 @@ +#pragma once + +#include <specs.h> +#include <spx_module.h> +#include <mesh_col.h> + +/* Clements MZI Mesh + +The mesh has a total of N(N-1)/2 MZIs, as specified in +Optimal design for universal multiport interferometers by Clements et al. (2016). + +Connection guide (above the X is electrical address of phi/theta): + 0 3 + 0__| __ ______ __| __ ______0 + \/ 2 \/ 5 + 1__/\__ __| __ __/\__ __| __1 + 1 \/ 4 \/ + 2__| __ __/\__ __| __ __/\__2 + \/ \/ + 3__/\__ ______ __/\__ ______3 +*/ + +class Clements : public spx_module{ +public: + vector<unique_ptr<spx::oa_port_in_type>> p_in; + vector<unique_ptr<spx::oa_port_out_type>> p_out; + vector<unique_ptr<sc_in<double>>> p_vphi; + vector<unique_ptr<sc_in<double>>> p_vtheta; + + // Member variables + size_t m_N; // represents the number of inputs of the mesh (rows) + + // Parameters for the internal MZIs + double m_length_cm; + double m_attenuation_wg_dB_cm; + double m_attenuation_coupler_dB; + double m_attenuation_ps_dB; + double m_neff; + double m_ng; + + // Submodules and wires + vector<unique_ptr<spx::oa_signal_type>> m_optical_connect; + vector<unique_ptr<MeshCol>> m_mesh_cols; + + // Initialization functions + void init_ports(); + void init(); + + Clements(sc_module_name name, const size_t &N, + const double &length_cm = 1e-2, + const double &attenuation_wg_dB_cm = 0, const double &attenuation_coupler_dB = 0, + const double &attenuation_ps_dB = 0, + const double &neff = 2.2111, const double &ng = 2.2637) + : spx_module(name) + , m_N(N) + , m_length_cm(length_cm) + , m_attenuation_wg_dB_cm(attenuation_wg_dB_cm) + , m_attenuation_coupler_dB(attenuation_coupler_dB) + , m_attenuation_ps_dB(attenuation_ps_dB) + , m_neff(neff) + , m_ng(ng) + { + assert(N > 1); + init_ports(); + } +};
\ No newline at end of file diff --git a/src/devices/crossing.cpp b/src/devices/crossing.cpp new file mode 100644 index 0000000..f8c8f5e --- /dev/null +++ b/src/devices/crossing.cpp @@ -0,0 +1,129 @@ +#include "specs.h" +#include "crossing.h" + +using namespace std; + +void CrossingUni::on_input_changed() +{ + // If it's NAN, it's because it was not specified and thus the linear should be zero (-inf dB) + const double crosstalk_field_lin = (isnan(m_crosstalk_power_dB)) ? 0 : pow(10.0, m_crosstalk_power_dB / 20); + const double transmission_field_lin = pow(10.0, -m_attenuation_power_dB / 20); // due to attenuations + + // Pre-calculate S-parameters + OpticalSignal::field_type S13, S14, S23, S24; + // the second part relates to power that is crossed over (not transmitted) + S13 = polar(transmission_field_lin, 0.0); // From in1 to out1 + S24 = polar(transmission_field_lin, 0.0); // From in2 to out2 + S14 = polar(crosstalk_field_lin, 0.0); // From in1 to out2 (crosstalk) + S23 = polar(crosstalk_field_lin, 0.0); // From in2 to out1 (crosstalk) + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "transmission_power = " << norm(S13) << " W/W" << endl; + cout << "crosstalk_power = " << norm(S14)<< " W/W" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in1.get_interface()))->name(); + cout << " --- ---> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out1.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in2.get_interface()))->name(); + cout << " --- ---> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out2.get_interface()))->name(); + cout << endl; + + cout << endl; + } + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + auto s1 = p_in1->read(); + auto s2 = p_in2->read(); + + // Apply S-parameters + auto s3 = s1 * S13 + s2 * S23; + auto s4 = s1 * S14 + s2 * S24; + + // Get new IDs for signal + s3.getNewId(); + s4.getNewId(); + + // Write to ouput port after delay + m_out1_writer.delayedWrite(s3, sc_time(0, SC_NS)); + m_out2_writer.delayedWrite(s4, sc_time(0, SC_NS)); + } +} + +void CrossingBi::on_input_changed() +{ + // If it's NAN, it's because it was not specified and thus the linear should be zero (-inf dB) + const double crosstalk_field_lin = (isnan(m_crosstalk_power_dB)) ? 0 : pow(10.0, m_crosstalk_power_dB / 20); + const double transmission_field_lin = pow(10.0, -m_attenuation_power_dB / 20); // due to attenuations + + // Pre-calculate S-parameters + OpticalSignal::field_type through = polar(transmission_field_lin, 0.0); + OpticalSignal::field_type cross = polar(crosstalk_field_lin, 0.0); + + OpticalSignal::field_type S02, S03, S12, S13; + // the second part relates to power that is crossed over (not transmitted) + S02 = through; // From in1 to out1 + S13 = through; // From in2 to out2 + S03 = cross; // From in1 to out2 (crosstalk) + S12 = cross; // From in2 to out1 (crosstalk) + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "transmission_power = " << norm(through) << " W/W" << endl; + cout << "crosstalk_power = " << norm(cross)<< " W/W" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_in.get_interface()))->name(); + cout << " --- ---> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p2_out.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_in.get_interface()))->name(); + cout << " --- ---> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p3_out.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p2_in.get_interface()))->name(); + cout << " --- ---> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_out.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p3_in.get_interface()))->name(); + cout << " --- ---> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_out.get_interface()))->name(); + cout << endl; + + cout << endl; + } + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + auto s0_in = p0_in->read(); + auto s1_in = p1_in->read(); + auto s2_in = p2_in->read(); + auto s3_in = p3_in->read(); + + // Apply S-parameters + auto s0_out = s2_in * S02 + s3_in * S03; + auto s1_out = s2_in * S12 + s3_in * S13; + auto s2_out = s0_in * S02 + s1_in * S12; + auto s3_out = s0_in * S03 + s1_in * S13; + + // Get new IDs for signal + s0_out.getNewId(); + s1_out.getNewId(); + s2_out.getNewId(); + s3_out.getNewId(); + + // Write to ouput port after delay + m_p0_out_writer.delayedWrite(s0_out, sc_time(0, SC_NS)); + m_p1_out_writer.delayedWrite(s1_out, sc_time(0, SC_NS)); + m_p2_out_writer.delayedWrite(s2_out, sc_time(0, SC_NS)); + m_p3_out_writer.delayedWrite(s3_out, sc_time(0, SC_NS)); + } +}
\ No newline at end of file diff --git a/src/devices/crossing.h b/src/devices/crossing.h new file mode 100644 index 0000000..8631ba4 --- /dev/null +++ b/src/devices/crossing.h @@ -0,0 +1,113 @@ +#pragma once + +#include <systemc.h> + +#include <spx_module.h> + +#include <optical_output_port.h> +#include <optical_signal.h> + + +/* A waveguide crossing that accounts for */ +/* loss and interchannel crosstalk */ +/* */ +/* (2)p_in2 */ +/* | */ +/* (1)p_in1----+---->p_out1(3) */ +/* | */ +/* v */ +/* p_out2(4) */ +/* */ +/* ---------------------------------------*/ +class CrossingBase : public spx_module { +public: + // Member variables + double m_attenuation_power_dB; + double m_crosstalk_power_dB; + + // Constructor with crosstalk + // Attenuation relates to out1/in1 when there's nothing in in2 + // Crosstalk relates to out2/in1 when there's nothing in in1 + CrossingBase(sc_module_name name, + double attenuation_power_dB = 0, + double crosstalk_power_dB = NAN) + : spx_module(name) + , m_attenuation_power_dB(attenuation_power_dB) + , m_crosstalk_power_dB(crosstalk_power_dB) + { + } +}; + +class CrossingUni : public CrossingBase { +public: + // Ports + spx::oa_port_in_type p_in1; + spx::oa_port_in_type p_in2; + spx::oa_port_out_type p_out1; + spx::oa_port_out_type p_out2; + + // Timed ports writers + OpticalOutputPort m_out1_writer; + OpticalOutputPort m_out2_writer; + + // Processes + void on_input_changed(); + + // Constructor with crosstalk + // Attenuation relates to out1/in1 when there's nothing in in2 + // Crosstalk relates to out2/in1 when there's nothing in in1 + CrossingUni(sc_module_name name, + double attenuation_power_dB = 0, + double crosstalk_power_dB = NAN) + : CrossingBase(name, attenuation_power_dB, crosstalk_power_dB) + , m_out1_writer("out1_delayed_writer", p_out1) + , m_out2_writer("out2_delayed_writer", p_out2) + { + SC_HAS_PROCESS(CrossingUni); + + SC_THREAD(on_input_changed); + sensitive << p_in1 << p_in2; + } +}; + +typedef CrossingUni Crossing; + +class CrossingBi : public CrossingBase { +public: + // Ports + spx::oa_port_in_type p0_in; + spx::oa_port_in_type p1_in; + spx::oa_port_in_type p2_in; + spx::oa_port_in_type p3_in; + spx::oa_port_out_type p0_out; + spx::oa_port_out_type p1_out; + spx::oa_port_out_type p2_out; + spx::oa_port_out_type p3_out; + + // Timed ports writers + OpticalOutputPort m_p0_out_writer; + OpticalOutputPort m_p1_out_writer; + OpticalOutputPort m_p2_out_writer; + OpticalOutputPort m_p3_out_writer; + + // Processes + void on_input_changed(); + + // Constructor with crosstalk + // Attenuation relates to out1/in1 when there's nothing in in2 + // Crosstalk relates to out2/in1 when there's nothing in in1 + CrossingBi(sc_module_name name, + double attenuation_power_dB = 0, + double crosstalk_power_dB = NAN) + : CrossingBase(name, attenuation_power_dB, crosstalk_power_dB) + , m_p0_out_writer("p0_out_delayed_writer", p0_out) + , m_p1_out_writer("p1_out_delayed_writer", p1_out) + , m_p2_out_writer("p2_out_delayed_writer", p2_out) + , m_p3_out_writer("p3_out_delayed_writer", p3_out) + { + SC_HAS_PROCESS(CrossingBi); + + SC_THREAD(on_input_changed); + sensitive << p0_in << p1_in << p2_in << p3_in; + } +};
\ No newline at end of file diff --git a/src/devices/crow.cpp b/src/devices/crow.cpp new file mode 100644 index 0000000..d411aa2 --- /dev/null +++ b/src/devices/crow.cpp @@ -0,0 +1,97 @@ +#include <crow.h> + +using namespace std; + +void CROW::connect_submodules() +{ + // Physical parameters of the components + // double neff = 2.6391; //2.2; + // double ng = 4.3416; //neff; + // double loss_db_cm = 2; //1; + // double coupling_through = (1 - pow(0.83645, 2.0));//0.85; + // double coupling_through = 1 - pow(0.83645, 2.0);//0.85; + // double coupling_through = 1 - pow(0.83645, 2.0);//0.85; + // coupling_through = 1 - 0.83645;//0.85; + //double pi_length = 1.55e-6/2/neff; + //double internal_length = 200*pi_length; + //double internal_length = 1001*pi_length; + // double internal_length = 2.0*((2.0 * M_PI * 3.2544e-6) + 10e-6); // 2pi*R+10um (R = 3.2544um) + // double internal_length = 2.0 * M_PI * (3.2544e-6 + 10e-6/(2.0*M_PI)); // 2pi*R+10um (R = 3.2544um) + //double var_factor = 1.01*pi_length; + // double var_factor = 0; + + // -- Parameterizing components -- // + for (size_t i = 0; i < N; i++) + { + // here is where variation is disabled (0 and uncomment) + // double _wg_length_variation = var_factor*i; + double _wg_length = m_ring_length / 2.0; + // double _wg_length = M_PI * 3.2544e-6 + 10e-6; + //double _wg_length = 200*100.0*(1550e-9 + 0.1e-9 * i)/(2.0*neff); + + //cout << _wg_length_variation << endl; + cout << wg_top.at(i)->name() << endl; + wg_top.at(i)->m_length_cm = _wg_length * 100.0; + wg_top.at(i)->m_neff = m_neff; + wg_top.at(i)->m_ng = m_ng; + wg_top.at(i)->m_attenuation_dB_cm = m_loss_db_cm; + + cout << wg_bot.at(i)->name() << endl; + wg_bot.at(i)->m_length_cm = _wg_length * 100.0; + wg_bot.at(i)->m_neff = m_neff; + wg_bot.at(i)->m_ng = m_ng; + wg_bot.at(i)->m_attenuation_dB_cm = m_loss_db_cm; + + cout << dc.at(i)->name() << endl; + dc.at(i)->m_dc_through_coupling_power = m_coupling_through; + } + dc.at(N)->m_dc_through_coupling_power = m_coupling_through; + + // -- Connecting components -- // + // Before loop, outer connections on left + dc.at(0)->p_in1(p_in); + dc.at(0)->p_out1(p_out_t); + //p_through.p_in(OUT_THROUGH); + + // Loop, inner connections + for (size_t i = 0; i < N; i++) + { + // Need to take care if odd or even, + // as inputs come from different directions + if (i%2 == 0) + { + // If i even, DC(i) input at bottom + dc.at(i)->p_in2(*S_BL.at(i)); + dc.at(i)->p_out2(*S_TL.at(i)); + // If i even, DC(i+1) input at the top + dc.at(i+1)->p_in1(*S_TR.at(i)); + dc.at(i+1)->p_out1(*S_BR.at(i)); + // If even, top waveguide(i) is L->R + wg_top.at(i)->p_in(*S_TL.at(i)); + wg_top.at(i)->p_out(*S_TR.at(i)); + // If even, bottom waveguide(i) is R->L + wg_bot.at(i)->p_in(*S_BR.at(i)); + wg_bot.at(i)->p_out(*S_BL.at(i)); + } + else{ + // If i odd, DC(i) input at top + dc.at(i)->p_in2(*S_TL.at(i)); + dc.at(i)->p_out2(*S_BL.at(i)); + // If i odd, DC(i+1) input at the bottom + dc.at(i+1)->p_in1(*S_BR.at(i)); + dc.at(i+1)->p_out1(*S_TR.at(i)); + // If odd, top waveguide(i) is R->L + wg_top.at(i)->p_in(*S_TR.at(i)); + wg_top.at(i)->p_out(*S_TL.at(i)); + // If odd, bottom waveguide(i) is L->R + wg_bot.at(i)->p_in(*S_BL.at(i)); + wg_bot.at(i)->p_out(*S_BR.at(i)); + } + } + // After loop, outer connections on right + //pd1.p_readout(PD_OUT); + dc.at(N)->p_in2(p_add); + dc.at(N)->p_out2(p_out_d); + + dc.at(0)->m_out1_writer.m_converger = false; +}
\ No newline at end of file diff --git a/src/devices/crow.h b/src/devices/crow.h new file mode 100644 index 0000000..d0e6ed2 --- /dev/null +++ b/src/devices/crow.h @@ -0,0 +1,98 @@ +#pragma once + +#include <systemc.h> +#include <waveguide.h> +#include <directional_coupler.h> +#include <detector.h> +#include <optical_output_port.h> +#include <optical_signal.h> +#include <pcm_device.h> +#include <directional_coupler.h> +#include <merger.h> + +#include <cassert> + +class CROW : public sc_module { +public: + // Ports + /** The optical input ports. */ + sc_port<sc_signal_in_if<OpticalSignal>> p_in; + sc_port<sc_signal_in_if<OpticalSignal>> p_add; + /** The electrical output port. */ + sc_port<sc_signal_out_if<OpticalSignal>> p_out_t; + sc_port<sc_signal_out_if<OpticalSignal>> p_out_d; + + // Member variables + size_t N; + double m_ring_length; + double m_neff = 2.2; + double m_ng = 4.3; + double m_loss_db_cm = 2; + double m_coupling_through = 0.85; + + // Wires + vector<shared_ptr<sc_signal<OpticalSignal>>> S_TL; + vector<shared_ptr<sc_signal<OpticalSignal>>> S_BL; + vector<shared_ptr<sc_signal<OpticalSignal>>> S_TR; + vector<shared_ptr<sc_signal<OpticalSignal>>> S_BR; + //sc_signal<OpticalSignal> terminator; + + // Member submodules + vector<shared_ptr<Waveguide>> wg_top; + vector<shared_ptr<Waveguide>> wg_bot; + vector<shared_ptr<DirectionalCoupler>> dc; + + + virtual void init() + { + assert(N > 0); + S_TL.clear(); + S_BL.clear(); + S_TR.clear(); + S_BR.clear(); + wg_bot.clear(); + wg_top.clear(); + dc.clear(); + stringstream ss; + string _i; + for (size_t i = 0; i < N; ++i) + { + ss.str(std::string()); + ss << i; + _i = ss.str(); + cout << _i << endl; + S_TL.push_back(make_shared<sc_signal<OpticalSignal>>((string("S_TL") + "_" + _i).c_str())); + S_BL.push_back(make_shared<sc_signal<OpticalSignal>>((string("S_BL") + "_" + _i).c_str())); + S_TR.push_back(make_shared<sc_signal<OpticalSignal>>((string("S_TR") + "_" + _i).c_str())); + S_BR.push_back(make_shared<sc_signal<OpticalSignal>>((string("S_BR") + "_" + _i).c_str())); + wg_bot.push_back(make_shared<Waveguide>((string("wg_bot") + "_" + _i).c_str())); + wg_top.push_back(make_shared<Waveguide>((string("wg_top") + "_" + _i).c_str())); + dc.push_back(make_shared<DirectionalCoupler>((string("dc") + "_" + _i).c_str())); + } + ss.str(std::string()); + ss << N; + _i = ss.str(); + cout << _i << endl; + dc.push_back(make_shared<DirectionalCoupler>((string("dc") + "_" + _i).c_str())); + connect_submodules(); + } + + void connect_submodules(); + + /** Constructor for Waveguide + * + * @param name name of the module + * */ + CROW(sc_module_name name, const size_t &nrings = 3, const double &ring_length = 0.0) + : sc_module(name) + , N(nrings) + , m_ring_length(ring_length) + { + } + + void setRingLength(const double &ring_length) + { + assert(ring_length >= 0); + m_ring_length = ring_length; + } +}; diff --git a/src/devices/cw_source.cpp b/src/devices/cw_source.cpp new file mode 100644 index 0000000..4be5934 --- /dev/null +++ b/src/devices/cw_source.cpp @@ -0,0 +1,45 @@ +#include "specs.h" +#include <cw_source.h> + +using std::cout; +using std::endl; + +void CWSource::runner() +{ + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "signal on: " << m_signal_on << endl; + cout << "--> " << + (dynamic_cast<spx::oa_signal_type *>(p_out.get_interface()))->name() << endl; + cout << endl; + } + + bool first_run = true; + + while (true) { + // Wait for enable signal + if (! enable.read().to_bool()) + { + // cout << name() << " waiting for enable" << endl; + wait(enable.posedge_event()); + } + // cout << name() << " was enabled" << endl; + auto s = m_signal_on; + s.getNewId(); + + // Write value to output + m_out_writer.delayedWrite(s, SC_ZERO_TIME); + cout << name() << " emitted: " << s << endl; + + // Wait for reset + if ( !first_run || !reset.read().to_bool()) + { + // cout << name() << " waiting for reset" << endl; + wait(reset.posedge_event()); + reset.write(sc_logic(0)); + wait(reset.negedge_event()); + } + // cout << name() << " was reset" << endl; + } +} diff --git a/src/devices/cw_source.h b/src/devices/cw_source.h new file mode 100644 index 0000000..487177c --- /dev/null +++ b/src/devices/cw_source.h @@ -0,0 +1,76 @@ +#pragma once + +#include <systemc.h> +#include <fstream> + +#include <optical_output_port.h> +#include <optical_signal.h> +#include "specs.h" +#include "spx_module.h" + +class CWSource : public spx_module { +public: + // Ports + spx::oa_port_out_type p_out; + + // Timed ports writers + OpticalOutputPort m_out_writer; + + // Signal characteristic + spx::oa_value_type m_signal_on; + double m_source_wavelength; + + // Source emission control + spx::ed_signal_type enable; + spx::ed_signal_type reset; + + // Processes + void runner(); + + inline void setWavelength(const double &wl) + { + m_source_wavelength = wl; + m_signal_on.m_wavelength_id = m_signal_on.getIDFromWavelength(wl); + } + inline void setFrequency(const double &f) + { + setWavelength(299792458.0 / f); + } + inline void setAmplitudePhase (const double &litude, const double &phase) + { + m_signal_on.m_field = polar(amplitude, phase); + } + inline void setPhase (const double &phase) + { + if (m_signal_on.modulus() == 0) + cerr << "Warning: setting phase has no effect on 0" << endl; + m_signal_on.m_field = polar(m_signal_on.modulus(), phase); + } + inline void setPower (const double &power) + { + m_signal_on.m_field = polar(sqrt(power), m_signal_on.phase()); + } + inline void setPower(const double &power, double phase) + { + setAmplitudePhase(sqrt(power), phase); + } + + // Constructor + CWSource(sc_module_name name) + : spx_module(name) + , m_out_writer("out_delayed_writer", p_out) + { + SC_HAS_PROCESS(CWSource); + + SC_THREAD(runner); + + enable = sc_logic(0); + reset = sc_logic(0); + } + + CWSource(sc_module_name name, const OpticalSignal& signal_on) + : CWSource(name) + { + m_signal_on = signal_on; + } +}; diff --git a/src/devices/detector.cpp b/src/devices/detector.cpp new file mode 100644 index 0000000..b93a5de --- /dev/null +++ b/src/devices/detector.cpp @@ -0,0 +1,136 @@ +#include "specs.h" +#include <detector.h> +#include <cstdlib> // system() +#include <random> +#include <complex> + +using namespace std; + +void Detector::on_port_in_changed() +{ + // always initialize memory + m_memory_in[0] = 0; + + // rng seed + init(); + + while (true) { + // Wait for a new input signal + wait(); + + const auto &p_in_read = p_in->read(); + + auto cur_wavelength_id = p_in_read.m_wavelength_id; + // Updating the field memory + m_memory_in[cur_wavelength_id] = p_in_read.m_field; + m_event_manual_trigger.notify(); + } +} + +void Detector::on_time_tick() +{ + sc_time sampling_time = sc_time(m_sampling_time, SC_SEC); + if (sampling_time.value() == 0) + sampling_time = sc_time::from_value(1); + + OpticalSignal::field_type total_field; + OpticalSignal::field_type::value_type total_power; + double photocurrent; + + // Wait for enable signal + if (! enable.read().to_bool()) + { + // cout << name() << " waiting for enable" << endl; + wait(enable.posedge_event()); + cout << name() << " was enabled" << endl; + } + + while(true) + { + if (sc_pending_activity()) { + wait(sampling_time, m_event_manual_trigger); + //wait(m_event_manual_trigger); // if only time-averaged signal is of interest + } else { + /* wait for reset */ + //TODO (see CWSource code) + wait(); // effectively wait until the end of the simulation + } + + /* Get current time tk*/ + double tk = sc_time_stamp().to_seconds(); + + /* Calculate current output value based on present fields */ + /* Calculate sum of fields at current time*/ + total_field = 0; + total_power = 0; + for (auto field : m_memory_in) + { + double wl = specsGlobalConfig.wavelengths_vector[field.first]; + double freq = 299792458 / wl; + total_field += field.second * exp(complex<double>(0, 2 * M_PI * freq * tk)); + total_power += norm(field.second); + } + + if (norm(total_field) == 0) + total_field = 1e-20*m_rngDist(m_rngGen); + + photocurrent = norm(total_field) * m_responsivity_A_W; + m_cur_readout = photocurrent + (!m_noiseBypass)*noise_gen(photocurrent) + m_darkCurrent_A; + m_cur_readout_no_interf = total_power * m_responsivity_A_W + (!m_noiseBypass)*noise_gen(photocurrent) + m_darkCurrent_A; + + + //m_cur_readout = total_field.real(); + // Write to output port + //p_readout->write(m_cur_readout); + } +} + +/* +Generates a current noise to be applied to the noiseless_readout, +calculated from the responsivity. + +Considers: TIA input referred, shot, and thermal +*/ +double Detector::noise_gen(const double &noiseless_readout) +{ + // elementary charge + const double q = 1.60217e-19; + + // Boltzmann constant + const double K = 1.38064e-23; + + double inoise_tia_2 = m_opFreq_Hz*pow(m_iTIA,2); + double inoise_shot_2 = m_opFreq_Hz*2*q*(noiseless_readout+m_darkCurrent_A); + double inoise_therm_2 = m_opFreq_Hz*4*K*m_temp_K/m_equivR_Ohm; + + // the RMS value is also the variance of the random variable + double inoise_rms = inoise_tia_2 + inoise_shot_2 + inoise_therm_2; + + // mean = noiseless, std = sqrt(variance) + // the second element of the product is the gaussian(0,1) + return sqrt(inoise_rms) * m_rngDist(m_rngGen); +} + +/* +To be implemented in the future, user can specify the wavelength response +of the photodiode +*/ +double Detector::wavelength_dependent_responsivity(const double &wavelength) +{ + (void)wavelength; + if(true) + { + return m_responsivity_A_W; + } + else + { + // custom responsivity curve + return 0; // should return the new responsivity + } +} + +void Detector::init() +{ + std::random_device rd; // Will be used to obtain a seed for the random number engine + m_rngGen.seed(rd()); +} diff --git a/src/devices/detector.h b/src/devices/detector.h new file mode 100644 index 0000000..d2e5e65 --- /dev/null +++ b/src/devices/detector.h @@ -0,0 +1,89 @@ +#pragma once + +#include <systemc.h> +#include <fstream> +#include <random> + +#include <optical_output_port.h> +#include <optical_signal.h> +#include "specs.h" +#include "spx_module.h" + +// TODO: rename to photodetector +class Detector : public spx_module { +public: + // Ports + spx::oa_port_in_type p_in; + spx::ea_port_out_type p_readout; // TODO: divide into cathode and anode + double m_cur_readout; + double m_cur_readout_no_interf; + + // Input memory for multi-wavelength purposes + std::map<uint32_t,OpticalSignal::field_type> m_memory_in; + + // Detector enable signal + spx::ed_signal_type enable; + + // Member variables + double m_responsivity_A_W; + double m_darkCurrent_A; + double m_opFreq_Hz; + double m_temp_K; + double m_equivR_Ohm; + double m_iTIA; // A/sqrt(Hz) + bool m_noiseBypass; + double m_sampling_time; + + // if each photodiode has an independent RNG device + std::default_random_engine m_rngGen; + std::normal_distribution<double> m_rngDist; + + sc_event m_event_manual_trigger; + + // Init all parameters + void init(); + + // Function that generates the noise applied to the output of this module + double noise_gen(const double &noiseless_readout); + double wavelength_dependent_responsivity(const double &wavelength); + + // Processes + void on_port_in_changed(); + void on_time_tick(); + + virtual void trace(sc_trace_file *Tf) const + { + sc_trace(Tf, m_cur_readout, (string(name()) + ".readout").c_str()); + sc_trace(Tf, m_cur_readout_no_interf, (string(name()) + ".readout_no_interference").c_str()); + } + + // Constructor + Detector(sc_module_name name, + double responsivity_A_W = 1, + double darkCurrent_A = 0, // 100e-12 is an OK value + bool noiseBypass = true, + double opFreq_Hz = 1e9, + double temp_K = 300, + double equivR_Ohm = 400, + double iTIA = 10e-12, + double sampling_time = 1e-12) + : spx_module(name) + , m_responsivity_A_W(responsivity_A_W) + , m_darkCurrent_A(darkCurrent_A) + , m_opFreq_Hz(opFreq_Hz) + , m_temp_K(temp_K) + , m_equivR_Ohm(equivR_Ohm) + , m_iTIA(iTIA) + , m_noiseBypass(noiseBypass) + , m_sampling_time(sampling_time) + , m_rngDist(0,1) + { + SC_HAS_PROCESS(Detector); + enable = sc_logic(0); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + + SC_THREAD(on_time_tick); + } +}; diff --git a/src/devices/directional_coupler.cpp b/src/devices/directional_coupler.cpp new file mode 100644 index 0000000..da0872b --- /dev/null +++ b/src/devices/directional_coupler.cpp @@ -0,0 +1,318 @@ +#include "specs.h" +#include <directional_coupler.h> + +using namespace std; + +void DirectionalCouplerUni::on_port_in1_changed() +{ + m_through_power_dB = 10*log10(m_dc_through_coupling_power) - m_dc_loss; + m_cross_power_dB = 10*log10(1.0 - m_dc_through_coupling_power) - m_dc_loss; + + m_memory_in1[0] = 0; // initializing for nan wavelength + + const double transmission_through = pow(10.0, m_through_power_dB / 20.0); + const double transmission_cross = pow(10.0, m_cross_power_dB / 20.0); + + // Pre-calculate S-parameters + OpticalSignal::field_type S13, S14, S23, S24; + S13 = polar(transmission_through, m_through_phase_rad); + S24 = polar(transmission_through, m_through_phase_rad); + S14 = polar(transmission_cross, m_cross_phase_rad); + S23 = polar(transmission_cross, m_cross_phase_rad); + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "through_power = " << norm(S13) << " W/W" << endl; + cout << "cross_power = " << norm(S14)<< " W/W" << endl; + cout << "through_field = " << abs(S13) << "" << endl; + cout << "cross_field = " << abs(S14)<< "" << endl; + cout << "insertion loss = " << m_dc_loss << "dB" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in1.get_interface()))->name(); + cout << " --,__,-> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out1.get_interface()))->name(); + cout << endl; + + cout << (dynamic_cast<spx::oa_signal_type *>(p_in2.get_interface()))->name(); + cout << " --' '-> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out2.get_interface()))->name(); + cout << endl; + + cout << endl; + } + + OpticalSignal p_in1_read; + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + p_in1_read = p_in1->read(); + + auto cur_wavelength_id = p_in1_read.m_wavelength_id; + // Updating the field memory + m_memory_in1[cur_wavelength_id] = p_in1_read.m_field; + + auto s3 = OpticalSignal(m_memory_in1[cur_wavelength_id] * S13 + + m_memory_in2[cur_wavelength_id] * S23 + , cur_wavelength_id); + + auto s4 = OpticalSignal(m_memory_in1[cur_wavelength_id] * S14 + + m_memory_in2[cur_wavelength_id] * S24 + , cur_wavelength_id); + + m_out1_writer.delayedWrite(s3, sc_time(m_delay_ns, SC_NS)); + m_out2_writer.delayedWrite(s4, sc_time(m_delay_ns, SC_NS)); + } +} + +void DirectionalCouplerUni::on_port_in2_changed() +{ + m_through_power_dB = 10*log10(m_dc_through_coupling_power) - m_dc_loss; + m_cross_power_dB = 10*log10(1.0 - m_dc_through_coupling_power) - m_dc_loss; + + m_memory_in2[0] = 0; // initializing for nan wavelength + + const double transmission_through = pow(10.0, m_through_power_dB / 20.0); + const double transmission_cross = pow(10.0, m_cross_power_dB / 20.0); + + // Pre-calculate S-parameters + OpticalSignal::field_type S13, S14, S23, S24; + S13 = polar(transmission_through, m_through_phase_rad); + S24 = polar(transmission_through, m_through_phase_rad); + S14 = polar(transmission_cross, m_cross_phase_rad); + S23 = polar(transmission_cross, m_cross_phase_rad); + + OpticalSignal p_in2_read; + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + p_in2_read = p_in2->read(); + + auto cur_wavelength_id = p_in2_read.m_wavelength_id; + // Updating the field memory + m_memory_in2[cur_wavelength_id] = p_in2_read.m_field; + + auto s3 = OpticalSignal(m_memory_in1[cur_wavelength_id] * S13 + + m_memory_in2[cur_wavelength_id] * S23 + , cur_wavelength_id); + + auto s4 = OpticalSignal(m_memory_in1[cur_wavelength_id] * S14 + + m_memory_in2[cur_wavelength_id] * S24 + , cur_wavelength_id); + + m_out1_writer.delayedWrite(s3, sc_time(m_delay_ns, SC_NS)); + m_out2_writer.delayedWrite(s4, sc_time(m_delay_ns, SC_NS)); + } +} + + +void DirectionalCouplerBi::on_p0_in_changed() +{ + m_through_power_dB = 10*log10(m_dc_through_coupling_power) - m_dc_loss; + m_cross_power_dB = 10*log10(1.0 - m_dc_through_coupling_power) - m_dc_loss; + + m_memory_in0[0] = 0; // initializing for nan wavelength + + const double transmission_through = pow(10.0, m_through_power_dB / 20.0); + const double transmission_cross = pow(10.0, m_cross_power_dB / 20.0); + + // Pre-calculate S-parameters + OpticalSignal::field_type S02, S13, S03, S12; + S02 = polar(transmission_through, m_through_phase_rad); + S13 = polar(transmission_through, m_through_phase_rad); + S03 = polar(transmission_cross, m_cross_phase_rad); + S12 = polar(transmission_cross, m_cross_phase_rad); + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "through_power = " << norm(S02) << " W/W" << endl; + cout << "cross_power = " << norm(S03)<< " W/W" << endl; + cout << "through_field = " << abs(S02) << "" << endl; + cout << "cross_field = " << abs(S03)<< "" << endl; + cout << "insertion loss = " << m_dc_loss << "dB" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_in.get_interface()))->name(); + + cout << " --,__,-> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p2_out.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_in.get_interface()))->name(); + cout << " --' '-> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p3_out.get_interface()))->name(); + cout << endl; + + cout << (dynamic_cast<spx::oa_signal_type *>(p0_out.get_interface()))->name(); + cout << " <-,__,-- "; + cout << (dynamic_cast<spx::oa_signal_type *>(p2_in.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_out.get_interface()))->name(); + cout << " <-' '-- "; + cout << (dynamic_cast<spx::oa_signal_type *>(p3_in.get_interface()))->name(); + cout << endl; + + cout << endl; + } + + OpticalSignal p0_in_read; + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + p0_in_read = p0_in->read(); + + auto cur_wavelength_id = p0_in_read.m_wavelength_id; + + // Updating the field memory + m_memory_in0[cur_wavelength_id] = p0_in_read.m_field; + + auto s2 = OpticalSignal(m_memory_in0[cur_wavelength_id] * S02 + + m_memory_in1[cur_wavelength_id] * S12 + , cur_wavelength_id); + + auto s3 = OpticalSignal(m_memory_in0[cur_wavelength_id] * S03 + + m_memory_in1[cur_wavelength_id] * S13 + , cur_wavelength_id); + + m_p2_out_writer.delayedWrite(s2, sc_time(m_delay_ns, SC_NS)); + m_p3_out_writer.delayedWrite(s3, sc_time(m_delay_ns, SC_NS)); + } +} + +void DirectionalCouplerBi::on_p1_in_changed() +{ + m_through_power_dB = 10*log10(m_dc_through_coupling_power) - m_dc_loss; + m_cross_power_dB = 10*log10(1.0 - m_dc_through_coupling_power) - m_dc_loss; + + m_memory_in1[0] = 0; // initializing for nan wavelength + + const double transmission_through = pow(10.0, m_through_power_dB / 20.0); + const double transmission_cross = pow(10.0, m_cross_power_dB / 20.0); + + // Pre-calculate S-parameters + OpticalSignal::field_type S02, S13, S03, S12; + S02 = polar(transmission_through, m_through_phase_rad); + S13 = polar(transmission_through, m_through_phase_rad); + S03 = polar(transmission_cross, m_cross_phase_rad); + S12 = polar(transmission_cross, m_cross_phase_rad); + + OpticalSignal p1_in_read; + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + p1_in_read = p1_in->read(); + + auto cur_wavelength_id = p1_in_read.m_wavelength_id; + + // Updating the field memory + m_memory_in1[cur_wavelength_id] = p1_in_read.m_field; + + auto s2 = OpticalSignal(m_memory_in0[cur_wavelength_id] * S02 + + m_memory_in1[cur_wavelength_id] * S12 + , cur_wavelength_id); + + auto s3 = OpticalSignal(m_memory_in0[cur_wavelength_id] * S03 + + m_memory_in1[cur_wavelength_id] * S13 + , cur_wavelength_id); + + m_p2_out_writer.delayedWrite(s2, sc_time(m_delay_ns, SC_NS)); + m_p3_out_writer.delayedWrite(s3, sc_time(m_delay_ns, SC_NS)); + } +} + +void DirectionalCouplerBi::on_p2_in_changed() +{ + m_through_power_dB = 10*log10(m_dc_through_coupling_power) - m_dc_loss; + m_cross_power_dB = 10*log10(1.0 - m_dc_through_coupling_power) - m_dc_loss; + + m_memory_in2[0] = 0; // initializing for nan wavelength + + const double transmission_through = pow(10.0, m_through_power_dB / 20.0); + const double transmission_cross = pow(10.0, m_cross_power_dB / 20.0); + + // Pre-calculate S-parameters + OpticalSignal::field_type S02, S13, S03, S12; + S02 = polar(transmission_through, m_through_phase_rad); + S13 = polar(transmission_through, m_through_phase_rad); + S03 = polar(transmission_cross, m_cross_phase_rad); + S12 = polar(transmission_cross, m_cross_phase_rad); + + OpticalSignal p2_in_read; + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + p2_in_read = p2_in->read(); + + auto cur_wavelength_id = p2_in_read.m_wavelength_id; + + // Updating the field memory + m_memory_in2[cur_wavelength_id] = p2_in_read.m_field; + + auto s0 = OpticalSignal(m_memory_in2[cur_wavelength_id] * S02 + + m_memory_in3[cur_wavelength_id] * S03 + , cur_wavelength_id); + + auto s1 = OpticalSignal(m_memory_in2[cur_wavelength_id] * S12 + + m_memory_in3[cur_wavelength_id] * S13 + , cur_wavelength_id); + + m_p0_out_writer.delayedWrite(s0, sc_time(m_delay_ns, SC_NS)); + m_p1_out_writer.delayedWrite(s1, sc_time(m_delay_ns, SC_NS)); + } +} + +void DirectionalCouplerBi::on_p3_in_changed() +{ + m_through_power_dB = 10*log10(m_dc_through_coupling_power) - m_dc_loss; + m_cross_power_dB = 10*log10(1.0 - m_dc_through_coupling_power) - m_dc_loss; + + m_memory_in3[0] = 0; // initializing for nan wavelength + + const double transmission_through = pow(10.0, m_through_power_dB / 20.0); + const double transmission_cross = pow(10.0, m_cross_power_dB / 20.0); + + // Pre-calculate S-parameters + OpticalSignal::field_type S02, S13, S03, S12; + S02 = polar(transmission_through, m_through_phase_rad); + S13 = polar(transmission_through, m_through_phase_rad); + S03 = polar(transmission_cross, m_cross_phase_rad); + S12 = polar(transmission_cross, m_cross_phase_rad); + + OpticalSignal p3_in_read; + + while (true) { + // Wait for a new input signal + wait(); + + // Read current inputs + p3_in_read = p3_in->read(); + + auto cur_wavelength_id = p3_in_read.m_wavelength_id; + + // Updating the field memory + m_memory_in3[cur_wavelength_id] = p3_in_read.m_field; + + auto s0 = OpticalSignal(m_memory_in2[cur_wavelength_id] * S02 + + m_memory_in3[cur_wavelength_id] * S03 + , cur_wavelength_id); + + auto s1 = OpticalSignal(m_memory_in2[cur_wavelength_id] * S12 + + m_memory_in3[cur_wavelength_id] * S13 + , cur_wavelength_id); + + m_p0_out_writer.delayedWrite(s0, sc_time(m_delay_ns, SC_NS)); + m_p1_out_writer.delayedWrite(s1, sc_time(m_delay_ns, SC_NS)); + } +}
\ No newline at end of file diff --git a/src/devices/directional_coupler.h b/src/devices/directional_coupler.h new file mode 100644 index 0000000..1e907a6 --- /dev/null +++ b/src/devices/directional_coupler.h @@ -0,0 +1,133 @@ +#pragma once + +#include <systemc.h> +#include <map> +#include <optical_output_port.h> +#include <optical_signal.h> +#include "spx_module.h" + + +class DirectionalCouplerBase : public spx_module { +public: + // Member variables + double m_delay_ns = 0; + double m_through_phase_rad = 0; + double m_cross_phase_rad = M_PI/2; + double m_dc_through_coupling_power; + + double m_through_power_dB; + double m_cross_power_dB; + double m_dc_loss; // is in dB + + // Constructor + DirectionalCouplerBase(sc_module_name name, + double dc_through_coupling_power = 0.5, + double dc_loss = 0) + : spx_module(name) + , m_dc_through_coupling_power(dc_through_coupling_power) + , m_dc_loss(dc_loss) + { + // nothing to do + } +}; + +class DirectionalCouplerUni : public DirectionalCouplerBase { +public: + // Ports + spx::oa_port_in_type p_in1; + spx::oa_port_in_type p_in2; + spx::oa_port_out_type p_out1; + spx::oa_port_out_type p_out2; + + // Timed ports writers + OpticalOutputPort m_out1_writer; + OpticalOutputPort m_out2_writer; + + // Memory for multi-wavelength purposes + // maybe with vector it has better performance + std::map<uint32_t,OpticalSignal::field_type> m_memory_in1; + std::map<uint32_t,OpticalSignal::field_type> m_memory_in2; + + // Processes + void on_port_in1_changed(); + void on_port_in2_changed(); + + // Constructor + DirectionalCouplerUni(sc_module_name name, + double dc_through_coupling_power = 0.5, + double dc_loss = 0) + : DirectionalCouplerBase(name, dc_through_coupling_power, dc_loss) + , m_out1_writer("out1_delayed_writer", p_out1) + , m_out2_writer("out2_delayed_writer", p_out2) + { + SC_HAS_PROCESS(DirectionalCouplerUni); + + SC_THREAD(on_port_in1_changed); + sensitive << p_in1; + + SC_THREAD(on_port_in2_changed); + sensitive << p_in2; + } +}; + +typedef DirectionalCouplerUni DirectionalCoupler; + +class DirectionalCouplerBi : public DirectionalCouplerBase { +public: + // Ports + /** The optical input ports. */ + spx::oa_port_in_type p0_in; + spx::oa_port_in_type p1_in; + spx::oa_port_in_type p2_in; + spx::oa_port_in_type p3_in; + + /** The optical output ports. */ + spx::oa_port_out_type p0_out; + spx::oa_port_out_type p1_out; + spx::oa_port_out_type p2_out; + spx::oa_port_out_type p3_out; + + // Timed ports writers + OpticalOutputPort m_p0_out_writer; + OpticalOutputPort m_p1_out_writer; + OpticalOutputPort m_p2_out_writer; + OpticalOutputPort m_p3_out_writer; + + // Memory for multi-wavelength purposes + // maybe with vector it has better performance + std::map<uint32_t,OpticalSignal::field_type> m_memory_in0; + std::map<uint32_t,OpticalSignal::field_type> m_memory_in1; + std::map<uint32_t,OpticalSignal::field_type> m_memory_in2; + std::map<uint32_t,OpticalSignal::field_type> m_memory_in3; + + // Processes + void on_p0_in_changed(); + void on_p1_in_changed(); + void on_p2_in_changed(); + void on_p3_in_changed(); + + // Constructor + DirectionalCouplerBi(sc_module_name name, + double dc_through_coupling_power = 0.5, + double dc_loss = 0) + : DirectionalCouplerBase(name, dc_through_coupling_power, dc_loss) + , m_p0_out_writer("p0_out_delayed_writer", p0_out) + , m_p1_out_writer("p1_out_delayed_writer", p1_out) + , m_p2_out_writer("p2_out_delayed_writer", p2_out) + , m_p3_out_writer("p3_out_delayed_writer", p3_out) + { + SC_HAS_PROCESS(DirectionalCouplerBi); + + SC_THREAD(on_p0_in_changed); + sensitive << p0_in; + + SC_THREAD(on_p1_in_changed); + sensitive << p1_in; + + SC_THREAD(on_p2_in_changed); + sensitive << p2_in; + + SC_THREAD(on_p3_in_changed); + sensitive << p3_in; + } +}; diff --git a/src/devices/electrical_value_list_source.cpp b/src/devices/electrical_value_list_source.cpp new file mode 100644 index 0000000..02b6af5 --- /dev/null +++ b/src/devices/electrical_value_list_source.cpp @@ -0,0 +1,67 @@ +#include "specs.h" +#include "electrical_value_list_source.h" + +using std::cout; +using std::cerr; +using std::endl; + +void EVLSource::runner() +{ + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "value list (" << m_values_queue.size() << " values)"; + if (false) + { + cout << ":" << endl; + for (const auto& val : m_values_queue) + cout << "\t" << "@" << sc_time(val.first, SC_SEC) << ": " << val.second << endl; + } + cout << endl; + cout << "--> " << + (dynamic_cast<spx::ea_signal_type *>(p_out.get_interface()))->name() << endl; + cout << endl; + } + + // Wait for enable signal + if (! enable.read().to_bool()) + { + // cout << name() << " waiting for enable" << endl; + wait(enable.posedge_event()); + cout << name() << " was enabled" << endl; + } + + // Emitting 0 at enable (will only go through if there is no value at t=0) + if (m_values_queue.cbegin() == m_values_queue.cend() + || sc_time(m_values_queue.front().first, SC_SEC).value() > 0) + { + cout << "@" << sc_time_stamp() << ", " << name() << " emitted: " << spx::ea_value_type(0) << endl; + p_out->write(spx::ea_value_type(0)); + } + + auto it = m_values_queue.cbegin(); + while (it != m_values_queue.cend()) + { + sc_time now = sc_time_stamp(); + if (it->first < now.to_seconds()) + { + ++it; + continue; + } + sc_time delay = sc_time(it->first, SC_SEC) - now; + + // Wait until next output time + wait(delay); + + auto Vout = it->second; + + // Write value to output + p_out->write(Vout); + cout << "@" << sc_time_stamp() << ", " << name() << " emitted: " << Vout << endl; + + ++it; + } + + // cout << name() << " completed" << endl; + while(true) { wait(); } +} diff --git a/src/devices/electrical_value_list_source.h b/src/devices/electrical_value_list_source.h new file mode 100644 index 0000000..0534784 --- /dev/null +++ b/src/devices/electrical_value_list_source.h @@ -0,0 +1,128 @@ +#pragma once + +#include <systemc.h> +#include <fstream> +#include <algorithm> +#include <vector> +#include <utility> + +#include "strutils.h" +#include "optical_output_port.h" +#include "optical_signal.h" +#include "specs.h" +#include "spx_module.h" + +using std::vector; +using std::pair; + +class EVLSource : public spx_module { +public: + typedef pair<double, spx::ea_value_type> time_value_pair_type; + + // Ports + spx::ea_port_out_type p_out; + + // Signal to emit + vector<time_value_pair_type> m_values_queue; + + // Source emission control + spx::ed_signal_type enable; + + // Processes + void runner(); + + EVLSource(sc_module_name name, const vector<time_value_pair_type> &values = {}) + : spx_module(name) + , m_values_queue(values) + { + sortValues(); + enable = sc_logic(0); + + SC_HAS_PROCESS(EVLSource); + SC_THREAD(runner); + } + + void setValues(const vector<time_value_pair_type> &values) + { + m_values_queue = values; + sortValues(); + } + + void setValues(const string &filename) + { + std::ifstream file(filename); + + if (!file.is_open()) { + cerr << "Error: Cannot open the file." << endl; + exit(1); + } + + string line; + + getline(file, line); + + int lineNumber = 0; + while (getline(file, line)) { + ++lineNumber; + istringstream s(line); + string field; + + double t, V; + + // Skip if line is empty or starts with ; + if (line.empty()) + { + cout << "Skipping empty line." << endl; + continue; + } + // Skip if line starts with ; + if (line[0] == ';') + { + cout << "Skipping commented line: " << line << endl; + continue; + } + + // Read first field (time) + getline(s, field, ','); + strutils::trim(field); + + // Skip header line if it exists + if(lineNumber == 1 && field == "time") + { + cout << "Skipping header line: " << line << endl; + continue; + } + + try { + t = stod(field); + } catch (std::invalid_argument const& ex) { + cerr << "Invalid value for time: \"" << field << "\"" << endl; + exit(1); + } + + // Read second field (V) + getline(s, field, ','); + try { + V = stod(field); + } catch (std::invalid_argument const& ex) { + cerr << "Invalid value for voltage: \"" << field << "\"" << endl; + exit(1); + } + + cout << t << ": " << V << "V" << endl; + m_values_queue.emplace_back(t, V); + } + + file.close(); + sortValues(); + } + + void sortValues() + { + auto cmp = [](const time_value_pair_type& p1, const time_value_pair_type& p2) { + return p1.first < p2.first; + }; + // Stable sort will keep initial ordering for values with identical time + std::stable_sort(m_values_queue.begin(), m_values_queue.end(), cmp); + } +}; diff --git a/src/devices/generic_2x2_coupler.h b/src/devices/generic_2x2_coupler.h new file mode 100644 index 0000000..6cafc17 --- /dev/null +++ b/src/devices/generic_2x2_coupler.h @@ -0,0 +1,86 @@ +#pragma once + +#include "devices/generic_transmission_device.h" + +class Generic2x2Coupler : public GenericTransmissionDevice { +public: + Generic2x2Coupler(sc_module_name name + , const double &k_power = 0.0 + , const double &insertion_loss = 0.0) + : GenericTransmissionDevice(name, 4) + { + setCouplingFactor(k_power); + setInsertionLoss(insertion_loss); + } + + void setCouplingFactor(const double &k_power) + { + assert(isfinite(k_power) && k_power >= 0 && k_power <= 1); + m_k_power = k_power; + } + + void setInsertionLoss(const double &insertion_loss) + { + assert(isfinite(insertion_loss) && insertion_loss >= 0); + m_insertion_loss = insertion_loss; + } + +private: + + virtual void prepareTM() + { + TM.clear(); + TM.resize(nports); + + double lambda0 = 1550e-9; + double transmission_cross = sqrt(m_k_power) * pow(10.0, -m_insertion_loss/20.0); + transmission_cross = max(0.0, min(1.0, transmission_cross)); + double transmission_through = sqrt(1 - m_k_power) * pow(10.0, -m_insertion_loss/20.0); + transmission_through = max(0.0, min(1.0, transmission_through)); + double phi_through = 0.0; + double phi_cross = M_PI / 2.0; + double tau = 0.0; + size_t k; + + // cout << transmission_through << endl; + // cout << transmission_cross << endl; + // cout << m_k_power << endl << endl << endl; + + // (13, 14, 23, 24 are the only active ones) + + // S13 + k = 0*nports + 2; + TM.Mactive[k] = true; + TM.Malpha[k] = {transmission_through}; + TM.Mphi[k] = {phi_through}; + TM.Mtau[k] = {tau}; + + // S14 + k = 0*nports + 3; + TM.Mactive[k] = true; + TM.Malpha[k] = {transmission_cross}; + TM.Mphi[k] = {phi_cross}; + TM.Mtau[k] = {tau}; + + // S23 + k = 1*nports + 2; + TM.Mactive[k] = true; + TM.Malpha[k] = {transmission_cross}; + TM.Mphi[k] = {phi_cross}; + TM.Mtau[k] = {tau}; + + // S24 + k = 1*nports + 3; + TM.Mactive[k] = true; + TM.Malpha[k] = {transmission_through}; + TM.Mphi[k] = {phi_through}; + TM.Mtau[k] = {tau}; + + // cout << TM.Mphi.size() << endl; + // cout << TM.Mphi[0].size() << endl; + // cout << TM.Mphi[1].size() << endl; + } + + double m_insertion_loss; + double m_k_power; // power coupling factor (1-k = transmission factor) +};
\ No newline at end of file diff --git a/src/devices/generic_transmission_device.cpp b/src/devices/generic_transmission_device.cpp new file mode 100644 index 0000000..e709109 --- /dev/null +++ b/src/devices/generic_transmission_device.cpp @@ -0,0 +1,224 @@ +#include "devices/generic_transmission_device.h" + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + SUFFIX + "_" + to_string(IDX)).c_str()) + +using std::size_t; +using std::pow; + +TransmissionMatrix::paramset_type TransmissionMatrix::operator()(const size_t &i, const size_t &j + , const wavelength_type &lambda, const size_t max_order) const +{ + // row/col to index + const size_t k = i * N + j; + + if (Mactive[k] == false) + return {0,0,0}; + + if (max_order == 0) + return {Malpha[k][0], Mphi[k][0], Mtau[k][0]}; + + // Alias relevant taylor series + auto &Malpha_ = Malpha[k]; + auto &Mphi_ = Mphi[k]; + auto &Mtau_ = Mtau[k]; + + // Get initial parameters (values at lambda0) + double alpha = Malpha_[0]; + double phi = Mphi_[0]; + double tau = Mtau_[0]; + + // Calculate distance to lambda0 + const wavelength_type dlambda = lambda - lambda0; + + // Perform taylor expansion of alpha + double dlambda_n_over_fact_n = 1.0; + for (size_t order = 1; order < min(1 + max_order, Malpha_.size()); ++order) + { + double dalpha_over_dlambda_n = Malpha_[order]; + dlambda_n_over_fact_n *= dlambda / order; + alpha += dalpha_over_dlambda_n * dlambda_n_over_fact_n; + } + + // Perform taylor expansion of phi + dlambda_n_over_fact_n = 1.0; + for (size_t order = 1; order < min(1 + max_order, Mphi_.size()); ++order) + { + double dphi_over_dlambda_n = Mphi_[order]; + dlambda_n_over_fact_n *= dlambda / order; + phi += dphi_over_dlambda_n * dlambda_n_over_fact_n; + } + + // Perform taylor expansion of tau + dlambda_n_over_fact_n = 1.0; + for (size_t order = 1; order < min(1 + max_order, Mtau_.size()); ++order) + { + double dtau_over_dlambda_n = Mtau_[order]; + dlambda_n_over_fact_n *= dlambda / order; + tau += dtau_over_dlambda_n * dlambda_n_over_fact_n; + } + + //cout << lambda << ": " << alpha << ", " << fmod(phi, 2*M_PI) << ", " << tau << endl; + return {alpha,phi,tau}; +} + +void GenericTransmissionDevice::pre_init() +{ + ports_in.clear(); + ports_out.clear(); + ports_out_writers.clear(); + + for (size_t i = 0; i < nports; ++i) + { + ports_in.push_back(make_shared<port_in_type>(__modname("_IN", i))); + ports_out.push_back(make_shared<port_out_type>(__modname("_OUT", i))); + ports_out_writers.push_back(make_shared<OpticalOutputPort>(__modname("_OOP", i), (*ports_out[i]))); + ports_out_writers[i]->m_use_deltas = true; + } +} + +void GenericTransmissionDevice::init() +{ + prepareTM(); + assert(nports == TM.N); + for (size_t i = 0; i < nports; ++i) + { + for (size_t j = 0; j < nports; ++j) + { + sc_spawn_options opts; + if (TM.isActive(i, j)) + { + opts.set_sensitivity(ports_in[i].get()); + sc_spawn( sc_bind(&GenericTransmissionDevice::input_on_i_output_on_j, this, i, j), + (string(name()) + "process_" + to_string(i) + "_" + to_string(j)).c_str(), &opts); + } + } + } +} + +string GenericTransmissionDevice::describe() const +{ + return ""s; +} + +void GenericTransmissionDevice::input_on_i(size_t i) +{ + auto last_signal = OpticalSignal(0); + const auto &p_in = (*ports_in[i]); + const bool active = TM.isInputActive(i); + + while(active) + { + // Wait for new input on i_in + wait(); + + // Read new input from i_in + const auto &s = p_in->read(); + + // cout << "received:" << endl << "\t" << s; + + // Compute delta + const auto deltaE_in = s - last_signal; + + // Store new input signal for next change + last_signal = s; + + // Loop on all device ports + for (size_t j = 0; j < nports; ++j) + { + if (!TM.isActive(i,j)) + continue; + // cout << "(i,j):" << i << ", " << j << endl; + + // Get transmission parameters at this wavelength + auto Tij = TM(i, j, s.getWavelength()); + + // Apply parameters + auto deltaE_out = deltaE_in * polar(Tij.alpha, Tij.phi); + + // cout << Tij.alpha << ", " << Tij.phi << ", " << Tij.tau << endl; + + deltaE_out.getNewId(); + + // Schedule writing the change in output port + ports_out_writers[j]->delayedWrite(deltaE_out, sc_time(Tij.tau, SC_SEC)); + } + } + while (true) { wait(); } +} + +void GenericTransmissionDevice::input_on_i_output_on_j(size_t i, size_t j) +{ + auto last_signal = OpticalSignal(0); + const auto &p_in = (*ports_in[i]); + //auto &p_out = (*ports_out[j]); + auto &p_out_writer = (*ports_out_writers[j]); + const bool active = TM.isActive(i, j); + cout << i << ", " << j << " is active" << endl; + + // Block if non active + while (!active) { wait(); } + + complex<double> Sij; + double delay; + + // Wait for first signal to calculate Sij and delay + volatile bool init_done = false; + while (!init_done) + { + // Wait for first input on p_in + wait(); + + // Read new input from i_in + const auto &s = p_in->read(); + + // cout << "received:" << endl << "\t" << s << endl; + + if (isnan(s.getWavelength())) + continue; + + // Find Sij at that wavelength + const auto Tij = TM(i, j, s.getWavelength()); + Sij = polar(Tij.alpha, Tij.phi); + delay = Tij.tau; + + auto deltaE = (s - last_signal) * Sij; + last_signal = s; + p_out_writer.delayedWrite(deltaE, sc_time(delay, SC_SEC)); + + init_done = true; + + // cout << "init done:" << endl << "\t" << norm(Sij) << ", " << arg(Sij) << ", " << delay << endl; + } + + while(true) + { + // Wait for new input on i_in + wait(); + + // Read new input from i_in + const auto &s = p_in->read(); + + if (s.getWavelength() != last_signal.getWavelength()) + { + cerr << "Cannot handle different wavelength (" << __FUNCTION__ << ")" << endl; + cerr << s << endl; + cerr << last_signal << endl; + sc_stop(); + } + + // cout << "received:" << endl << "\t" << s << endl; + + // Compute new delta + auto deltaE = (s - last_signal) * Sij; + + // Store new input signal for next change + last_signal = s; + + //deltaE_out.getNewId(); + + // Schedule writing the change in output port + p_out_writer.delayedWrite(deltaE, sc_time(delay, SC_SEC)); + //wait(SC_ZERO_TIME); + } +}
\ No newline at end of file diff --git a/src/devices/generic_transmission_device.h b/src/devices/generic_transmission_device.h new file mode 100644 index 0000000..bfd110b --- /dev/null +++ b/src/devices/generic_transmission_device.h @@ -0,0 +1,94 @@ +#pragma once + +#define SC_INCLUDE_DYNAMIC_PROCESSES + +#include <systemc.h> +#include <vector> +#include <valarray> +#include "devices/spx_module.h" +#include "optical_signal.h" +#include "optical_output_port.h" + +using std::vector; +using std::valarray; +using std::string; +using std::cout; +using std::endl; +using std::cerr; + +class TransmissionMatrix { +public: + typedef TransmissionMatrix this_type; + typedef double wavelength_type; + typedef double param_type; + typedef valarray<param_type> taylor_series_type; + typedef valarray<taylor_series_type> matrix_type; + typedef struct{ double alpha, phi, tau; } paramset_type; + + size_t N; // Number of ports (= Nrow = Ncol) in the matrix + // Arrays of matrices describing alpha, phi and the group delay via their taylor coefficients (starting from alpha0) + matrix_type Malpha; + matrix_type Mphi; + matrix_type Mtau; + valarray<bool> Mactive; + wavelength_type lambda0; // Wavelength at which the taylor coefficients were calculated + + paramset_type operator()(const size_t &i, const size_t &j, const wavelength_type &lambda, const size_t max_order=2) const; + inline bool isActive(const size_t &i, const size_t &j) const + { return Mactive[i * N + j]; } + inline bool isInputActive(const size_t &i) const + { + bool ret = false; + for (size_t j = 0; j < N; ++j) + ret |= Mactive[i * N + j]; + return ret; + } + + void clear() + { + N = 0; + lambda0 = 0; + Malpha.resize(0); + Mphi.resize(0); + Mtau.resize(0); + Mactive.resize(0); + } + + void resize(size_t nports) + { + N = nports; + Malpha.resize(nports*nports, {0}); + Mphi.resize(nports*nports, {0}); + Mtau.resize(nports*nports, {0}); + Mactive.resize(nports*nports, false); + } +}; + +class GenericTransmissionDevice : public spx_module { +public: + typedef GenericTransmissionDevice this_type; + + /* ------------------------ */ + size_t nports; + vector<shared_ptr<port_in_type>> ports_in; + vector<shared_ptr<port_out_type>> ports_out; + vector<shared_ptr<OpticalOutputPort>> ports_out_writers; + TransmissionMatrix TM; + + /* ------------------------ */ + virtual void pre_init(); + virtual void init(); + virtual string describe() const; + virtual void prepareTM() = 0; + + // Process input on i + void input_on_i(size_t i); + void input_on_i_output_on_j(size_t i, size_t j); + + GenericTransmissionDevice(sc_module_name name, size_t N = 1) + : spx_module(name) + , nports(N) + { + pre_init(); + } +};
\ No newline at end of file diff --git a/src/devices/generic_waveguide.h b/src/devices/generic_waveguide.h new file mode 100644 index 0000000..d704678 --- /dev/null +++ b/src/devices/generic_waveguide.h @@ -0,0 +1,119 @@ +#pragma once + +#include "devices/generic_transmission_device.h" + +using std::isfinite; + +class GenericWaveguide : public GenericTransmissionDevice { +public: + GenericWaveguide(sc_module_name name + , const double &length = 0 + , const double &loss = 0 + , const double &neff = 1 + , const double &ng = 1 + , const double &D = 0 + , const double &lambda0 = 1.55e-6) + : GenericTransmissionDevice(name, 2) + { + cerr << "GenericWaveguide is disabled (not working)." << endl; + exit(1); + + setLength(length); + setLoss(loss); + setEffectiveIndex(neff); + setGroupIndex(ng); + setDispersion(D); + setLambda0(lambda0); + } + + void setLength(const double &length) + { + assert(isfinite(length) && length >= 0); + m_length = length; + } + + void setLoss(const double &loss) + { + cout << loss << endl; + assert(isfinite(loss)); + m_loss = loss; + } + + void setEffectiveIndex(const double &neff) + { + assert(isfinite(neff) && neff >= 0); + m_neff = neff; + } + + void setGroupIndex(const double &ng) + { + assert(isfinite(ng) && ng >= 0); + m_ng = ng; + } + + void setDispersion(const double &D) + { + assert(isfinite(D)); + m_D = D; + } + + void setLambda0(const double &lambda0) + { + assert(isfinite(lambda0) && lambda0 > 0); + m_lambda0 = lambda0; + } + + +private: + + virtual void prepareTM() + { + TM.clear(); + TM.resize(nports); + + const double c = 299792458.0; + double lambda0 = m_lambda0; + double transmission = pow(10.0, -(m_loss * m_length)/20.0); + double two_pi_L = 2 * M_PI * m_length; + double dphi_0 = fmod(two_pi_L * m_neff, 2 * M_PI); + + // The following 2 lines are wrong... + double dphi_1 = - two_pi_L * m_ng / lambda0 / lambda0; // Here it should be -2pi*L*ng/(lambda*lambda0) (instead of lambda0^2) + double dphi_2 = two_pi_L * 2 * m_ng / lambda0 / lambda0 / lambda0; + + double group_delay_0 = m_length * m_ng / c; + double group_delay_1 = m_length * m_D; + + TM.lambda0 = lambda0; + TM.Mactive = {false, true, true, false}; + TM.Malpha = { + {0}, + {transmission}, + {transmission}, + {0}}; + TM.Mphi = { + {0}, + {dphi_0, dphi_1, dphi_2}, + {dphi_0, dphi_1, dphi_2}, + {0}}; + TM.Mtau = { + {0}, + {group_delay_0, group_delay_1}, + {group_delay_0, group_delay_1}, + {0}}; + + // cout << "----------- " << name() << " -----------" << endl; + // cout << "- alpha: " << TM.Malpha[1][0] << " (V/m)/(V/m)" << endl; + // cout << "- transmission: " << pow(TM.Malpha[1][0],2.0) << " W/W" << endl; + // cout << "- phi: " << TM.Mphi[1][0] << " rad" << endl; + // cout << "- dphi/dlambda: " << TM.Mphi[1][1] << " rad/m" << endl; + // cout << "- group delay: " << TM.Mtau[1][0] << " s" << endl; + } + + double m_loss; // loss in dB/m + double m_neff; // real part of neff + double m_ng; // (real part of) ng + double m_D; // dispersion + double m_lambda0; // dispersion + double m_length; // waveguide length +};
\ No newline at end of file diff --git a/src/devices/merger.cpp b/src/devices/merger.cpp new file mode 100644 index 0000000..2aa3e9f --- /dev/null +++ b/src/devices/merger.cpp @@ -0,0 +1,69 @@ +#include <merger.h> +#include <specs.h> + +using namespace std; + +void Merger::on_port_in1_changed() +{ + const double transmission = pow(10.0, - m_attenuation_dB / 20) / sqrt(2); + m_memory_in1[0] = 0; // initializing for nan wavelength + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "transmission = " << pow(transmission, 2) << " W/W" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in1.get_interface()))->name() << endl; + cout << "\t --> \t" << (dynamic_cast<spx::oa_signal_type *>(p_out.get_interface()))->name() << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in2.get_interface()))->name(); + cout << endl; + cout << endl; + } + + OpticalSignal p_in1_read; + + while (true) { + // Wait for a new input signal + wait(); + // Read sum of input signals + p_in1_read = p_in1->read(); + + auto cur_wavelength_id = p_in1_read.m_wavelength_id; + // Updating the field memory + m_memory_in1[cur_wavelength_id] = p_in1_read.m_field; + + auto s = OpticalSignal(m_memory_in1[cur_wavelength_id] + + m_memory_in2[cur_wavelength_id] + , cur_wavelength_id); + + s *= transmission; + + m_out_writer.delayedWrite(s,SC_ZERO_TIME); + } +} + +void Merger::on_port_in2_changed() +{ + const double transmission = pow(10.0, - m_attenuation_dB / 20) / sqrt(2); + m_memory_in2[0] = 0; // initializing for nan wavelength + + OpticalSignal p_in2_read; + + while (true) { + // Wait for a new input signal + wait(); + // Read sum of input signals + p_in2_read = p_in2->read(); + + auto cur_wavelength_id = p_in2_read.m_wavelength_id; + // Updating the field memory + m_memory_in2[cur_wavelength_id] = p_in2_read.m_field; + + auto s = OpticalSignal(m_memory_in1[cur_wavelength_id] + + m_memory_in2[cur_wavelength_id] + , cur_wavelength_id); + + s *= transmission; + + m_out_writer.delayedWrite(s,SC_ZERO_TIME); + } +}
\ No newline at end of file diff --git a/src/devices/merger.h b/src/devices/merger.h new file mode 100644 index 0000000..a3c0704 --- /dev/null +++ b/src/devices/merger.h @@ -0,0 +1,51 @@ +#pragma once + +#include <systemc.h> +#include <map> + +#include <spx_module.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +#include "specs.h" +#include "spx_module.h" + +// A symmetric no-delay merger +class Merger : public spx_module { +public: + // Ports + spx::oa_port_in_type p_in1; + spx::oa_port_in_type p_in2; + spx::oa_port_out_type p_out; + + // Timed ports writers + OpticalOutputPort m_out_writer; + + // Member variables + double m_attenuation_dB; + + // Memory for multi-wavelength purposes + // maybe with vector it has better performance + std::map<uint32_t,OpticalSignal::field_type> m_memory_in1; + std::map<uint32_t,OpticalSignal::field_type> m_memory_in2; + + // Processes + void on_port_in1_changed(); + void on_port_in2_changed(); + + // Constructor + Merger(sc_module_name name, + double attenuation_dB = 0) + : spx_module(name) + , m_out_writer("out_delayed_writer", p_out) + , m_attenuation_dB(attenuation_dB) + { + SC_HAS_PROCESS(Merger); + + SC_THREAD(on_port_in1_changed); + sensitive << p_in1; + + SC_THREAD(on_port_in2_changed); + sensitive << p_in2; + } +}; diff --git a/src/devices/mesh_col.cpp b/src/devices/mesh_col.cpp new file mode 100644 index 0000000..5723b17 --- /dev/null +++ b/src/devices/mesh_col.cpp @@ -0,0 +1,243 @@ +#include <mesh_col.h> + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + +void MeshCol::init_ports() +{ + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing optical input ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_in.clear(); + for(size_t i = 0; i < m_N; i++) + { + p_in.push_back(make_unique<spx::oa_port_in_type>(__modname("IN_", i))); + } + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing optical output ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_out.clear(); + for(size_t i = 0; i < m_N; i++) + { + p_out.push_back(make_unique<spx::oa_port_out_type>(__modname("OUT_", i))); + } + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing electrical input ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_vphi.clear(); + p_vtheta.clear(); + + size_t num_of_electrical_ports = m_N/2; + if ((m_N % 2 == 0) && !(m_j % 2 == 0)) // if even-odd, there is one less MZI + num_of_electrical_ports = m_N/2 - 1; + + + for(size_t i = 0; i < num_of_electrical_ports; i++) + { + p_vphi.push_back(make_unique<sc_in<double>>(__modname("VPHI_", i))); + p_vtheta.push_back(make_unique<sc_in<double>>(__modname("VTHETA_", i))); + } +} + +void MeshCol::init() +{ + if (m_N % 2 == 0) + { + if (m_j % 2 == 0) + init_N_even_j_even(); + else + init_N_even_j_odd(); + } + else + { + if (m_j % 2 == 0) + init_N_odd_j_even(); + else + init_N_odd_j_odd(); + } +} + +/* + For N=4 that's how it looks + 0__ __0 + \/ + 1__/\__1 + + 2__ __2 + \/ + 3__/\__3 + + TODO: snap to 2pi phase instead of setting neff = 0 +*/ +void MeshCol::init_N_even_j_even() +{ + for(size_t i = 0; i < m_N/2; i++) + { + m_mzi.push_back(make_unique<MZI>(__modname("MZI_", i), + m_length_cm, m_attenuation_wg_dB_cm, + m_attenuation_coupler_dB, m_attenuation_ps_dB, + m_neff, m_ng)); + + m_mzi[i]->p_in1(*p_in[2*i]); + m_mzi[i]->p_in2(*p_in[2*i+1]); + m_mzi[i]->p_out1(*p_out[2*i]); + m_mzi[i]->p_out2(*p_out[2*i+1]); + m_mzi[i]->p_vphi(*p_vphi[i]); + m_mzi[i]->p_vtheta(*p_vtheta[i]); + m_mzi[i]->init(); + } +} + + +/* For N=4 that's how it looks + + 0______0 + + 1__ __1 + \/ + 2__/\__2 + + 3______3 + + The empty rows have a waveguide that adds zero phase + but can have loss and time delay. + + TODO: snap to 2pi phase instead of setting neff = 0 + +*/ +void MeshCol::init_N_even_j_odd() +{ + assert(m_N >= 4); + + // Zero neff so it doesn't add any phase + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", 0), + m_length_cm, m_attenuation_wg_dB_cm, + m_neff, m_ng)); + m_wg[0]->p_in(*p_in[0]); + m_wg[0]->p_out(*p_out[0]); + + for(size_t i = 1; i <= m_N/2 - 1; i++) + { + m_mzi.push_back(make_unique<MZI>(__modname("MZI_", i), + m_length_cm, m_attenuation_wg_dB_cm, + m_attenuation_coupler_dB, m_attenuation_ps_dB, + m_neff, m_ng)); + + m_mzi[i - 1]->p_in1(*p_in[2 * i - 1]); + m_mzi[i - 1]->p_in2(*p_in[2 * i]); + m_mzi[i - 1]->p_out1(*p_out[2 * i - 1]); + m_mzi[i - 1]->p_out2(*p_out[2 * i]); + m_mzi[i - 1]->p_vphi(*p_vphi[i - 1]); + m_mzi[i - 1]->p_vtheta(*p_vtheta[i - 1]); + m_mzi[i - 1]->init(); + + } + + // Zero neff so it doesn't add any phase + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", 1), + m_length_cm, m_attenuation_wg_dB_cm, + m_neff, m_ng)); + m_wg[1]->p_in(*p_in[m_N-1]); + m_wg[1]->p_out(*p_out[m_N-1]); + +} + +/* For N=5 that's how it looks + + 0__ __0 + \/ + 1__/\__1 + + 2__ __2 + \/ + 3__/\__3 + + 4______4 + + The empty rows have a waveguide that adds zero phase + but can have loss and time delay. + + TODO: snap to 2pi phase instead of setting neff = 0 + +*/ +void MeshCol::init_N_odd_j_even() +{ + cout << "odd-even" << endl; + for(size_t i = 0; i < m_N/2; i++) + { + m_mzi.push_back(make_unique<MZI>(__modname("MZI_", i), + m_length_cm, m_attenuation_wg_dB_cm, + m_attenuation_coupler_dB, m_attenuation_ps_dB, + m_neff, m_ng)); + + m_mzi[i]->p_in1(*p_in[2*i]); + m_mzi[i]->p_in2(*p_in[2*i+1]); + m_mzi[i]->p_out1(*p_out[2*i]); + m_mzi[i]->p_out2(*p_out[2*i+1]); + m_mzi[i]->p_vphi(*p_vphi[i]); + m_mzi[i]->p_vtheta(*p_vtheta[i]); + m_mzi[i]->init(); + } + // Zero neff so it doesn't add any phase + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", 0), + m_length_cm, m_attenuation_wg_dB_cm, + m_neff, m_ng)); + m_wg[0]->p_in(*p_in[m_N-1]); + m_wg[0]->p_out(*p_out[m_N-1]); +} + +/* For N=5 that's how it looks + + 0______0 + + 1__ __1 + \/ + 2__/\__2 + + 3__ __3 + \/ + 4__/\__4 + + The empty rows have a waveguide that adds zero phase + but can have loss and time delay. + + TODO: snap to 2pi phase instead of setting neff = 0 + +*/ +void MeshCol::init_N_odd_j_odd() +{ + cout << "odd-odd" << endl; + // Zero neff so it doesn't add any phase + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", 0), + m_length_cm, m_attenuation_wg_dB_cm, + m_neff, m_ng)); + m_wg[0]->p_in(*p_in[0]); + m_wg[0]->p_out(*p_out[0]); + + for(size_t i = 1; i <= m_N/2; i++) + { + m_mzi.push_back(make_unique<MZI>(__modname("MZI_", i), + m_length_cm, m_attenuation_wg_dB_cm, + m_attenuation_coupler_dB, m_attenuation_ps_dB, + m_neff, m_ng)); + + m_mzi[i - 1]->p_in1(*p_in[2 * i - 1]); + m_mzi[i - 1]->p_in2(*p_in[2 * i]); + m_mzi[i - 1]->p_out1(*p_out[2 * i - 1]); + m_mzi[i - 1]->p_out2(*p_out[2 * i]); + m_mzi[i - 1]->p_vphi(*p_vphi[i - 1]); + m_mzi[i - 1]->p_vtheta(*p_vtheta[i - 1]); + m_mzi[i - 1]->init(); + } +}
\ No newline at end of file diff --git a/src/devices/mesh_col.h b/src/devices/mesh_col.h new file mode 100644 index 0000000..e0a6066 --- /dev/null +++ b/src/devices/mesh_col.h @@ -0,0 +1,76 @@ +#pragma once + +#include <systemc.h> +#include <specs.h> +#include <spx_module.h> +#include <mzi.h> +#include <waveguide.h> + +/** + * This class implements a single column of an MZI mesh + * specified in the work: Optimal design for universal multiport interferometers + * by Clements et al. (2016). +*/ + +class MeshCol : public spx_module{ +public: + // Ports + vector<unique_ptr<spx::oa_port_in_type>> p_in; + vector<unique_ptr<spx::oa_port_out_type>> p_out; + vector<unique_ptr<sc_in<double>>> p_vphi; + vector<unique_ptr<sc_in<double>>> p_vtheta; + + // Member variables + size_t m_N; // represents the number of inputs of the mesh (rows) + size_t m_j; // represents the current row being evaluated + + // Parameters for the internal MZIs + double m_length_cm; + double m_attenuation_wg_dB_cm; + double m_attenuation_coupler_dB; + double m_attenuation_ps_dB; + double m_neff; + double m_ng; + + // Submodules + vector<unique_ptr<MZI>> m_mzi; + vector<unique_ptr<Waveguide>> m_wg; + + + // Initialization functions + void init_ports(); + void init(); + + void init_N_even_j_even(); + void init_N_even_j_odd(); + + void init_N_odd_j_even(); + void init_N_odd_j_odd(); + + /** Constructor for MZI Mesh Column + * + * @param name name of the module + * @param N number of rows contained in the module + * @param j current column being created, from 0 to N-1 + * */ + MeshCol(sc_module_name name, const size_t &N, const size_t &j, + const double &length_cm = 1e-2, + const double &attenuation_wg_dB_cm = 0, const double &attenuation_coupler_dB = 0, + const double &attenuation_ps_dB = 0, + const double &neff = 2.2111, const double &ng = 2.2637) + : spx_module(name) + , m_N(N) + , m_j(j) + , m_length_cm(length_cm) + , m_attenuation_wg_dB_cm(attenuation_wg_dB_cm) + , m_attenuation_coupler_dB(attenuation_coupler_dB) + , m_attenuation_ps_dB(attenuation_ps_dB) + , m_neff(neff) + , m_ng(ng) + { + assert(N > 1); + assert(j < N); + + init_ports(); + } +};
\ No newline at end of file diff --git a/src/devices/mzi.cpp b/src/devices/mzi.cpp new file mode 100644 index 0000000..6999fd9 --- /dev/null +++ b/src/devices/mzi.cpp @@ -0,0 +1,55 @@ +#include <mzi.h> + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + +using namespace std; + +void MZI::init() +{ + DC1.reset(); + DC2.reset(); + PS1.reset(); + PS2.reset(); + WG1.reset(); + WG2.reset(); + + // Creating instances + WG1 = make_unique<Waveguide>((string(name()) + "/WG1").c_str(), + m_length_cm, m_attenuation_dB_cm, m_neff, m_ng); + WG2 = make_unique<Waveguide>((string(name()) + "/WG2").c_str(), + m_length_cm, m_attenuation_dB_cm, m_neff, m_ng); + DC1 = make_unique<DirectionalCoupler>((string(name()) + "/DC1").c_str(), 0.5, m_attenuation_coupler_dB); + DC2 = make_unique<DirectionalCoupler>((string(name()) + "/DC2").c_str(), 0.5, m_attenuation_coupler_dB); + PS1 = make_unique<PhaseShifter>((string(name()) + "/PS1").c_str(), m_attenuation_ps_dB); + PS2 = make_unique<PhaseShifter>((string(name()) + "/PS2").c_str(), m_attenuation_ps_dB); + + // Connecting + + PS1->p_in(p_in1); + PS1->p_out(w1); + PS1->p_vin(p_vphi); + + DC1->p_in1(w1); + DC1->p_in2(p_in2); + DC1->p_out1(w2); + DC1->p_out2(w5); + + // Upper branch + PS2->p_in(w2); + PS2->p_out(w3); + PS2->p_vin(p_vtheta); + + WG1->p_in(w3); + WG1->p_out(w4); + + // Bottom branch + WG2->p_in(w5); + WG2->p_out(w6); + + // End + DC2->p_in1(w4); + DC2->p_in2(w6); + DC2->p_out1(p_out1); + DC2->p_out2(p_out2); +}
\ No newline at end of file diff --git a/src/devices/mzi.h b/src/devices/mzi.h new file mode 100644 index 0000000..95089ad --- /dev/null +++ b/src/devices/mzi.h @@ -0,0 +1,67 @@ +#pragma once + +#include <systemc.h> + +#include <optical_output_port.h> +#include <optical_signal.h> +#include "specs.h" +#include "spx_module.h" + +#include <directional_coupler.h> +#include <phaseshifter.h> +#include <waveguide.h> + +/** A unidirectional waveguide module. */ +class MZI : public spx_module { +public: + // Ports + /** The optical input ports. */ + spx::oa_port_in_type p_in1, p_in2; + /** The optical output ports. */ + spx::oa_port_out_type p_out1, p_out2; + /** The electrical input ports */ + spx::ea_port_in_type p_vphi, p_vtheta; + + // Member variables + + /** Waveguide-related. */ + double m_length_cm; + double m_attenuation_dB_cm; + double m_neff; + double m_ng; + + /** DC-related */ + double m_attenuation_coupler_dB; + + /** PhaseShifter-related */ + double m_attenuation_ps_dB; + + // Member submodules and wires + spx::oa_signal_type w1, w2, w3, w4, w5, w6; + + unique_ptr<PhaseShifter> PS1, PS2; + unique_ptr<Waveguide> WG1, WG2, WG3; + unique_ptr<DirectionalCoupler> DC1,DC2; + + virtual void init(); + + /** Constructor for MZI + * + * @param name name of the module + * @param length_cm internal branch length in cm + * */ + MZI(sc_module_name name, const double &length_cm = 1e-2, + const double &attenuation_wg_dB_cm = 0, const double &attenuation_coupler_dB = 0, + const double &attenuation_ps_dB = 0, + const double &neff = 2.2111, const double &ng = 2.2637) + : spx_module(name) + , m_length_cm(length_cm) + , m_attenuation_dB_cm(attenuation_wg_dB_cm) + , m_neff(neff) + , m_ng(ng) + , m_attenuation_coupler_dB(attenuation_coupler_dB) + , m_attenuation_ps_dB(attenuation_ps_dB) + { + + } +}; diff --git a/src/devices/mzi_active.cpp b/src/devices/mzi_active.cpp new file mode 100644 index 0000000..4a8b8a8 --- /dev/null +++ b/src/devices/mzi_active.cpp @@ -0,0 +1,206 @@ +#include <mzi_active.h> + +void MZIActiveUni::init() +{ + m_dc1_o1 = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_out1").c_str()); + m_dc1_o2 = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_out2").c_str()); + m_dc2_i1 = make_shared<spx::oa_signal_type>((string(name()) + "/DC2_in1").c_str()); + m_dc2_i2 = make_shared<spx::oa_signal_type>((string(name()) + "/DC2_in2").c_str()); + m_ps_in = make_shared<spx::oa_signal_type>((string(name()) + "/PS1_in").c_str()); + m_ps_out = make_shared<spx::oa_signal_type>((string(name()) + "/PS1_out").c_str()); + + m_wg1 = make_shared<WaveguideUni>((string(name()) + "/WG1").c_str()); + m_wg2 = make_shared<WaveguideUni>((string(name()) + "/WG2").c_str()); + m_wg3 = make_shared<WaveguideUni>((string(name()) + "/WG3").c_str()); + m_dc1 = make_shared<DirectionalCouplerUni>((string(name()) + "/DC1").c_str()); + m_dc2 = make_shared<DirectionalCouplerUni>((string(name()) + "/DC2").c_str()); + m_ps = make_shared<PhaseShifterUni>((string(name()) + "/PS1").c_str()); + + connect_submodules(); +} + +void MZIActiveUni::connect_submodules() +{ + // Parametrizing the instances + + // cast as unidirectional devices + WaveguideUni * const wg1 = dynamic_cast<WaveguideUni *>(m_wg1.get()); + WaveguideUni * const wg2 = dynamic_cast<WaveguideUni *>(m_wg2.get()); + WaveguideUni * const wg3 = dynamic_cast<WaveguideUni *>(m_wg3.get()); + DirectionalCouplerUni * const dc1 = dynamic_cast<DirectionalCouplerUni *>(m_dc1.get()); + DirectionalCouplerUni * const dc2 = dynamic_cast<DirectionalCouplerUni *>(m_dc2.get()); + PhaseShifterUni * const ps = dynamic_cast<PhaseShifterUni *>(m_ps.get()); + + + // Top waveguides are divided by two to preserve + // the same length in the arms + wg1->m_length_cm = m_length_cm/2; + wg1->m_attenuation_dB_cm = m_attenuation_dB_cm; + wg1->m_neff = m_neff; + wg1->m_ng = m_ng; + + wg2->m_length_cm = m_length_cm/2; + wg2->m_attenuation_dB_cm = m_attenuation_dB_cm; + wg2->m_neff = m_neff; + wg2->m_ng = m_ng; + + wg3->m_length_cm = m_length_ref_cm; + wg3->m_attenuation_dB_cm = m_attenuation_dB_cm; + wg3->m_neff = m_neff; + wg3->m_ng = m_ng; + + dc1->m_dc_loss = m_dc_loss_dB; + dc2->m_dc_loss = m_dc_loss_dB; + + ps->m_sensitivity = m_ps_sens_rad_v; + ps->m_attenuation_dB = m_ps_loss_dB; + + // Connecting the blocks + + dc1->p_in1(p_in1); + dc1->p_in2(p_in2); + dc1->p_out1(*m_dc1_o1); + dc1->p_out2(*m_dc1_o2); + + // Top arm + wg1->p_in(*m_dc1_o1); + wg1->p_out(*m_ps_in); + + ps->p_in(*m_ps_in); + ps->p_out(*m_ps_out); + ps->p_vin(p_vin); + + wg2->p_in(*m_ps_out); + wg2->p_out(*m_dc2_i1); + + // Bot arm + wg3->p_in(*m_dc1_o2); + wg3->p_out(*m_dc2_i2); + + dc2->p_in1(*m_dc2_i1); + dc2->p_in2(*m_dc2_i2); + dc2->p_out1(p_out1); + dc2->p_out2(p_out2); +} + +void MZIActiveBi::init() +{ + // forward + m_dc1_p2_out = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_out1_0").c_str()); + m_dc1_p3_out = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_out2_0").c_str()); + m_dc2_p0_in = make_shared<spx::oa_signal_type>((string(name()) + "/DC2_in1_0").c_str()); + m_dc2_p1_in = make_shared<spx::oa_signal_type>((string(name()) + "/DC2_in2_0").c_str()); + m_ps_p0_in = make_shared<spx::oa_signal_type>((string(name()) + "/PS1_in_0").c_str()); + m_ps_p1_out = make_shared<spx::oa_signal_type>((string(name()) + "/PS1_out_0").c_str()); + + // backward + m_dc1_p2_in = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_out1_1").c_str()); + m_dc1_p3_in = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_out2_1").c_str()); + m_dc2_p0_out = make_shared<spx::oa_signal_type>((string(name()) + "/DC2_in1_1").c_str()); + m_dc2_p1_out = make_shared<spx::oa_signal_type>((string(name()) + "/DC1_in2_1").c_str()); + m_ps_p0_out = make_shared<spx::oa_signal_type>((string(name()) + "/PS1_in_1").c_str()); + m_ps_p1_in = make_shared<spx::oa_signal_type>((string(name()) + "/PS1_out_1").c_str()); + + // devices + m_wg1 = make_shared<WaveguideBi>((string(name()) + "/WG1").c_str()); + m_wg2 = make_shared<WaveguideBi>((string(name()) + "/WG2").c_str()); + m_wg3 = make_shared<WaveguideBi>((string(name()) + "/WG3").c_str()); + m_dc1 = make_shared<DirectionalCouplerBi>((string(name()) + "/DC1").c_str()); + m_dc2 = make_shared<DirectionalCouplerBi>((string(name()) + "/DC2").c_str()); + m_ps = make_shared<PhaseShifterBi>((string(name()) + "/PS1").c_str()); + + connect_submodules(); +} + +void MZIActiveBi::connect_submodules() +{ + // Parametrizing the instances + + // cast as unidirectional devices + WaveguideBi * const wg1 = dynamic_cast<WaveguideBi *>(m_wg1.get()); + WaveguideBi * const wg2 = dynamic_cast<WaveguideBi *>(m_wg2.get()); + WaveguideBi * const wg3 = dynamic_cast<WaveguideBi *>(m_wg3.get()); + DirectionalCouplerBi * const dc1 = dynamic_cast<DirectionalCouplerBi *>(m_dc1.get()); + DirectionalCouplerBi * const dc2 = dynamic_cast<DirectionalCouplerBi *>(m_dc2.get()); + PhaseShifterBi * const ps = dynamic_cast<PhaseShifterBi *>(m_ps.get()); + + + // Top waveguides are divided by two to preserve + // the same length in the arms + wg1->m_length_cm = m_length_cm/2; + wg1->m_attenuation_dB_cm = m_attenuation_dB_cm; + wg1->m_neff = m_neff; + wg1->m_ng = m_ng; + + wg2->m_length_cm = m_length_cm/2; + wg2->m_attenuation_dB_cm = m_attenuation_dB_cm; + wg2->m_neff = m_neff; + wg2->m_ng = m_ng; + + wg3->m_length_cm = m_length_ref_cm; + wg3->m_attenuation_dB_cm = m_attenuation_dB_cm; + wg3->m_neff = m_neff; + wg3->m_ng = m_ng; + + dc1->m_dc_loss = m_dc_loss_dB; + dc2->m_dc_loss = m_dc_loss_dB; + + ps->m_sensitivity = m_ps_sens_rad_v; + ps->m_attenuation_dB = m_ps_loss_dB; + + // Connecting the blocks + + { // forward + dc1->p0_in(p0_in); + dc1->p1_in(p1_in); + dc1->p2_out(*m_dc1_p2_out); + dc1->p3_out(*m_dc1_p3_out); + + // Top arm + wg1->p0_in(*m_dc1_p2_out); + wg1->p1_out(*m_ps_p0_in); + + ps->p0_in(*m_ps_p0_in); + ps->p1_out(*m_ps_p1_out); + ps->p_vin(p_vin); + + wg2->p0_in(*m_ps_p1_out); + wg2->p1_out(*m_dc2_p0_in); + + // Bot arm + wg3->p0_in(*m_dc1_p3_out); + wg3->p1_out(*m_ps_p1_out); + + dc2->p0_in(*m_dc2_p0_in); + dc2->p1_in(*m_ps_p1_out); + dc2->p2_out(p2_out); + dc2->p3_out(p3_out); + } + + { // backward + dc1->p0_out(p0_out); + dc1->p1_out(p1_out); + dc1->p2_in(*m_dc1_p2_in); + dc1->p3_in(*m_dc1_p3_in); + + // Top arm + wg1->p0_out(*m_dc1_p2_in); + wg1->p1_in(*m_ps_p0_out); + + ps->p0_out(*m_ps_p0_out); + ps->p1_in(*m_ps_p1_in); + ps->p_vin(p_vin); + + wg2->p0_out(*m_ps_p1_in); + wg2->p1_in(*m_dc2_p0_out); + + // Bot arm + wg3->p0_out(*m_dc1_p3_in); + wg3->p1_in(*m_ps_p1_in); + + dc2->p0_out(*m_dc2_p0_out); + dc2->p1_out(*m_ps_p1_in); + dc2->p2_in(p2_in); + dc2->p3_in(p3_in); + } +}
\ No newline at end of file diff --git a/src/devices/mzi_active.h b/src/devices/mzi_active.h new file mode 100644 index 0000000..890322e --- /dev/null +++ b/src/devices/mzi_active.h @@ -0,0 +1,179 @@ +#pragma once + +#include "specs.h" +#include <systemc.h> +#include <waveguide.h> +#include <phaseshifter.h> +#include <directional_coupler.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +//TODO: pass element's characteristics as argument, for instance, pass an example of waveguide, +// or an example of DC such that it copies. Requires: constructors in each element to build +// by copying. + +class MZIActiveBase : public spx_module { +public: + // Member variables + double m_ps_sens_rad_v; + double m_length_cm; + double m_length_ref_cm; + double m_attenuation_dB_cm; + double m_neff; + double m_ng; + double m_dc_loss_dB; // loss of the splitter/merger + double m_ps_loss_dB; // loss of the phase shifter + + virtual void init() = 0; + virtual void connect_submodules() = 0; + + // Member submodules + shared_ptr<WaveguideBase> m_wg1, m_wg2, m_wg3; + shared_ptr<DirectionalCouplerBase> m_dc1, m_dc2; + shared_ptr<PhaseShifterBase> m_ps; + + /** Constructor for Waveguide + * + * @param name name of the module + * @param m_ps_sens_rad_v sensitivity of phase shifter + * @param m_length_cm length of the phase-shifter arm + * @param m_length_ref_cm length of the reference arm + * @param m_attenuation_dB_cm loss per cm of wgs + * @param m_neff neff of wgs + * @param m_ng ng of wgs + * @param m_dc_loss_dB insertion loss of the y-junctions + * @param m_ps_loss_dB insertion loss of the phase shifter + * */ + MZIActiveBase(sc_module_name name, + double ps_sens_rad_v = 1, + double length_cm = 0, double length_ref_cm = 0, + double attenuation_dB_cm = 0, + double neff = 2.2, double ng = 2.6, double dc_loss_dB = 0, + double ps_loss_dB = 0) + : spx_module(name) + , m_ps_sens_rad_v(ps_sens_rad_v) + , m_length_cm(length_cm) + , m_length_ref_cm(length_ref_cm) + , m_attenuation_dB_cm(attenuation_dB_cm) + , m_neff(neff) + , m_ng(ng) + , m_dc_loss_dB(dc_loss_dB) + , m_ps_loss_dB(ps_loss_dB) + { + } +}; + +class MZIActiveUni : public MZIActiveBase { +public: + // Ports + /** The optical input ports. */ + spx::oa_port_in_type p_in1, p_in2; + /** The optical output ports. */ + spx::oa_port_out_type p_out1, p_out2; + /** The electrical input ports */ + spx::ea_port_in_type p_vin; + + // Wires + shared_ptr<spx::oa_signal_type> m_dc1_o1, m_dc1_o2, m_dc2_i1, m_dc2_i2; + shared_ptr<spx::oa_signal_type> m_ps_in, m_ps_out; + + virtual void init(); + virtual void connect_submodules(); + + /** Constructor for Waveguide + * + * @param name name of the module + * @param m_ps_sens_rad_v sensitivity of phase shifter + * @param m_length_cm length of the phase-shifter arm + * @param m_length_ref_cm length of the reference arm + * @param m_attenuation_dB_cm loss per cm of wgs + * @param m_neff neff of wgs + * @param m_ng ng of wgs + * @param m_dc_loss_dB insertion loss of the y-junctions + * @param m_ps_loss_dB insertion loss of the phase shifter + * */ + MZIActiveUni(sc_module_name name, + double ps_sens_rad_v = 1, + double length_cm = 0, + double length_ref_cm = 0, + double attenuation_dB_cm = 0, + double neff = 2.2, + double ng = 2.6, + double dc_loss_dB = 0, + double ps_loss_dB = 0) + : MZIActiveBase(name, + ps_sens_rad_v, + length_cm, + length_ref_cm, + attenuation_dB_cm, + neff, + ng, + dc_loss_dB, + ps_loss_dB) + { + + } +}; + +typedef MZIActiveUni MZIActive; + +class MZIActiveBi : public MZIActiveBase { +public: + // Ports + /** The optical input ports. */ + spx::oa_port_in_type p0_in; + spx::oa_port_in_type p1_in; + spx::oa_port_in_type p2_in; + spx::oa_port_in_type p3_in; + + /** The optical output ports. */ + spx::oa_port_out_type p0_out; + spx::oa_port_out_type p1_out; + spx::oa_port_out_type p2_out; + spx::oa_port_out_type p3_out; + + /** The electrical input ports */ + spx::ea_port_in_type p_vin; + + // Wires + shared_ptr<spx::oa_signal_type> m_dc1_p2_out, m_dc1_p3_out, m_dc2_p0_in, m_dc2_p1_in; + shared_ptr<spx::oa_signal_type> m_dc1_p2_in, m_dc1_p3_in, m_dc2_p0_out, m_dc2_p1_out; + shared_ptr<spx::oa_signal_type> m_ps_p0_in, m_ps_p1_in, m_ps_p0_out, m_ps_p1_out; + + virtual void init(); + virtual void connect_submodules(); + + /** Constructor for Waveguide + * + * @param name name of the module + * @param m_ps_sens_rad_v sensitivity of phase shifter + * @param m_length_cm length of the phase-shifter arm + * @param m_length_ref_cm length of the reference arm + * @param m_attenuation_dB_cm loss per cm of wgs + * @param m_neff neff of wgs + * @param m_ng ng of wgs + * @param m_dc_loss_dB insertion loss of the y-junctions + * @param m_ps_loss_dB insertion loss of the phase shifter + * */ + MZIActiveBi(sc_module_name name, + double ps_sens_rad_v = 1, + double length_cm = 0, + double length_ref_cm = 0, + double attenuation_dB_cm = 0, + double neff = 2.2, + double ng = 2.6, + double dc_loss_dB = 0, + double ps_loss_dB = 0) + : MZIActiveBase(name, + ps_sens_rad_v, + length_cm, + length_ref_cm, + attenuation_dB_cm, + neff, + ng, + dc_loss_dB, + ps_loss_dB) + { + + } +}; diff --git a/src/devices/octane_cell.cpp b/src/devices/octane_cell.cpp new file mode 100644 index 0000000..1b5c59c --- /dev/null +++ b/src/devices/octane_cell.cpp @@ -0,0 +1,91 @@ +#include <octane_cell.h> + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + +void OctaneCell::init() +{ + if(m_isCompact) + init_compact(); + else + init_full(); +} + +void OctaneCell::init_full() +{ + // Physical parameters of the components + double lambda = 1550e-9; // the wavelength used by the circuit + double neff = 2.2; + double ng = 2.2; + double loss_per_cm = 0; // in waveguide + double loss_merger = 0; + double length_for_2pi = 100*lambda/(neff); + + // Constructing the instances + m_wg1 = make_unique<Waveguide>(__modname("WG_", 0), length_for_2pi, loss_per_cm, neff, ng); + m_wg2 = make_unique<Waveguide>(__modname("WG_", 1), length_for_2pi, loss_per_cm, neff, ng); + m_wg3 = make_unique<Waveguide>(__modname("WG_", 2), length_for_2pi, loss_per_cm, neff, ng); + m_wg4 = make_unique<Waveguide>(__modname("WG_", 3), length_for_2pi, loss_per_cm, neff, ng); + + m_merger = make_unique<Merger>(__modname("Y_", 0), loss_merger); + + m_pcm = make_unique<PCMElement>(__modname("PCM_", 0), m_meltEnergy, m_nStates, 0); + + m_pd = make_unique<Detector>(__modname("PD_", 0)); + + // Connecting + m_wg1->p_in(p_in_r); + m_wg1->p_out(m_merg_in1); + + m_wg2->p_in(p_in_c); + m_wg2->p_out(m_merg_in2); + + m_merger->p_in1(m_merg_in1); + m_merger->p_in2(m_merg_in2); + m_merger->p_out(m_merg_out); + + m_wg3->p_in(m_merg_out); + m_wg3->p_out(m_pcm_in); + + m_pcm->p_in(m_pcm_in); + m_pcm->p_out(m_pcm_out); + + // m_wg4->p_in(m_pcm_in); + m_wg4->p_in(m_pcm_out); + m_wg4->p_out(m_pd_in); + + m_pd->p_in(m_pd_in); + m_pd->p_readout(p_readout); +} + +void OctaneCell::init_compact() +{ + // Physical parameters of the components + double lambda = 1550e-9; // the wavelength used by the circuit + double neff = 2.2; + double ng = 2.2; + double loss_per_cm = 0; // in waveguide + double loss_merger = 0; + double length_for_2pi = 100*lambda/(neff); + + (void)ng; + (void)loss_per_cm; + (void)length_for_2pi; + + m_merger = make_unique<Merger>(__modname("Y_", 0), loss_merger); + + m_pcm = make_unique<PCMElement>(__modname("PCM_", 0), m_meltEnergy, m_nStates, 0); + + m_pd = make_unique<Detector>(__modname("PD_", 0)); + + // Connecting + m_merger->p_in1(p_in_r); + m_merger->p_in2(p_in_c); + m_merger->p_out(m_merg_out); + + m_pcm->p_in(m_merg_out); + m_pcm->p_out(m_pcm_out); + + m_pd->p_in(m_pcm_out); + m_pd->p_readout(p_readout); +}
\ No newline at end of file diff --git a/src/devices/octane_cell.h b/src/devices/octane_cell.h new file mode 100644 index 0000000..aadcd20 --- /dev/null +++ b/src/devices/octane_cell.h @@ -0,0 +1,61 @@ +#pragma once + +#include <systemc.h> +#include <waveguide.h> +#include <pcm_device.h> +#include <merger.h> +#include <detector.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +/** The minimal octane cell composed of merger, waveguides, PCM and a detector. */ +/** For now, all photonic parameters will be internal and constant. The only */ +/** one that can be changed is the PCM levels.*/ + +//TODO: pass element's characteristics as argument, for instance, pass an example of waveguide, +// or an example of DC, PCM such that it copies. Requires: constructors in each element to build +// by copying. + +class OctaneCell : public sc_module { +public: + // Ports + /** The optical input ports. */ + sc_port<sc_signal_in_if<OpticalSignal>> p_in_r, p_in_c; + /** The electrical output port. */ + sc_out<double> p_readout; + + // Member variables + double m_meltEnergy; + bool m_isCompact; + int m_nStates; + + // Wires + sc_signal<OpticalSignal> m_merg_in1, m_merg_in2, m_merg_out, m_pcm_in, m_pcm_out, m_pd_in; + + // Member submodules + unique_ptr<Waveguide> m_wg1, m_wg2, m_wg3, m_wg4; + unique_ptr<Merger> m_merger; + unique_ptr<PCMElement> m_pcm; + unique_ptr<Detector> m_pd; + + // This function should be called right after + // Instantiation (either declaration or make_shared or new) + void init(); + void init_compact(); + void init_full(); + + /** Constructor for Waveguide + * + * @param name name of the module + * @param meltEnergy energy needed to amorphize by one step + * @param nStates number of internal states supported by the PCM + * */ + OctaneCell(sc_module_name name, double meltEnergy = 10e-12, int nStates = 63, bool isCompact = false) + : sc_module(name) + , m_meltEnergy(meltEnergy) + , m_isCompact(isCompact) + , m_nStates(nStates) + { + } + +}; diff --git a/src/devices/octane_matrix.cpp b/src/devices/octane_matrix.cpp new file mode 100644 index 0000000..d8126f3 --- /dev/null +++ b/src/devices/octane_matrix.cpp @@ -0,0 +1,365 @@ +#include <octane_matrix.h> + + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + +#define __outname(SUFFIX, IDX, IDY) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX) + "_" + to_string(IDY)).c_str()) + +using std::size_t; +using std::pow; + +void OctaneMatrix::init_ports() +{ + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing input ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_in_r.clear(); + p_in_c.clear(); + + // cout << "Initializing input ports of " << name() << endl; + + for(size_t i = 0; i < m_rows; i++) + p_in_r.push_back(make_unique<port_in_type>(__modname("IN_R_", i))); + + for(size_t i = 0; i < m_columns; i++) + p_in_c.push_back(make_unique<port_in_type>(__modname("IN_C_", i))); + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing output port matrix + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_readout.clear(); // clearing before start + + // cout << "Initializing output ports of " << name() << endl; + + vector<unique_ptr<sc_out<double>>> temp_vector; + + for(size_t i = 0; i < m_rows; i++) + { + temp_vector.clear(); // moving to new row + for(size_t j = 0; j < m_columns; j++) + { + temp_vector.push_back(make_unique<sc_out<double>>(__outname("PD_", i, j))); + } + p_readout.push_back(std::move(temp_vector)); // adding new row + } + + // cout << "Successful port initialization of " << name() << endl; + +} + +void OctaneMatrix::init() +{ + + double crossing_loss = 0; + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing circuit elements (waveguides, DCs, octanecell) + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + m_optical_connect_horizontal.clear(); + m_optical_connect_vertical.clear(); + m_segment.clear(); + m_cross.clear(); + + // cout << "Initializing submodules of " << name() << endl; + + // Optical wires + unsigned long num_of_nets_horizontal = 3*m_rows*(m_columns-1); + unsigned long num_of_nets_vertical = (m_rows-1)*m_columns; + + for(unsigned long i = 0; i < num_of_nets_horizontal; i++) + m_optical_connect_horizontal.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("wh_", i))); + for(unsigned long i = 0; i < num_of_nets_vertical; i++) + m_optical_connect_vertical.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("wv_", i))); + + // Crossings + for(unsigned long i = 0; i < m_rows; i++) + { // Last column doesn't have crossings, thus the -1 in the loop + for(unsigned long j = 0; j < (m_columns - 1); j++) + { + m_cross.push_back(make_unique<Crossing>(__outname("X_", i, j), crossing_loss)); + } + } + + // Octane segments + bool term_row = false; + bool term_col = false; + double coupling_through_row = 0; + double coupling_through_col = 0; + + for(unsigned long i = 0; i < m_rows; i++) + { + for(unsigned long j = 0; j < m_columns; j++) + { + if(isLastRow(i) && isLastCol(j)) + { + // Last element + term_col = true; + term_row = true; + coupling_through_row = 0; + coupling_through_col = 0; + } + else if(isLastRow(i)) + { + // Term row + term_col = false; + term_row = true; + coupling_through_row = (1.0 - 1.0/(m_columns - j)); + coupling_through_col = 0; + } + else if(isLastCol(j)) + { + // Term col + term_col = true; + term_row = false; + coupling_through_row = 0; + coupling_through_col = (1.0 - 1.0/(m_rows - i)); + } + else + { + // Inner element + term_col = false; + term_row = false; + coupling_through_row = (1.0 - 1.0/(m_columns - j)); + coupling_through_col = (1.0 - 1.0/(m_rows - i)); + } + auto temp_segment = make_unique<OctaneSegment> + ( + __outname("SEG_", i, j), + term_row, term_col, + coupling_through_row, coupling_through_col, + m_meltEnergy, m_nStates, m_isCompact + ); + temp_segment->init(); // mandatory initialization + m_segment.push_back(std::move(temp_segment)); + } + } + + // cout << "Successful module initialization of " << name() << endl; + + // Modules are constructed in their vectors, time to connect ! + connect_submodules(); + +} + +void OctaneMatrix::connect_submodules() +{ + + // cout << "Connecting submodules of " << name() << endl; + + // If there is only one element in the matrix + // the pins are connected directly + if((m_rows == 1) && (m_columns == 1)) + { + // cout << name() << "contains only one element. " << endl; + + m_segment.at(0)->p_in[0]->bind(*p_in_r.at(0)); + m_segment.at(0)->p_in[1]->bind(*p_in_c.at(0)); + m_segment.at(0)->p_readout->bind(*p_readout[0][0]); + + // cout << "Successful connection of " << name() << endl; + return; + } + + // Column vector + if(m_columns == 1) + { + // cout << name() << "contains only one column. " << endl; + + for(unsigned long i = 0; i < m_rows; i++) + { + // in segment, in row is p_in[0] + m_segment.at(i)->p_in[0]->bind(*p_in_r.at(i)); + + if(isFirstRow(i)) // should connect to the port + m_segment.at(i)->p_in[1]->bind(*p_in_c.at(0)); + else // connects to intermediate net which is output of the previous block + m_segment.at(i)->p_in[1]->bind(*m_optical_connect_vertical.at(i-1)); + + if(!isLastRow(i)) // there's only one output in vector segment + m_segment.at(i)->p_out[0]->bind(*m_optical_connect_vertical.at(i)); + + m_segment.at(i)->p_readout->bind(*p_readout[i][0]); + + } + // cout << "Successful connection of " << name() << endl; + return; + } + + // Row vector + if(m_rows == 1) + { + // cout << name() << "contains only one row. " << endl; + + for(unsigned long j = 0; j < m_columns; j++) + { + if(isFirstCol(j)) + { + // in segment, in row is p_in[0] + m_segment.at(j)->p_in[0]->bind(*p_in_r.at(0)); + m_segment.at(j)->p_in[1]->bind(*m_optical_connect_horizontal.at(3*j+1)); + m_segment.at(j)->p_out[0]->bind(*m_optical_connect_horizontal.at(3*j)); + + // in1, out1 are horizontal connections + m_cross.at(j)->p_in1.bind(*m_optical_connect_horizontal.at(3*j)); + m_cross.at(j)->p_in2.bind(*p_in_c.at(j)); + m_cross.at(j)->p_out1.bind(*m_optical_connect_horizontal.at(3*j+2)); + m_cross.at(j)->p_out2.bind(*m_optical_connect_horizontal.at(3*j+1)); + } + else if(!isLastCol(j)) + { // middle element + m_segment.at(j)->p_in[0]->bind(*m_optical_connect_horizontal.at(3*j-1)); + m_segment.at(j)->p_in[1]->bind(*m_optical_connect_horizontal.at(3*j+1)); + m_segment.at(j)->p_out[0]->bind(*m_optical_connect_horizontal.at(3*j)); + + // in1, out1 are horizontal connections + m_cross.at(j)->p_in1.bind(*m_optical_connect_horizontal.at(3*j)); + m_cross.at(j)->p_in2.bind(*p_in_c.at(j)); + m_cross.at(j)->p_out1.bind(*m_optical_connect_horizontal.at(3*j+2)); + m_cross.at(j)->p_out2.bind(*m_optical_connect_horizontal.at(3*j+1)); + } + else + { // last column here + m_segment.at(j)->p_in[0]->bind(*m_optical_connect_horizontal.at(3*j-1)); + m_segment.at(j)->p_in[1]->bind(*p_in_c.at(j)); + } + m_segment.at(j)->p_readout->bind(*p_readout[0][j]); + } + // cout << "Successful connection of " << name() << endl; + return; + } + + // Getting here means it's an actual matrix with more than one element + unsigned long cur_pos; + unsigned long cur_cross; + unsigned long seg_out_h; + unsigned long seg_out_v; + for(unsigned long i = 0; i < m_rows; i++) + { + for(unsigned long j = 0; j < m_columns; j++) + { + cur_pos = m_columns*i + j; + cur_cross = (m_columns-1)*i + j; + seg_out_h = 3*(m_columns-1)*i+3*j; + seg_out_v = m_columns*i+j; + // cout << "cur_pos: " << cur_pos << endl; + // cout << "cur_cross: " << cur_cross << endl; + // cout << "out_h: " << seg_out_h << endl; + // cout << "out_v: " << seg_out_v << endl; + + if(isFirstRow(i) && isFirstCol(j)) + { + // cout << "first element" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*p_in_r.at(i)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_segment.at(cur_pos)->p_out[1]->bind(*m_optical_connect_vertical.at(seg_out_v)); + + m_cross.at(cur_cross)->p_in1.bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_cross.at(cur_cross)->p_in2.bind(*p_in_c.at(j)); + m_cross.at(cur_cross)->p_out1.bind(*m_optical_connect_horizontal.at(seg_out_h+2)); + m_cross.at(cur_cross)->p_out2.bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + } + else if(isFirstRow(i) && !isLastCol(j)) + { + // cout << "first row not last col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*m_optical_connect_horizontal.at(seg_out_h-1)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_segment.at(cur_pos)->p_out[1]->bind(*m_optical_connect_vertical.at(seg_out_v)); + + m_cross.at(cur_cross)->p_in1.bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_cross.at(cur_cross)->p_in2.bind(*p_in_c.at(j)); + m_cross.at(cur_cross)->p_out1.bind(*m_optical_connect_horizontal.at(seg_out_h+2)); + m_cross.at(cur_cross)->p_out2.bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + } + else if(isFirstRow(i) && isLastCol(j)) + { + // cout << "first row last col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*m_optical_connect_horizontal.at(seg_out_h-1)); + m_segment.at(cur_pos)->p_in[1]->bind(*p_in_c.at(j)); + // no row output + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_vertical.at(seg_out_v)); + } + else if(!isFirstRow(i) && !isLastRow(i) && isFirstCol(j)) + { + // cout << "middle row first col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*p_in_r.at(i)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_segment.at(cur_pos)->p_out[1]->bind(*m_optical_connect_vertical.at(seg_out_v)); + + m_cross.at(cur_cross)->p_in1.bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_cross.at(cur_cross)->p_in2.bind(*m_optical_connect_vertical.at(seg_out_v-m_columns)); + m_cross.at(cur_cross)->p_out1.bind(*m_optical_connect_horizontal.at(seg_out_h+2)); + m_cross.at(cur_cross)->p_out2.bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + } + else if(!isFirstRow(i) && !isLastRow(i) && !isLastCol(j)) + { + // cout << "middle row middle col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*m_optical_connect_horizontal.at(seg_out_h-1)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_segment.at(cur_pos)->p_out[1]->bind(*m_optical_connect_vertical.at(seg_out_v)); + + m_cross.at(cur_cross)->p_in1.bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_cross.at(cur_cross)->p_in2.bind(*m_optical_connect_vertical.at(seg_out_v-m_columns)); + m_cross.at(cur_cross)->p_out1.bind(*m_optical_connect_horizontal.at(seg_out_h+2)); + m_cross.at(cur_cross)->p_out2.bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + } + else if(!isFirstRow(i) && !isLastRow(i) && isLastCol(j)) + { + // cout << "middle row last col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*m_optical_connect_horizontal.at(seg_out_h-1)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_vertical.at(seg_out_v-m_columns)); + // no row output + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_vertical.at(seg_out_v)); + } + else if(isLastRow(i) && isFirstCol(j)) + { + // cout << "last row first col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*p_in_r.at(i)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_horizontal.at(seg_out_h)); + + m_cross.at(cur_cross)->p_in1.bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_cross.at(cur_cross)->p_in2.bind(*m_optical_connect_vertical.at(seg_out_v-m_columns)); + m_cross.at(cur_cross)->p_out1.bind(*m_optical_connect_horizontal.at(seg_out_h+2)); + m_cross.at(cur_cross)->p_out2.bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + } + else if(isLastRow(i) && !isLastCol(j)) + { + // cout << "last row middle col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*m_optical_connect_horizontal.at(seg_out_h-1)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + m_segment.at(cur_pos)->p_out[0]->bind(*m_optical_connect_horizontal.at(seg_out_h)); + + m_cross.at(cur_cross)->p_in1.bind(*m_optical_connect_horizontal.at(seg_out_h)); + m_cross.at(cur_cross)->p_in2.bind(*m_optical_connect_vertical.at(seg_out_v-m_columns)); + m_cross.at(cur_cross)->p_out1.bind(*m_optical_connect_horizontal.at(seg_out_h+2)); + m_cross.at(cur_cross)->p_out2.bind(*m_optical_connect_horizontal.at(seg_out_h+1)); + } + else if(isLastRow(i) && isLastCol(j)) + { + // cout << "last row last col" << endl; + m_segment.at(cur_pos)->p_in[0]->bind(*m_optical_connect_horizontal.at(seg_out_h-1)); + m_segment.at(cur_pos)->p_in[1]->bind(*m_optical_connect_vertical.at(seg_out_v-m_columns)); + } + else + cout<< endl << endl << "This condition should not appear" << endl << endl; + + m_segment.at(cur_pos)->p_readout->bind(*p_readout[i][j]); + + } + } +}
\ No newline at end of file diff --git a/src/devices/octane_matrix.h b/src/devices/octane_matrix.h new file mode 100644 index 0000000..afcf06a --- /dev/null +++ b/src/devices/octane_matrix.h @@ -0,0 +1,99 @@ +#pragma once + +#include <systemc.h> +#include <octane_segment.h> +#include <crossing.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +// TODO: remove these (are in spx_module.h) +typedef sc_signal_in_if<OpticalSignal > if_in_type; +typedef sc_signal_out_if<OpticalSignal > if_out_type; +typedef sc_port<if_in_type> port_in_type; +typedef sc_port<if_out_type> port_out_type; + + +/** Building block for the OCTANE circuit + * The current implementation includes all + * intermediate components allowing modelling of imperfections, + * but at the cost of increased module count. + * + * A simpler way would be to disregard all intermediate waveguides + * and model their effects on `octane_cell` + * + * Maybe I could add an argument to init(bool isCompact), defining + * if the model will be compact or not. +*/ + +//TODO: pass element's characteristics as argument, for instance, pass an example of waveguide, +// or an example of DC, PCM such that it copies. Requires: constructors in each element to build +// by copying. + +class OctaneMatrix : public sc_module { +public: + // Ports + /** The optical input ports. */ + vector<unique_ptr<port_in_type>> p_in_r; + vector<unique_ptr<port_in_type>> p_in_c; + + /** The optical output ports. */ + vector<unique_ptr<port_out_type>> p_out; + + /** The electric output ports in matrix format*/ + // TODO: verify if a matrix library should be used + vector<vector<unique_ptr<sc_out<double>>>> p_readout; + + // Define the size of the matrix + std::size_t m_rows; + std::size_t m_columns; + + bool m_isCompact; + + // For internal octane_cell + double m_meltEnergy; + int m_nStates; + + // Wires + vector<unique_ptr<sc_signal<OpticalSignal>>> m_optical_connect_horizontal; + vector<unique_ptr<sc_signal<OpticalSignal>>> m_optical_connect_vertical; + + // Member submodules + vector<unique_ptr<Crossing>> m_cross; + vector<unique_ptr<OctaneSegment>> m_segment; + + //Init() must be called after declaration + void init(); + void init_ports(); + void connect_submodules(); + + // auxiliar functions for readability + // they were written with 0 to N-1 indexing in mind! + inline bool isFirstRow(unsigned long i){return (i==0);} + bool isFirstCol(unsigned long j){return (j==0);} + bool isLastRow(unsigned long i){return (i==m_rows-1);} + bool isLastCol(unsigned long j){return (j==m_columns-1);} + + /** Constructor for Octane Matrix + * + * @param name name of the module + * @param meltEnergy energy needed to amorphize by one step + * @param nStates number of internal states supported by the PCM + * */ + OctaneMatrix(sc_module_name name, std::size_t rows, std::size_t columns, + double meltEnergy = 10e-12, int nStates = 63, bool isCompact = false) + : sc_module(name) + , m_rows(rows) + , m_columns(columns) + , m_isCompact(isCompact) + , m_meltEnergy(meltEnergy) + , m_nStates(nStates) + { + + assert(rows > 0); + assert(columns > 0); + + init_ports(); // At least the ports should always be + // in the constructor + } + +}; diff --git a/src/devices/octane_segment.cpp b/src/devices/octane_segment.cpp new file mode 100644 index 0000000..32dcd84 --- /dev/null +++ b/src/devices/octane_segment.cpp @@ -0,0 +1,396 @@ +#include <octane_segment.h> + + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + +using std::size_t; +using std::pow; + +void OctaneSegment::init_ports() +{ + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing input ports + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_in.clear(); + + // cout << "Initializing input ports of " << name() << endl; + // 0 is row, 1 is column + p_in.push_back(make_unique<port_in_type>("IN_R")); + p_in.push_back(make_unique<port_in_type>("IN_C")); + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing output ports based on termination + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + p_out.clear(); + + // cout << "Initializing output ports of " << name() << endl; + // If there is only one output, the vector has only one element + if (m_term_row && m_term_col) + { + ; // no optical output + } + else if(m_term_row) + { + // Last row, so only has row outputs + p_out.push_back(make_unique<port_out_type>("OUT_R")); + } + else if(m_term_col) + { + // Last column, so only has only column outputs + p_out.push_back(make_unique<port_out_type>("OUT_C")); + } + else + { + // Internal elements have both outputs + p_out.push_back(make_unique<port_out_type>("OUT_R")); + p_out.push_back(make_unique<port_out_type>("OUT_C")); + } + p_readout = make_unique<sc_out<double>>("OUT_PD"); + + // cout << "Successful port initialization of " << name() << endl; + +} + +void OctaneSegment::init() +{ + if(m_isCompact) + init_compact(); + else + init_full(); + +} + +void OctaneSegment::init_full() +{ + // Physical parameters of the components + double lambda = 1550e-9; // the wavelength used by the circuit + double neff = 2.2; + double ng = 2.2; + double loss_per_cm = 0; // in waveguide + double dc_loss = 0; + double length_for_2pi = 100*lambda/(neff); + double length_for_pi_2 = length_for_2pi/4; + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing circuit elements (waveguides, DCs, octanecell) + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + m_wg.clear(); + m_dc.clear(); + m_optical_connect.clear(); + + // cout << "Initializing submodules of " << name() << endl; + + m_oct = make_unique<OctaneCell>(__modname("OCT_", 0), m_meltEnergy, m_nStates, m_isCompact); + m_oct->init(); + + if (m_term_row && m_term_col) + { + // Last element + for(size_t i = 0; i < 2; i++) + { + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", i), length_for_2pi, loss_per_cm, neff, ng)); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", i))); + } + } + else if(m_term_row) + { + // Last row + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_R_", 0), m_coupling_through_row, dc_loss)); + for(size_t i = 0; i < 4; i++) + { + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", i), length_for_2pi, loss_per_cm, neff, ng)); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", i))); + } + // Adjusting the last waveguide to give pi/2 shift + // compensating for the lack of DC + m_wg.at(3)->m_length_cm = length_for_2pi + length_for_pi_2; + // We have one extra wire with respect to waveguides + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 4))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 0))); // terminator + } + else if(m_term_col) + { + // Last column + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_C_", 0), m_coupling_through_col, dc_loss)); + for(size_t i = 0; i < 4; i++) + { + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", i), length_for_2pi, loss_per_cm, neff, ng)); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", i))); + } + // Adjusting the last waveguide to give pi/2 shift + // compensating for the lack of DC + m_wg.at(3)->m_length_cm = length_for_2pi + length_for_pi_2; + // We have one extra wire with respect to waveguides + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 4))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 0))); // terminator + } + else + { + // Internal element + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_R_", 0), m_coupling_through_row, dc_loss)); + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_C_", 0), m_coupling_through_col, dc_loss)); + for(size_t i = 0; i < 6; i++) + { + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", i), length_for_2pi, loss_per_cm, neff, ng)); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", i))); + } + // We have two extra wires with respect to waveguides + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 6))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 7))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 0))); // terminator + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 1))); // terminator + } + + // cout << "Successful module initialization of " << name() << endl; + + // Modules are constructed in their vectors, time to connect ! + connect_submodules_full(); + +} + +void OctaneSegment::connect_submodules_full() +{ + + // cout << "Connecting submodules of " << name() << endl; + + if (m_term_row && m_term_col) + { + // Last element + m_wg.at(0)->p_in(*p_in.at(0)); + m_wg.at(0)->p_out(*m_optical_connect.at(0)); + + m_wg.at(1)->p_in(*p_in.at(1)); + m_wg.at(1)->p_out(*m_optical_connect.at(1)); + + m_oct->p_in_r(*m_optical_connect.at(0)); + m_oct->p_in_c(*m_optical_connect.at(1)); + + } + else if(m_term_row) + { + // Last row + m_wg.at(0)->p_in(*p_in.at(0)); // input at row + m_wg.at(0)->p_out(*m_optical_connect.at(0)); + + m_dc.at(0)->p_in1(*m_optical_connect.at(0)); + m_dc.at(0)->p_in2(*m_optical_connect.at(5)); // Terminated + m_dc.at(0)->p_out1(*m_optical_connect.at(1)); // Through + m_dc.at(0)->p_out2(*m_optical_connect.at(2)); // Cross + + m_wg.at(1)->p_in(*m_optical_connect.at(1)); + m_wg.at(1)->p_out(*p_out.at(0)); // Out row + + m_wg.at(2)->p_in(*m_optical_connect.at(2)); + m_wg.at(2)->p_out(*m_optical_connect.at(3)); + + // Side without DC (must be conmpensated with pi/2) + m_wg.at(3)->p_in(*p_in.at(1)); + m_wg.at(3)->p_out(*m_optical_connect.at(4)); + + m_oct->p_in_r(*m_optical_connect.at(3)); + m_oct->p_in_c(*m_optical_connect.at(4)); + } + else if(m_term_col) + { + // Last column + m_wg.at(0)->p_in(*p_in.at(1)); // input at col + m_wg.at(0)->p_out(*m_optical_connect.at(0)); + + m_dc.at(0)->p_in1(*m_optical_connect.at(0)); + m_dc.at(0)->p_in2(*m_optical_connect.at(5)); // Terminated + m_dc.at(0)->p_out1(*m_optical_connect.at(1)); // Through + m_dc.at(0)->p_out2(*m_optical_connect.at(2)); // Cross + + m_wg.at(1)->p_in(*m_optical_connect.at(1)); + m_wg.at(1)->p_out(*p_out.at(0)); // Out column + + m_wg.at(2)->p_in(*m_optical_connect.at(2)); + m_wg.at(2)->p_out(*m_optical_connect.at(3)); + + // Side without DC (must be conmpensated with pi/2) + m_wg.at(3)->p_in(*p_in.at(0)); + m_wg.at(3)->p_out(*m_optical_connect.at(4)); + + m_oct->p_in_r(*m_optical_connect.at(4)); + m_oct->p_in_c(*m_optical_connect.at(3)); + } + else + { + // Internal element + m_wg.at(0)->p_in(*p_in.at(0)); // input at row + m_wg.at(0)->p_out(*m_optical_connect.at(0)); + + m_dc.at(0)->p_in1(*m_optical_connect.at(0)); + m_dc.at(0)->p_in2(*m_optical_connect.at(8)); // Terminated + m_dc.at(0)->p_out1(*m_optical_connect.at(1)); // Through + m_dc.at(0)->p_out2(*m_optical_connect.at(2)); // Cross + + m_wg.at(1)->p_in(*m_optical_connect.at(1)); + m_wg.at(1)->p_out(*p_out.at(0)); // Out row + + m_wg.at(2)->p_in(*m_optical_connect.at(2)); + m_wg.at(2)->p_out(*m_optical_connect.at(3)); + + m_wg.at(3)->p_in(*p_in.at(1)); + m_wg.at(3)->p_out(*m_optical_connect.at(4)); + + m_dc.at(1)->p_in1(*m_optical_connect.at(4)); + m_dc.at(1)->p_in2(*m_optical_connect.at(9)); // Terminated + m_dc.at(1)->p_out1(*m_optical_connect.at(5)); // Through + m_dc.at(1)->p_out2(*m_optical_connect.at(6)); // Cross + + m_wg.at(4)->p_in(*m_optical_connect.at(5)); + m_wg.at(4)->p_out(*p_out.at(1)); // Out col + + m_wg.at(5)->p_in(*m_optical_connect.at(6)); + m_wg.at(5)->p_out(*m_optical_connect.at(7)); + + m_oct->p_in_r(*m_optical_connect.at(3)); + m_oct->p_in_c(*m_optical_connect.at(7)); + } + m_oct->p_readout(*p_readout); + + // cout << "Successful connection of " << name() << endl; + +} + +void OctaneSegment::init_compact() +{ + // Physical parameters of the components + double lambda = 1550e-9; // the wavelength used by the circuit + double neff = 2.2; + double ng = 2.2; + double loss_per_cm = 0; // in waveguide + double dc_loss = 0; + double length_for_2pi = 100*lambda/(neff); + double length_for_pi_2 = length_for_2pi/4; + + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + // Initializing circuit elements (waveguides, DCs, octanecell) + // --------------------------------------------------------------------------// + // --------------------------------------------------------------------------// + + m_wg.clear(); + m_dc.clear(); + m_optical_connect.clear(); + + // cout << "Initializing submodules of " << name() << endl; + + m_oct = make_unique<OctaneCell>(__modname("OCT_", 0), m_meltEnergy, m_nStates, m_isCompact); + m_oct->init(); + + if (m_term_row && m_term_col) + { + ; + } + else if(m_term_row) + { + // Last row + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_R_", 0), m_coupling_through_row, dc_loss)); + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", 0), length_for_pi_2, loss_per_cm, neff, ng)); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 0))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 1))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 0))); // terminator + } + else if(m_term_col) + { + // Last column + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_C_", 0), m_coupling_through_col, dc_loss)); + m_wg.push_back(make_unique<Waveguide>(__modname("WG_", 0), length_for_pi_2, loss_per_cm, neff, ng)); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 0))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 1))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 0))); // terminator + } + else + { + // Internal element + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_R_", 0), m_coupling_through_row, dc_loss)); + m_dc.push_back(make_unique<DirectionalCoupler>(__modname("DC_C_", 0), m_coupling_through_col, dc_loss)); + // We have two extra wires with respect to waveguides + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 0))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("W_", 1))); + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 0))); // terminator + m_optical_connect.push_back(make_unique<sc_signal<OpticalSignal>>(__modname("TERM_", 1))); // terminator + } + + // cout << "Successful module initialization of " << name() << endl; + + // Modules are constructed in their vectors, time to connect ! + connect_submodules_compact(); + +} + +void OctaneSegment::connect_submodules_compact() +{ + + // cout << "Connecting submodules of " << name() << endl; + + if (m_term_row && m_term_col) + { + // Last element + m_oct->p_in_r(*p_in.at(0)); + m_oct->p_in_c(*p_in.at(1)); + + } + else if(m_term_row) + { + // Last row + m_dc.at(0)->p_in1(*p_in.at(0)); + m_dc.at(0)->p_in2(*m_optical_connect.at(2)); // Terminated + m_dc.at(0)->p_out1(*p_out.at(0)); // Through + m_dc.at(0)->p_out2(*m_optical_connect.at(0)); // Cross + + // Side without DC (must be conmpensated with pi/2) + m_wg.at(0)->p_in(*p_in.at(1)); + m_wg.at(0)->p_out(*m_optical_connect.at(1)); + + m_oct->p_in_r(*m_optical_connect.at(0)); + m_oct->p_in_c(*m_optical_connect.at(1)); + } + else if(m_term_col) + { + // Last column + m_dc.at(0)->p_in1(*p_in.at(1)); + m_dc.at(0)->p_in2(*m_optical_connect.at(2)); // Terminated + m_dc.at(0)->p_out1(*p_out.at(0)); // Through + m_dc.at(0)->p_out2(*m_optical_connect.at(0)); // Cross + + // Side without DC (must be conmpensated with pi/2) + m_wg.at(0)->p_in(*p_in.at(0)); + m_wg.at(0)->p_out(*m_optical_connect.at(1)); + + m_oct->p_in_r(*m_optical_connect.at(1)); + m_oct->p_in_c(*m_optical_connect.at(0)); + } + else + { + // Internal element + m_dc.at(0)->p_in1(*p_in.at(0)); + m_dc.at(0)->p_in2(*m_optical_connect.at(2)); // Terminated + m_dc.at(0)->p_out1(*p_out.at(0)); // Through + m_dc.at(0)->p_out2(*m_optical_connect.at(0)); // Cross + + m_dc.at(1)->p_in1(*p_in.at(1)); + m_dc.at(1)->p_in2(*m_optical_connect.at(3)); // Terminated + m_dc.at(1)->p_out1(*p_out.at(1)); // Through + m_dc.at(1)->p_out2(*m_optical_connect.at(1)); // Cross + + m_oct->p_in_r(*m_optical_connect.at(0)); + m_oct->p_in_c(*m_optical_connect.at(1)); + } + m_oct->p_readout(*p_readout); + + // cout << "Successful connection of " << name() << endl; + +}
\ No newline at end of file diff --git a/src/devices/octane_segment.h b/src/devices/octane_segment.h new file mode 100644 index 0000000..ea28f03 --- /dev/null +++ b/src/devices/octane_segment.h @@ -0,0 +1,98 @@ +#pragma once + +#include <systemc.h> +#include <waveguide.h> +#include <directional_coupler.h> +#include <octane_cell.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +// TODO: remove these (are in spx_module.h) +typedef sc_signal_in_if<OpticalSignal > if_in_type; +typedef sc_signal_out_if<OpticalSignal > if_out_type; +typedef sc_port<if_in_type> port_in_type; +typedef sc_port<if_out_type> port_out_type; + + +/** Building block for the OCTANE circuit + * The current implementation includes all + * intermediate components allowing modelling of imperfections, + * but at the cost of increased module count. + * + * A simpler way would be to disregard all intermediate waveguides + * and model their effects on `octane_cell` + * + * Maybe I could add an argument to init(bool isCompact), defining + * if the model will be compact or not. +*/ + +//TODO: pass element's characteristics as argument, for instance, pass an example of waveguide, +// or an example of DC, PCM such that it copies. Requires: constructors in each element to build +// by copying. + +class OctaneSegment : public sc_module { +public: + // Ports + /** The optical input ports. */ + vector<unique_ptr<port_in_type>> p_in; + + /** The optical output ports. */ + vector<unique_ptr<port_out_type>> p_out; + + /** The electric output port*/ + unique_ptr<sc_out<double>> p_readout; + + // Member variables + // Defines the number of ports and elements + bool m_term_row; + bool m_term_col; + bool m_isCompact; + + // Defines the coupling in the DCs (should change as more elements are added) + double m_coupling_through_row; + double m_coupling_through_col; + + // For internal octane_cell + double m_meltEnergy; + int m_nStates; + + + // Wires + vector<unique_ptr<sc_signal<OpticalSignal>>> m_optical_connect; + + // Member submodules + vector<unique_ptr<Waveguide>> m_wg; + vector<unique_ptr<DirectionalCoupler>> m_dc; + unique_ptr<OctaneCell> m_oct; + + // init() should be called after declaration + void init(); + void init_compact(); + void init_full(); + void init_ports(); + void connect_submodules_full(); + void connect_submodules_compact(); + + /** Constructor for Octane Segment + * + * @param name name of the module + * @param meltEnergy energy needed to amorphize by one step + * @param nStates number of internal states supported by the PCM + * */ + OctaneSegment(sc_module_name name, bool term_row, bool term_col, + double coupling_through_row, double coupling_through_col, + double meltEnergy, int nStates, bool isCompact = false) + : sc_module(name) + , m_term_row(term_row) + , m_term_col(term_col) + , m_isCompact(isCompact) + , m_coupling_through_row(coupling_through_row) + , m_coupling_through_col(coupling_through_col) + , m_meltEnergy(meltEnergy) + , m_nStates(nStates) + { + init_ports(); // At least the ports should always be + // in the constructor + } + +}; diff --git a/src/devices/pcm_device.cpp b/src/devices/pcm_device.cpp new file mode 100644 index 0000000..dc018da --- /dev/null +++ b/src/devices/pcm_device.cpp @@ -0,0 +1,150 @@ +#include <algorithm> +#include <iostream> + +#include <pcm_device.h> + +#define ZERO_PULSE_THRESHOLD (1e-10) + +using namespace std; + +void PCMElement::on_input_changed() +{ + // setting the transmission for the initial state + update_transmission_local(); + + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "Emelt = " << m_meltEnergy*1e9 << " nJ" << endl; + cout << "Nstates = " << m_nStates << "" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in.get_interface()))->name(); + cout << " --> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out.get_interface()))->name(); + cout << endl; + cout << endl; + } + + m_last_pulse_power = 0; + bool in_window = false; + vector<pulse_sample_t> vector_of_samples; + uint32_t cur_wavelength_id; + m_memory_in[0] = 0; + double total_in_power = 0; + + while (true) { + // Wait next input change + wait(); + + // Read signal and store field in memory for that wavelength + auto s = p_in->read(); + cur_wavelength_id = s.m_wavelength_id; + m_memory_in[cur_wavelength_id] = s.m_field; + + // Summing powers of all wavelengths + total_in_power = 0; + for (auto lambdaID_field : m_memory_in) + { + total_in_power += norm(lambdaID_field.second); + } + + // Storage of optical state on the input + const sc_time &now = sc_time_stamp(); + + bool last_was_zero = m_last_pulse_power < ZERO_PULSE_THRESHOLD; + bool current_is_zero = total_in_power < ZERO_PULSE_THRESHOLD; + bool rising_edge = last_was_zero && !current_is_zero; + if (!rising_edge) + { + // Enter here when: + // - a signal is received on top of another one (pulse intersect) + // - a signal ends (power falls to 0) + + // Record the event + vector_of_samples.emplace_back(now.to_seconds(), total_in_power); + } + else + { + // Enter here when: + // - a signal starts (power rises from 0 to non-0 value) + // This case is necessarily the first rise + + // Will unroll events and check if there was a phase change before according to + // the vector and advance the state accordingly to get the transmission + // cout << "\t\t first rise detected" << endl; + in_window = phase_change(vector_of_samples, true); + if (!in_window) + vector_of_samples.clear(); + + // Record the current event + vector_of_samples.emplace_back(now.to_seconds(), total_in_power); + } + + m_last_pulse_power = total_in_power; + + // Write attenuated signal to output + s *= m_transmission; + s.getNewId(); + + m_out_writer.delayedWrite(s, SC_ZERO_TIME); + } +} + +bool PCMElement::phase_change(const vector<pulse_sample_t> &samples, const bool &local) +{ + // Here should decide between sending the + // sim off to external or resolving inside + + // Should set new values for m_state and m_transmission + + double energy_absorbed = 0; + double dur_pulse = 0; + // will return true if we shouldn't erase the vector + bool in_influence_window = false; + + if (samples.empty()) + return true; + + if (sc_time_stamp().to_seconds() - samples.back().first < influence_time_ns*1e-9) + return true; + + if (local) + { + // Integrating power along each duration + // pulse 0 stays at pow[0] for tim[1]-tim[0] seconds + // the last sample is zero in power, just here to get the final time + for (unsigned int i = 0; i < samples.size()-1; i++) + { + dur_pulse = samples[i+1].first - samples[i].first; + energy_absorbed += samples[i].second * dur_pulse; + } + // if enough energy and not saturated + if ((energy_absorbed > m_meltEnergy) && (m_state < m_nStates)) + { + // cout << sc_time_stamp() << ": \n\t" << name() << " phase changed with " + // << energy_absorbed*1e6 << " uJ" << endl; + m_state++; + // cout << "\tnew state: " << m_state << endl; + update_transmission_local(); + } + } + else // external phase change simulation + { + // send the simulation to external software + cout << "TODO: implement handles to external sim" + << endl; + } + return in_influence_window; +} + +void PCMElement::update_transmission_local() +{ + double sp = 0.85; + double ep = 0.95; + double speed = 3; + m_transmission = sp+(ep-sp)*tanh(speed*m_state/m_nStates); + // cout << "\tnew trans_power: " << m_transmission << "- W/W" << endl; + + // For field need to do a square root + m_transmission = sqrt(m_transmission); +} diff --git a/src/devices/pcm_device.h b/src/devices/pcm_device.h new file mode 100644 index 0000000..4510591 --- /dev/null +++ b/src/devices/pcm_device.h @@ -0,0 +1,60 @@ +#pragma once + +#include <vector> + +#include <systemc.h> + +#include <spx_module.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +#include "specs.h" +#include "spx_module.h" + +class PCMElement : public spx_module { +public: + // Ports + spx::oa_port_in_type p_in; + spx::oa_port_out_type p_out; + + // Timed ports writers + OpticalOutputPort m_out_writer; + + // Auxiliary struct - stores tuples of value-time + typedef pair<double,double> pulse_sample_t; + + // Member variables + double m_meltEnergy; + int m_state; + int m_nStates; + double m_transmission = 1; + double influence_time_ns = 1; + + /** Current information about the optical input, before any attenuation and phase shift. */ + double m_last_pulse_power; + std::map<uint32_t,OpticalSignal::field_type> m_memory_in; + + + // Processes + void on_input_changed(); + bool phase_change(const vector<pulse_sample_t> &vec, const bool &local); + void update_transmission_local(); + + + // Constructor + PCMElement(sc_module_name name, + double meltEnergy = 0, + int nStates = 0, + int state = 0) + : spx_module(name) + , m_out_writer("out_delayed_writer", p_out) + , m_meltEnergy(meltEnergy) + , m_state(state) + , m_nStates(nStates) + { + SC_HAS_PROCESS(PCMElement); + + SC_THREAD(on_input_changed); + sensitive << p_in; + } +}; diff --git a/src/devices/phaseshifter.cpp b/src/devices/phaseshifter.cpp new file mode 100644 index 0000000..620243d --- /dev/null +++ b/src/devices/phaseshifter.cpp @@ -0,0 +1,198 @@ +#include "specs.h" +#include <phaseshifter.h> + +using namespace std; + +void PhaseShifterUni::on_port_in_changed() +{ + auto transmission_field = pow(10.0, - m_attenuation_dB / 20); + m_memory_in[0] = 0; // initializing for nan wavelength + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "transmission_power = " << pow(transmission_field,2) << " W/W" << endl; + cout << "sensitivity = " << m_sensitivity << " rad/V" << endl; + cout << "initial phase delay = " << m_phaseshift_rad << " rad @1.55)" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in.get_interface()))->name(); + cout << " --> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out.get_interface()))->name(); + cout << endl << "\t^" << endl; + cout << "\t|" << endl << "\t"; + cout << (dynamic_cast<spx::ea_signal_type *>(p_vin.get_interface()))->name(); + cout << endl; + cout << endl; + } + while (true) { + // Wait for a new input signal + wait(); + + // Read the input signal and apply attenuation + OpticalSignal s = p_in->read(); + + + // Store field value in memory + m_memory_in[s.m_wavelength_id] = s.m_field; + + // Get new ID for output event + s.getNewId(); + + // Apply transmission and phase-shift + s *= polar(transmission_field, m_sensitivity * p_vin->read()); + + // Write to ouput port after zero delay + m_out_writer.delayedWrite(s, SC_ZERO_TIME); + } +} + +void PhaseShifterUni::on_port_vin_changed() +{ + auto transmission_field = pow(10.0, - m_attenuation_dB / 20); + + uint32_t cur_wavelength_id = 0; + OpticalSignal::field_type cur_field = (complex<double>)0; + + while (true) + { + wait(); + // Read the new phase-delay + m_phaseshift_rad = m_sensitivity * p_vin->read(); + + // writes the signals of all wavelengths with the new phase shift + for(auto id_field : m_memory_in) + { + cur_wavelength_id = id_field.first; + cur_field = id_field.second; + auto s = OpticalSignal(cur_field, cur_wavelength_id); + + // Get a new ID for the signal + s.getNewId(); + + // Apply transmission and phase-shift + s *= polar(transmission_field, m_phaseshift_rad); + + // Write to ouput port after zero delay + m_out_writer.delayedWrite(s, SC_ZERO_TIME); + } + } +} + + +void PhaseShifterBi::on_p0_in_changed() +{ + auto transmission_field = pow(10.0, - m_attenuation_dB / 20); + m_memory_p0[0] = 0; // initializing for nan wavelength + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "transmission_power = " << pow(transmission_field,2) << " W/W" << endl; + cout << "sensitivity = " << m_sensitivity << " rad/V" << endl; + cout << "initial phase delay = " << m_phaseshift_rad << " rad @1.55)" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_in.get_interface()))->name(); + cout << " --> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_out.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_out.get_interface()))->name(); + cout << " <-- "; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_in.get_interface()))->name(); + cout << endl << "\t^" << endl; + cout << "\t|" << endl << "\t"; + cout << (dynamic_cast<spx::ea_signal_type *>(p_vin.get_interface()))->name(); + cout << endl; + cout << endl; + } + while (true) { + // Wait for a new input signal + wait(); + + // Read the input signal and apply attenuation + OpticalSignal s = p0_in->read(); + + + // Store field value in memory + m_memory_p0[s.m_wavelength_id] = s.m_field; + + // Get new ID for output event + s.getNewId(); + + // Apply transmission and phase-shift + s *= polar(transmission_field, m_sensitivity * p_vin->read()); + + // Write to ouput port after zero delay + m_p1_writer.delayedWrite(s, SC_ZERO_TIME); + } +} + +void PhaseShifterBi::on_p1_in_changed() +{ + auto transmission_field = pow(10.0, - m_attenuation_dB / 20); + m_memory_p1[0] = 0; // initializing for nan wavelength + + while (true) { + // Wait for a new input signal + wait(); + + // Read the input signal and apply attenuation + OpticalSignal s = p1_in->read(); + + // Store field value in memory + m_memory_p1[s.m_wavelength_id] = s.m_field; + + // Get new ID for output event + s.getNewId(); + + // Apply transmission and phase-shift + s *= polar(transmission_field, m_sensitivity * p_vin->read()); + + // Write to ouput port after zero delay + m_p0_writer.delayedWrite(s, SC_ZERO_TIME); + } +} + +void PhaseShifterBi::on_port_vin_changed() +{ + auto transmission_field = pow(10.0, - m_attenuation_dB / 20); + + uint32_t cur_wavelength_id = 0; + OpticalSignal::field_type cur_field = (complex<double>)0; + + while (true) + { + wait(); + // Read the new phase-delay + m_phaseshift_rad = m_sensitivity * p_vin->read(); + + // writes the signals of all wavelengths with the new phase shift + for(auto id_field : m_memory_p0) + { + cur_wavelength_id = id_field.first; + cur_field = id_field.second; + auto s = OpticalSignal(cur_field, cur_wavelength_id); + + // Get a new ID for the signal + s.getNewId(); + + // Apply transmission and phase-shift + s *= polar(transmission_field, m_phaseshift_rad); + + // Write to ouput port after zero delay + m_p1_writer.delayedWrite(s, SC_ZERO_TIME); + } + for(auto id_field : m_memory_p1) + { + cur_wavelength_id = id_field.first; + cur_field = id_field.second; + auto s = OpticalSignal(cur_field, cur_wavelength_id); + + // Get a new ID for the signal + s.getNewId(); + + // Apply transmission and phase-shift + s *= polar(transmission_field, m_phaseshift_rad); + + // Write to ouput port after zero delay + m_p0_writer.delayedWrite(s, SC_ZERO_TIME); + } + } +} diff --git a/src/devices/phaseshifter.h b/src/devices/phaseshifter.h new file mode 100644 index 0000000..04ac803 --- /dev/null +++ b/src/devices/phaseshifter.h @@ -0,0 +1,166 @@ +#pragma once + +#include "specs.h" +#include <systemc.h> + +#include <spx_module.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +/** An electrically-controllable phase shifter. */ +class PhaseShifterBase : public spx_module { +public: + // Member variables + /** The phaseshift applied to the pulse, in rad. */ + double m_phaseshift_rad = 0; + + /** The attenuation of the device in dB. */ + double m_attenuation_dB; + + /** The responsivity of the phase-shifter in rad/V. */ + double m_sensitivity = 1; + + /** Constructor for PhaseShifter + * + * @param name name of the module + * */ + PhaseShifterBase(sc_module_name name, double attenuation_dB = 0) + : spx_module(name) + , m_phaseshift_rad(0) + , m_attenuation_dB(attenuation_dB) + {} +}; + +class PhaseShifterUni : public PhaseShifterBase { +public: + // Ports + /** The electrical input port. */ + spx::ea_port_in_type p_vin; + /** The optical input port. */ + spx::oa_port_in_type p_in; + /** The optical output port. */ + spx::oa_port_out_type p_out; + + // Timed ports writers + /** Timed writer to the output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_out_writer; + + /** Memory of the current input value for all wavelengths. */ + std::map<uint32_t,OpticalSignal::field_type> m_memory_in; + + // Processes + /** Main process of the module. + * + * It copies the input to the output, after attenuation and delay. + * Will use the current m_phaseshift_rad at that moment. + * + * **SystemC type:** thread + * + * **Sensitivity list:** p_in + * */ + void on_port_in_changed(); + + /** Auxiliary process of the module. + * + * Updates @param m_phaseshift_rad and creates a new event + * using the current optical input, sending it to the output + * after zero time. + * + * **SystemC type:** thread + * + * **Sensitivity list:** v_in + * */ + void on_port_vin_changed(); + + /** Constructor for PhaseShifter + * + * @param name name of the module + * */ + PhaseShifterUni(sc_module_name name, double attenuation_dB = 0) + : PhaseShifterBase(name, attenuation_dB) + , m_out_writer("out_delayed_writer", p_out) + { + SC_HAS_PROCESS(PhaseShifterUni); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + SC_THREAD(on_port_vin_changed); + sensitive << p_vin; + } +}; + +typedef PhaseShifterUni PhaseShifter; + +class PhaseShifterBi : public PhaseShifterBase { +public: + // Ports + /** The electrical input port. */ + spx::ea_port_in_type p_vin; + + /** The optical input ports. */ + spx::oa_port_in_type p0_in; + spx::oa_port_in_type p1_in; + + /** The optical output ports. */ + spx::oa_port_out_type p0_out; + spx::oa_port_out_type p1_out; + + // Timed ports writers + /** Timed writer to the output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_p0_writer; + OpticalOutputPort m_p1_writer; + + /** Memory of the current input value for all wavelengths. */ + std::map<uint32_t,OpticalSignal::field_type> m_memory_p0; + std::map<uint32_t,OpticalSignal::field_type> m_memory_p1; + + // Processes + /** Main process of the module. + * + * It copies the input to the output, after attenuation and delay. + * Will use the current m_phaseshift_rad at that moment. + * + * **SystemC type:** thread + * + * **Sensitivity list:** p0_in + * */ + void on_p0_in_changed(); + void on_p1_in_changed(); + + /** Auxiliary process of the module. + * + * Updates @param m_phaseshift_rad and creates a new event + * using the current optical input, sending it to the output + * after zero time. + * + * **SystemC type:** thread + * + * **Sensitivity list:** v_in + * */ + void on_port_vin_changed(); + + /** Constructor for PhaseShifter + * + * @param name name of the module + * */ + PhaseShifterBi(sc_module_name name, double attenuation_dB = 0) + : PhaseShifterBase(name, attenuation_dB) + , m_p0_writer("p0_out_delayed_writer", p0_out) + , m_p1_writer("p1_out_delayed_writer", p1_out) + { + SC_HAS_PROCESS(PhaseShifterBi); + + SC_THREAD(on_p0_in_changed); + sensitive << p0_in; + SC_THREAD(on_p1_in_changed); + sensitive << p1_in; + SC_THREAD(on_port_vin_changed); + sensitive << p_vin; + } +}; diff --git a/src/devices/probe.cpp b/src/devices/probe.cpp new file mode 100644 index 0000000..f9054e9 --- /dev/null +++ b/src/devices/probe.cpp @@ -0,0 +1,164 @@ +#include <ios> +#include <probe.h> +#include <cstdlib> // system() + +#define __modname(SUFFIX, IDX) \ + ((""s + this->name() + "_" + SUFFIX + to_string(IDX)).c_str()) + + +void Probe::on_port_in_changed() +{ + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "Signal: " << (dynamic_cast<spx::oa_signal_type *>(p_in.get_interface()))->name() << endl; + cout << "trace power: " << m_trace_power << endl; + cout << "trace modulus: " << m_trace_modulus << endl; + cout << "trace phase: " << m_trace_phase << endl; + cout << "trace wavelength: " << m_trace_wavelength << endl; + cout << endl; + } + + while (true) { + // Wait for a new input signal + wait(); + + // Check if enabled first + if (!enable.read().to_bool()) + { + wait(enable.posedge_event()); + continue; + } + + auto &s = p_in->read(); + // cout << name() << ": " << s << endl; + if (!isnan(s.getWavelength())) + { + if (m_trace_power) + m_trace_sig_power.write(s.power()); + if (m_trace_modulus) + m_trace_sig_modulus.write(s.modulus()); + if (m_trace_phase) + m_trace_sig_phase.write(s.phase()); + if (m_trace_wavelength) + // m_trace_sig_wavelength.write(299792458.0 / s.m_wavelength); + m_trace_sig_wavelength.write(s.getWavelength()); + } + } +} + +void PowerProbe::on_port_in_changed() +{ + //m_trace_sig.write(0); + + while (true) { + // Wait for a new input signal + wait(); + auto &s = p_in->read(); + if (!isnan(s.getWavelength())) + m_trace_sig_power.write(s.power()); + } +} + +void PhaseProbe::on_port_in_changed() +{ + //m_trace_sig.write(0); + + while (true) { + // Wait for a new input signal + wait(); + auto &s = p_in->read(); + if (!isnan(s.getWavelength())) + m_trace_sig_phase.write(s.phase()); + } +} + +//__modname(SUFFIX, IDX) +void MLambdaProbe::setTraceFile(sc_trace_file *Tf) +{ + m_Tf = Tf; + if (!m_Tf) + return; + + unique_ptr<sc_signal<double>> temp_signal; + std::vector<unique_ptr<sc_signal<double>>> temp_vector; + + // for each wavelength, create three signals: + // power, abs, phase, that will monitor these characteristics in + // the input optical signals that arrive + int i = 0; + for(const auto &wl : m_lambdas) + { + stringstream ss; + // int wl_nm = floor(wl*1e9); + // int wl_sub_nm = round((wl*1e9 - wl_nm) * 1e6); + // ss << wl_nm << "nm" << wl_sub_nm; + ss << setprecision(6) << std::fixed << wl*1e9; + string wl_str = ss.str(); + // Necessary because '.' is interpreted by traces as the hierarchical separator + std::replace(wl_str.begin(), wl_str.end(), '.', '_'); + + temp_vector.clear(); + + temp_signal = make_unique<sc_signal<double>>(__modname("trace_pow", i*3)); + sc_trace(m_Tf, *temp_signal, (string(this->name()) + ".power@" + wl_str).c_str()); + temp_vector.push_back(std::move(temp_signal)); + + temp_signal = make_unique<sc_signal<double>>(__modname("trace_mod", i*3)); + sc_trace(m_Tf, *temp_signal, (string(this->name()) + ".abs@" + wl_str).c_str()); + temp_vector.push_back(std::move(temp_signal)); + + temp_signal = make_unique<sc_signal<double>>(__modname("trace_phase", i*3)); + sc_trace(m_Tf, *temp_signal, (string(this->name()) + ".phase@" + wl_str).c_str()); + temp_vector.push_back(std::move(temp_signal)); + + //m_lambda_signals[m_lambdas[i]] = std::move(temp_vector); + //or + m_lambda_signals.insert({wl, std::move(temp_vector)}); + + ++i; + } +} +void MLambdaProbe::on_port_in_changed() +{ + // std::map< int, std::vector< unique_ptr<sc_signal<double> > > > wl_map; + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << " ready ("; + for (const auto &p : m_lambda_signals) + { + cout << p.first << ", "; + } + cout << "\b\b)" << endl; + cout << "Signal: " << (dynamic_cast<spx::oa_signal_type *>(p_in.get_interface()))->name() << endl; + cout << endl; + } + //m_trace_sig.write(0); + + while (true) { + // Wait for a new input signal + wait(); + + // Check if enabled first + if (!enable.read().to_bool()) + { + wait(enable.posedge_event()); + continue; + } + + auto &s = p_in->read(); + auto search = m_lambda_signals.find(s.getWavelength()); + + if (search != m_lambda_signals.end()) + { + //cout << name() << " received supported signal (lambda = " << s.getWavelength() << "m)" << endl; + m_lambda_signals[s.getWavelength()][0]->write(s.power()); + m_lambda_signals[s.getWavelength()][1]->write(s.modulus()); + m_lambda_signals[s.getWavelength()][2]->write(s.phase()); + } + else { + cout << name() << " received unsupported signal (lambda = " << s.getWavelength() << "m)" << endl; + } + } +}
\ No newline at end of file diff --git a/src/devices/probe.h b/src/devices/probe.h new file mode 100644 index 0000000..10865ba --- /dev/null +++ b/src/devices/probe.h @@ -0,0 +1,131 @@ +#pragma once + +#include <systemc.h> +#include <fstream> +#include <map> +#include <set> + +#include <optical_output_port.h> +#include <optical_signal.h> +#include "specs.h" +#include "spx_module.h" + +/* +This class defines an ideal optical probe. It will sample the signal at its input and +write it in a file. Any OpticalSignal can be its input, without caring for optical +splitting, as it is completely ideal. +*/ +class Probe : public spx_module { +public: + // Ports + spx::oa_port_in_type p_in; + + // Processes + virtual void on_port_in_changed(); + + // Member variables + + // If given a valid trace file as argument + // Will not save to txt and rather use VCD tracing + sc_trace_file *m_Tf; + sc_signal<double> m_trace_sig_power; + sc_signal<double> m_trace_sig_modulus; + sc_signal<double> m_trace_sig_phase; + sc_signal<double> m_trace_sig_wavelength; + + sc_signal<sc_logic> enable; + bool m_trace_power; + bool m_trace_modulus; + bool m_trace_phase; + bool m_trace_wavelength; + + // Constructor + Probe(sc_module_name name, const bool &trace_power = true, const bool &trace_modulus = true + , const bool &trace_phase = true, const bool &trace_wavelength = true) + : spx_module(name) + , m_Tf(nullptr) + , enable((string(this->name()) + "_enable").c_str(), sc_logic(1)) + , m_trace_power(trace_power) + , m_trace_modulus(trace_modulus) + , m_trace_phase(trace_phase) + , m_trace_wavelength(trace_wavelength) + { + SC_HAS_PROCESS(Probe); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + } + + // Constructor overloading + Probe(sc_module_name name, sc_trace_file *Tf, const bool &trace_power = true, const bool &trace_modulus = true + , const bool &trace_phase = true, const bool &trace_wavelength = true) + : Probe(name, trace_power, trace_modulus, trace_phase, trace_wavelength) + { + setTraceFile(Tf); + } + + void setTraceFile(sc_trace_file *Tf) + { + if (m_Tf == Tf) + return; + m_Tf = Tf; + if (m_Tf) + { + if (m_trace_power) sc_trace(m_Tf, m_trace_sig_power, (string(this->name()) + ".power").c_str()); + if (m_trace_modulus) sc_trace(m_Tf, m_trace_sig_modulus, (string(this->name()) + ".abs").c_str()); + if (m_trace_phase) sc_trace(m_Tf, m_trace_sig_phase, (string(this->name()) + ".phase").c_str()); + if (m_trace_wavelength) sc_trace(m_Tf, m_trace_sig_wavelength, (string(this->name()) + ".wavelength").c_str()); + } + } +}; + +class PowerProbe : public Probe { +public: + virtual void on_port_in_changed(); +}; + +class PhaseProbe : public Probe { +public: + virtual void on_port_in_changed(); +}; + +class MLambdaProbe : public spx_module { +public: + // Ports + spx::oa_port_in_type p_in; + + // Processes + virtual void on_port_in_changed(); + + // Member variables + + // If given a valid trace file as argument + // Will not save to txt and rather use VCD tracing + sc_signal<sc_logic> enable; + sc_trace_file *m_Tf; + + sc_signal<double> m_trace_sig_power; + sc_signal<double> m_trace_sig_modulus; + sc_signal<double> m_trace_sig_phase; + + std::set<double> m_lambdas; + std::map< double, std::vector< unique_ptr<sc_signal<double> > > > m_lambda_signals; + + void setTraceFile(sc_trace_file *Tf); + void prepare(); + + // Constructor + MLambdaProbe(sc_module_name name, set<double> lambdas = {}) + : spx_module(name) + , enable((string(this->name()) + "_enable").c_str(), sc_logic(1)) + , m_Tf(nullptr) + , m_lambdas(lambdas) + { + SC_HAS_PROCESS(MLambdaProbe); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + } + + // TODO: overload the constructor for the case of not informing lambdas, need to check all components +}; diff --git a/src/devices/ring.cpp b/src/devices/ring.cpp new file mode 100644 index 0000000..42f901e --- /dev/null +++ b/src/devices/ring.cpp @@ -0,0 +1,8 @@ +#include <waveguide.h> + +//void Ring::on_port_tuning_changed() +//{ +// // Tuning of the ring parameters... +// // e.g. wg.neff = ... +//} + diff --git a/src/devices/ring.h b/src/devices/ring.h new file mode 100644 index 0000000..0633c13 --- /dev/null +++ b/src/devices/ring.h @@ -0,0 +1,99 @@ +#pragma once + +#include <systemc.h> + +#include <waveguide.h> +#include <directional_coupler.h> +#include <optical_output_port.h> +#include <optical_signal.h> + +/** A unidirectional waveguide module. */ +class Ring : public sc_module { +public: + // Ports + /** The optical input port. */ + sc_port<sc_signal_in_if<OpticalSignal>> p_in; + /** The optical output port. */ + sc_port<sc_signal_out_if<OpticalSignal>> p_out; + + // Timed ports writers + /** Timed writer to the output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_out_writer; + + sc_signal<OpticalSignal> sig_in; + sc_signal<OpticalSignal> sig_internal_0; + sc_signal<OpticalSignal> sig_internal_1; + sc_signal<OpticalSignal> sig_out; + DirectionalCoupler dc; + Waveguide wg; + + // Member variables + /** The attenuation inside the waveguide, in dB/cm. */ + double m_attenuation_dB_cm = 0.2; + /** The effective index of the waveguide */ + double m_neff = 2.2111; + /** The group index of the waveguide */ + double m_ng = 2.2637; + + /** The coupling from waveguide to ring, in dB. */ + double m_cross_power_dB = 10*std::log10(0.5) - 0.15; + double m_through_power_dB = 10*std::log10(0.5) - 0.15; + double m_cross_phase_rad = M_PI / 2; + double m_through_phase_rad = M_PI / 2; + + /** The radius of the ring in um. */ + double m_radius_um = 0; + + // Processes + /** Main process of the module. + * + * It copies the input to the output, after attenuation and delay. + * + * **SystemC type:** thread + * + * **Sensitivity list:** p_in + * */ + void on_port_in_changed(); + + /** Constructor for Waveguide + * + * @param name name of the module + * @param length_cm length of the waveguide in cm + * */ + Ring(sc_module_name name, double length_cm = 30e-6) + : sc_module(name) + , m_out_writer("out_delayed_writer", p_out) + , dc((std::string(name) + ".DC1").c_str()) + , wg((std::string(name) + ".WG1").c_str()) + { + dc.p_in1(sig_in); + dc.p_in2(sig_internal_1); + dc.p_out1(sig_out); + dc.p_out2(sig_internal_0); + + wg.p_in(sig_internal_0); + wg.p_out(sig_internal_1); + + p_in(sig_in); + p_out(sig_out); + + setLength(length_cm); + + SC_HAS_PROCESS(Waveguide); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + } + + void setRadius(double radius_um) { + wg.setLength(2 * M_PI * radius_um * 1e-4); + m_radius_um = radius_um; + } + + void setLength(double length_cm) { + setRadius(length_cm * 1e4 / 2 / M_PI); + } +}; diff --git a/src/devices/splitter.cpp b/src/devices/splitter.cpp new file mode 100644 index 0000000..e6464f6 --- /dev/null +++ b/src/devices/splitter.cpp @@ -0,0 +1,41 @@ +#include <splitter.h> +#include <specs.h> + +void Splitter::on_port_in_changed() +{ + const double transmission = pow(10.0, - m_attenuation_dB / 20); + const double S12 = transmission * sqrt(m_split_ratio); + const double S13 = transmission * sqrt(1 - m_split_ratio); + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "transmission = " << pow(transmission, 2) << " W/W" << endl; + cout << "splitting ratio_power = 0.5" << " W/W" << endl; + cout << "\t " << (dynamic_cast<spx::oa_signal_type *>(p_out1.get_interface()))->name() << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in.get_interface()))->name() << " -->" << endl; + cout << "\t " << (dynamic_cast<spx::oa_signal_type *>(p_out2.get_interface()))->name(); + cout << endl; + cout << endl; + } + + while (true) { + // Wait for a new input signal + wait(); + + // Read input signal + const auto &s = p_in->read(); + + // Apply device's transmission + auto s1 = S12 * s; + auto s2 = S13 * s; + + // Get new IDs + s1.getNewId(); + s2.getNewId(); + + // Write to output ports after delay + m_out1_writer.delayedWrite(s1, SC_ZERO_TIME); + m_out2_writer.delayedWrite(s2, SC_ZERO_TIME); + } +} diff --git a/src/devices/splitter.h b/src/devices/splitter.h new file mode 100644 index 0000000..1d5e730 --- /dev/null +++ b/src/devices/splitter.h @@ -0,0 +1,88 @@ +#pragma once + +#include <systemc.h> + +#include <spx_module.h> +#include <optical_output_port.h> +#include <optical_signal.h> +#include "specs.h" +#include "spx_module.h" + +/** A 1x2 waveguide splitter module. + * + * This device copies any output to its two output, with power values defines by the + * split ratio and attenuation. + * */ +class Splitter : public spx_module { +public: + // Ports + /** The optical input port. */ + spx::oa_port_in_type p_in; + /** The first optical output port. */ + spx::oa_port_out_type p_out1; + /** The second optical output port. */ + spx::oa_port_out_type p_out2; + +private: + // Timed ports writers + /** Timed writer to the first output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_out1_writer; + /** Timed writer to the second output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_out2_writer; + +public: + // Member variables + /** The power transmission from input to branch 1, exclusive of losses + * + * The power transmission from input to branch 2 is (1 - m_split_ratio) + * */ + double m_split_ratio; + + /** The delay for an output to propagate to the outputs in ns. + * + * The delay is the same for both outputs. + * */ + // static double m_delay_ns; + /** The attenuation of the signal in dB. + * + * The attenuation is applied before the split (although it does not really make a + * difference. */ + double m_attenuation_dB; + + // Processes + /** Main process of the module. + * + * It copies the input to both output, after attenuation and delay. + * + * **SystemC type:** thread + * + * **Sensitivity list:** p_in + * */ + void on_port_in_changed(); + + // Constructor + /** Constructor for Splitter + * + * @param name name of the module + * @param split_ratio ratio of the light which goes to the first ouptut + * (pre-attenuation) + * */ + Splitter(sc_module_name name, double split_ratio = 0.5, double attenuation_dB = 0) + : spx_module(name) + , m_out1_writer("out1_delayed_writer", p_out1) + , m_out2_writer("out2_delayed_writer", p_out2) + , m_split_ratio(split_ratio) + , m_attenuation_dB(attenuation_dB) + { + SC_HAS_PROCESS(Splitter); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + } +}; diff --git a/src/devices/spx_module.h b/src/devices/spx_module.h new file mode 100644 index 0000000..0a4506f --- /dev/null +++ b/src/devices/spx_module.h @@ -0,0 +1,36 @@ +#pragma once + +#include "optical_signal.h" +#include "specs.h" + +#include <systemc.h> +#include <string> + +using std::string; +using namespace std::string_literals; + +class spx_module : public sc_module { +public: + typedef spx_module this_type; + typedef spx::oa_value_type sigval_type; + typedef spx::oa_signal_type sig_type; + typedef spx::oa_if_in_type if_in_type; + typedef spx::oa_if_out_type if_out_type; + typedef spx::oa_port_in_type port_in_type; + typedef spx::oa_port_out_type port_out_type; + + enum ModuleFlags { + NON_LINEAR = 0b0001, + TIME_VARIANT = 0b0010, + FREQUENCY_DEPENDENT = 0b0100, + }; + + ModuleFlags flags = FREQUENCY_DEPENDENT; + + virtual void init() {} + virtual string describe() const { return ""s; } + + spx_module(sc_module_name name) + : sc_module(name) + {} +};
\ No newline at end of file diff --git a/src/devices/subcircuit_instance.h b/src/devices/subcircuit_instance.h new file mode 100644 index 0000000..5c835e8 --- /dev/null +++ b/src/devices/subcircuit_instance.h @@ -0,0 +1,25 @@ +#pragma once + +#include <memory> +#include <vector> + +#include "specs.h" +#include "spx_module.h" + +using std::vector; +using std::string; +using std::shared_ptr; + +class SubcircuitInstance: public spx_module { +public: + // vector<shared_ptr<spx::oa_port_inout_type>> ports; + vector<shared_ptr<sc_object>> signals; + vector<shared_ptr<sc_object>> modules; + + SubcircuitInstance(sc_module_name name) + : spx_module(name) + {} + + ~SubcircuitInstance() + {} +};
\ No newline at end of file diff --git a/src/devices/time_monitor.cpp b/src/devices/time_monitor.cpp new file mode 100644 index 0000000..0c4ab91 --- /dev/null +++ b/src/devices/time_monitor.cpp @@ -0,0 +1,152 @@ + +#include "time_monitor.h" +#include "optical_output_port.h" +#include "specs.h" +#include "sysc_utils.h" +#include <vector> +#include <set> + +using namespace std; + +string vec2str(const vector<bool> &v) +{ + string str; + for (const auto &x : v) + if (x) + str += "1|"; + else + str += "0|"; + + return str; +} + +void TimeMonitor::on_trigger() { + auto first = system_clock::now(); + auto last = first; + + set<OpticalOutputPort *> oops = sc_get_all_module_by_type<OpticalOutputPort>(); + sc_time delay = sc_time(m_poll_period, SC_SEC); + + //wait(1, SC_PS); + while (true) { + // Wait for next polling event + if (!sc_pending_activity()) + { + // cout << "a" << endl; + wait(); + } + else if (sc_pending_activity_at_current_time() && delay.value() != 0) + { + // cout << "b" << endl; + wait(delay); + } + else if (sc_pending_activity_at_current_time() && delay.value() == 0) + { + //cout << "c" << endl; + wait(delay); + } + else if (sc_pending_activity_at_future_time() && delay.value() != 0) + { + // cout << "d" << endl; + wait(delay); + } + else if (sc_pending_activity_at_future_time() && delay.value() == 0) + { + // cout << "e" << endl; + wait(sc_time_to_pending_activity()); + } + else + cerr << "How did you get here ?" << endl; + + + // Get current wall clock + auto now = system_clock::now(); + std::chrono::duration<double> elapsed_seconds = now - last; + + // Report if it's time to do it + if (elapsed_seconds.count() >= m_wallclock_period) + { + #if 0 + double error_sum = 0; + double max_error = 0; + double emitted_power_sum = 0; + double max_emitted_power = 0; + string max_error_name; + complex<double> culprit_emitted; + double culprit_emitted_pow = 0.0; + complex<double> culprit_wanted; + vector<bool> is_empty(oops.size(), false); + int i = 0; + int max_i = 0; + for (const auto &oop : oops) + { + is_empty[i] = oop->isempty(); + error_sum += oop->current_err_fd(); + max_error = max(max_error, oop->current_err_fd()); + if (max_error == oop->current_err_fd()) + // if (strcmp(oop->name(), "crow.dc_0.out1_delayed_writer") == 0) + { + max_error_name = oop->name(); + // deprecated following lines on 05/04: + // culprit_emitted = oop->m_emitted_val_fd; + // culprit_emitted_pow = oop->m_emitted_val_fd.power(); + culprit_wanted = oop->m_cur_val_fd; + max_i = i; + } + // deprecated following lines on 05/04: + // emitted_power_sum += oop->m_emitted_val_fd.power(); + // max_emitted_power = max(max_emitted_power, oop->m_emitted_val_fd.power()); + i++; + } + #endif + + std::chrono::duration<double> elapsed_seconds_since_start = now - first; + last = now; + auto t = sc_time_stamp().to_seconds(); + cout << "---------------------------------------------------------------------------" << endl; + cerr << "Time monitor incompatible with new multi-wavelength features" << endl; + exit(1); + cout << "Current simulation time (after "<< (int)(elapsed_seconds_since_start.count()) <<"s): " << endl + << "\tIn NS: " << t*1e9 << endl + << "\tIn PS: " << t*1e12 << endl + << "\tDelta-cycles at current time: " << sc_delta_count_at_current_time() << endl + //<< "\tCumulated error in ports: " << error_sum << endl + //<< "\tIsempty: " << vec2str(is_empty) << endl + //<< "\tCulprit: " << max_error_name << endl + //<< "\tCulprit i: " << max_i << endl + //<< setprecision(12) + //<< "\tWanted: " << norm(culprit_wanted) << "W " << arg(culprit_wanted) << "rad" << endl + //<< "\tEmitted: " << norm(culprit_emitted) << "W " << arg(culprit_emitted) << "rad" << endl + //<< "\tDiff: " << abs(norm(culprit_emitted) - norm(culprit_wanted)) << "W " << abs(arg(culprit_emitted) - arg(culprit_wanted)) << "rad" << endl + //<< "\tMax error in ports: " << max_error << endl + //<< "\tCumulated power output of all ports: " << emitted_power_sum << endl + //<< "\tMax port power output: " << max_emitted_power << endl + << "\tSimulation speed (NS/s): " << t*1e9 / elapsed_seconds_since_start.count() << endl; + + // if (max_error < specsGlobalConfig.oop_configs[0]->m_abs_tol_power) + if (false) + { + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // DOES NOT WORK IF CODE IS COMPILED WITH -O3 ??? + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + specsGlobalConfig.drop_all_events = true; + wait(SC_ZERO_TIME); + while (true) { + volatile bool isempty = true; + for (const auto &oop : oops) { + isempty &= oop->isempty(); + if (oop->isempty()) + { + cout << oop->name() << " didnt empty its queue" << endl; + } + } + if (isempty) + break; + wait(SC_ZERO_TIME); + } + specsGlobalConfig.drop_all_events = false; + wait(sc_time::from_value(1)); + } + } + } +} diff --git a/src/devices/time_monitor.h b/src/devices/time_monitor.h new file mode 100644 index 0000000..62d5626 --- /dev/null +++ b/src/devices/time_monitor.h @@ -0,0 +1,26 @@ +#pragma once + +#include <systemc.h> +#include <chrono> +#include <iostream> + +using std::chrono::system_clock; +using std::shared_ptr; +using std::make_shared; + +class TimeMonitor : public sc_module { +public: + double m_poll_period; // in seconds + double m_wallclock_period; // in seconds + + void on_trigger(); + + TimeMonitor(sc_module_name name, double poll_period=100e-12, double wallclock_period = 2) + : sc_module(name), + m_poll_period(poll_period), + m_wallclock_period(wallclock_period) + { + SC_HAS_PROCESS(TimeMonitor); + SC_THREAD(on_trigger); + } +}; diff --git a/src/devices/value_list_source.cpp b/src/devices/value_list_source.cpp new file mode 100644 index 0000000..a10c1a1 --- /dev/null +++ b/src/devices/value_list_source.cpp @@ -0,0 +1,69 @@ +#include "specs.h" +#include "value_list_source.h" + +using std::cout; +using std::cerr; +using std::endl; + +void VLSource::runner() +{ + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "value list (" << m_values_queue.size() << " values)"; + if (false) + { + cout << ":" << endl; + for (const auto& val : m_values_queue) + cout << "\t" << "@" << sc_time(val.first, SC_SEC) << ": " << val.second << endl; + } + cout << endl; + cout << "--> " << + (dynamic_cast<spx::oa_signal_type *>(p_out.get_interface()))->name() << endl; + cout << endl; + } + + // Wait for enable signal + if (! enable.read().to_bool()) + { + // cout << name() << " waiting for enable" << endl; + wait(enable.posedge_event()); + cout << name() << " was enabled" << endl; + } + + // Emitting 0 at enable (will only go through if there is no value at t=0) + if (m_values_queue.cbegin() == m_values_queue.cend() + || sc_time(m_values_queue.front().first, SC_SEC).value() > 0) + { + cout << "@" << sc_time_stamp() << ", " << name() << " emitted: " << spx::oa_value_type(0) << endl; + m_out_writer.delayedWrite(spx::oa_value_type(0), SC_ZERO_TIME); + } + + auto it = m_values_queue.cbegin(); + while (it != m_values_queue.cend()) + { + sc_time now = sc_time_stamp(); + sc_time next_emit; + if (sc_time(it->first, SC_SEC) < now) + { + cout << name() << ": invalid time for signal emission !" << endl; + ++it; + continue; + } + sc_time delay = sc_time(it->first, SC_SEC) - now; + + // Wait until next output time + wait(delay); + + auto s = it->second; + + // Write value to output + m_out_writer.delayedWrite(s, SC_ZERO_TIME); + cout << "@" << sc_time_stamp() << ", " << name() << " emitted: " << s << endl; + + ++it; + } + + // cout << name() << " completed" << endl; + while(true) { wait(); } +} diff --git a/src/devices/value_list_source.h b/src/devices/value_list_source.h new file mode 100644 index 0000000..a7ddb6e --- /dev/null +++ b/src/devices/value_list_source.h @@ -0,0 +1,140 @@ +#pragma once + +#include <systemc.h> +#include <fstream> +#include <algorithm> +#include <vector> +#include <utility> + +#include "strutils.h" +#include "optical_output_port.h" +#include "optical_signal.h" +#include "specs.h" +#include "spx_module.h" + +using std::vector; +using std::pair; + +class VLSource : public spx_module { +public: + typedef pair<double, spx::oa_value_type> time_value_pair_type; + // Ports + spx::oa_port_out_type p_out; + + // Timed ports writers + OpticalOutputPort m_out_writer; + + // Signal to emit + vector<time_value_pair_type> m_values_queue; + + // Source emission control + spx::ed_signal_type enable; + + // Processes + void runner(); + + VLSource(sc_module_name name, const vector<time_value_pair_type> &values = {}) + : spx_module(name) + , m_out_writer((string(this->name()) + "_out_writer").c_str(), p_out) + , m_values_queue(values) + { + sortValues(); + enable = sc_logic(0); + + SC_HAS_PROCESS(VLSource); + SC_THREAD(runner); + } + + void setValues(const vector<time_value_pair_type> &values) + { + m_values_queue = values; + sortValues(); + } + + void setValues(const string &filename) + { + std::ifstream file(filename); + + if (!file.is_open()) { + cerr << "Error: Cannot open the file." << endl; + exit(1); + } + + string line; + + getline(file, line); + + int lineNumber = 0; + while (getline(file, line)) { + ++lineNumber; + istringstream s(line); + string field; + + double t, P, WL; + + // Skip if line is empty or starts with ; + if (line.empty()) + { + cout << "Skipping empty line." << endl; + continue; + } + // Skip if line starts with ; + if (line[0] == ';') + { + cout << "Skipping commented line: " << line << endl; + continue; + } + + // Read first field (time) + getline(s, field, ','); + strutils::trim(field); + + // Skip header line if it exists + if(lineNumber == 1 && field == "time") + { + cout << "Skipping header line: " << line << endl; + continue; + } + + try { + t = stod(field); + } catch (std::invalid_argument const& ex) { + cerr << "Invalid value for time: \"" << field << "\"" << endl; + exit(1); + } + + // Read second field (P) + getline(s, field, ','); + try { + P = stod(field); + } catch (std::invalid_argument const& ex) { + cerr << "Invalid value for power: \"" << field << "\"" << endl; + exit(1); + } + + // Read wavelength (WL) + std::getline(s, field); + try { + WL = stod(field); + } catch (std::invalid_argument const& ex) { + cerr << "Invalid value for wavelength: \"" << field << "\"" << endl; + exit(1); + } + + cout << t << ": " << P << "W @" << WL*1e9 << "nm" << endl; + m_values_queue.emplace_back(t, OpticalSignal(sqrt(P), WL)); + } + + file.close(); + sortValues(); + } + + void sortValues() + { + auto cmp = [](const time_value_pair_type& p1, const time_value_pair_type& p2) { + return p1.first < p2.first; + }; + // Stable sort will keep initial ordering for values with identical time + std::stable_sort(m_values_queue.begin(), m_values_queue.end(), cmp); + } +}; diff --git a/src/devices/waveguide.cpp b/src/devices/waveguide.cpp new file mode 100644 index 0000000..dc20ec7 --- /dev/null +++ b/src/devices/waveguide.cpp @@ -0,0 +1,280 @@ +#include "specs.h" +#include <waveguide.h> + +using namespace std; + +void WaveguideUni::on_port_in_changed() +{ + const double c = 299792458.0; + + // attenuation in dB + m_attenuation_dB = m_attenuation_dB_cm * m_length_cm; + + // transmission in field: 10^(-dB/20) + const double transmission = pow(10.0, - m_attenuation_dB / 20.0); + + // vg = c/ng + // => delay = L / vg = (L * ng) / c + const double group_delay_ns = 1e9 * m_length_cm * 1e-2 / (c / m_ng); + + // precalculate 2 * pi * L + double phase_delay_factor = 2.0 * M_PI * m_length_cm * 1e-2; + + // ng = neff - lambda * dneff/dlambda + // => dneff/dlambda = (neff - ng)/lambda + double dneff_dlambda = (m_neff - m_ng) / 1.55e-6; + + // Parameters relative to dispersion + double d2neff_dlambda2_over_2 = -1 * c * m_D / (2 * 1.55e-6); + double dng_dlambda = c*m_D; + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "length = " << m_length_cm/100 << " m" << endl; + cout << "neff = " << m_neff << "" << endl; + cout << "ng = " << m_ng << "" << endl; + cout << "transmission_power = " << pow(transmission, 2) << " W/W" << endl; + cout << "group delay = " << group_delay_ns << " ns" << endl; + // cout << "dneff/dlambda = " << dneff_dlambda*1e-6 << " um^-1" << endl; + cout << "phase delay = " << 1e9 * m_length_cm * 1e-2 / (c / m_neff) << " ns"; + cout << " (" + << fmod((2 * M_PI * m_neff / 1.55e-6) * m_length_cm * 1e-2, 2 * M_PI) + << "rad @1.55)" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p_in.get_interface()))->name(); + cout << " --> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p_out.get_interface()))->name(); + cout << endl; + cout << endl; + } + + if(m_D == 0) + { + while (true) { + // Wait for a new input signal + wait(); + // Read the input signal + auto s = p_in->read(); + + // calculate phase-delay + const double neff = m_neff + dneff_dlambda * (s.getWavelength() - 1.55e-6); + + const double phase_delay = phase_delay_factor * neff / s.getWavelength(); + + // Apply transmission function + const OpticalSignal::field_type S12 = polar(transmission, phase_delay); + s *= S12; + + // Get new ID for output event + s.getNewId(); + + // Write to ouput port after group delay + m_out_writer.delayedWrite(s, sc_time(group_delay_ns, SC_NS)); + } + } + else // dispersion has a defined value + { + while (true) { + // Wait for a new input signal + wait(); + // Read the input signal + auto s = p_in->read(); + + // calculate phase-delay + const double neff = m_neff + dneff_dlambda * (s.getWavelength() - 1.55e-6) + + d2neff_dlambda2_over_2 * pow(s.getWavelength() - 1.55e-6, 2); + const double ng = m_ng + dng_dlambda * (s.getWavelength() - 1.55e-6); + + const double phase_delay_disp = phase_delay_factor * neff / s.getWavelength(); + const double group_delay_ns_disp = 1e9 * m_length_cm * 1e-2 / (c / ng); + // Apply transmission function + const OpticalSignal::field_type S12 = polar(transmission, phase_delay_disp); + s *= S12; + + // Get new ID for output event + s.getNewId(); + + // Write to ouput port after group delay + m_out_writer.delayedWrite(s, sc_time(group_delay_ns_disp, SC_NS)); + } + } +} + + +void WaveguideBi::on_p0_in_changed() +{ + const double c = 299792458.0; + + // attenuation in dB + m_attenuation_dB = m_attenuation_dB_cm * m_length_cm; + + // transmission in field: 10^(-dB/20) + const double transmission = pow(10.0, - m_attenuation_dB / 20.0); + + // vg = c/ng + // => delay = L / vg = (L * ng) / c + const double group_delay_ns = 1e9 * m_length_cm * 1e-2 / (c / m_ng); + + // precalculate 2 * pi * L + double phase_delay_factor = 2.0 * M_PI * m_length_cm * 1e-2; + + // ng = neff - lambda * dneff/dlambda + // => dneff/dlambda = (neff - ng)/lambda + double dneff_dlambda = (m_neff - m_ng) / 1.55e-6; + + // Parameters relative to dispersion + double d2neff_dlambda2_over_2 = -1 * c * m_D / (2 * 1.55e-6); + double dng_dlambda = c*m_D; + + if (specsGlobalConfig.verbose_component_initialization) + { + cout << name() << ":" << endl; + cout << "length = " << m_length_cm/100 << " m" << endl; + cout << "neff = " << m_neff << "" << endl; + cout << "ng = " << m_ng << "" << endl; + cout << "transmission_power = " << pow(transmission, 2) << " W/W" << endl; + cout << "group delay = " << group_delay_ns << " ns" << endl; + // cout << "dneff/dlambda = " << dneff_dlambda*1e-6 << " um^-1" << endl; + cout << "phase delay = " << 1e9 * m_length_cm * 1e-2 / (c / m_neff) << " ns"; + cout << " (" + << fmod((2 * M_PI * m_neff / 1.55e-6) * m_length_cm * 1e-2, 2 * M_PI) + << "rad @1.55)" << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_in.get_interface()))->name(); + cout << " --> "; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_out.get_interface()))->name(); + cout << endl; + cout << (dynamic_cast<spx::oa_signal_type *>(p0_out.get_interface()))->name(); + cout << " <-- "; + cout << (dynamic_cast<spx::oa_signal_type *>(p1_in.get_interface()))->name(); + cout << endl; + cout << endl; + } + + if(m_D == 0) + { + while (true) { + // Wait for a new input signal + wait(); + // Read the input signal + auto s = p0_in->read(); + + // calculate phase-delay + const double neff = m_neff + dneff_dlambda * (s.getWavelength() - 1.55e-6); + + const double phase_delay = phase_delay_factor * neff / s.getWavelength(); + + // Apply transmission function + const OpticalSignal::field_type S12 = polar(transmission, phase_delay); + s *= S12; + + // Get new ID for output event + s.getNewId(); + + // Write to ouput port after group delay + m_p1_out_writer.delayedWrite(s, sc_time(group_delay_ns, SC_NS)); + } + } + else // dispersion has a defined value + { + while (true) { + // Wait for a new input signal + wait(); + // Read the input signal + auto s = p0_in->read(); + + // calculate phase-delay + const double neff = m_neff + dneff_dlambda * (s.getWavelength() - 1.55e-6) + + d2neff_dlambda2_over_2 * pow(s.getWavelength() - 1.55e-6, 2); + const double ng = m_ng + dng_dlambda * (s.getWavelength() - 1.55e-6); + + const double phase_delay_disp = phase_delay_factor * neff / s.getWavelength(); + const double group_delay_ns_disp = 1e9 * m_length_cm * 1e-2 / (c / ng); + // Apply transmission function + const OpticalSignal::field_type S12 = polar(transmission, phase_delay_disp); + s *= S12; + + // Get new ID for output event + s.getNewId(); + + // Write to ouput port after group delay + m_p1_out_writer.delayedWrite(s, sc_time(group_delay_ns_disp, SC_NS)); + } + } +} + +void WaveguideBi::on_p1_in_changed() +{ + const double c = 299792458.0; + + // attenuation in dB + m_attenuation_dB = m_attenuation_dB_cm * m_length_cm; + + // transmission in field: 10^(-dB/20) + const double transmission = pow(10.0, - m_attenuation_dB / 20.0); + + // vg = c/ng + // => delay = L / vg = (L * ng) / c + const double group_delay_ns = 1e9 * m_length_cm * 1e-2 / (c / m_ng); + + // precalculate 2 * pi * L + double phase_delay_factor = 2.0 * M_PI * m_length_cm * 1e-2; + + // ng = neff - lambda * dneff/dlambda + // => dneff/dlambda = (neff - ng)/lambda + double dneff_dlambda = (m_neff - m_ng) / 1.55e-6; + + // Parameters relative to dispersion + double d2neff_dlambda2_over_2 = -1 * c * m_D / (2 * 1.55e-6); + double dng_dlambda = c*m_D; + + if(m_D == 0) + { + while (true) { + // Wait for a new input signal + wait(); + // Read the input signal + auto s = p1_in->read(); + + // calculate phase-delay + const double neff = m_neff + dneff_dlambda * (s.getWavelength() - 1.55e-6); + + const double phase_delay = phase_delay_factor * neff / s.getWavelength(); + + // Apply transmission function + const OpticalSignal::field_type S12 = polar(transmission, phase_delay); + s *= S12; + + // Get new ID for output event + s.getNewId(); + + // Write to ouput port after group delay + m_p0_out_writer.delayedWrite(s, sc_time(group_delay_ns, SC_NS)); + } + } + else // dispersion has a defined value + { + while (true) { + // Wait for a new input signal + wait(); + // Read the input signal + auto s = p1_in->read(); + + // calculate phase-delay + const double neff = m_neff + dneff_dlambda * (s.getWavelength() - 1.55e-6) + + d2neff_dlambda2_over_2 * pow(s.getWavelength() - 1.55e-6, 2); + const double ng = m_ng + dng_dlambda * (s.getWavelength() - 1.55e-6); + + const double phase_delay_disp = phase_delay_factor * neff / s.getWavelength(); + const double group_delay_ns_disp = 1e9 * m_length_cm * 1e-2 / (c / ng); + // Apply transmission function + const OpticalSignal::field_type S12 = polar(transmission, phase_delay_disp); + s *= S12; + + // Get new ID for output event + s.getNewId(); + + // Write to ouput port after group delay + m_p0_out_writer.delayedWrite(s, sc_time(group_delay_ns_disp, SC_NS)); + } + } +}
\ No newline at end of file diff --git a/src/devices/waveguide.h b/src/devices/waveguide.h new file mode 100644 index 0000000..c686bba --- /dev/null +++ b/src/devices/waveguide.h @@ -0,0 +1,154 @@ +#pragma once + +#include <systemc.h> + +#include <optical_output_port.h> +#include <optical_signal.h> +#include "specs.h" +#include "spx_module.h" + +/** The base class for the waveguide module */ +class WaveguideBase : public spx_module { +public: + // Member variables + + /** The length of the waveguide in cm. */ + double m_length_cm; + /** The attenuation of the waveguide in dB. */ + double m_attenuation_dB; + /** The attenuation inside the waveguide, in dB/cm */ + double m_attenuation_dB_cm; + + /** The effective index of the waveguide */ + double m_neff; + /** The group index of the waveguide */ + double m_ng; + /** The group velocity dispersion Dlambda of the waveguide in [s/m/m] */ + double m_D; + + /** Constructor for WaveguideBase + * + * @param name name of the module + * @param length_cm length of the waveguide in cm + * */ + WaveguideBase(sc_module_name name, double length_cm = 1e-2, + double attenuation_dB_cm = 0, double neff = 2.2111, + double ng = 2.2637, double D = 0) + : spx_module(name) + , m_length_cm(length_cm) + , m_attenuation_dB_cm(attenuation_dB_cm) + , m_neff(neff) + , m_ng(ng) + , m_D(D) + { + // nothing to do + } + + inline void setLength(double length_cm) { + if (length_cm < 0) { + std::cerr << "Error: waveguide length < 0" << std::endl; + } + m_length_cm = length_cm; + } +}; + + +/** A unidirectional waveguide module */ +class WaveguideUni : public WaveguideBase { +public: + // Ports + /** The optical input port. */ + spx::oa_port_in_type p_in; + /** The optical output port. */ + spx::oa_port_out_type p_out; + + // Timed ports writers + /** Timed writer to the output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_out_writer; + + // Processes + /** Main process of the module. + * + * It copies the input to the output, after attenuation and delay. + * + * **SystemC type:** thread + * + * **Sensitivity list:** p_in + * */ + void on_port_in_changed(); + + /** Constructor for Waveguide + * + * @param name name of the module + * @param length_cm length of the waveguide in cm + * */ + WaveguideUni(sc_module_name name, double length_cm = 1e-2, + double attenuation_dB_cm = 0, double neff = 2.2111, + double ng = 2.2637, double D = 0) + : WaveguideBase(name, length_cm, attenuation_dB_cm, neff, ng, D) + , m_out_writer("out_delayed_writer", p_out) + { + SC_HAS_PROCESS(WaveguideUni); + + SC_THREAD(on_port_in_changed); + sensitive << p_in; + } +}; + +typedef WaveguideUni Waveguide; + +/** A bidirectional waveguide module */ +class WaveguideBi : public WaveguideBase { +public: + // Ports + /** The optical input ports. */ + spx::oa_port_in_type p0_in; + spx::oa_port_in_type p1_in; + + /** The optical output ports. */ + spx::oa_port_out_type p0_out; + spx::oa_port_out_type p1_out; + + // Timed ports writers + /** Timed writer to the output port. + * + * @sa DelayedWriter + * */ + OpticalOutputPort m_p0_out_writer; + OpticalOutputPort m_p1_out_writer; + + // Processes + /** Main process of the module. + * + * It copies the input to the output, after attenuation and delay. + * + * **SystemC type:** thread + * + * **Sensitivity list:** p0_in or p1_in + * */ + void on_p0_in_changed(); + void on_p1_in_changed(); + + /** Constructor for Waveguide + * + * @param name name of the module + * @param length_cm length of the waveguide in cm + * */ + WaveguideBi(sc_module_name name, double length_cm = 1e-2, + double attenuation_dB_cm = 0, double neff = 2.2111, + double ng = 2.2637, double D = 0) + : WaveguideBase(name, length_cm, attenuation_dB_cm, neff, ng, D) + , m_p0_out_writer("p0_out_delayed_writer", p0_out) + , m_p1_out_writer("p1_out_delayed_writer", p1_out) + { + SC_HAS_PROCESS(WaveguideBi); + + SC_THREAD(on_p0_in_changed); + sensitive << p0_in; + SC_THREAD(on_p1_in_changed); + sensitive << p1_in; + } +}; diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..2dc9e93 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,325 @@ +#include <ctime> +#include <iomanip> +#include <sstream> +#include <chrono> + +#include <optical_signal.h> +#include <time_monitor.h> +#include <tb/alltestbenches.h> +#include <utils/strutils.h> + +#include <systemc.h> + +#include <args.hxx> + +#include <specs.h> +#include "optical_output_port.h" +#include "parser/parse_tree.h" + +class OpticalOutputPort; + +using namespace std; +using namespace std::chrono; +using namespace literals; + +#include "../build/parser/parser.tab.h" +#include "../build/parser/parser.yy.h" +extern int yydebug; + +int do_list_tests() +{ + cout << "Valid testbench identifiers:" << endl; + if (tb_map.empty()) + cout << "\t # No test available #" << endl; + for (const auto &test_pair : tb_map) { + cout << "\t" << test_pair.first << endl; + } + return 0; +} + +int do_test(const string &testname) +{ + // Try to find the test specified by testname from the tb_mab + auto it = tb_map.find(testname); + if (it == tb_map.end()) { + // Not found + cerr << "Test not found: " << testname << endl; + return 1; + } + + // Call the testbench function associated with testname + auto start = high_resolution_clock::now(); + it->second(); + auto stop = high_resolution_clock::now(); + auto duration = duration_cast<microseconds>(stop - start); + std::cout << "Total runtime: " << duration.count()/1000.0 << " ms" << std::endl; + return 0; +} + +int do_circuit(const string &filename, bool is_dry_run = false, const string& json_filename = "") +{ + // Check whether the file exists + FILE *f; + if (filename == "-"s) { + f = NULL; + } else if (!(f = fopen(filename.c_str(), "r"))) { + cerr << "Error: File not found \"" << filename << "\"" << endl; + return 1; + } + + cout << "╔═══════════════════╗" << endl; + cout << "║ PARSING CIRCUIT ║" << endl; + cout << "╚═══════════════════╝" << endl; + + yyscan_t scanner; + YY_BUFFER_STATE buf; + + yylex_init(&scanner); + buf = yy_create_buffer(f, YY_BUF_SIZE, scanner); + yy_switch_to_buffer(buf, scanner); + + ParseTree pt("ROOT"); + int parsing_result = yyparse(scanner, &pt); + + //yy_delete_buffer(buf, scanner); + yylex_destroy(scanner); + + // Close the file + if (f) + fclose(f); + + // Return if unsuccessful + if (parsing_result != 0) { + return parsing_result; + } + + pt.print(); + + cout << "╔══════════════════════╗" << endl; + cout << "║ BUILDING CIRCUIT ║" << endl; + cout << "╚══════════════════════╝" << endl; + + pt.build_circuit(); + + if (!json_filename.empty()) + { + ofstream outfile; + outfile.open(json_filename, ios::out | ios::trunc); + outfile << pt.to_json(); + outfile.close(); + cout << "Exported flattened circuit as JSON > " << json_filename << endl; + } + + if (!is_dry_run) + { + cout << "╔══════════════════════╗" << endl; + cout << "║ SIMULATION ║" << endl; + cout << "╚══════════════════════╝" << endl; + + specsGlobalConfig.runAnalysis(); + } + else + { + cout << "╔══════════════════════╗" << endl; + cout << "║ SIMULATION SKIPPED ║" << endl; + cout << "╚══════════════════════╝" << endl; + } + + cout << "╔═══════════════════╗" << endl; + cout << "║ DONE ║" << endl; + cout << "╚═══════════════════╝" << endl; + + return 0; +} + +int raphael_main() { cout<< "Hello world" << endl; return 0; } + +int tests_module_registry_access(); + +int sc_main(int argc, char *argv[]) +{ + // Define command line interface using args + args::ArgumentParser parser("The Scalable Photonic Event-driven Circuit Simulator.", ""); + args::ValueFlag<string> file( + parser, "circuit", "Simulate from circuit file", { 'f', "file" }); + args::ValueFlag<int> set_timescale(parser, + "set_timescale", + "Set the engine timescale (as log10(timestep/1s))" + "(0: seconds, -3: ms, -6:µs, ..., -15: fs)", + { 'R', "resolution" }); + args::ValueFlag<string> set_simulator_mode(parser, + "set_simulator_mode", + "Set simulator mode. Possible values:\n" + " - time-domain, event-driven, td (default)\n" + " - sampled-time\n" + " - frequency-domain, fd", + { 'm', "mode"}); + args::Flag run_manual_test(parser, + "run_manual_test", + "Run manual test function", + { 'T', "run-manual-test" }); +#if YYDEBUG + args::Flag debug_netlist_parser(parser, + "debug_netlist_parser", + "Run with netlist parser debug information", + { "debug-parser" }); +#endif + args::ValueFlag<string> set_tracefile(parser, + "set_tracefile", + "Set the default trace file", + { 'o', "output" }); + args::ValueFlag<string> export_json(parser, + "export_json", + "Export json of completed circuit to file", + { "json" }); + args::Flag set_dry_run(parser, + "dry_run", + "Do not run simulation directives", + { 'n', "dryrun" }); + // args::ValueFlag<double> set_reltol(parser, + // "set_reltol", + // "Set the value of the rel_tol parameter", + // { "reltol" }); + args::ValueFlag<double> set_reltol(parser, + "set_reltol", + "Set the value of the relative tolerance parameter for field", + { "reltol" }); + args::ValueFlag<double> set_abstol(parser, + "set_abstol", + "Set the value of the absolute tolerance parameter for field", + { "abstol" }); + + args::ValueFlag<size_t> set_nrings_crow(parser, + "set_nrings_crow", + "temporary", + { "nrings_crow" }); + + args::Flag set_verbose_component_initialization(parser, + "set_verbose_component_initialization", + "Print components detail before starting simulation", + { "vci", "verbose_ci" }); + + args::Flag list_tests(parser, + "list_tests", + "List available testbenches", + { 'p', "list-testbenches" }); + args::Flag add_time_monitor(parser, + "add_time_monitor", + "Monitor simulation status", + { "mon" }); + args::ValueFlag<string> test( + parser, + "test_name", + "Run the specified testbench (use -p to list available testbenches)", + { 't', "testbench" }); + args::HelpFlag help(parser, "help", "Display this help menu", { 'h', "help" }); + args::CompletionFlag completion(parser, { "complete" }); + try { + parser.ParseCLI(argc, argv); + } catch (const args::Completion &e) { + cout << e.what(); + return 0; + } catch (const args::Help &) { + cout << parser; + return 0; + } catch (const args::ParseError &e) { + cerr << e.what() << endl; + cerr << parser; + return 1; + } catch (const args::ValidationError &e) { + cerr << e.what() << endl; + cerr << parser; + return 1; + } + + if (set_simulator_mode) { + const string &s = set_simulator_mode.Get(); + if (strutils::iequals(s, "event-driven") || strutils::iequals(s, "time-domain") || strutils::iequals(s, "td")) + { + cout << "Optical ports working in event-driven mode by default" << endl; + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + } + else if (strutils::iequals(s, "sampled-time")) + { + cout << "Optical ports working in sampled-time mode by default" << endl; + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::SAMPLED_TIME; + } + else if (strutils::iequals(s, "frequency-domain") || strutils::iequals(s, "fd")) + { + cout << "Simulation mode set to frequency domain" << endl; + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::FREQUENCY_DOMAIN; + } + else + { + cerr << "Unknown mode: '" << s << "'" << endl; + return 1; + } + } + if (set_reltol) { + if (set_reltol.Get() > 0) { + specsGlobalConfig.default_reltol = set_reltol.Get(); + } else { + cerr << "Invalid abs_tol_phase value" << endl; + return 1; + } + } + if (set_abstol) { + if (set_abstol.Get() > 0) { + specsGlobalConfig.default_abstol = set_abstol.Get(); + } else { + cerr << "Invalid abs_tol_power value" << endl; + return 1; + } + } + if (set_verbose_component_initialization) { + specsGlobalConfig.verbose_component_initialization = set_verbose_component_initialization.Get(); + } + if (set_nrings_crow) { + #if BUILD_TB == 1 + //nrings_crow = set_nrings_crow.Get(); + #endif + } + if (set_timescale) { + cout << set_timescale.Get() << endl; + specsGlobalConfig.engine_timescale = SPECSConfig::EngineTimescale(set_timescale.Get()); + } + if (run_manual_test) { + return 0; + } +#if YYDEBUG + if (debug_netlist_parser) { + yydebug = 1; + } +#endif + if (list_tests) { + return do_list_tests(); + } + if (set_tracefile) { + cout << "Using trace file: " << set_tracefile.Get() << endl; + // TODO: validate filename + specsGlobalConfig.trace_filename = set_tracefile.Get(); + } + + shared_ptr<TimeMonitor> tm; + if (add_time_monitor) { + if (specsGlobalConfig.simulation_mode == OpticalOutputPortMode::FREQUENCY_DOMAIN) + tm = make_shared<TimeMonitor>("TM", 0, 0.5); + else + tm = make_shared<TimeMonitor>("TM", 1e-14, 0.5); + } + + if (file) { + return do_circuit(file.Get(), set_dry_run.Get(), export_json.Get()); + } + if (set_dry_run) + { + return 0; + } + if (test) { + return do_test(test.Get()); + } + + // Print help if nothing else was done + cout << parser; + return 1; +} diff --git a/src/optical_output_port.cpp b/src/optical_output_port.cpp new file mode 100644 index 0000000..7a6fe9c --- /dev/null +++ b/src/optical_output_port.cpp @@ -0,0 +1,424 @@ +#include <optical_output_port.h> +#include <optical_signal.h> +#include <specs.h> + +string oopPortMode2str(OpticalOutputPortMode mode) +{ + switch (mode) { + case EVENT_DRIVEN: + return "Event-driven time-domain"; + case SAMPLED_TIME: + return "Emulated time-driven time-domain"; + case FREQUENCY_DOMAIN: + return "Event-driven frequency-domain"; + default: + return "UNDEFINED"; + } +} + +OpticalOutputPort::OpticalOutputPort(sc_module_name name, port_type &p) + : sc_module(name) + , m_port(p) + , m_config(nullptr) +{ + SC_HAS_PROCESS(OpticalOutputPort); + + // SC_THREAD(on_data_ready); + // sensitive << m_event_queue; + + SC_THREAD(on_data_ready); + sensitive << m_event_queue; + + // SC_THREAD(on_data_ready_fd); + // sensitive << m_event_queue_fd; + + // SC_THREAD(drop_all_events); + // sensitive << specsGlobalConfig.drop_all_events; +} + +// void OpticalOutputPort::drop_all_events() { +// while(true) +// { +// wait(); +// cout << name() << ": dropping all events!" << endl; +// while (!isempty()) +// { +// cout << name() << ": dropping all events" << endl; +// m_event_queue.cancel_all(); +// m_queue = queue_type(); +// m_emitted_val = OpticalSignal(0); +// m_queue_td = queue_type(); +// m_emitted_val = OpticalSignal(0); +// m_queue_fd = queue_type(); +// m_emitted_val = OpticalSignal(0); +// m_cur_val = OpticalSignal(0); +// wait(SC_ZERO_TIME); +// } +// } +// } + +inline bool OpticalOutputPort::check_emit_by_abstol(const OpticalSignal::field_type &desired, + const OpticalSignal::field_type &last) +{ + double vector_distance = abs(desired - last); + return vector_distance > m_abstol; +} + +inline bool OpticalOutputPort::check_emit_by_reltol(const OpticalSignal::field_type &desired, + const OpticalSignal::field_type &last) +{ + double vector_distance = abs(desired - last); + double last_size = abs(last); + return (vector_distance/last_size) > m_reltol; +} + +void OpticalOutputPort::applyConfig() { + if (!m_config) + { + // Shouldn't ever need to come here if prepareSimulation was called + cerr << "Found OpticalOutputPort without configuration. "; + cerr << "Did you forget to run prepareSimulation() ?" << endl; + exit(1); + //m_config = make_shared<OpticalOutputPortConfig>(); + } + + m_temporal_resolution = sc_time::from_value(m_config->m_timestep_value); + m_mode = m_config->m_mode; + m_reltol = m_config->m_reltol; + m_abstol = m_config->m_abstol; +} + +void OpticalOutputPort::start_of_simulation() { + applyConfig(); +} + +void OpticalOutputPort::on_data_ready() +{ + // Initialize output queue + m_queue = queue_type(); + + spx::oa_value_type::field_type desired; + + while (true) { + // Wait for data ready notification + wait(); + + // Check if output queue is empty (would be a bug) + if (m_queue.size() == 0) { + if (specsGlobalConfig.drop_all_events) + continue; + cerr << "error: write cancelled, because no values are present" << endl; + if (true) sc_stop(); + else continue; + } + + // Get current time + sc_time now = sc_time_stamp(); + + // Get the next queue item and pop it from the queue + auto tuple = m_queue.top(); + m_queue.pop(); + + // If next event is also now, notify event queue + // if (m_queue.top().first == now) + // m_event_queue.notify(SC_ZERO_TIME); + + // Assign to more readable names + const auto &t = tuple.first; //time + const auto &s = tuple.second; //signal + + // Check whether the signal should indeed be emitted now (if not, it's a bug) + if (t != now) + { + cerr << "error: desync in optical output port " << this->name() << endl; + cerr << "\t - expected time:" << t.to_seconds() << endl; + cerr << "\t - current time:" << now.to_seconds() << endl; + cerr << "\t - signal:" << s << endl; + if (true) sc_stop(); + else continue; + } + + // Check signal error to decice whether to emit signal + bool emit_signal = false; + bool pass_abstol = false; + bool pass_reltol = false; + + uint32_t wlid = s.m_wavelength_id; + + //auto &desired = m_desired_fields[wlid]; + auto &emitted = m_emitted_fields[wlid]; + + // Store the desired output value which we know is valid + if (m_use_deltas) + { + desired = m_desired_fields[wlid] + s.m_field; + m_desired_fields[wlid] = desired; + } + else + desired = s.m_field; + + // Decide whether to emit signal or not + pass_abstol = check_emit_by_abstol(desired, emitted); + pass_reltol = check_emit_by_reltol(desired, emitted); + + // Only emits when passes both tests + emit_signal = pass_abstol && pass_reltol; + + // Emit zeros instead of signals smaller than a 10 abstol + // TODO: check this !! + if (emit_signal && (abs(desired) < 10*m_abstol)) + desired = complex<double>(0,0); + + + // cout << "emit: " << emit_signal << endl; + // Emit the desired output value if its stars are aligned + if (emit_signal || m_skip_next_convergence_check || m_skip_convergence_check) + { + // cout << dynamic_cast<spx::oa_signal_type *>(m_port.get_interface())->name(); + // cout << " emitting " << m_desired_fields[wlid] << endl; + m_skip_next_convergence_check = false; + + // Replace the stored emitted output value at that wavelength + emitted = desired; + + // Write the value to the port + m_port->write(spx::oa_value_type(desired, wlid)); + } + } +} + +// Should be removed +void OpticalOutputPort::on_data_ready_fd() +{ + cerr << "Using deprecated function: " << __FUNCTION__ << endl; + exit(1); +#if 0 + // Initialize output queue + m_queue_fd = queue_type(); + + m_cur_val_fd = OpticalSignal(0); + m_emitted_val_fd = OpticalSignal(0); + + // Current error between cur_val and emitted_val + double err_abs_power = 0; + double err_abs_phase = 0; + + while (true) { + // Wait for data ready notification + wait(); + + // Check if output queue is empty (would be a bug) + if (m_queue_fd.size() == 0) { + if (specsGlobalConfig.drop_all_events) + continue; + cerr << "error: write cancelled, because no values are present" << endl; + if (true) sc_stop(); + else continue; + } + + // Get current time + sc_time now = sc_time_stamp(); + + // Get the next queue item and pop it from the queue + auto tuple = m_queue_fd.top(); + m_queue_fd.pop(); + + // Assign to more readable names + const auto &t = tuple.first; + const auto &s = tuple.second; + + // Check whether the signal should indeed be emitted now (if not, it's a bug) + if (t != now) + { + cerr << "error: desync in optical output port" << endl; + cerr << "\t - expected time:" << t.to_seconds() << endl; + cerr << "\t - current time:" << now.to_seconds() << endl; + if (true) sc_stop(); + else continue; + } + + // If the new desired signal has NaN wavelength, ignore it + if (isnan(s.getWavelength())) + { + continue; + } + + // Check if wavelength is the same as stored signal + bool wavelength_nan = isnan(m_emitted_val_fd.getWavelength()); + bool wavelength_same = s.m_wavelength_id == m_emitted_val_fd.m_wavelength_id; + bool wavelength_greater = s.getWavelength() > m_emitted_val_fd.getWavelength(); + bool wavelength_ok = wavelength_same || wavelength_nan || wavelength_greater; + + // Check signal error to decice whether to emit signal + bool emit_signal = false; + bool pass_abstol = false; + bool pass_reltol = false; + + // If new wavelength should not be emitted, don't do anything and + // wait for the next signal + if (!wavelength_ok) + continue; + + // Here we know s can be emitted. Update the desired output value + if (m_use_deltas) + m_cur_val_fd += s; + else + m_cur_val_fd = s; + + // If previous wavelength was NaN or smaller than current wavelength, emit new signal + if (wavelength_nan || wavelength_greater) + { + emit_signal = true; + } + + // If same wavelength, decide whether to emit signal or not based on tolerances + if (wavelength_same) + { + pass_abstol = check_emit_by_abstol(m_cur_val_fd, m_emitted_val_fd); + pass_reltol = check_emit_by_reltol(m_cur_val_fd, m_emitted_val_fd); + + // Only emits when passes both tests + emit_signal = pass_abstol && pass_reltol; + + // Emit zeros instead of signals smaller than 10 abstol + if (emit_signal && (abs(m_cur_val_fd.m_field) < 10*m_abstol)) + m_cur_val_fd.m_field = complex<double>(0,0); + } + + // Emit the desired output value if its stars are aligned + if (emit_signal) + { + // Replace the stored emitted output value + m_emitted_val_fd = m_cur_val_fd; + + // Write the value to the port + m_port->write(m_cur_val_fd); + } + } +#endif +} + +sc_time OpticalOutputPort::snap_to_next_valid_time(const sc_time &t, const unsigned int resolution_multiplier) +{ + // Squash time to closest timestamp using device temporal resolution and multiplier + + // Find the effective number of ticks/timestep of the output port + sc_time::value_type dt_val = m_temporal_resolution.value() * resolution_multiplier; + + // Should be at least one tick + if (dt_val <= 1) + return t; + + // Snap the time to the closest multiple of dt + //auto t_snap_value = dt_val * round((double)t.value() / dt_val); + auto t_snap_value = dt_val * ((t.value() + dt_val/2)/ dt_val); + + // If we end up before current time, snap to the next multiple of dt + // We do this instead of using ceil() because in the case where the event + // is far into the future, it is more accurate to round(). + if (t_snap_value < sc_time_stamp().value()) + t_snap_value += dt_val; + + // Return the snaped time value (in number of simulation ticks) + return sc_time::from_value(t_snap_value); +} + +void OpticalOutputPort::delayedWriteEventDriven(const OpticalSignal &value, const sc_time &delay, const unsigned int resolution_multiplier) +{ + // Calculate the simulation time at which event was requested to be emitted. + auto t = sc_time_stamp() + delay; + if (t.value() - sc_time_stamp().value() != delay.value()) + cerr << "Event cannot be correctly described with current timestep" << endl; + + // + if (true /*&& resolution_multiplier > 1*/) { + // squash time to closest timestamp using device temporal resolution + t = snap_to_next_valid_time(t, resolution_multiplier); + } + + + // find first scheduled signal with this timestamp and this lambda + auto it = std::find_if(m_queue.begin(), m_queue.end(), [&value,&t](const auto &x) { + return t == x.first && value.m_wavelength_id == x.second.m_wavelength_id; + }); + + // check if an event was already scheduled for the same timestamp + if (it == m_queue.cend()) { + // if not, just schedule the new event + m_queue.push(std::make_pair(t, value)); + m_event_queue.notify(t - sc_time_stamp()); + } + else { + // if yes, just replace or sum with the old one + if (m_use_deltas) + it->second += value; + else + it->second = value; + } +} + +void OpticalOutputPort::delayedWriteSampledTime(const OpticalSignal &value, const sc_time &delay, const unsigned int resolution_multiplier) +{ + (void)value; + (void)delay; + (void)resolution_multiplier; + // TODO + // Goal here will be to manage, maybe, some averaging + // i.e. when we output sampled-time, if we receive event-driven signals, we convert them + // to sampled-time by averaging over the timestep and emitting the average +} + +void OpticalOutputPort::immediateWriteFrequencyDomain(const OpticalSignal &value) +{ +#if 1 + //if (specsGlobalConfig.drop_all_events) + // return; + //if (value.power() <= m_abs_tol_power && m_emitted_val_fd.power() <= m_abs_tol_power) + // return; + + const sc_time &now = sc_time_stamp(); + if (m_queue.empty() || m_queue.cbegin()->first != now) { + // if the queue is empty, or contains no event for current time, + // push the signal directly + m_queue.push(make_pair(now, value)); + m_event_queue.notify(SC_ZERO_TIME); + } + else { + // if the queue is contains an event for current time + if (m_queue.cbegin()->second.m_wavelength_id == value.m_wavelength_id) { + // if wavelengths are equal, just replace or sum with the old one + if (m_use_deltas) + m_queue.begin()->second += value; + else + m_queue.begin()->second = value; + //m_event_queue_fd.cancel_all(); + //m_event_queue_fd.notify(SC_ZERO_TIME); + } else { + // otherwise just schedule event separately + m_queue.push(make_pair(now, value)); + m_event_queue.notify(SC_ZERO_TIME); + } + } +#else + cerr << "Using implemented function: " << __FUNCTION__ << endl; +#endif +} + +void OpticalOutputPort::delayedWrite(const OpticalSignal &value, const sc_time &delay, const unsigned int resolution_multiplier) +{ + switch(m_mode) { + case OpticalOutputPortMode::EVENT_DRIVEN: + delayedWriteEventDriven(value, delay, resolution_multiplier); + return; + case OpticalOutputPortMode::SAMPLED_TIME: + delayedWriteSampledTime(value, delay, resolution_multiplier); + return; + case OpticalOutputPortMode::FREQUENCY_DOMAIN: + //delayedWriteEventDriven(value, SC_ZERO_TIME, 1); + immediateWriteFrequencyDomain(value); + default: + break; // throw here + } + +} + diff --git a/src/optical_output_port.h b/src/optical_output_port.h new file mode 100644 index 0000000..c0cd7dd --- /dev/null +++ b/src/optical_output_port.h @@ -0,0 +1,178 @@ +#pragma once + +#include <cstdlib> +#include <deque> +#include <systemc.h> +#include <utility> +#include <vector> +#include <queue> +#include <map> + +#include <optical_signal.h> +#include <pqueue.h> + +using std::cout; +using std::endl; + +using std::pair; +using std::vector; +using std::priority_queue; + +enum OpticalOutputPortMode { + PORT_MODE_MINVAL, + EVENT_DRIVEN, + SAMPLED_TIME, + NO_DELAY, + PORT_MODE_MAXVAL, + + // aliases + TIME_DOMAIN = EVENT_DRIVEN, + FREQUENCY_DOMAIN = NO_DELAY, + DEFAULT = EVENT_DRIVEN, + UNDEFINED = PORT_MODE_MAXVAL, +}; + +string oopPortMode2str(OpticalOutputPortMode mode); + +class OpticalOutputPortConfig { +public: + OpticalOutputPortMode m_mode = OpticalOutputPortMode::DEFAULT; + double m_abstol = 1e-8; + double m_reltol = 1e-4; + sc_time::value_type m_timestep_value = 1; // relative to systemc timestep + + OpticalOutputPortConfig() {} +}; + +class OpticalOutputPort : public sc_module { +public: + typedef OpticalOutputPort this_type; + typedef sc_port<sc_signal_out_if<OpticalSignal>> port_type; + typedef pair<sc_time, OpticalSignal> pair_type; + typedef PQueue<pair_type> queue_type; + + +// private: +public: + port_type &m_port; + queue_type m_queue; + // queue_type m_queue_fd; + // queue_type m_queue_td; + sc_event_queue m_event_queue; + // sc_event_queue m_event_queue_td; + // sc_event_queue m_event_queue_fd; + // OpticalSignal m_cur_val; + // OpticalSignal m_cur_val_td; + // OpticalSignal m_cur_val_fd; + // OpticalSignal m_emitted_val; + // OpticalSignal m_emitted_val_fd; + + std::map<uint32_t,OpticalSignal::field_type> m_desired_fields; + std::map<uint32_t,OpticalSignal::field_type> m_emitted_fields; + + sc_time m_temporal_resolution; + OpticalOutputPortMode m_mode; + double m_reltol; + double m_abstol; + bool m_use_deltas = false; + bool m_converger = false; + bool m_skip_next_convergence_check = false; + bool m_skip_convergence_check = false; + + std::shared_ptr<const OpticalOutputPortConfig> m_config; + + // void drop_all_events(); + void on_data_ready(); + void on_data_ready_fd(); + bool check_emit_by_abstol(const OpticalSignal::field_type &desired, const OpticalSignal::field_type &last); + bool check_emit_by_reltol(const OpticalSignal::field_type &desired, const OpticalSignal::field_type &last); + + void applyConfig(); + virtual void start_of_simulation(); + sc_time snap_to_next_valid_time(const sc_time &t, const unsigned int resolution_multiplier=1); + void delayedWriteEventDriven(const OpticalSignal &value, const sc_time &delay, const unsigned int resolution_multiplier=1); + void delayedWriteSampledTime(const OpticalSignal &value, const sc_time &delay, const unsigned int resolution_multiplier=1); + void immediateWriteFrequencyDomain(const OpticalSignal &value); + +public: + OpticalOutputPort(sc_module_name name, port_type &p); + + ~OpticalOutputPort() {} + + // Set config + void setConfig(shared_ptr<OpticalOutputPortConfig> &config) + { + m_config = config; + } + const shared_ptr<const OpticalOutputPortConfig>& getConfig() const + { + return m_config; + } + + void drop_queue() + { + if (sc_get_simulator_status() == SC_RUNNING) + { + cerr << "Cannot drop if simulation is running" << endl; + exit(1); + } + m_event_queue.cancel_all(); + m_queue = queue_type(); + } + + void reset() + { + drop_queue(); + m_desired_fields.clear(); + m_emitted_fields.clear(); + } + + void swap_wavelengths(uint32_t wl1, uint32_t wl2) + { + drop_queue(); + + // Create entries with 0 if they don't exist + m_desired_fields.emplace(wl1, 0); + m_desired_fields.emplace(wl2, 0); + m_emitted_fields.emplace(wl1, 0); + m_emitted_fields.emplace(wl2, 0); + + // Swap wl1 and wl2 entries + swap(m_desired_fields.at(wl1), m_desired_fields.at(wl2)); + swap(m_emitted_fields.at(wl1), m_emitted_fields.at(wl2)); + } + + void delete_wavelength(uint32_t wl) + { + drop_queue(); + // Create entries with 0 if they don't exist + m_desired_fields.erase(wl); + m_emitted_fields.erase(wl); + } + + // inline double current_err() const { + // double err_abs_power = abs(m_cur_val.power() - m_emitted_val.power()); + // double err_abs_phase = abs(m_cur_val.phase() - m_emitted_val.phase()); + // if (m_cur_val.power() > m_abstol) + // return max(err_abs_power, err_abs_phase); + // return err_abs_power; + // } + + inline double current_err_fd() const { + cerr << "Using deprecated function: " << __FUNCTION__ << endl; + exit(1); + // double err_abs_power = abs(m_cur_val_fd.power() - m_emitted_val_fd.power()); + // double err_abs_phase = abs(m_cur_val_fd.phase() - m_emitted_val_fd.phase()); + // if (m_cur_val_fd.power() >= m_abstol) + // return max(err_abs_power, err_abs_phase); + // return err_abs_power; + return 0; + } + + inline bool isempty() const + { + return m_queue.empty(); + } + + void delayedWrite(const OpticalSignal &value, const sc_time &delay, const unsigned int resolution_multiplier=1); +}; diff --git a/src/optical_signal.cpp b/src/optical_signal.cpp new file mode 100644 index 0000000..704dfd6 --- /dev/null +++ b/src/optical_signal.cpp @@ -0,0 +1,157 @@ +#include <optical_signal.h> +#include <specs.h> + +using namespace std::complex_literals; + +unsigned int OpticalSignal::nextId = 0; + +OpticalSignal &OpticalSignal::operator+=(const OpticalSignal &rhs) +{ + // cout << "Summing two signals: " << endl; + // cout << "\t" << *this << endl; + // cout << "\t" << rhs << endl; + + auto this_wavelength = this->getWavelength(); + auto rhs_wavelength = rhs.getWavelength(); + + if (this_wavelength == rhs_wavelength) + m_field += rhs.m_field; + else if (isnan(rhs_wavelength)) + (void)rhs; // nothing to do + else if (isnan(this_wavelength)) + *this = rhs; + else if (specsGlobalConfig.simulation_mode == FREQUENCY_DOMAIN) + { + // TODO: move that somewhere else ??? + // Replace with rhs + if (rhs_wavelength > this_wavelength) + *this = rhs; + } + else + cerr << "Attempted to sum signals of different wavelengths, but current" + << "simulation mode doesn't allow it (" << __FUNCTION__ << ")" << endl; + // cout << "\t--> " << *this << endl; + return *this; +} + +OpticalSignal &OpticalSignal::operator-=(const OpticalSignal &rhs) +{ + // cout << "Substracting two signals: " << endl; + // cout << "\t" << *this << endl; + // cout << "\t" << rhs << endl; + + auto this_wavelength = this->getWavelength(); + auto rhs_wavelength = rhs.getWavelength(); + + if (this_wavelength == rhs_wavelength) + m_field -= rhs.m_field; + else if (isnan(rhs_wavelength)) + (void)rhs; // nothing to do + else if (isnan(this_wavelength)) + *this = rhs; + else if (specsGlobalConfig.simulation_mode == FREQUENCY_DOMAIN) + { + // TODO: move that somewhere else ??? + // Replace with rhs + if (rhs_wavelength > this_wavelength) + *this = rhs; + } + else + cerr << "Attempted to substract signals of different wavelengths, but current" + << "simulation mode doesn't allow it (" << __FUNCTION__ << ")" << endl; + // cout << "\t--> " << *this << endl; + return *this; +} + +OpticalSignal OpticalSignal::sumSignals(OpticalSignal s0, OpticalSignal s1) +{ + cerr << "Use of deprecated" << __FUNCTION__<< endl; + + // Maybe doing just the sum is faster than this + if (s0.m_field == 0.0) { + OpticalSignal os_sum = s1; + os_sum.getNewId(); + return os_sum; + } + if (s1.m_field == (complex<double>) 0) { + OpticalSignal os_sum = s0; + os_sum.getNewId(); + return os_sum; + } + + if (s0.getWavelength() != s1.getWavelength()) + { + bool ignore_wavelength_error = false; + if (ignore_wavelength_error) + { + cerr << "Signals have different wavelengths:" << std::endl; + cerr << "\t" << s0.getWavelength() << "(" << norm(s0.m_field) << ")" + << "\t" << s1.getWavelength() << "(" << norm(s1.m_field) << ")" + << std::endl; + + sc_stop(); + } else { + OpticalSignal os_sum = s0; + if (norm(s1.m_field) > norm(s0.m_field)) + os_sum = s1; + os_sum.getNewId(); + return os_sum; + } + } + + complex<double> Asum = s0.m_field + s1.m_field; + + OpticalSignal os_sum = s0; + os_sum.m_field = Asum; + os_sum.getNewId(); + + return os_sum; +} + +uint32_t OpticalSignal::getIDFromWavelength(const double &wavelength) +{ + auto it = find (specsGlobalConfig.wavelengths_vector.cbegin(), + specsGlobalConfig.wavelengths_vector.cend(), + wavelength); + + uint32_t index; + + if (it != specsGlobalConfig.wavelengths_vector.cend()) + { // Found + index = it - specsGlobalConfig.wavelengths_vector.cbegin(); + } + else + { // Didn't find, has to add it to the vector + specsGlobalConfig.wavelengths_vector.push_back(wavelength); + index = specsGlobalConfig.wavelengths_vector.size() - 1; + // -1 because of zero indexing + } + + if (index == (uint32_t)(-1)) + { + cerr << "Error: too many wavelengths being used ." << endl; + exit(1); + } + + return index; +} + +double OpticalSignal::getWavelength() const +{ + if (m_wavelength_id >= specsGlobalConfig.wavelengths_vector.size()) + { + cerr << "Wavelength not found in global vector." << endl; + exit(1); + } + return specsGlobalConfig.wavelengths_vector[m_wavelength_id]; +} + +double OpticalSignal::getWavelength(const uint32_t &wavelength_id) +{ + if (wavelength_id >= specsGlobalConfig.wavelengths_vector.size()) + { + cerr << "Wavelength not found in global vector." << endl; + exit(1); + } + return specsGlobalConfig.wavelengths_vector[wavelength_id]; +}
\ No newline at end of file diff --git a/src/optical_signal.h b/src/optical_signal.h new file mode 100644 index 0000000..b597b98 --- /dev/null +++ b/src/optical_signal.h @@ -0,0 +1,251 @@ +#pragma once + +#include <iomanip> +#include <iostream> +#include <string> +#include <utility> +#include <vector> +#include <algorithm> +#include <cmath> +#include <complex> +#include <stdlib.h> + +#include <systemc.h> + +using namespace std; + +class OpticalSignal { +public: + typedef complex<double> field_type; + +private: + // class variable for holding next id to attribute + static unsigned int nextId; + +public: + field_type m_field; // complex field of the signal (V/m) + uint32_t m_wavelength_id; // accesses the global vector of wavelengths + unsigned int m_id; + + // Constructor from values + OpticalSignal(const field_type &field = 0.0, + const double &wavelength = numeric_limits<double>::quiet_NaN()) + : m_field(field) + { + if (!isnan(wavelength)) + m_wavelength_id = getIDFromWavelength(wavelength); + else + m_wavelength_id = 0; + getNewId(); + } + + // Constructor sending an id + OpticalSignal(const field_type &field, + const uint32_t &wavelength_id) + : m_field(field) + , m_wavelength_id(wavelength_id) + { + getNewId(); + } + + // Copy constructor + OpticalSignal(const OpticalSignal &s) + : m_field(s.m_field) + , m_wavelength_id(s.m_wavelength_id) + , m_id(s.m_id) + { getNewId(); } + + virtual ~OpticalSignal() {} + + inline void getNewId() + { + m_id = nextId++; + } + + void setWavelength(const double &wavelength) + { + if (!isnan(wavelength)) + m_wavelength_id = getIDFromWavelength(wavelength); + else + m_wavelength_id = 0; + } + + double getWavelength() const; + + static double getWavelength(const uint32_t &wavelength_id); + + uint32_t getIDFromWavelength(const double &wavelength); + + inline static complex<double> amplitudePhaseToField(double amplitude, double phase) + { + return polar(amplitude, phase); + } + + inline double modulus() const { + return abs(m_field); + } + + inline double power() const { + return norm(m_field); + } + + inline double phase() const { + return arg(m_field); + } + + // Equality is used to determine if a signal changes + // which is why true `==` is used here in field + // TODO: check if we need to use is_close() instead + // For wavelength, there should be no need not to use `==` + // for now, as no calculation is done on it. But in the future, + // we might need to review this as well + bool operator==(const OpticalSignal &rhs) const + { +#if 0 + // Work with ID + return rhs.m_id == m_id + || (isnan(rhs.m_wavelength) && isnan(m_wavelength)); +#else + // Work with field value + return rhs.m_field == m_field + && rhs.m_wavelength_id == m_wavelength_id; +#endif + } + + bool operator!=(const OpticalSignal &rhs) const + { + return !(*this == rhs); + } + + bool operator<(const OpticalSignal &rhs) const + { + return rhs.modulus() < modulus(); + } + + inline void advancePhaseByPhase(const double &phase_rad) + { + m_field *= polar(1.0, phase_rad); + } + + inline void advancePhaseByTime(const double &time_s) + { + // phase in rad = w * t = (2pi * (c/lambda)) * t + constexpr const auto c_2pi = 2 * M_PI * 299792458.0; + const auto phase_rad = (c_2pi / this->getWavelength()) * time_s; + + advancePhaseByPhase(phase_rad); + } + + static OpticalSignal sumSignals( + OpticalSignal s0, + OpticalSignal s1); + + operator field_type() const { + return m_field; + } + + OpticalSignal operator=(const OpticalSignal &rhs) + { + m_field = rhs.m_field; + m_wavelength_id = rhs.m_wavelength_id; + getNewId(); + return *this; + } + + OpticalSignal &operator+=(const OpticalSignal &rhs); + OpticalSignal &operator-=(const OpticalSignal &rhs); + + OpticalSignal &operator*=(const field_type &rhs) + { + m_field *= rhs; + return *this; + } + + OpticalSignal &operator*=(const double &rhs) + { + m_field *= rhs; + return *this; + } + + OpticalSignal &operator/=(const double &rhs) + { + (*this) *= (1 / rhs); + return *this; + } + + inline friend OpticalSignal operator+(OpticalSignal lhs, const OpticalSignal &rhs); + inline friend OpticalSignal operator-(OpticalSignal lhs, const OpticalSignal &rhs); + + template <typename T> + inline friend OpticalSignal operator*(OpticalSignal lhs, const T &rhs); + + template <typename T> + inline friend OpticalSignal operator*(const T &lhs, OpticalSignal rhs); + + template <typename T> + inline friend OpticalSignal operator/(OpticalSignal lhs, const T &rhs); + + inline friend std::ostream &operator<<(std::ostream &os, const OpticalSignal &s); + inline friend void + sc_trace(sc_trace_file *tf, const OpticalSignal &s, const std::string &NAME); +}; + +OpticalSignal operator+(OpticalSignal lhs, const OpticalSignal &rhs) +{ + return lhs += rhs; +} + +OpticalSignal operator-(OpticalSignal lhs, const OpticalSignal &rhs) +{ + return lhs -= rhs; +} + +template <typename T> +OpticalSignal operator*(OpticalSignal lhs, const T &rhs) +{ + return lhs *= rhs; +} + +template <typename T> +OpticalSignal operator*(const T &lhs, OpticalSignal rhs) +{ + return rhs *= lhs; +} + +template <typename T> +inline OpticalSignal operator/(OpticalSignal lhs, const T &rhs) +{ + return lhs /= rhs; +} + +inline std::ostream &operator<<(std::ostream &os, const OpticalSignal &s) +{ + using std::defaultfloat; + using std::fixed; + using std::setfill; + using std::setprecision; + using std::setw; + + std::ostringstream oss; + + oss << "[" << setw(4) << setfill('0') << s.m_id << setfill(' ') << "] "; + oss << " @ " << setw(4) << setprecision(8) << s.getWavelength() * 1e9 << setw(2) + << (isnan(s.getWavelength()) ? "" : " nm"); + oss << " (" << setprecision(6) << fixed << s.modulus() << " V.m⁻¹"; + oss << ", " << setprecision(6) << fixed << s.power() << " W"; + oss << ", " << setprecision(4) << fixed << s.phase() << " rad"; + oss << ")"; + + os << oss.str(); + return os; +} + +inline void sc_trace(sc_trace_file *tf, const OpticalSignal &s, const std::string &NAME) +{ + cerr << "Use of deprecated" << __FUNCTION__<< endl; + + // Note: C++ complex doesn't provide access to real and imaginary part + // Therefore we cannot have references or pointers to it... + sc_trace(tf, s.m_id, NAME + ".id"); + sc_trace(tf, s.m_wavelength_id, NAME + ".wavelengthid"); +} diff --git a/src/parser/parse_analysis.cpp b/src/parser/parse_analysis.cpp new file mode 100644 index 0000000..3168858 --- /dev/null +++ b/src/parser/parse_analysis.cpp @@ -0,0 +1,109 @@ +#include "parse_analysis.h" +#include "cw_source.h" +#include "devices/alldevices.h" +#include "directional_coupler.h" +#include "optical_output_port.h" +#include "parse_tree.h" +#include "specs.h" +#include "strutils.h" +#include "sysc_utils.h" +#include "general_utils.h" +#include <functional> + +using spx::oa_value_type; +using spx::ea_value_type; +using spx::ed_value_type; + +using spx::ed_bus_type; +using spx::oa_signal_type; +using spx::ea_signal_type; +using spx::ed_signal_type; +using spx::ed_bus_type; + +void OPAnalysis::create() const +{ + specsGlobalConfig.analysis_type = SPECSConfig::OP; + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::FREQUENCY_DOMAIN; +} + +void DCAnalysis::create() const +{ + specsGlobalConfig.analysis_type = SPECSConfig::DC; + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::FREQUENCY_DOMAIN; + + assert(sweep_orders.size() > 0); + + set<CWSource *> all_cws = sc_get_all_object_by_type<CWSource>(); + vector<CWSource *> all_cws_vec(all_cws.begin(), all_cws.end()); + + int i = 0; + for (const auto &sweep_order: sweep_orders) + { + string element_name = parent->name_prefix() + sweep_order.first.first; + string attribute_name = sweep_order.first.second; + + auto is_desired_element = [&element_name](const auto &x){ return x->name() == element_name; }; + auto it = std::find_if(all_cws_vec.begin(), all_cws_vec.end(), is_desired_element); + if (it == all_cws_vec.end()) + { + cerr << "Element not found: " << element_name << endl; + exit(1); + } + CWSource *elem = *it; + // cout << elem << endl; + // cout << &CWSource::setWavelength << endl; + + function<void(double)> f; + if (attribute_name == "WL" || attribute_name == "WAVELENGTH" || attribute_name == "LAMBDA") + { + f = std::bind(&CWSource::setWavelength, elem, placeholders::_1); + } + else if (attribute_name == "P" || attribute_name == "POW" || attribute_name == "POWER") + { + f = std::bind(static_cast<void (CWSource::*)(const double&)>(&CWSource::setPower), elem, placeholders::_1); + } + else if (attribute_name == "F" || attribute_name == "FREQ" || attribute_name == "FREQUENCY") + { + f = std::bind((&CWSource::setFrequency), elem, placeholders::_1); + } + else + { + cerr << "Unknown attribute for " << sweep_order.first.first << ": " << attribute_name << endl; + exit(1); + } + auto values = range(sweep_order.second[0], sweep_order.second[1], sweep_order.second[2]); + auto order = pair<function<void(double)>, vector<double>>(f, values); + auto order_name = attribute_name + "(" + element_name + ")"; + specsGlobalConfig.cw_sweep_orders.emplace(order_name, order); + ++i; + } +} + +void TRANAnalysis::create() const +{ + specsGlobalConfig.analysis_type = SPECSConfig::TRAN; + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::TIME_DOMAIN; + + assert(args.size() <= 1); + + if (args.size() >= 1) + { + double val = args[0].as_double(); + // cout << val << endl; + if (val > 0) + specsGlobalConfig.tran_duration = args[0].as_double(); + else + { + cerr << "Negative simulation duration is not accepted" << endl; + exit(1); + } + } + + for (const auto &p : kwargs) + { + string kw = p.first; + strutils::toupper(kw); + cerr << "Unknown keyword " << kw << endl; + exit(1); + } +} diff --git a/src/parser/parse_analysis.h b/src/parser/parse_analysis.h new file mode 100644 index 0000000..9e3f44c --- /dev/null +++ b/src/parser/parse_analysis.h @@ -0,0 +1,94 @@ +#pragma once + +#include "parse_tree.h" +#include "specs.h" +#include "strutils.h" + +#include <initializer_list> +#include <utility> +#include <memory> +#include <string> +#include <vector> +#include <map> +#include <iostream> + +using std::pair; +using std::make_pair; +using std::string; +using std::vector; +using std::map; +using std::cout; +using std::cerr; +using std::endl; +using std::pair; +using std::unique_ptr; + +/* OP: operating point analysis */ +struct OPAnalysis : public ParseAnalysis { + /* Import constructor from ParseAnalysis */ + using ParseAnalysis::ParseAnalysis; + + virtual ParseAnalysis* clone() const + { return new OPAnalysis(*this); } + virtual void create() const; + virtual string kind() const + { return "OP"; } +}; + +/* DC: stepped-source operating point analysis */ +struct DCAnalysis : public ParseAnalysis { + typedef pair<string, string> sweep_param_type; + typedef vector<double> sweep_range_type; + typedef pair<sweep_param_type, sweep_range_type> sweep_order_type; + + /* Import constructor from ParseAnalysis */ + using ParseAnalysis::ParseAnalysis; + + map<sweep_param_type, sweep_range_type> sweep_orders; + + void register_sweep_order(sweep_param_type param, sweep_range_type range) + { + strutils::toupper(param.first); + strutils::toupper(param.second); + if (sweep_orders.count(param) != 0) + { + cerr << "A sweep order for " << param.second << "(" << param.first << ")"; + cerr << " was already recoreded." << endl; + exit(1); + } + auto n = (range[1] - range[0]) / range[2]; + n = max(0.0, n); + n = floor(n); + if (n <= 1.5) + { + cerr << "Sweep order must contain at least 2 point." << endl; + exit(1); + } + cout << "Recorded sweep order for " << param.second << "(" << param.first << ")"; + cout << " (" << n << "points)" << endl; + sweep_orders.emplace(param, range); + } + + void register_sweep_order(sweep_order_type order) + { + register_sweep_order(order.first, order.second); + } + + virtual ParseAnalysis* clone() const + { return new DCAnalysis(*this); } + virtual void create() const; + virtual string kind() const + { return "DC"; } +}; + +/* TRAN: transient analysis */ +struct TRANAnalysis : public ParseAnalysis { + /* Import constructor from ParseElement */ + using ParseAnalysis::ParseAnalysis; + + virtual ParseAnalysis* clone() const + { return new TRANAnalysis(*this); } + virtual void create() const; + virtual string kind() const + { return "TRAN"; } +};
\ No newline at end of file diff --git a/src/parser/parse_directive.cpp b/src/parser/parse_directive.cpp new file mode 100644 index 0000000..e66e8cf --- /dev/null +++ b/src/parser/parse_directive.cpp @@ -0,0 +1,132 @@ +#include "parse_directive.h" +#include "devices/alldevices.h" +#include "directional_coupler.h" +#include "optical_signal.h" +#include "parse_tree.h" +#include "specs.h" + +using spx::oa_value_type; +using spx::ea_value_type; +using spx::ed_value_type; + +using spx::ed_bus_type; +using spx::oa_signal_type; +using spx::ea_signal_type; +using spx::ed_signal_type; +using spx::ed_bus_type; + +void OPTIONSDirective::create() const +{ + // Verify number of nodes + assert(args.size() == 0); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "TRACEALL") + specsGlobalConfig.trace_all_optical_nets = p.second.as_boolean(); + else if (kw == "ABSTOL") + specsGlobalConfig.default_abstol = p.second.as_double(); + else if (kw == "RELTOL") + specsGlobalConfig.default_reltol = p.second.as_double(); + else if (kw == "TS" || kw == "TIMESCALE") + specsGlobalConfig.engine_timescale = (SPECSConfig::EngineTimescale)p.second.as_integer(); + else if (kw == "RESOLUTION") + specsGlobalConfig.default_resolution_multiplier = p.second.as_double(); + else if (kw == "TRACEALL") + specsGlobalConfig.trace_all_optical_nets = p.second.as_double(); + else if (kw == "TEST_VARIABLE") + cout << kw << "(" << p.second.kind() << "): " << p.second.get_str() << endl; + else { + cerr << "Unknown keyword: " << p.first; + cerr << " (value: " << p.second.get_str() << " (" << p.second.kind() << "))" <<endl; + exit(1); + } + } +} + +void NODESETDirective::print() const +{ + ParseDirective::print(); + cout << "{"; + for (const auto &x : net_assignments) + { + for (const auto &ass : x.second) + cout << ass.first << "(" << x.first << ") = " + << ass.second.get_str() << " (" << ass.second.kind() << ") , "; + } + if ( !net_assignments.empty() ) + cout << "\b\b"; + cout << "}" << endl; +} + +void NODESETDirective::create() const +{ + cerr << "NODESET is disabled pending bugfixes" << endl; + exit(1); +#if 0 + map<string, pair<spx::oa_signal_type *, oa_value_type>> ic_map; + auto &signals = parent->circuit_nets; + for (const auto &x : net_assignments) + { + const auto &key = x.first; + if (signals.count(key) == 0) + { + cerr << "Net not found " << key << endl; + exit(1); + } + if (ic_map.count(key) == 0) + { + //FIXME: + auto sig = dynamic_cast<oa_signal_type *>(signals[key].get()); + auto initial_val = sig->read(); + auto sig_address = dynamic_cast<oa_signal_type *>(signals[key].get()); + pair<oa_signal_type *, oa_value_type> assignment{sig_address, initial_val}; + ic_map.emplace(key, assignment); + } + oa_value_type signal_val = ic_map[key].second; + for (const auto &assignment: x.second) + { + string attribute_name = assignment.first; + strutils::toupper(attribute_name); + const Variable &value = assignment.second; + + // cout << attribute_name << endl; + if (attribute_name == "P" || attribute_name == "POW" || attribute_name == "POWER") + { + signal_val.m_field = polar(sqrt(value.as_double()), arg(signal_val.m_field)); + // cout << "################" << endl; + // cout << signal_val << endl; + } + else if (attribute_name == "PHASE" || attribute_name == "PHI") + { + signal_val.m_field = polar(abs(signal_val.m_field), value.as_double()); + // cout << "################" << endl; + // cout << signal_val << endl; + } + else if (attribute_name == "WL" || attribute_name == "LAMBDA" || attribute_name == "WAVELENGTH") + { + signal_val.setWavelength(value.as_double()); + // cout << "################" << endl; + // cout << signal_val << endl; + } + else + { + cerr << "Unknown attribute" << endl; + exit(1); + } + } + specsGlobalConfig.nodeset_orders[key] = pair<oa_signal_type *, oa_value_type>( + dynamic_cast<oa_signal_type *>(signals[key].get()) + , signal_val); + } +#endif +} + +void ICDirective::create() const +{ + cerr << "IC directive is not implemented" << endl; + exit(1); +}
\ No newline at end of file diff --git a/src/parser/parse_directive.h b/src/parser/parse_directive.h new file mode 100644 index 0000000..212fd4a --- /dev/null +++ b/src/parser/parse_directive.h @@ -0,0 +1,68 @@ +#pragma once + +#include "parse_tree.h" + +#include <initializer_list> +#include <utility> +#include <memory> +#include <string> +#include <vector> +#include <map> +#include <iostream> + +using std::pair; +using std::make_pair; +using std::string; +using std::vector; +using std::map; +using std::cout; +using std::cerr; +using std::endl; +using std::pair; +using std::unique_ptr; + +/* OPTIONS: specify simulator options */ +struct OPTIONSDirective : public ParseDirective { + /* Import constructor from ParseDirective */ + using ParseDirective::ParseDirective; + + virtual ParseDirective* clone() const + { return new OPTIONSDirective(*this); } + virtual void create() const; + virtual string kind() const + { return "OPTIONS"; } +}; + +/* NODESET: specify initial guesses */ +struct NODESETDirective : public ParseDirective { + typedef string net_name; + typedef string property_name; + typedef Variable property_val; + typedef pair<property_name, property_val> assignment; + + map<net_name, vector<assignment>> net_assignments; + + /* Import constructor from ParseDirective */ + using ParseDirective::ParseDirective; + + virtual void print() const; + + virtual ParseDirective* clone() const + { return new NODESETDirective(*this); } + virtual void create() const; + virtual string kind() const + { return "NODESET"; } +}; + +/* IC: specify initial conditions options */ +// Inherit from NODESETDirective as options are the same. +struct ICDirective : public NODESETDirective { + /* Import constructor from ParseDirective */ + using NODESETDirective::NODESETDirective; + + virtual ParseDirective* clone() const + { return new ICDirective(*this); } + virtual void create() const; + virtual string kind() const + { return "IC"; } +};
\ No newline at end of file diff --git a/src/parser/parse_element.cpp b/src/parser/parse_element.cpp new file mode 100644 index 0000000..14de6e9 --- /dev/null +++ b/src/parser/parse_element.cpp @@ -0,0 +1,1266 @@ +#include "parse_element.h" +#include "alldevices.h" +#include "subcircuit_instance.h" +#include "specs.h" +#include "strutils.h" + +#include <string> + +/** ******************************************* **/ +/** Helper macros and defines **/ +/** ******************************************* **/ +#define AS_READER (false) +#define AS_WRITER (!AS_READER) + +#define INSTANTIATE_AND_CONNECT_UNI(ELEM_NAME, pt_helper) \ +ELEM_NAME::element_type_base *ELEM_NAME::instantiate_and_connect_uni(ParseTreeCreationHelper &pt_helper) const + +#define INSTANTIATE_AND_CONNECT_BI(ELEM_NAME, pt_helper) \ +ELEM_NAME::element_type_base *ELEM_NAME::instantiate_and_connect_bi(ParseTreeCreationHelper &pt_helper) const + +#define INSTANTIATE(pt_helper, bidirectional) \ +\ +if (bidirectional)\ + obj = (element_type_base *)instantiate_and_connect_bi(pt_helper);\ +else\ + obj = (element_type_base *)instantiate_and_connect_uni(pt_helper); + +/** ******************************************* **/ +/** Waveguide **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(WGElement, pt_helper) +{ + // create object with default params + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out, nets[1], AS_WRITER); + + // return the module + return obj; +} + +INSTANTIATE_AND_CONNECT_BI(WGElement, pt_helper) +{ + // create object with default params + element_type_bi *obj = new element_type_bi(name.c_str()); + + // Update unidirectional nets connected to the waveguide + if (!pt_helper.nets->at(nets[0]).bidirectional()) + (*pt_helper.nets)[nets[0]].m_writers_count++; + if (!pt_helper.nets->at(nets[1]).bidirectional()) + (*pt_helper.nets)[nets[1]].m_readers_count++; + + // Bidirectional waveguide needs all nets as bidir + for (const auto &net : nets) + pt_helper.upgrade_signal(net); + + // connect ports + pt_helper.connect_bi<spx::oa_signal_type>(obj->p0_in, obj->p0_out, nets[0]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p1_in, obj->p1_out, nets[1]); + + return obj; +} + +sc_module *WGElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Prevent connecting a waveguide to itself, it will hang the execution!!! + if (nets[0] == nets[1]) + { + cerr << "Error: A waveguide cannot be looped back upon himself" << endl; + exit(1); + } + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Check if device has to be bidirectional + bool bidirectional = false; + for (const auto &net : nets) + { + // for waveguide, if any net is bidir, module has to be bidir + bidirectional |= pt_helper.nets->at(net).bidirectional(); + } + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, bidirectional); + + // Parse positional arguments + if(args.size() > 0) + obj->m_length_cm = args[0].as_double() * 100; + if(args.size() > 1) + obj->m_neff = args[1].as_double(); + if(args.size() > 2) + obj->m_ng = args[2].as_double(); + if(args.size() > 3) + obj->m_attenuation_dB_cm = args[3].as_double(); + if(args.size() > 4) + obj->m_D = args[4].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "NEFF") + obj->m_neff = p.second.as_double(); + else if (kw == "NG") + obj->m_ng = p.second.as_double(); + else if (kw == "L" || kw == "LENGTH") + obj->m_length_cm = p.second.as_double() * 100; + else if (kw == "ATT") + obj->m_attenuation_dB_cm = p.second.as_double(); + else if (kw == "D") + obj->m_D = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + + return obj; +} + +/** ******************************************* **/ +/** Merger **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(MergerElement, pt_helper) +{ + // create object with default params + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in1, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in2, nets[1], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out, nets[2], AS_WRITER); + + // return the module + return obj; +} + +sc_module *MergerElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 0) + obj->m_attenuation_dB = args[0].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "IL" || kw == "INSERTION_LOSS") + obj->m_attenuation_dB = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** Splitter **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(SplitterElement, pt_helper) +{ + // create object with default params + element_type_uni *obj = new element_type_base(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out1, nets[1], AS_WRITER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out2, nets[2], AS_WRITER); + + // return the module + return obj; +} + +sc_module *SplitterElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 0) + obj->m_split_ratio = args[0].as_double(); + if(args.size() > 1) + obj->m_attenuation_dB = args[1].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "IL" || kw == "INSERTION_LOSS") + obj->m_attenuation_dB = p.second.as_double(); + else if (kw == "SPLITTING_RATIO" || kw == "RATIO") + obj->m_split_ratio = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** Directional coupler **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(DCElement, pt_helper) +{ + // create object with default params + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect p_in1 + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in1, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in2, nets[1], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out1, nets[2], AS_WRITER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out2, nets[3], AS_WRITER); + + // return the module + return obj; +} + +INSTANTIATE_AND_CONNECT_BI(DCElement, pt_helper) +{ + // create object with default params + element_type_bi *obj = new element_type_bi(name.c_str()); + + // Update unidirectional nets connected to the waveguide + if (!pt_helper.nets->at(nets[0]).bidirectional()) + (*pt_helper.nets)[nets[0]].m_writers_count++; + if (!pt_helper.nets->at(nets[1]).bidirectional()) + (*pt_helper.nets)[nets[1]].m_writers_count++; + if (!pt_helper.nets->at(nets[2]).bidirectional()) + (*pt_helper.nets)[nets[2]].m_readers_count++; + if (!pt_helper.nets->at(nets[3]).bidirectional()) + (*pt_helper.nets)[nets[3]].m_readers_count++; + + // Bidirectional DC needs all nets as bidir + for (const auto &net : nets) + pt_helper.upgrade_signal(net); + + // connect ports + pt_helper.connect_bi<spx::oa_signal_type>(obj->p0_in, obj->p0_out, nets[0]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p1_in, obj->p1_out, nets[1]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p2_in, obj->p2_out, nets[2]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p3_in, obj->p3_out, nets[3]); + + // return the module + return obj; +} + +sc_module *DCElement::create(ParseTreeCreationHelper &pt_helper) const +{ + // TODO: change from field to power? + cout << "Warning: coupling power for DC currently set to field." << endl; + + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Check if device has to be bidirectional + bool bidirectional = false; + for (const auto &net : nets) + { + // for waveguide, if any net is bidir, module has to be bidir + bidirectional |= pt_helper.nets->at(net).bidirectional(); + } + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, bidirectional); + + // Parse positional arguments + if(args.size() > 0) + // convert from cross-coupling field coef + obj->m_dc_through_coupling_power = 1 - pow(args[0].as_double(), 2); + if(args.size() > 1) + obj->m_dc_loss = args[1].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "K" || kw == "KF" || kw == "KFIELD") + // convert from cross-coupling field coef + obj->m_dc_through_coupling_power = 1 - pow(p.second.as_double(), 2); + else if (kw == "KP" || kw == "KPOW" || kw == "KPOWER") + // convert from cross-coupling field coef + obj->m_dc_through_coupling_power = 1 - p.second.as_double(); + else if (kw == "T") + // convert from cross-coupling field coef + obj->m_dc_through_coupling_power = pow(p.second.as_double(), 2); + else if (kw == "LOSS") + obj->m_dc_loss = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** Phase-shifter **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(PhaseShifterElement, pt_helper) +{ + // create object with default params + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out, nets[1], AS_WRITER); + pt_helper.connect_uni<spx::ea_signal_type>(obj->p_vin, nets[2], AS_READER); + + // return the module + return obj; +} + +INSTANTIATE_AND_CONNECT_BI(PhaseShifterElement, pt_helper) +{ + // create object with default params + element_type_bi *obj = new element_type_bi(name.c_str()); + + // Update unidirectional nets connected to the waveguide + if (!pt_helper.nets->at(nets[0]).bidirectional()) + (*pt_helper.nets)[nets[0]].m_writers_count++; + if (!pt_helper.nets->at(nets[1]).bidirectional()) + (*pt_helper.nets)[nets[1]].m_readers_count++; + + // Bidirectional phase-shifter needs only optical nets as bidir + pt_helper.upgrade_signal(nets[0]); + pt_helper.upgrade_signal(nets[1]); + + // connect ports + pt_helper.connect_bi<spx::oa_signal_type>(obj->p0_in, obj->p0_out, nets[0]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p1_in, obj->p1_out, nets[1]); + pt_helper.connect_uni<spx::ea_signal_type>(obj->p_vin, nets[2], AS_READER); + + // return the module + return obj; +} + +sc_module *PhaseShifterElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + cout << "Warning (" << name << "): default coupling power for DC currently set to field." << endl; + + // Verify number of nodes + assert(nets.size() == n_nets); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Check if device has to be bidirectional + // for PS, if any optical net is bidir, module has to be bidir + bool bidirectional = false; + bidirectional |= pt_helper.nets->at(nets[0]).bidirectional(); + bidirectional |= pt_helper.nets->at(nets[1]).bidirectional(); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, bidirectional); + + // Verify number of args + assert(args.size() <= 2); + + // Parse positional arguments + if(args.size() > 0) + obj->m_sensitivity = args[0].as_double(); + if(args.size() > 1) + obj->m_attenuation_dB = args[1].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + + if (kw == "ATTENUATION" || kw == "ATT") + obj->m_attenuation_dB = p.second.as_double(); + else if (kw == "SENSITIVITY" || kw == "GAIN" || kw == "G") + obj->m_sensitivity = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** MZI **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(MZIElement, pt_helper) +{ + // create object with default params + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in1, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in2, nets[1], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out1, nets[2], AS_WRITER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out2, nets[3], AS_WRITER); + pt_helper.connect_uni<spx::ea_signal_type>(obj->p_vin, nets[4], AS_READER); + + return obj; +} + +INSTANTIATE_AND_CONNECT_BI(MZIElement, pt_helper) +{ + // create object with default params + element_type_bi *obj = new element_type_bi(name.c_str()); + + // Update unidirectional nets connected to the waveguide + if (!pt_helper.nets->at(nets[0]).bidirectional()) + (*pt_helper.nets)[nets[0]].m_writers_count++; + if (!pt_helper.nets->at(nets[1]).bidirectional()) + (*pt_helper.nets)[nets[1]].m_writers_count++; + if (!pt_helper.nets->at(nets[2]).bidirectional()) + (*pt_helper.nets)[nets[2]].m_readers_count++; + if (!pt_helper.nets->at(nets[3]).bidirectional()) + (*pt_helper.nets)[nets[3]].m_readers_count++; + + // Bidirectional phase-shifter needs only optical nets as bidir + pt_helper.upgrade_signal(nets[0]); + pt_helper.upgrade_signal(nets[1]); + pt_helper.upgrade_signal(nets[2]); + pt_helper.upgrade_signal(nets[3]); + + // connect ports + pt_helper.connect_bi<spx::oa_signal_type>(obj->p0_in, obj->p0_out, nets[0]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p1_in, obj->p1_out, nets[1]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p2_in, obj->p2_out, nets[2]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p3_in, obj->p3_out, nets[3]); + pt_helper.connect_uni<spx::ea_signal_type>(obj->p_vin, nets[4], AS_READER); + + return obj; +} + +sc_module *MZIElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + cout << "Warning (" << name << "): default coupling power for DC currently set to field." << endl; + + // Verify number of nodes + assert(nets.size() == n_nets); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Check if device has to be bidirectional + // for PS, if any optical net is bidir, module has to be bidir + bool bidirectional = false; + bidirectional |= pt_helper.nets->at(nets[0]).bidirectional(); + bidirectional |= pt_helper.nets->at(nets[1]).bidirectional(); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, bidirectional); + + assert(args.size() <= 1); + // Parse positional arguments + if(args.size() > 0) + // convert from cross-coupling field coef + obj->m_ps_sens_rad_v = args[0].as_double(); + // TODO: other positional args + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "SENSITIVITY") + // convert from cross-coupling field coef + obj->m_ps_sens_rad_v = p.second.as_double(); + else if (kw == "LENGTH") + obj->m_length_cm = 100 * p.second.as_double(); + else if (kw == "LENGTH_REF") + obj->m_length_ref_cm = 100 * p.second.as_double(); + else if (kw == "NEFF") + obj->m_neff = p.second.as_double(); + else if (kw == "NG") + obj->m_ng = p.second.as_double(); + else if (kw == "ATT") + obj->m_attenuation_dB_cm = p.second.as_double(); + else if (kw == "IL_DC") + obj->m_dc_loss_dB = p.second.as_double(); + else if (kw == "IL_PHASESHIFTER") + obj->m_ps_loss_dB = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** Crossing **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(CrossingElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in1, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in2, nets[1], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out1, nets[2], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out2, nets[3], AS_READER); + + // return the module + return obj; +} + +INSTANTIATE_AND_CONNECT_BI(CrossingElement, pt_helper) +{ + element_type_bi *obj = new element_type_bi(name.c_str()); + + // Update unidirectional nets connected to the waveguide + if (!pt_helper.nets->at(nets[0]).bidirectional()) + (*pt_helper.nets)[nets[0]].m_writers_count++; + if (!pt_helper.nets->at(nets[1]).bidirectional()) + (*pt_helper.nets)[nets[1]].m_writers_count++; + if (!pt_helper.nets->at(nets[2]).bidirectional()) + (*pt_helper.nets)[nets[2]].m_readers_count++; + if (!pt_helper.nets->at(nets[3]).bidirectional()) + (*pt_helper.nets)[nets[3]].m_readers_count++; + + // Bidirectional crossing needs all optical nets as bidir + pt_helper.upgrade_signal(nets[0]); + pt_helper.upgrade_signal(nets[1]); + pt_helper.upgrade_signal(nets[2]); + pt_helper.upgrade_signal(nets[3]); + + // connect ports + pt_helper.connect_bi<spx::oa_signal_type>(obj->p0_in, obj->p0_out, nets[0]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p1_in, obj->p1_out, nets[1]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p2_in, obj->p2_out, nets[2]); + pt_helper.connect_bi<spx::oa_signal_type>(obj->p3_in, obj->p3_out, nets[3]); + + // return the module + return obj; +} + +sc_module *CrossingElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 2); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 0) + obj->m_attenuation_power_dB = args[0].as_double(); + if(args.size() > 1) + obj->m_crosstalk_power_dB = args[1].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "ATTENUATION" || kw == "ATT") + obj->m_attenuation_power_dB = p.second.as_double(); + else if (kw == "CROSSTALK" || kw == "XTALK") + obj->m_crosstalk_power_dB = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** CW Source **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(CWSourceElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out, nets[0], AS_WRITER); + + // return the module + return obj; +} + +sc_module *CWSourceElement::create(ParseTreeCreationHelper &pt_helper) const +{ + CWSource *obj = nullptr; + + // Verify number of nets + assert(nets.size() == 1); + + // Verify number of positional args + assert(args.size() <= 3); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 1) + // convert from cross-coupling field coef + obj->setWavelength(args[1].as_double()); + if(args.size() > 2) + obj->setPower(args[2].as_double()); + if(args.size() > 3) + obj->setPhase(args[3].as_double()); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "WL" || kw == "WAVELENGTH") + // convert from cross-coupling field coef + obj->setWavelength(p.second.as_double()); + else if (kw == "POWER") + // convert from cross-coupling field coef + obj->setPower(p.second.as_double()); + else if (kw == "PHI") + continue; // handle it after all power commands are executed + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + // TODO: make this cleaner (priority between setting kwargs...) + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "PHI") + obj->setPhase(p.second.as_double()); + } + return obj; +} + +/** ******************************************* **/ +/** VL Source **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(VLSourceElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out, nets[0], AS_WRITER); + + // return the module + return obj; +} + +sc_module *VLSourceElement::create(ParseTreeCreationHelper &pt_helper) const +{ + VLSource *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 1); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 1) + obj->setValues(args[0].as_string()); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "FILE") + { + cerr << "not implemented" << endl; + exit(1); + } + else if (kw == "SCALE") + { + cerr << "not implemented" << endl; + exit(1); + } + else if (kw == "VALUES") + { + // cout << "here" << endl; + vector<VLSource::time_value_pair_type> values; + bool is_string = p.second.type == Variable::STRING; + bool is_list = p.second.type == Variable::LIST; + if (!is_list && !is_string) + { + // cout << "A" << endl; + cerr << "Variable passed to keyword 'values' should be either:"<< endl; + cerr << " - an Nx3 list [[t0, p0, wl0], ...] with t0, p0 and wl0 convertible to double" + << " (or None if no change from previous entry)" << endl; + cerr << " - a filename containing the list" << endl; + exit(1); + } + + if (is_list) + { + for (const Variable &var : p.second.vec) + { + if (var.type != Variable::LIST || var.vec.size() != 3) + { + // cout << "B" << endl; + cerr << "Variable passed to keyword 'values' should be a an Nx3 list [[t0, p0, wl0], ...]" << endl; + cerr << "with t0, p0 and wl0 convertible to double (or None if no change from previous entry)" << endl; + exit(1); + } + for (const Variable &ivar : var.vec) + { + // cout << "C" << ivar.get_str() << endl; + + if (ivar.is_number() || ivar.is_none()) + continue; + + cerr << "Variable passed to keyword 'values' should be a an Nx3 list [[t0, p0, wl0], ...]" << endl; + cerr << "with t0, p0 and wl0 convertible to double (or None if no change from previous entry)" << endl; + exit(1); + } + double t, p, wl; + int none_cnt = 0; + if (var.vec[0].is_number()) + t = var.vec[0].as_double(); + else if (var.vec[0].is_none() && ! values.empty()) + { + t = values.back().first; + ++none_cnt; + } + else + { + cerr << "First values list entry should be fully specified" << endl; + exit(1); + } + + if (var.vec[1].is_number()) + p = var.vec[1].as_double(); + else if (var.vec[1].is_none() && ! values.empty()) + { + p = values.back().second.power(); + ++none_cnt; + } + else + { + cerr << "First values list entry should be fully specified" << endl; + exit(1); + } + + if (var.vec[2].is_number()) + wl = var.vec[2].as_double(); + else if (var.vec[2].is_none() && ! values.empty()) + { + wl = values.back().second.getWavelength(); + ++none_cnt; + } + else + { + cerr << "First values list entry should be fully specified" << endl; + exit(1); + } + + if (none_cnt < 3) + // OpticalSignal takes amplitude as value in the constructor + values.emplace_back(t, spx::oa_value_type(sqrt(p), wl)); + else + { + cerr << "Values list entry cannot be all none" << endl; + } + } + obj->setValues(values); + } + + if (is_string) + { + obj->setValues(p.second.as_string()); + } + } + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + + } + return obj; +} + +/** ******************************************* **/ +/** EVL Source **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(EVLSourceElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::ea_signal_type>(obj->p_out, nets[0], AS_WRITER); + + // return the module + return obj; +} + +sc_module *EVLSourceElement::create(ParseTreeCreationHelper &pt_helper) const +{ + EVLSource *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 1); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 1) + obj->setValues(args[0].as_string()); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "FILE") + { + cerr << "not implemented" << endl; + exit(1); + } + else if (kw == "SCALE") + { + cerr << "not implemented" << endl; + exit(1); + } + else if (kw == "VALUES") + { + // cout << "here" << endl; + vector<EVLSource::time_value_pair_type> values; + bool is_string = p.second.type == Variable::STRING; + bool is_list = p.second.type == Variable::LIST; + if (!is_list && !is_string) + { + cerr << "Variable passed to keyword 'values' should be either:"<< endl; + cerr << " - an Nx2 list [[t0, V0], ...] with t0 and V0 convertible to double" + << " (or None if no change from previous entry)" << endl; + cerr << " - a filename containing the list" << endl; + exit(1); + } + + if (is_list) + { + for (const Variable &var : p.second.vec) + { + if (var.type != Variable::LIST || var.vec.size() != 2) + { + cerr << "Variable passed to keyword 'values' should be either:"<< endl; + cerr << " - an Nx2 list [[t0, V0], ...] with t0 and V0 convertible to double" + << " (or None if no change from previous entry)" << endl; + cerr << " - a filename containing the list" << endl; + exit(1); + } + for (const Variable &ivar : var.vec) + { + if (ivar.is_number() || ivar.is_none()) + continue; + + cerr << "Variable passed to keyword 'values' should be either:"<< endl; + cerr << " - an Nx2 list [[t0, V0], ...] with t0 and V0 convertible to double" + << " (or None if no change from previous entry)" << endl; + cerr << " - a filename containing the list" << endl; + exit(1); + } + double t, V; + int none_cnt = 0; + if (var.vec[0].is_number()) + t = var.vec[0].as_double(); + else if (var.vec[0].is_none() && ! values.empty()) + { + t = values.back().first; + ++none_cnt; + } + else + { + cerr << "First values list entry should be fully specified" << endl; + exit(1); + } + + if (var.vec[1].is_number()) + V = var.vec[1].as_double(); + else if (var.vec[1].is_none() && ! values.empty()) + { + V = values.back().second; + ++none_cnt; + } + else + { + cerr << "First values list entry should be fully specified" << endl; + exit(1); + } + + if (none_cnt < 2) + values.emplace_back(t, spx::ea_value_type(V)); + else + { + cerr << "Values list entry cannot be all none" << endl; + } + } + obj->setValues(values); + } + + if (is_string) + { + obj->setValues(p.second.as_string()); + } + } + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + + } + return obj; +} + +/** ******************************************* **/ +/** Probe **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(ProbeElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect p_in + pt_helper.connect_uni<spx::oa_signal_type>( + obj->p_in, + nets[0], + AS_READER + ); + + // return the module + return obj; +} + +sc_module *ProbeElement::create(ParseTreeCreationHelper &pt_helper) const +{ + Probe *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 4); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + if (args.empty() && kwargs.empty()) + { + // cout << "empty args" << endl; + obj->m_trace_power = true; + obj->m_trace_modulus = true; + obj->m_trace_phase = true; + obj->m_trace_wavelength = true; + } + + // Parse positional args + for (size_t i = 0; i < args.size(); ++i) + { + switch (i) { + case 0: + obj->m_trace_power = args[i].as_boolean(); + break; + case 1: + obj->m_trace_modulus = args[i].as_boolean(); + break; + case 2: + obj->m_trace_phase = args[i].as_boolean(); + break; + case 3: + obj->m_trace_wavelength = args[i].as_boolean(); + break; + default: + cerr << "Too many input arguments for " << name << endl; + exit(1); + } + } + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "POWER" || kw == "POW" || kw == "P") + obj->m_trace_power = p.second.as_boolean(); + else if (kw == "MAGNITUDE" || kw == "MAG" || kw == "MODULUS" || kw == "MOD" || kw == "E") + obj->m_trace_modulus = p.second.as_boolean(); + else if (kw == "PHASE" || kw == "PHI") + obj->m_trace_phase = p.second.as_boolean(); + else if (kw == "WAVELENGTH" || kw == "WL") + obj->m_trace_wavelength = p.second.as_boolean(); + else { + cerr << name << ": unknown keyword: " << p.first << endl; + exit(1); + } + } + cout<< "created " << obj->name() << endl; + return obj; +} + +/** ******************************************* **/ +/** Multilambda Probe **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(MLProbeElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect p_in + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in, nets[0], AS_READER); + + // return the module + return obj; +} + +sc_module *MLProbeElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 1); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional args + if (args.size() > 0) + { + if (args[0].is_list()) + { + for(auto v: args[0].vec) + { + obj->m_lambdas.insert(v.as_double()); + } + } + else { + cerr << "Positional arg to MLPROBE should be a list of wavelengths (e.g. [1.55e-6, 1.54e-6,...])" << endl; + exit(1); + } + } + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "WAVELENGTHS" || kw == "WL") { + if (p.second.is_list()) + { + for(auto v: p.second.vec) + { + obj->m_lambdas.insert(v.as_double()); + //obj->m_lambdas.push_back(v.as_double()); + } + } + else { + cerr << "value of kwarg \"" << kw << "\" to MLPROBE should be a list of wavelengths (e.g. [1.55e-6, 1.54e-6,...])" << endl; + exit(1); + } + } else { + cerr << name << ": unknown keyword: " << p.first << endl; + exit(1); + } + } + + return obj; +} + +/** ******************************************* **/ +/** Photodetector **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(PCMCellElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in, nets[0], AS_READER); + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_out, nets[1], AS_WRITER); + + // return the module + return obj; +} + +sc_module *PCMCellElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 2); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 0) + obj->m_meltEnergy = args[0].as_double(); + if(args.size() > 1) + obj->m_nStates = args[1].as_integer(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "MELT_ENERGY" || kw == "EMELT") + obj->m_meltEnergy = p.second.as_double(); + else if (kw == "N" || kw == "NSTATES") + obj->m_nStates = p.second.as_integer(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + if (obj->m_meltEnergy == 0 || obj->m_nStates == 0) + { + cerr << "PCM Cell needs values for both Emelt and Nstates" << endl; + exit(1); + } + cout << "-----" << endl; + return obj; +} + + +/** ******************************************* **/ +/** Photodetector **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(PhotodetectorElement, pt_helper) +{ + element_type_uni *obj = new element_type_uni(name.c_str()); + + // connect ports + pt_helper.connect_uni<spx::oa_signal_type>(obj->p_in, nets[0], AS_READER); + pt_helper.connect_uni<spx::ea_signal_type>(obj->p_readout, nets[1], AS_WRITER); + + // return the module + return obj; +} + +sc_module *PhotodetectorElement::create(ParseTreeCreationHelper &pt_helper) const +{ + element_type_base *obj = nullptr; + + // Verify number of nets + assert(nets.size() == n_nets); + + // Verify number of positional args + assert(args.size() <= 2); + + // Create signals if they don't exist + pt_helper.create_signals(this); + + // Create the object and connect ports to signals + INSTANTIATE(pt_helper, false); + + // Parse positional arguments + if(args.size() > 0) + obj->m_sampling_time = args[0].as_double(); + if(args.size() > 1) + obj->m_responsivity_A_W = args[1].as_double(); + + // Parse keyword arguments + for (auto &p: kwargs) + { + string kw = p.first; + strutils::toupper(kw); + if (kw == "SAMPLING_TIME" || kw == "TS") + obj->m_sampling_time = p.second.as_double(); + else if (kw == "R" || kw == "RESPONSIVITY" || kw == "GAIN") + obj->m_responsivity_A_W = p.second.as_double(); + else { + cerr << "Unknown keyword: " << p.first << endl; + exit(1); + } + } + return obj; +} + +/** ******************************************* **/ +/** Subcircuit instance **/ +/** ******************************************* **/ +INSTANTIATE_AND_CONNECT_UNI(XElement, pt_helper) +{ + (void)pt_helper; + return nullptr; +} + +sc_module *XElement::create(ParseTreeCreationHelper &pt_helper) const +{ + (void)pt_helper; + cerr << "X element should never be called directly" << endl; + exit(1); + return nullptr; +} diff --git a/src/parser/parse_element.h b/src/parser/parse_element.h new file mode 100644 index 0000000..58ad694 --- /dev/null +++ b/src/parser/parse_element.h @@ -0,0 +1,104 @@ +#pragma once + +#include "alldevices.h" +#include "subcircuit_instance.h" +#include "parse_tree.h" +#include "specs.h" + +#include <initializer_list> +#include <utility> +#include <memory> +#include <string> +#include <vector> +#include <map> +#include <iostream> + +using std::pair; +using std::make_pair; +using std::string; +using std::vector; +using std::map; +using std::cout; +using std::cerr; +using std::endl; +using std::pair; +using std::unique_ptr; + +/** ******************************************* **/ +/** Helper macros for declaring devices **/ +/** ******************************************* **/ +#define DECLARE_UNIDIR_ELEMENT(ELEM_NAME, ELEM_NAME_LONG, MOD_CLASS_PREFIX, N_NETS) \ + struct ELEM_NAME : public ParseElement { \ + typedef MOD_CLASS_PREFIX element_type_base; \ + typedef MOD_CLASS_PREFIX element_type_uni; \ + \ + const size_t n_nets = N_NETS; \ + \ + /* Import constructor from ParseElement */ \ + using ParseElement::ParseElement; \ + \ + virtual ParseElement *clone() const \ + { return new ELEM_NAME(*this); } \ + /* Implement virtual function create(...) to construct element */ \ + virtual sc_module *create(ParseTreeCreationHelper &pt_helper) const; \ + virtual element_type_base * \ + instantiate_and_connect_uni(ParseTreeCreationHelper &pt_helper) const; \ + \ + virtual string kind() const { return ELEM_NAME_LONG; } \ + }; + +/*************************************************/ + +#define DECLARE_BIDIR_ELEMENT(ELEM_NAME, ELEM_NAME_LONG, MOD_CLASS_PREFIX, N_NETS) \ + \ + struct ELEM_NAME : public ParseElement { \ + typedef MOD_CLASS_PREFIX##Base element_type_base; \ + typedef MOD_CLASS_PREFIX##Uni element_type_uni; \ + typedef MOD_CLASS_PREFIX##Bi element_type_bi; \ + \ + const size_t n_nets = N_NETS; \ + \ + /* Import constructor from ParseElement */ \ + using ParseElement::ParseElement; \ + \ + virtual ParseElement *clone() const \ + { return new ELEM_NAME(*this); } \ + /* Implement virtual function create(...) to construct element */ \ + virtual sc_module *create(ParseTreeCreationHelper &pt_helper) const; \ + virtual element_type_base * \ + instantiate_and_connect_uni(ParseTreeCreationHelper &pt_helper) const; \ + virtual element_type_base * \ + instantiate_and_connect_bi(ParseTreeCreationHelper &pt_helper) const; \ + \ + virtual string kind() const { return string(ELEM_NAME_LONG) + " (bidir)"; } \ + }; + +/** ******************************************* **/ +/** Devices declarations **/ +/** ******************************************* **/ +DECLARE_BIDIR_ELEMENT(WGElement, "WAVEGUIDE", Waveguide, 2); +DECLARE_BIDIR_ELEMENT(DCElement, "DIRECTIONAL COUPLER", DirectionalCoupler, 4); +DECLARE_UNIDIR_ELEMENT(MergerElement, "MERGER", Merger, 3); +DECLARE_UNIDIR_ELEMENT(SplitterElement, "SPLITTER", Splitter, 3); +DECLARE_BIDIR_ELEMENT(PhaseShifterElement, "PHASE SHIFTER", PhaseShifter, 3); +DECLARE_BIDIR_ELEMENT(MZIElement, "MZI MODULATOR", MZIActive, 5); +//DECLARE_UNIDIR_ELEMENT(MZIElement, "MZI MODULATOR (2 PHASE-SHIFTER)", MZI, 6); +DECLARE_BIDIR_ELEMENT(CrossingElement, "CROSSING", Crossing, 4); +DECLARE_UNIDIR_ELEMENT(CWSourceElement, "CW SOURCE", CWSource, 1); +DECLARE_UNIDIR_ELEMENT(VLSourceElement, "VALUE LIST SOURCE (OPTICAL)", VLSource, 1); +DECLARE_UNIDIR_ELEMENT(EVLSourceElement, "VALUE LIST SOURCE (ELECTRICAL)", EVLSource, 1); + +// TODO: make the following bidirectional +DECLARE_UNIDIR_ELEMENT(PCMCellElement, "PCM CELL", PCMElement, 2); +DECLARE_UNIDIR_ELEMENT(PhotodetectorElement, "PHOTODETECTOR", Detector, 2); +DECLARE_UNIDIR_ELEMENT(ProbeElement, "PROBE", Probe, 1); +DECLARE_UNIDIR_ELEMENT(MLProbeElement, "MULTIWAVELENGTH PROBE", MLambdaProbe, 1); + +// TODO: take care of subcircuit instance... +DECLARE_UNIDIR_ELEMENT(XElement, "SUBCIRCUIT", SubcircuitInstance, 1); + +/** ******************************************* **/ +/** Undefine macros **/ +/** ******************************************* **/ +#undef DECLARE_UNIDIR_ELEMENT +#undef DECLARE_BIDIR_ELEMENT
\ No newline at end of file diff --git a/src/parser/parse_tree.cpp b/src/parser/parse_tree.cpp new file mode 100644 index 0000000..76c67b0 --- /dev/null +++ b/src/parser/parse_tree.cpp @@ -0,0 +1,972 @@ +#include "parse_tree.h" +#include "parse_directive.h" +#include "parse_element.h" +#include "specs.h" + +#include <sstream> +#include <iomanip> + +using std::ostringstream; + +using spx::oa_value_type; +using spx::ea_value_type; +using spx::ed_value_type; + +using spx::ed_bus_type; +using spx::oa_signal_type; +using spx::ea_signal_type; +using spx::ed_signal_type; +using spx::ed_bus_type; + +#include "../build/parser/parser.tab.h" +#include "../build/parser/parser.yy.h" + +vector<shared_ptr<sc_object>> ParseNet::create(const string &name, bool force_bidir) const +{ + if ( !bidirectional() && !force_bidir ) + return { create_uni(name) }; + else + { + assert(type() == OANALOG && "Only optical nets can be bidirectional for now"); + return { create_uni((name + "_0").c_str()), create_uni((name + "_1").c_str()) }; + } +} + +shared_ptr<sc_object> ParseNet::create_uni(const string &name) const +{ + switch (m_type) + { + case OANALOG: + return { make_shared<spx::oa_signal_type>(name.c_str()) }; + case EANALOG: + return { make_shared<spx::ea_signal_type>(name.c_str()) }; + case EDIGITAL: + if (m_size == 1) + return { make_shared<spx::ed_signal_type>(name.c_str()) }; + else + return { make_shared<spx::ed_bus_type>(name.c_str(), sc_lv_base(m_size)) }; + default: + cerr << "Unknown net type: " << name << endl; + exit(1); + } + return { nullptr }; +} + +string ParseNet::name_from_id(int id) +{ + assert(id >= 0); + ostringstream ss; + ss << "N" << std::setfill('0') << std::setw(5) << id; + return ss.str(); +} + +// return next bidir net which doesn't have a corresponding signal in circuit_signals +map<string, ParseNet>::iterator ParseTreeCreationHelper::next_fresh_bidir_net() +{ + for (auto it = pt->nets.begin(); it != pt->nets.end(); ++it) + { + const auto &net = *it; + + // check if net is bidirectional + if (!net.second.bidirectional()) + continue; + + // check if net has a corresponding signal instanciated + auto it_sig = find_if(circuit_signals.cbegin(), circuit_signals.cend(), [&it](const auto &p) + { return p.first == it->first; } + ); + if (it_sig != circuit_signals.cend()) + continue; + + // check if net is unbound + auto it_elem = next_fresh_element_bound_to(it->first); + if (it_elem == pt->elements.cend()) + continue; + + return it; + } + return pt->nets.end(); +} + +// return next bidir net which doesn't have a corresponding signal in circuit_signals +map<string, ParseNet>::iterator ParseTreeCreationHelper::next_fresh_net() +{ + for (auto it = pt->nets.begin(); it != pt->nets.end(); ++it) + { + // check if net has a corresponding signal + auto it_sig = find_if(circuit_signals.cbegin(), circuit_signals.cend(), [&it](const auto &p) + { return p.first == it->first; } + ); + if (it_sig != circuit_signals.cend()) + continue; + + // check if net is unbound + auto it_elem = next_fresh_element_bound_to(it->first); + if (it_elem == pt->elements.cend()) + continue; + + return it; + } + return pt->nets.end(); +} + +// return next element which is connected to "net_name" and doesnt have a corresponding +// module in circuit_modules and isn't already in the backlog +vector<ParseElement *>::iterator ParseTreeCreationHelper::next_fresh_element_bound_to(const string &net_name, const set<const ParseElement *> &excludes) +{ + // Loop over elements + for (auto it = pt->elements.begin(); it != pt->elements.end(); ++it) + { + const auto &elem = *it; + + // Check if element is part of exlude set + if (excludes.find(elem) != excludes.cend()) + continue; + + // Check if element is part of backlog set + if (elements_backlog.find(elem) != elements_backlog.cend()) + continue; + + // Check if net_name is in element nets + if (find(elem->nets.cbegin(), elem->nets.cend(), net_name) == elem->nets.cend()) + continue; + + // Check if element has a corresponding module instantiated + auto it_mod = find_if(circuit_modules.cbegin(), circuit_modules.cend(), [&it](const auto &p) + { return p.first == (*it)->name; } + ); + + // if not, return current iterator `it` + if (it_mod == circuit_modules.cend()) + return it; + } + return pt->elements.end(); +} + +void ParseTreeCreationHelper::create_signals(const ParseElement *elem) +{ + // element should be in the parsetree + assert(find(pt->elements.begin(), pt->elements.end(), elem) != pt->elements.end()); + + // for all nets connected to elements + for (const auto &net : elem->nets) + { + // find whether it has already been instantiated + if (circuit_signals.find(net) == circuit_signals.end()) + { + // if not, do it + circuit_signals.emplace(net, pt->nets.at(net).create(net)); + + // verify the net had no connection (it would be a bug otherwise, + // since it hadn't been instantiated) + assert(pt->nets.at(net).m_connect_count == 0); + + // find all elements connected to net and add them to the elements backlog + // FIXME: potential bug here if an element can have both bidir and unidir nets + auto it = next_fresh_element_bound_to(net, {elem}); + while (it != pt->elements.end()) + { + elements_backlog.insert(*it); + it = next_fresh_element_bound_to(net, {elem}); + } + } + } +} + +void ParseTreeCreationHelper::upgrade_signal(const string &net_name) +{ + // Upgrade even if: net.bidirectional() is false + + // The signal should exist because it has been created by pt_helper.create_signals() + // but it doesn't hurt to check once more time + assert(circuit_signals.find(net_name) != circuit_signals.end()); + + // Set the bidirectional flag to true + pt->nets[net_name].m_bidirectional = true; + + // Check if the net was created as unidirectional (only one signal) + if (circuit_signals.at(net_name).size() == 1) + { + // if the existing signal is unidirectional + + // check if a port is already connected to the signal + if (pt->nets[net_name].m_connect_count) + { + // if yes, that means a port is already connected to the signal + // we cannot easily re-instantiate it as it may be bound to a port; + // instead, we add a second signal to the vector to make it bidirectional + circuit_signals[net_name].push_back(pt->nets[net_name].create_uni(net_name + "_1")); + + // For bidirectional signals, first port to connect binds to signal_0 + // for writing and signal_1 for reading + // Therefore we have to "re-create" this scenario, as if the first device + // connected to a bidirectional net. But for this we need to know which + // if the first device was a writer or a reader. + + // first determine if the connected port was writing or reading the signal + bool has_writer = pt->nets[net_name].m_connect_writer_count; + bool has_reader = pt->nets[net_name].m_connect_reader_count; + + // only one should be true since the net was unidirectional + assert(has_writer ^ has_reader); + + // if a writer, then it's as expected + if (has_writer) + { + // if a writer, then it's as expected: + // the next port will connect to signal_1 for writing + // we just need to update the number of "readers" connected to the net + pt->nets[net_name].m_readers_count++; + } + else + { + // if a writer, then the next port needs to reverse its order. + // for this we swap signal_0 and signal_1 + swap(circuit_signals[net_name][0], circuit_signals[net_name][1]); + // then we need to update the number of "writers" connected to the net + pt->nets[net_name].m_writers_count++; + } + } + else + { + // otherwise, we can recreate the first signal as well + circuit_signals[net_name].clear(); // will delete the net through the constructor + circuit_signals[net_name] = pt->nets.at(net_name).create(net_name); + } + } +} + +string ParseElement::to_json() const +{ + // name + // kind() + // nets + // args + // kwargs + + stringstream ss; + ss << "{"; + ss << "\"name\":" << '"' << name << '"'; + ss << ','; + ss << "\"type\":" << '"' << kind() << '"'; + ss << ','; + ss << "\"nets\":"; + { + ss << '['; + for (size_t i = 0; i < nets.size(); ++i) + { + ss << '"' << nets[i] << '"'; + if (i != nets.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"args\":"; + { + ss << '['; + for (size_t i = 0; i < args.size(); ++i) + { + ss << args[i].to_json(); + if (i != args.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"kwargs\":"; + { + ss << '{'; + for (auto it = kwargs.begin(); it != kwargs.end(); ++it) + { + if (it != kwargs.begin()) + ss << ','; + ss << '"' << it->first << '"' << ':'; + ss << it->second.to_json(); + } + ss << '}'; + } + ss << '}'; + return ss.str(); +} + +ParseTree::ParseTree(const string &name, const ParseSubcircuit &subcircuit, const map<string, Variable> &kwargs) +: ParseTree(name) +{ + parent = subcircuit.parent; + is_subcircuit = true; + + // take kwargs as local assignments + local_assignments = subcircuit.kwargs; + + for (const auto &p : kwargs) + { + if (local_assignments.count(p.first) == 0) + { + cerr << name << ": Unknown subcircuit parameter " << p.first << endl; + exit(1); + } + local_assignments[p.first] = p.second; + } + + yyscan_t scanner; + YY_BUFFER_STATE buf; + + yylex_init(&scanner); + buf = yy_scan_string(subcircuit.netlist.c_str(), scanner); + yy_switch_to_buffer(buf, scanner); + + int parsing_result = yyparse(scanner, this); + + //yy_delete_buffer(buf, scanner); + yylex_destroy(scanner); + + // Return if unsuccessful + if (parsing_result != 0) { + cerr << name << ": failed parsing subcircuit netlist" << endl; + exit(1); + } + + if (directives.size() > 0) + { + cerr << name << ": found a directive in subcircuit, ignoring." << endl; + directives.clear(); + } + + if (analyses.size() > 0) + { + cerr << name << ": found an analysis in subcircuit, ignoring." << endl; + analyses.clear(); + } + // print(); +} + +int ParseTree::register_directive(ParseDirective *directive) +{ + directive->parent = this; + directives.push_back(directive); + // cout << "Created directive " << directive->kind() << endl; + // cout << "current number of directives: " << directives.size() << endl; + return directives.size() - 1; + +} + +int ParseTree::register_element(ParseElement *element) +{ + element->name = name_prefix() + element->name; + strutils::toupper(element->name); + element->parent = this; + elements.push_back(element); + // cout << "Created element " << element->name << endl; + // cout << "current number of elements: " << elements.size() << endl; + return elements.size() - 1; +} + +int ParseTree::register_analysis(ParseAnalysis *analysis) +{ + if ( !analyses.empty() ) + { + cerr << "Attempted to register a new analysis (" << analysis->kind() << ")" << endl; + cerr << "But another one was already specified (" << analyses[0]->kind() << ")" << endl; + exit(1); + } + analysis->parent = this; + analyses.push_back(analysis); + // cout << "Created analysis " << analysis->kind() << endl; + // cout << "current number of analysis: " << analyses.size() << endl; + return analyses.size() - 1; +} + +int ParseTree::register_subcircuit(string name) +{ + strutils::toupper(name); + //name = name_prefix() + name; + + auto it = find_if(subcircuits.cbegin(), subcircuits.cend(), + [&name](const ParseSubcircuit *p){ return p->name == name;}); + if (it != subcircuits.cend()) + { + cerr << "Attempted to register a new subcircuit with name " << name << endl; + cerr << "But another subcircuit with this name already exists" << endl; + exit(1); + } + + subcircuits.push_back(new ParseSubcircuit(name, this)); + int i = subcircuits.size() - 1; + + // TODO: Copy variables definitions ? + + // cout << "Created subcircuit " << subcircuits[i]->name << endl; + // cout << "(current number of subcircuits: " << subcircuits.size() << ")" << endl; + + return i; +} + +const ParseSubcircuit *ParseTree::find_subcircuit(const string &name) const +{ + auto pred = [&name](const ParseSubcircuit *p) { + return p->name == name; + }; + auto it = find_if(subcircuits.begin(), subcircuits.end(), pred); + if (it != subcircuits.end()) + return *it; + + cerr << "Subcircuit definition not found: " << name << endl; + exit(1); +} + +void ParseTree::print() const +{ + cout << "-----------" << endl; + cout << global_assignments.size() << " global assignments" << endl; + for (const auto &x : global_assignments) + cout << " - " << x.first << " (" << x.second.kind() + << ") = " << x.second.get_str() << endl; + + cout << "-----------" << endl; + cout << local_assignments.size() << " local assignments" << endl; + for (const auto &x : local_assignments) + cout << " - " << x.first << " (" << x.second.kind() + << ") = " << x.second.get_str() << endl; + + cout << "-----------" << endl; + cout << elements.size() << " elements" << endl; + for (const auto &x : elements) + { + cout << " - "; + x->print(); + } + + cout << "-----------" << endl; + cout << nets.size() << " named nets" << endl; + for (const auto &x : nets) + cout << " - " << x.first << ": " << x.second.type_str() + << "<" << x.second.size() << ">" + << (x.second.bidirectional() ? "b" : "u") + << " (" << x.second.m_writers_count << "|" << x.second.m_readers_count << ")" + << endl; + + cout << "-----------" << endl; + cout << directives.size() << " directives" << endl; + for (const auto &x : directives) + { + cout << " - "; + x->print(); + } + + cout << "-----------" << endl; + cout << subcircuits.size() << " subcircuits" << endl; + for (const auto &x : subcircuits) + { + cout << " - "; + x->print(); + } + + cout << "-----------" << endl; + cout << analyses.size() << " analyses" << endl; + for (const auto &x : analyses) + { + cout << " - "; + x->print(); + } +} + +string ParseDirective::to_json() const +{ + stringstream ss; + ss << "{"; + ss << "\"type\":" << '"' << kind() << '"'; + ss << ','; + ss << "\"args\":"; + { + ss << '['; + for (size_t i = 0; i < args.size(); ++i) + { + ss << args[i].to_json(); + if (i != args.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"kwargs\":"; + { + ss << '{'; + for (auto it = kwargs.begin(); it != kwargs.end(); ++it) + { + if (it != kwargs.begin()) + ss << ','; + ss << '"' << it->first << '"' << ':'; + ss << it->second.to_json(); + } + ss << '}'; + } + ss << '}'; + return ss.str(); +} + +string ParseAnalysis::to_json() const +{ + stringstream ss; + ss << "{"; + ss << "\"type\":" << '"' << kind() << '"'; + ss << ','; + ss << "\"args\":"; + { + ss << '['; + for (size_t i = 0; i < args.size(); ++i) + { + ss << args[i].to_json(); + if (i != args.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"kwargs\":"; + { + ss << '{'; + for (auto it = kwargs.begin(); it != kwargs.end(); ++it) + { + if (it != kwargs.begin()) + ss << ','; + ss << '"' << it->first << '"' << ':'; + ss << it->second.to_json(); + } + ss << '}'; + } + ss << '}'; + return ss.str(); +} + +string ParseSubcircuit::to_json() const +{ + stringstream ss; + ss << "TODO"; + return ss.str(); +} + +string ParseNet::to_json() const +{ + stringstream ss; + ss << "{"; + ss << "\"type\":" << '"' << type_str() << '"'; + ss << ','; + ss << "\"size\":" << m_size; + ss << ','; + ss << "\"bidirectional\":" << bidirectional(); + ss << ','; + ss << "\"readers\":" << m_readers_count; + ss << ','; + ss << "\"writers\":" << m_readers_count; + ss << '}'; + return ss.str(); +} + +string ParseTree::to_json() const +{ + stringstream ss; + ss << "{"; + ss << "\"name\":" << '"' << name << '"'; + ss << ','; + ss << "\"parent\":"; + if (parent) + ss << '"' << parent->name << '"'; + else + ss << "null"; + ss << ','; + ss << "\"is_subcircuit\":" << (is_subcircuit ? "true" : "false"); + ss << ','; + ss << "\"unnamed_nets\":" << unnamed_net_count; + ss << ','; + ss << "\"nets\":"; + { + ss << '{'; + for (auto it = nets.begin(); it != nets.end(); ++it) + { + if (it != nets.begin()) + ss << ','; + ss << '"' << it->first << '"' << ':'; + ss << it->second.to_json(); + } + ss << '}'; + } + ss << ','; + ss << "\"elements\":"; + { + ss << '['; + for (size_t i = 0; i < elements.size(); ++i) + { + ss << elements[i]->to_json(); + if (i != elements.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"directives\":"; + { + ss << '['; + for (size_t i = 0; i < directives.size(); ++i) + { + ss << directives[i]->to_json(); + if (i != directives.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"analyses\":"; + { + ss << '['; + for (size_t i = 0; i < analyses.size(); ++i) + { + ss << analyses[i]->to_json(); + if (i != analyses.size() - 1) + ss << ", "; + } + ss << ']'; + } + ss << ','; + ss << "\"subcircuits\":"; + { + ss << "\"TODO\""; + if (false) + { + ss << '['; + for (size_t i = 0; i < subcircuits.size(); ++i) + { + ss << subcircuits[i]->to_json(); + if (i != subcircuits.size() - 1) + ss << ", "; + } + ss << ']'; + } + } + ss << ','; + ss << "\"local_variables\":"; + { + ss << '{'; + for (auto it = local_assignments.begin(); it != local_assignments.end(); ++it) + { + if (it != local_assignments.begin()) + ss << ','; + ss << '"' << it->first << '"' << ':'; + ss << it->second.to_json(); + } + ss << '}'; + } + ss << ','; + ss << "\"global_variables\":"; + { + ss << '{'; + for (auto it = global_assignments.begin(); it != global_assignments.end(); ++it) + { + if (it != global_assignments.begin()) + ss << ','; + ss << '"' << it->first << '"' << ':'; + ss << it->second.to_json(); + } + ss << '}'; + } + ss << '}'; + return ss.str(); +} + +void ParseTree::build_circuit() +{ + cout << "Flattening..." << endl; + // flatten current parse tree by expanding subcircuits + flatten(); + cout << "Done (flattening)" << endl; + + auto pt_helper = ParseTreeCreationHelper(this); + + auto &elements_backlog = pt_helper.elements_backlog; + auto &circuit_signals = pt_helper.circuit_signals; + auto &circuit_modules = pt_helper.circuit_modules; + + // Find first bidirectional net in nets that is not in circuit_nets + auto next_net = pt_helper.next_fresh_bidir_net(); + while(next_net != nets.end()) + { + cout << "Elaborating network of " << next_net->first << "..." << endl; + + // Find elements which are connected + auto elem = pt_helper.next_fresh_element_bound_to(next_net->first); + while (elem != elements.end()) + { + cout << "Creating " << (*elem)->name << " (reason: connection to bidir net)" << endl; + auto mod = (*elem)->create(pt_helper); + cout << "Done creating " << (*elem)->name << endl; + if (mod->name() != (*elem)->name) + { + cerr << "Error: a module with name '" << (*elem)->name << "' already exists or"; + cerr << " it was renamed due to a bad naming." << endl; + cerr << "Make sure there is no naming conflict in the netlist" << endl; + exit(1); + } + circuit_modules.emplace(mod->name(), mod); + + // Process backlog elements (elements that were connected to the nets) + while ( !elements_backlog.empty() ) + { + auto it = elements_backlog.begin(); + auto &backlog_elem = *it; + cout << "Creating " << backlog_elem->name << " (reason: backlog)" << endl; + auto mod = backlog_elem->create(pt_helper); + cout << "Done creating " << backlog_elem->name << endl; + + if (mod->name() != (*it)->name) + { + cerr << "Error: a module with name '" << (*it)->name << "' already exists or"; + cerr << " it was renamed due to a bad naming." << endl; + cerr << "Make sure there is no naming conflict in the netlist" << endl; + exit(1); + } + + circuit_modules.emplace(mod->name(), mod); + elements_backlog.erase(*it); + } + elem = pt_helper.next_fresh_element_bound_to(next_net->first); + } + + cout << "Done (elaborating network of " << next_net->first << ")" << endl; + + // At this point all elements connected to the bidirectional net have been created + // move on to the next one + next_net = pt_helper.next_fresh_bidir_net(); + } + cout << "Done with bidirectional nets" << endl; + // At this point all bidirectional nets have been created, and all devices + // connected to them as well we can proceed with unidirectional nets + next_net = pt_helper.next_fresh_net(); + while(next_net != nets.end()) + { + cout << "Elaborating network of " << next_net->first << "..." << endl; + + // Find elements which are connected + auto elem = pt_helper.next_fresh_element_bound_to(next_net->first); + while (elem != elements.end()) + { + cout << "Creating " << (*elem)->name << " (reason: connection to unidir net)" << endl; + auto mod = (*elem)->create(pt_helper); + cout << "Done creating " << (*elem)->name << endl; + if (mod->name() != (*elem)->name) + { + cerr << "Error: a module with name '" << (*elem)->name << "' already exists or"; + cerr << " it was renamed due to a bad naming." << endl; + cerr << "Make sure there is no naming conflict in the netlist" << endl; + exit(1); + } + circuit_modules.emplace(mod->name(), mod); + + // Process backlog elements (elements that were connected to the nets) + while ( !elements_backlog.empty() ) + { + auto it = elements_backlog.begin(); + auto &backlog_elem = *it; + cout << "Creating " << backlog_elem->name << " (reason: backlog)" << endl; + auto mod = backlog_elem->create(pt_helper); + cout << "Done creating " << backlog_elem->name << endl; + + if (mod->name() != (*it)->name) + { + cerr << "Error: a module with name '" << (*it)->name << "' already exists or"; + cerr << " it was renamed due to a bad naming." << endl; + cerr << "Make sure there is no naming conflict in the netlist" << endl; + exit(1); + } + + circuit_modules.emplace(mod->name(), mod); + elements_backlog.erase(*it); + } + elem = pt_helper.next_fresh_element_bound_to(next_net->first); + } + + cout << "Done (elaborating network of " << next_net->first << ")" << endl; + + // At this point all elements connected to the bidirectional net have been created + // move on to the next one + next_net = pt_helper.next_fresh_net(); + } + for (const auto &x : directives) + x->create(); + + if (! analyses.empty()) + analyses.at(0)->create(); + + // Add all nets and elements to SPECSGlobalConfig + for (const auto &x: circuit_modules) + specsGlobalConfig.register_object(x.second); + for (const auto &x: circuit_signals) + for (const auto &sig: x.second) + specsGlobalConfig.register_object(sig); +} + +void ParseTree::flatten() +{ + cout << "Flattening " << name << endl; + + vector<ParseElement *> elements_flat; + map<string, ParseNet> nets_flat = nets; + + // First, find all subcircuit instances (X elements) and ingest their parse-tree + // (flattening the global parse-tree) + for (auto &elem : elements) + { + // try to cast as XElement + XElement *xelem = dynamic_cast<XElement *>(elem); + + // if unsuccessful, it means the device doesnt need to be flattened + if (!xelem) + { + elements_flat.push_back(elem); + continue; + } + + // get subcircuit name + string subcircuit_name = xelem->args.back().as_string(); + strutils::toupper(subcircuit_name); + + // get subcircuit definition in element's parent + // TODO: figure out if we want global subcircuits + auto subcircuit = xelem->parent->find_subcircuit(subcircuit_name); + + // parse the subcircuit netlist into a new parse tree + ParseTree sub_pt(xelem->name, *subcircuit, xelem->kwargs); + + // flatten it + sub_pt.flatten(); + + // Check the number of nets (in args) + if(xelem->args.size() - 1 != subcircuit->ports.size()) + { + cerr << "Wrong number of nets for subcircuit instance: "; + cerr << xelem->name << endl; + exit(1); + } + + // Compute net_name equivalence between internal and external nets + map<string, string> net_names_translations; + for (size_t i = 0; i < subcircuit->ports.size(); ++i) + { + Variable v = xelem->args[i]; // naming from Xnn ... line + string internal_net_name = sub_pt.name_prefix() + subcircuit->ports[i]; // naming from .SUBCKT line + string external_net_name = ""; + + // build full exposed net_name + string net_base; + + // extract from Variable (either string or integer) + // normally parser should always transform it to a string variable + // for us + if (v.type == Variable::STRING) + net_base = v.as_string(); + else if (v.type == Variable::INTEGER) + net_base = ParseNet::name_from_id(v.as_integer()); + else + { + cerr << "Incompatible net name for " << xelem->name << endl; + exit(1); + } + + // if a single underscore was given, use the unnamed net count to + // define a unique net + // FIXME: this way is not correct; it should really increment the + // parent's unnamed net count; I think it would be acceptable to + // discard const for this, as the user specifically doesn't care about + // the actual name of unnamed nets. + if (net_base == "_") + net_base = "_" + to_string(this->unnamed_net_count++); + + // add current prefix + external_net_name = name_prefix() + net_base; + + // see if the net was already defined (was used by another device) + if (nets.find(external_net_name) != nets.end()) + { + // if so, combined the previously defined net with the internal one + bool ok = sub_pt.nets[internal_net_name].combine_with(nets.at(external_net_name)); + if (!ok) + { + cerr << "Could not reconcile nets: " << internal_net_name; + cerr << " and " << external_net_name << endl; + cerr << "During flattening of " << xelem->name << endl; + exit(1); + } + } + // Add the (potentially combined) net to pt_helper nets + nets_flat[external_net_name] = sub_pt.nets.at(internal_net_name); + + // Update the net name translations list + net_names_translations[internal_net_name] = external_net_name; + + // Erase the internal net_name (replaced by the global net name) + sub_pt.nets.erase(internal_net_name); + } // for (size_t i = 0; i < subcircuit->ports.size(); ++i) + + // show result of translation + if (false) + for (const auto &p : net_names_translations) + cout << p.first << " <==> " << p.second << endl; + + // translate internal net names by modifying the elements within the + // subcircuit which are bound to them + for (auto subelem : sub_pt.elements) + { + // loop over translation, and update if necessary + for (const auto &p : net_names_translations) + { + auto it = find(subelem->nets.begin(), subelem->nets.end(), p.first); + if (it == subelem->nets.end()) + continue; + *it = p.second; + } + } // for (auto subelem : sub_pt.elements) + + // insert the (globally named) internal-only nets into flattened netlist + nets_flat.insert(sub_pt.nets.cbegin(), sub_pt.nets.cend()); + // insert the (potentially updated) elements to flattened netlist + elements_flat.insert(elements_flat.end(), sub_pt.elements.cbegin(), sub_pt.elements.cend()); + + // finally, free the memory of the elem object + // note that the pointer itself is still in the elements vector! + // we cannot remove it due to the for loop + delete elem; + elem = nullptr; + } // for (auto elem : elements) + + // Print new list of elements and nets + if (false) + { + cout << "-----------" << endl; + cout << elements_flat.size() << " elements" << endl; + for (const auto &x : elements_flat) + { + cout << " - "; + x->print(); + } + + cout << "-----------" << endl; + cout << nets_flat.size() << " named nets" << endl; + for (const auto &x : nets_flat) + cout << " - " << x.first << ": " << x.second.type_str() + << "<" << x.second.size() << ">" + << (x.second.bidirectional() ? "b" : "u") + << " (" << x.second.m_writers_count << "|" << x.second.m_readers_count << ")" + << endl; + } + + // move to flattened nets and elements + nets = nets_flat; + elements = elements_flat; + + return; +} + +map<string, Variable> ParseTree::global_assignments = +{ + { "pi", Variable(M_PI) }, + { "c", Variable(299792458.0) }, +};
\ No newline at end of file diff --git a/src/parser/parse_tree.h b/src/parser/parse_tree.h new file mode 100644 index 0000000..fbcefbc --- /dev/null +++ b/src/parser/parse_tree.h @@ -0,0 +1,890 @@ +#pragma once + +#include "specs.h" +#include "strutils.h" + +#include <initializer_list> +#include <utility> +#include <memory> +#include <string> +#include <vector> +#include <map> +#include <iostream> + +using std::pair; +using std::make_pair; +using std::string; +using std::vector; +using std::map; +using std::cout; +using std::cerr; +using std::endl; +using std::pair; +using std::unique_ptr; + +struct ParseTree; +struct SUBCKTDirective; + +/* Struct to hold a typed variable */ +struct Variable { + enum Type { + TYPE_MIN = -1, + DOUBLE = 0, + COMPLEX_DOUBLE, + INTEGER, + BOOLEAN, + STRING, + LIST, + NONE, + TYPE_MAX, + }; + Type type; + double num; + complex<double> cnum; + int inum; + bool bnum; + string str; + vector<Variable> vec; + + Variable(const Variable &v) { *this = v; } + Variable(Type type): type(type) {} + Variable(double num = 0): type(DOUBLE), num(num) {} + explicit Variable(const complex<double> &cnum): type(COMPLEX_DOUBLE), cnum(cnum) {} + explicit Variable(int inum): type(INTEGER), inum(inum) {} + explicit Variable(bool bnum): type(BOOLEAN), bnum(bnum) {} + explicit Variable(const string &str): type(STRING), str(str) {} + explicit Variable(const vector<Variable> &vec): type(LIST), vec(vec) {} + explicit Variable(const vector<double> &dvec): type(LIST) + { + vec.resize(dvec.size()); + for (size_t i = 0; i < dvec.size(); ++i) + { + vec[i] = Variable(dvec[i]); + } + } + + bool type_is_valid() const { + return TYPE_MIN < type && type < TYPE_MAX; + } + + bool is_none() const { + return type == NONE; + } + + bool is_list() const { + return type == LIST; + } + + bool is_number() const { + return type == DOUBLE || type == INTEGER || type == BOOLEAN; + } + + string get_str() const + { + stringstream ss; + switch (type) + { + case STRING: + return str; + case DOUBLE: + ss << num; + return ss.str(); + case COMPLEX_DOUBLE: + ss << cnum.real() << " + " << cnum.imag() << "i"; + return ss.str(); + case INTEGER: + ss << inum; + return ss.str(); + case BOOLEAN: + ss << bnum; + return ss.str(); + case LIST: + ss << "["; + for (size_t i = 0; i < vec.size(); ++i) + { + ss << vec[i].to_json(); + if (i != vec.size() - 1) + ss << ", "; + } + ss << "]"; + return ss.str(); + case NONE: + return "None"; + default: + cerr << "error: cannot convert variable to string" << endl; + exit(1); + } + } + + string to_json() const + { + stringstream ss; + ss << '{'; + ss << "\"type\":" << '"' << kind() << '"' << ','; + ss << "\"value\":"; + { + stringstream tss; + switch (type) { + case STRING: + tss << '"' << str << '"'; + break; + case DOUBLE: + tss << scientific << num; + break; + case COMPLEX_DOUBLE: + tss << "{\"real\":"; + tss << scientific << cnum.real(); + tss << ",\"imag\":" << cnum.imag(); + tss << '}'; + break; + case INTEGER: + tss << inum; + break; + case BOOLEAN: + tss << (bnum ? "true" : "false"); + break; + case LIST: + tss << "["; + for (size_t i = 0; i < vec.size(); ++i) { + tss << vec[i].to_json(); + if (i != vec.size() - 1) + tss << ", "; + } + tss << "]"; + break; + case NONE: + tss << "null"; + break; + default: + cerr << "error: cannot convert variable to json representation" << endl; + exit(1); + } + ss << tss.str(); + } + ss << '}'; + return ss.str(); + } + + double as_double() const + { + if (type == DOUBLE) + return num; + if (type == INTEGER) + return inum; + if (type == BOOLEAN) + return bnum; + cerr << "Variable cannot be converted to a double value: " << get_str() << endl; + exit(1); + } + + int as_integer() const + { + if (type == DOUBLE) + return num; + if (type == INTEGER) + return inum; + if (type == BOOLEAN) + return bnum; + cerr << "Variable cannot be converted to an integer value: " << get_str() << endl; + exit(1); + } + + bool as_boolean() const + { + if (type == DOUBLE) + return num; + if (type == INTEGER) + return inum; + if (type == BOOLEAN) + return bnum; + cerr << "Variable cannot be converted to a boolean value: " << get_str() << endl; + exit(1); + } + + complex<double> as_complex() const + { + if (type == DOUBLE) + return num; + if (type == COMPLEX_DOUBLE) + return cnum; + if (type == INTEGER) + return inum; + if (type == BOOLEAN) + return bnum; + cerr << "Variable cannot be converted to a complex value: " << get_str() << endl; + exit(1); + } + + string as_string() const + { + if (type == STRING) + return str; + cerr << "Variable is not a string: " << get_str() << endl; + exit(1); + return 0; + } + + string kind() const + { + if (type == DOUBLE) + return "DOUBLE"; + if (type == COMPLEX_DOUBLE) + return "COMPLEX_DOUBLE"; + if (type == INTEGER) + return "INTEGER"; + if (type == BOOLEAN) + return "BOOLEAN"; + if (type == STRING) + return "STRING"; + if (type == LIST) + return "LIST"; + if (type == NONE) + return "NONE"; + + return "UNDEFINED"; + } + + Variable &operator+=(const Variable &rhs) + { + num = as_double() + rhs.as_double(); + type = DOUBLE; + return *this; + } + Variable &operator-=(const Variable &rhs) + { + num = as_double() - rhs.as_double(); + type = DOUBLE; + return *this; + } + Variable &operator*=(const Variable &rhs) + { + num = as_double() * rhs.as_double(); + type = DOUBLE; + return *this; + } + Variable &operator/=(const Variable &rhs) + { + num = as_double() / rhs.as_double(); + type = DOUBLE; + return *this; + } + Variable &operator^=(const Variable &rhs) + { + num = pow(as_double(), rhs.as_double()); + type = DOUBLE; + return *this; + } + Variable &operator=(const Variable &rhs) = default; + operator string() const { return get_str(); } +}; + +/* Dummy circuit directive struct */ +struct ParseDirective { + ParseTree *parent; + vector<Variable> args; // list of non-keyword arguments found on netlist + map<string, Variable> kwargs; // list of kw arguments found on netlist + + ParseDirective() + {} + + ParseDirective(const ParseDirective& other) = default; + + virtual void print() const + { + cout << "DIRECTIVE[" << kind() << "] "; + cout << "{"; + for (const auto &x : args) + cout << x.get_str() << " (" << x.kind() << "), "; + if ( !args.empty() ) + cout << "\b\b"; + cout << "} "; + cout << "{"; + for (const auto &x : kwargs) + cout << x.first << " (" << x.second.kind() << ") = " << x.second.get_str() << ", "; + if ( !kwargs.empty() ) + cout << "\b\b"; + cout << "}" << endl; + } + virtual string to_json() const; + + virtual ParseDirective *clone() const = 0; + virtual void create() const = 0; + virtual string kind() const { return "UNDEFINED"; } + virtual ~ParseDirective() {} +}; + +/* Dummy circuit analysis struct */ +struct ParseAnalysis { + const ParseTree *parent; + vector<Variable> args; // list of non-keyword arguments found on netlist + map<string, Variable> kwargs; // list of kw arguments found on netlist + + ParseAnalysis() + {} + + ParseAnalysis(const ParseAnalysis& other) = default; + + void print() const + { + cout << "ANALYSIS[" << kind() << "] "; + cout << "{"; + for (const auto &x : args) + cout << x.get_str() << " (" << x.kind() << "), "; + if ( !args.empty() ) + cout << "\b\b"; + cout << "} "; + cout << "{"; + for (const auto &x : kwargs) + cout << x.first << " (" << x.second.kind() << ") = " << x.second.get_str() << ", "; + if ( !kwargs.empty() ) + cout << "\b\b"; + cout << "}" << endl; + } + virtual string to_json() const; + + virtual ParseAnalysis *clone() const = 0; + virtual void create() const = 0; + virtual string kind() const { return "UNDEFINED"; } + virtual ~ParseAnalysis() {} +}; + +/* SUBCKT: subcircuit definition */ +struct ParseSubcircuit { + string name; // name of the subcircuit + string netlist; // subcircuit netlist (extracted from parent netlist) + vector<string> ports; // name of ports + map<string, Variable> kwargs; // list of kw arguments found on netlist + const ParseTree *parent; + + ParseSubcircuit(const string &name, ParseTree *parent = nullptr) + : name(name) + , parent(parent) + {} + + ParseSubcircuit(const ParseSubcircuit& other) = default; + + void register_port(const string &port_name) + { + auto it = find(ports.cbegin(), ports.cend(), port_name); + if (it == ports.cend()) + { + ports.push_back(port_name); + } + else + { + cerr << "Subcircuit cannot have duplicate port names"; + cerr << "(" << port_name << " was already defined)" << endl; + exit(1); + } + } + //ParseTree *instantiate(const string &instance_name, const map<string,Variable> &kwargs) const; + void print() const + { + cout << name << " (" << kind() << ") "; + for (const auto &x : ports) + cout << x << " "; + cout << "{"; + for (const auto &x : kwargs) + cout << x.first << " (" << x.second.kind() << ") = " << x.second.get_str() << ", "; + if ( !kwargs.empty() ) + cout << "\b\b"; + cout << "}" << endl; + if (false) + { + cout << "###########################" << endl; + cout << "## Start netlist of " << name << endl; + cout << "###########################" << endl; + cout << netlist; + cout << "###########################" << endl; + cout << "## End netlist of " << name << endl; + cout << "###########################" << endl; + } + } + string to_json() const; + string kind() const + { return "SUBCIRCUIT DEFINITION"; } + ParseSubcircuit *clone() const + { return new ParseSubcircuit(*this); } +}; + +/* Dummy circuit net struct (although close to what it should look like) */ +struct ParseNet { + /* Possible net types */ + enum Type { + NONE, + OANALOG, + EANALOG, + EDIGITAL, + }; + + /* Member variables */ + Type m_type; + unsigned int m_size; // number of "wires (more than 1 for buses) + bool m_bidirectional = false; // whether the signal should be bidirectional (for oanalog and eanalog representing forward/backward waves) + unsigned int m_writers_count = 0; // number of writers + unsigned int m_readers_count = 0; // number of readers + unsigned int m_ports_count = 0; // number of individual ports connected (in total) + unsigned int m_connect_count = 0; // number of ports actually connected (updated during creation phase only) + unsigned int m_connect_writer_count = 0; // number of writer ports actually connected (updated during creation phase only) + unsigned int m_connect_reader_count = 0; // number of reader ports actually connected (updated during creation phase only) + + /* Constructor */ + ParseNet(Type type = NONE, unsigned int size = 1): m_type(type), m_size(size) {} + ParseNet(const ParseNet &n) = default; + inline ParseNet& operator=(const ParseNet &n) = default; + bool combine_with(const ParseNet &n) + { + if (m_type != n.m_type) + return false; + if (m_size != n.m_size) + return false; + if (m_connect_count || n.m_connect_count) + return false; + + m_bidirectional |= n.m_bidirectional; + m_writers_count += n.m_writers_count; + m_readers_count += n.m_readers_count; + m_ports_count += n.m_ports_count; + + return true; + } + + /* const Getters */ + unsigned int size() const { return m_size; } + Type type() const { return m_type; } + bool bidirectional() const + { + return m_bidirectional || (m_writers_count == 2); + //return m_bidirectional || (m_writers_count == 2) || (m_readers_count == 2); + } + bool validate() const + { + return m_writers_count <= 2 && m_ports_count <= 2; + } + + /* setters */ + inline bool setType(Type type, bool force = false) { + //cout << type_str() << " - " << ParseNet(type).type_str() << endl; + if (m_type == type) + // no need to do anything + return true; + if (m_type == NONE || force) + { + m_type = type; + return true; + } + // cerr << "Incompatible net type assignment" << endl; + return false; + } + + string type_str() const + { + switch (m_type) { + case Type::NONE: + return "NONE"; + case Type::OANALOG: + return "OANALOG"; + case Type::EANALOG: + return "EANALOG"; + case Type::EDIGITAL: + return "EDIGITAL"; + default: + cerr << "Unexpected type" << endl; + exit(1); + } + } + + string to_json() const; + + // create the net + vector<shared_ptr<sc_object>> create(const string &name, bool force_bidir = false) const; + shared_ptr<sc_object> create_uni(const string &name) const; + + /* Get a generic net name from net number (different from id) */ + static string name_from_id(int net_number); +}; + +struct ParseTreeCreationHelper; + +/* Dummy circuit element struct (although close to )*/ +struct ParseElement { + typedef sc_module element_type_base; + + string name; + const ParseTree *parent; + vector<string> nets; // name of parent nets connected to element + vector<Variable> args; // list of non-keyword arguments found on netlist + map<string, Variable> kwargs; // list of kw arguments found on netlist + + const int n_nets = 0; + const bool bidirectionalable = false; + + ParseElement(const string &name) + : name(name) + {} + + ParseElement(const string &name, const vector<string> &nets) + : name(name) + , nets(nets) + {} + + ParseElement(const ParseElement& other) = default; + + void print() const + { + cout << name << " (" << kind() << ") "; + for (const auto &x : nets) + cout << x << " "; + cout << "{"; + for (const auto &x : args) + cout << x.get_str() << " (" << x.kind() << "), "; + if ( !args.empty() ) + cout << "\b\b"; + cout << "} "; + cout << "{"; + for (const auto &x : kwargs) + cout << x.first << " (" << x.second.kind() << ") = " << x.second.get_str() << ", "; + if ( !kwargs.empty() ) + cout << "\b\b"; + cout << "}" << endl; + } + + virtual ParseElement *clone() const = 0; + virtual sc_module *create(ParseTreeCreationHelper &pt_helper) const = 0; + virtual element_type_base *instantiate_and_connect_uni(ParseTreeCreationHelper &pt_helper) const = 0; + virtual element_type_base *instantiate_and_connect_bi(ParseTreeCreationHelper &pt_helper) const + { + (void) pt_helper; + cerr << "Elements of type " << kind() << " cannot be bidirectional" << endl; + exit(1); + } + + virtual string kind() const { return "UNDEFINED"; } + virtual ~ParseElement() {} + + virtual string to_json() const; +}; + +struct ParseTree { + string name; + const ParseTree *parent = nullptr; + bool is_subcircuit = false; + size_t unnamed_net_count = 0; + + map<string, ParseNet> nets; + vector<string> ports; // only for subcircuits + vector<ParseElement *> elements; + vector<ParseAnalysis *> analyses; + vector<ParseDirective *> directives; + vector<ParseSubcircuit *> subcircuits; + map<string, Variable> local_assignments; + static map<string, Variable> global_assignments; + + ParseTree(const string &name = "ROOT") + : name(name) + {} + + ParseTree(const string &name, const ParseSubcircuit &subcircuit, const map<string, Variable> &kwargs); + + int register_directive(ParseDirective *directive); + int register_element(ParseElement *element); + int register_analysis(ParseAnalysis *analysis); + int register_subcircuit(string name); + const ParseSubcircuit *find_subcircuit(const string &name) const; + + string get_or_create_net(string net_name, unsigned int size = 1, + ParseNet::Type type = ParseNet::NONE) + { + if (net_name == "_") + { + net_name = "_" + to_string(unnamed_net_count++); + } + + string full_net_name = name_prefix() + net_name; + if (nets.count(full_net_name) == 0) + { + nets.emplace(full_net_name, ParseNet(type, size)); + return full_net_name; + } + if (nets[full_net_name].size() != size) + { + cerr << "Incompatible size: " << net_name << "<" << size << ">" + << " (previously declared size was: " << nets[full_net_name].size() + << ")" << endl; + exit(1); + } + if (nets[full_net_name].type() == ParseNet::NONE && type != ParseNet::NONE) + nets[full_net_name].m_type = type; + if (type == ParseNet::NONE && nets[full_net_name].type() != ParseNet::NONE) + type = nets[full_net_name].m_type; + if (nets[full_net_name].type() != type) + { + cerr << "Incompatible type: " << net_name << "[" << ParseNet(type).type_str() << "]" + << " (previously declared type was: " << nets[full_net_name].type_str() + << ")" << endl; + exit(1); + } + return full_net_name; + } + + string get_or_create_net(int i, unsigned int size = 1, + ParseNet::Type type = ParseNet::NONE) + { + return get_or_create_net(ParseNet::name_from_id(i), size, type); + } + string get_or_create_net(Variable v, unsigned int size = 1, + ParseNet::Type type = ParseNet::NONE) + { + if (v.type == Variable::STRING) + return get_or_create_net(v.as_string(), size, type); + else if (v.type == Variable::INTEGER) + return get_or_create_net(v.as_integer(), size, type); + else + { + cerr << "Incompatible variable type for creating a net" << endl; + exit(1); + } + } + + string name_prefix() const + { + string ret = ""; + if ( !is_subcircuit && parent ) + { + ret = parent->name_prefix(); + if ( name.empty() ) + { + cerr << "Name of child parse tree should not be empty" << endl; + exit(1); + } + } + ret += name + "/"; + strutils::toupper(ret); + return ret; + } + + template <typename T> + void set_local_variable(string &name, T val) + { + // will throw a compile error if type T is not supported by Variable + local_assignments[name] = val; + } + + template <typename T> + void set_global_variable(string &name, T val) + { + // will throw a compile error if type T is not supported by Variable + global_assignments[name] = val; + } + + Variable get_variable(string &name) + { + // try to find variable in locals table first + auto it = local_assignments.find(name); + if (it != local_assignments.end()) + return it->second; + + // try to find variable in globals table + it = global_assignments.find(name); + if (it != global_assignments.end()) + return it->second; + + // error + cerr << "Variable not found: " << name << endl; + exit(1); + } + + void print() const; + string to_json() const; + + ParseTree *clone() const + { + ParseTree *clone = new ParseTree(name); + + clone->parent = nullptr; + clone->ports = ports; + clone->nets = nets; + clone->local_assignments = local_assignments; + clone->unnamed_net_count = unnamed_net_count; + + for (const auto &x : elements) + clone->elements.push_back(x->clone()); + for (const auto &x : analyses) + clone->analyses.push_back(x->clone()); + for (const auto &x : directives) + clone->directives.push_back(x->clone()); + for (const auto &x : subcircuits) + clone->subcircuits.push_back(x->clone()); + + return clone; + } + void build_circuit(); + void flatten(); + + ~ParseTree() + { + if (!parent) + { + for (const auto &x : elements) + if(x) delete x; + for (const auto &x : analyses) + if(x) delete x; + for (const auto &x : directives) + if(x) delete x; + for (const auto &x : subcircuits) + if(x) delete x; + } + } +}; + +struct ParseTreeCreationHelper { + ParseTree *pt; + + // backlog: elements to be created in priority + map<string, ParseNet> *nets; + + // backlog: elements to be created in priority + set<const ParseElement *> elements_backlog; + + // Circuit elements generated by build + map<string, vector<shared_ptr<sc_object>>> circuit_signals; + map<string, shared_ptr<sc_module>> circuit_modules; + + ParseTreeCreationHelper() + : pt(nullptr) + {} + + ParseTreeCreationHelper(ParseTree *parse_tree) + { + resetParseTree(parse_tree); + } + + void resetParseTree(ParseTree *parse_tree) + { + pt = parse_tree; + nets = &parse_tree->nets; + elements_backlog.clear(); + circuit_signals.clear(); + circuit_modules.clear(); + } + + // return next bidir net which doesn't have a corresponding signal in circuit_signals + map<string, ParseNet>::iterator next_fresh_bidir_net(); + + // return next net which doesn't have a corresponding signal in circuit_signals + map<string, ParseNet>::iterator next_fresh_net(); + + // return next element which is connected to "net_name" and doesnt have a corresponding module in circuit_modules + vector<ParseElement *>::iterator next_fresh_element_bound_to(const string &net_name, const set<const ParseElement *> &excludes = {}); + + // upgrade a signal to bidirectional + void upgrade_signal(const string &name); + + // Create signals connected to a given element + void create_signals(const ParseElement *elem); + + // Connect a port to a signal using the net name + template <typename signal_type, typename port_type> + void connect_uni(port_type &port, const string& net_name, bool as_writer); + + // Connect a bidirectional port to a signal pair using the net name + template <typename signal_type, typename port_in_type, typename port_out_type> + void connect_bi(port_in_type &p_in, port_out_type &p_out, const string& net_name); + + ~ParseTreeCreationHelper() + {} +}; + +/** ******************************************* **/ +/** Non-specialized template implementations **/ +/** ******************************************* **/ + +template <typename signal_type, typename port_type> +void ParseTreeCreationHelper::connect_uni(port_type &port, const string& net_name, bool as_writer) +{ + assert(pt->nets.find(net_name) != pt->nets.end()); + const auto &net = pt->nets.at(net_name); + + // Get the signal to be written or read + signal_type *sig = nullptr; + if ( !net.bidirectional()) + { + auto sig_raw = circuit_signals.at(net_name)[0].get(); + sig = dynamic_cast<signal_type *>(sig_raw); + } + else + { + int i_write = pt->nets.at(net_name).m_connect_count; + int i_read = (i_write + 1) % 2; + int i = as_writer ? i_write : i_read; + + auto sig_raw = circuit_signals.at(net_name)[i].get(); + sig = dynamic_cast<signal_type *>(sig_raw); + } + + // Check it could correctly be cast to requested type + if (!sig) + { + cerr << "Wrong signal type for " << sig << " connected to " + << net_name << endl; + exit(1); + } + + // Connect the port to the signal + port.bind(*sig); + + // Update connection count of the net + pt->nets[net_name].m_connect_count++; + if (as_writer) + pt->nets[net_name].m_connect_writer_count++; + else + pt->nets[net_name].m_connect_reader_count++; +} + +template <typename signal_type, typename port_in_type, typename port_out_type> +void ParseTreeCreationHelper::connect_bi(port_in_type &p_in, port_out_type &p_out, const string& net_name) +{ + assert(pt->nets.find(net_name) != pt->nets.end()); + const auto &net = pt->nets.at(net_name); + + if (net.bidirectional()) + { + + // First get the signal to be written or read (in the right order) + int i_write = pt->nets.at(net_name).m_connect_count; + int i_read = (i_write + 1) % 2; + + auto sig_writeable_raw = circuit_signals.at(net_name)[i_write].get(); + auto sig_readable_raw = circuit_signals.at(net_name)[i_read].get(); + auto sig_writeable = dynamic_cast<signal_type *>(sig_writeable_raw); + auto sig_readable = dynamic_cast<signal_type *>(sig_readable_raw); + + // Check they could correctly be cast to requested type + if (!sig_writeable) + { + cerr << "Wrong signal type for " << sig_writeable << " connected to " + << net_name << endl; + exit(1); + } + if (!sig_readable) + { + cerr << "Wrong signal type for " << sig_readable << " connected to " + << net_name << endl; + exit(1); + } + + // Connect ports to both signals + p_out.bind(*sig_writeable); + p_in.bind(*sig_readable); + + // Update connection count of the net + pt->nets[net_name].m_connect_count++; + pt->nets[net_name].m_connect_writer_count++; + pt->nets[net_name].m_connect_reader_count++; + } + else + { + cerr << "Expected a bidirectional net for " << net_name << endl; + exit(1); + } +}
\ No newline at end of file diff --git a/src/parser/parser.l b/src/parser/parser.l new file mode 100644 index 0000000..ca689a3 --- /dev/null +++ b/src/parser/parser.l @@ -0,0 +1,438 @@ +ALPHA [[:alpha:]] +DIGIT [0-9] +ALPHA_NUM {ALPHA}|{DIGIT} +ALPHA_PLUS {ALPHA}|[_] +ALPHA_PLUS_NUM {ALPHA}|[_]|{DIGIT} +D {DIGIT} + +DOUBLE (({D}+)|({D}*\.{D}+))([eE][-+]?[0-9]+)? + +BIDIR_SPECIFIER [&] +BIN_OPERATOR [,=\*/\+\-\^] +PAR_OPERATOR [\{\}\(\)\[\]<>] +OPERATOR {BIN_OPERATOR}|{PAR_OPERATOR}|{BIDIR_SPECIFIER} + + +WS [ \t] +WS_BREAK (?:[^{WS}]) + +/* EOL_DOS \r\n */ +/* EOL_UNIX \n */ +/* EOL_OLD_MAC \n */ +EOL_PORTABLE \r?\n +EOL {EOL_PORTABLE} + +%option warn +%option yylineno +%option noyywrap +%option caseless +%option reentrant +%option bison-bridge +%option stack + +%{ +#include <string> +#include <sstream> // for conversions of numbers from str +#include <cstring> // for strcpy +#include <vector> +#include "parse_tree.h" + +#include "parser.tab.h" + +using std::string; +using std::vector; + +#define YY_NO_INPUT +#define YY_NO_UNPUT +#define YY_EXTRA_TYPE void* + +YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size, yyscan_t scanner); +void yypush_buffer_state ( YY_BUFFER_STATE buffer, yyscan_t scanner); +void yypop_buffer_state ( yyscan_t scanner ); +int yyget_lineno ( yyscan_t scanner ); +int yyget_column ( yyscan_t scanner ); +void yyset_extra ( YY_EXTRA_TYPE user_defined, yyscan_t scanner ); +YY_EXTRA_TYPE yyget_extra ( yyscan_t scanner ); + +int yylerror(yyscan_t scanner, const char *p) +{ + cerr << "error (line " << yyget_lineno(scanner) << "): " << p << endl; + string * str = (string *)yyget_extra(scanner); + if (str) + cerr << "\twhile parsing line: " << *str << endl; + return 3; +} + +ParseTree *cur_pt = nullptr; + +static int internal_subckt_count = 0; +static size_t delete_me_npos = 0; + +template<typename T> +static T from_string(const string &str) +{ + std::stringstream ss(str); + T ret; + ss >> ret; + return ret; +} + +%} + +/*** States ***/ +/* %x IN_DQUOTES */ +%x INCLUDE +%s SUBCKT_DECLARATION +%x SUBCKT_DEFINITION +/*Quoted string (returns char[]) (capture until next '"' and throw error on newline)*/ +%x IN_DQUOTES + + + +/* To ignore case: (?i:xxx) */ + +%% /*** Rules section ***/ + +^\.include {yy_push_state(INCLUDE, yyscanner);} +<INCLUDE>{WS}* /* eat the whitespace */ +<INCLUDE>[^ ;\t\n\r]+ { /* got the include file name */ + yyin = fopen( yytext, "r" ); + + if ( ! yyin ) + { + cerr << "Error: included file not found \"" << yytext << "\"" << endl; + exit(1); + } + cout << "Including file: " << yytext << endl; + yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE, yyscanner), yyscanner); + + //yy_push_state(INITIAL, yyscanner); + BEGIN(INITIAL); + } + +<IN_DQUOTES>\" { + yy_pop_state(yyscanner); + // cout << "leaving dquotes mode" << endl; + return '"'; + } +<IN_DQUOTES>{EOL} { exit(yylerror(yyscanner, "Unmatched double quote")); } +<IN_DQUOTES>[^\"\r\n]* { + // cout << "found quoted string: " << yytext << endl; + yylval_param->s_ptr = new string(yytext); + return T_STR; + } + +<SUBCKT_DECLARATION>{EOL} { + // end of subcircuit declaration line (.subckt name node1 node2...) + // go into subckt_definition state, which copies all text to a string + // until the corresponding .ends is reached + yylval_param->s_ptr = new string; + internal_subckt_count = 0; + delete_me_npos = 0; + // cout << endl << "going to subckt definition mode" << endl; + BEGIN(SUBCKT_DEFINITION); //needs BEGIN and not yy_push_state +} + +<SUBCKT_DEFINITION>^\.SUBCKT { + // cout << "hello2" << endl; + // increase internal count for keeping track of included subcircuits + internal_subckt_count++; + // but reject the rule and go to the next matching pattern + // (i.e. save the line to the string) + REJECT; +} + +<SUBCKT_DEFINITION>^\.ENDS { + if (internal_subckt_count) + { + // found .ends of included subcircuit + // decrease internal count + --internal_subckt_count; + // but reject the rule and go to the next matching pattern + // (i.e. save the line to the string) + REJECT; + } + else + { + // found .ends of current subcircuit + // go back to normal parsing + //BEGIN(INITIAL); + yy_pop_state(yyscanner); + // return .ends token so that the subcircuit string is recorded + return T_DIRECTIVE_ENDS; + } +} + +<SUBCKT_DEFINITION>. { + /* save characters to buffer as-is */ + *yylval_param->s_ptr += yytext; +} + +<SUBCKT_DEFINITION>{EOL} { + /* save characters to buffer */ + *yylval_param->s_ptr += yytext; + + // cout << "found subckt line: " << yylval_param->s_ptr->substr(delete_me_npos); + // delete_me_npos = yylval_param->s_ptr->size(); +} + +<SUBCKT_DEFINITION><<EOF>> { + cerr << "Reached end of file before end of subcircuit definition" << endl; + exit(1); +} + +\" { + yy_push_state(IN_DQUOTES, yyscanner); + // cout << "entering dquotes mode" << endl; + return '"'; + } + +[+-]?{D}+ { + /* signed integer number */ + yylval_param->i_val = from_string<int>(yytext); + return T_INT; +} + +[+-]?{DOUBLE} { + /* signed floating point number */ + yylval_param->d_val = from_string<double>(yytext); + return T_NUM; +} + +(;[^\n]*) { + /* inline comment starts with ; */ + continue; +} + +^(\*[^\n]*) { + /* full line comment starts with **/ + continue; +} + +^X({ALPHA_PLUS_NUM})+ { + /* subcircuit instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_X; +} + +^WG({ALPHA_PLUS_NUM})+ { + /* waveguide instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_WG; +} + +^MERGER({ALPHA_PLUS_NUM})+ { + /* merger instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_MERGER; +} + +^SPLITTER({ALPHA_PLUS_NUM})+ { + /* merger instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_SPLITTER; +} + +^COUPLER({ALPHA_PLUS_NUM})+ { + /* DC instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_COUPLER; +} + +^PSHIFT({ALPHA_PLUS_NUM})+ { + /* PHASESHIFTER instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_PSHIFT; +} + +^MZI({ALPHA_PLUS_NUM})+ { + /* MZI instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_MZI; +} + +^CROSSING({ALPHA_PLUS_NUM})+ { + /* CROSSING instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_CROSSING; +} + +^CWSRC({ALPHA_PLUS_NUM})+ { + /* Continuous-wave source instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_CWSRC; +} + +^VLSRC({ALPHA_PLUS_NUM})+ { + /* Value-list source instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_VLSRC; +} + +^EVLSRC({ALPHA_PLUS_NUM})+ { + /* Electric Value-list source instance name */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_EVLSRC; +} + +^PROBE({ALPHA_PLUS_NUM})+ { + /* Probe instance */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_PROBE; +} + +^MLPROBE({ALPHA_PLUS_NUM})+ { + /* Probe instance */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_MLPROBE; +} + +^PDET({ALPHA_PLUS_NUM})+ { + /* Probe instance */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_PDET; +} + +^PCMCELL({ALPHA_PLUS_NUM})+ { + /* Probe instance */ + yylval_param->s_ptr = new string(yytext); + return T_ELEM_PCMCELL; +} + +^\.ASSIGN { return T_LOCAL_ASSIGNMENT; } +^\.PARAM { return T_LOCAL_ASSIGNMENT; } +^\.SAVE { return T_DIRECTIVE_SAVE; } + +^\.OP { return T_ANALYSIS_OP; } +^\.DC { return T_ANALYSIS_DC; } +^\.TRAN { return T_ANALYSIS_TRAN; } + +^\.OPTIONS { return T_DIRECTIVE_OPTIONS; } +^\.NODESET { return T_DIRECTIVE_NODESET; } +^\.IC { exit(1); } +^\.SUBCKT { + /* Subcircuit declaration */ + // enter new parser state + yy_push_state(SUBCKT_DECLARATION, yyscanner); + // return token so bison can correctly parse the declaration + return T_DIRECTIVE_SUBCKT; +} + +<INITIAL>^\.ENDS { + cerr << "Unexpeced '.ENDS' directive" << endl; + exit(1); +} + +{ALPHA_PLUS}{ALPHA_PLUS_NUM}*/{WS}*= { + yylval_param->s_ptr = new string(yytext); + + return T_ASSIGN_ID; +} + +{ALPHA_PLUS}{ALPHA_PLUS_NUM}* { + yylval_param->s_ptr = new string(yytext); + + /* + if (yylval_param->s_ptr == "null") + return T_NONE; + if (yylval_param->s_ptr == "true") + { + yylval_param->b_val = true; + return T_BOOL; + } + if (yylval_param->s_ptr == "false") + { + yylval_param->b_val = false; + return T_BOOL; + } + */ + return T_STR; +} + +{OPERATOR} { + yylval_param->c_val = yytext[0]; + return yytext[0]; +} + +{WS} ; + +^.*/{EOL} { + string * str = (string *)yyget_extra(yyscanner); + if (!str) + str = new string; + *str = yytext; + yyset_extra((void *)str, yyscanner); + REJECT; +} + +(?# the following lines are for compatibility with KiCad generated netlists) +(?# they were added fast with relatively no checking for potential problems if) +(?# the keywords are found in subcircuit files or included files) +^\.TITLE({WS}.*)?/{EOL} { + // cout << "Found '.title' directive, ignoring." << endl; +} +^\.END { + // cout << "Found '.end' directive, ignoring." << endl; +} + +(?# Ignore EOL followed by '+' -- line continuation) +{EOL}\+ ; + +{EOL} { return '\n'; } + +<INITIAL,INCLUDE><<EOF>> { + yypop_buffer_state(yyscanner); + + if ( !YY_CURRENT_BUFFER ) + { + yyterminate(); + } + return '\n'; + } + +<SUBCKT_DECLARATION,IN_DQUOTES><<EOF>> { + exit(yylerror(yyscanner, "Unexpected end of file.")); +} + +<*>. { + stringstream msg; + msg << "Unexpected character: \""; + switch (yytext[0]) + { + case '\r': + msg << "\\r"; + break; + case '\n': + msg << "\\n"; + break; + case '\t': + msg << "\\t"; + break; + case '\b': + msg << "\\b"; + break; + default: + msg << yytext[0]; + break; + } + msg << "\""; + exit(yylerror(yyscanner, msg.str().c_str())); + } +%% + +/* END */ + +/* ^.OP(?:{WS}+) { return T_DIRECTIVE_OP; } */ +/* ^.DC(?:{WS}+) { return T_DIRECTIVE_DC; } */ + +/* Quoted string with 2 strings on the same line (returns char []) +\"[^\"\\]*\" { + int n = strlen(yytext) - 2; + yylval_param->sv = new char[n+1]; + strncpy(yylval_param->sv, yytext + 1, n); + yylval_param->sv[n] = '\0'; + return T_QUOTED_STR; +} +*/ + + diff --git a/src/parser/parser.y b/src/parser/parser.y new file mode 100644 index 0000000..36be00f --- /dev/null +++ b/src/parser/parser.y @@ -0,0 +1,961 @@ +%define api.pure full +%param { yyscan_t scanner } + + +%code requires{ + typedef void * yyscan_t; + // char *yyget_text ( yyscan_t yyscanner ); + // int yyget_lineno ( yyscan_t yyscanner ); + // int yylex(YYSTYPE * yylval, yyscan_t scanner); + + //extern int yylineno; + //extern char *yytext; +} + +%{ +#include <iostream> +#include <string> +#include <vector> +#include <cstring> +#include <cmath> +#include <memory> +#include "parse_tree.h" +#include "parse_element.h" +#include "parse_analysis.h" +#include "parse_directive.h" + +#include "../build/parser/parser.tab.h" +#include "../build/parser/parser.yy.h" + +using std::string; +using std::vector; +using std::pow; + +extern ParseTree *cur_pt; + +/*int yyerror(yyscan_t scanner, ParseTree *pt, const char *err) +{ + (void)pt; + (void)p; + printf("Error in the netlist (line %u:\"%s\")\n", yylineno, yytext); + printf("-- Error at line %u:\n\t%s\n", yylineno, err); + return 0; +} +*/ +int yyerror(yyscan_t scanner, ParseTree *pt, const char *err); +%} + +%union { + double d_val; + int i_val; + char c_val; + string *s_ptr; + char *c_ptr; + vector<double> *vec_d_ptr; + pair<string, Variable> *assig_ptr; + Variable *variable_ptr; + vector<Variable> *vec_var_ptr; + pair<string, string> *elemattr_ptr; + pair<string, pair<string, Variable>> *netval_assign_ptr; + pair<pair<string, string>, vector<double>> *cw_sweep_order_ptr; +} + +// %define api.value.type {struct YYSTYPE} + +%token <d_val> T_NUM +%token <i_val> T_INT +%token <i_val> T_NONE +%token <s_ptr> T_STR +%token <s_ptr> T_ASSIGN_ID +%token <s_ptr> T_ELEM_CWSRC T_ELEM_VLSRC T_ELEM_EVLSRC +%token <s_ptr> T_ELEM_WG T_ELEM_COUPLER T_ELEM_MERGER T_ELEM_SPLITTER +%token <s_ptr> T_ELEM_PSHIFT T_ELEM_MZI T_ELEM_CROSSING T_ELEM_PCMCELL +%token <s_ptr> T_ELEM_PROBE T_ELEM_MLPROBE T_ELEM_PDET +%token <s_ptr> T_ELEM_X +%token <i_val> T_ANALYSIS_OP T_ANALYSIS_DC T_ANALYSIS_TRAN +%token <i_val> T_DIRECTIVE_OPTIONS T_DIRECTIVE_NODESET +%token <i_val> T_DIRECTIVE_SUBCKT +%token <s_ptr> T_DIRECTIVE_ENDS +%token <s_ptr> T_DIRECTIVE_SAVE +%token <i_val> T_LOCAL_ASSIGNMENT +%type <c_val> '=' + + +// Available circuit elements +%type <i_val> element.wg +%type <i_val> element.merger +%type <i_val> element.splitter +%type <i_val> element.coupler +%type <i_val> element.pshift +%type <i_val> element.mzi +%type <i_val> element.crossing +%type <i_val> element.pcm_cell +%type <i_val> element.cwsrc +%type <i_val> element.vlsrc +%type <i_val> element.evlsrc +%type <i_val> element.probe +%type <i_val> element.mlprobe +%type <i_val> element.pdet +%type <i_val> element.x + +// Available analysis +%type <i_val> analysis.op +%type <i_val> analysis.dc +%type <i_val> analysis.tran +%type <cw_sweep_order_ptr> cw_sweep_order + +// Available directives +%type <i_val> directive.options +%type <i_val> directive.nodeset + +// Rules for circuit nets (value is index in PT elements) +%type <s_ptr> net_name.base.str +%type <s_ptr> net_name_base +%type <s_ptr> net_name +%type <s_ptr> net.oanalog net.eanalog net.edigital +%type <s_ptr> net.oa.explicit_bidir +%type <s_ptr> net.oa.bidir +%type <s_ptr> net.oa.in +%type <s_ptr> net.oa.out + +//%type <s_ptr> bus_name bus bus.oanalog bus.eanalog bus.edigital + +// Rules related to subcircuits +%type <i_val> subcircuit +%type <i_val> subcircuit.with_ports +%type <i_val> subcircuit.with_assignments +%type <s_ptr> port_name + +// Rules for circuit elements (value is index in PT elements arrays) +%type <i_val> atomelement element +%type <i_val> element.with_args element.with_kwargs +%type <i_val> element.x.with_args element.x.with_kwargs + +// Rules for circuit analysis (value is ptr to ParseAnalysis) +%type <i_val> atomanalysis analysis +%type <i_val> analysis.with_args analysis.with_kwargs + +// Rules for simulator directives (value is ptr to ParseDirective) +%type <i_val> atomdirective directive +%type <i_val> directive.with_args directive.with_kwargs + +// For argument parsing +%type <assig_ptr> assignment +%type <variable_ptr> variable variable_base variable_or_empty +%type <variable_ptr> variable.free_expr variable.delimited_expr +//%type <variable_ptr> variable.str_without_quotes +%type <netval_assign_ptr> netval_assignment +%type <elemattr_ptr> element_attribute + +// For expression parsing +%type <variable_ptr> expr term fact pow constant +%type <variable_ptr> listvar.tail listvar.unbound listvar.bound //TODO: check + +// Add parse tree parameter to yyparse signature +%parse-param {ParseTree *pt} +//%verbose +//%define parse.error detailed +//%define parse.trace + +// On start, set current parse tree to the one passed in call to yyparse +%initial-action { + cur_pt = pt; + if (!pt) + yyerror(scanner, pt, "Invalid parse tree pointer"); +} + + +%% + +input: %empty + | input line '\n' +; + +line: %empty + | element { /* cout << "Inserted element: " << cur_pt->elements[$1]->name << endl; */ } + | analysis { /* cout << "Registered analysis [...]" << endl; */ } + | directive { /* cout << "Registered directive [...]" << endl; */ } + | subcircuit { /* cout << "Parsed subcircuit [...]" << endl; */ } + | local_assignment { /* cout << "Processed local assignment [...]" << endl; */ } +; + +local_assignment: T_LOCAL_ASSIGNMENT assignment + { + cur_pt->set_local_variable($2->first, $2->second); + } + | local_assignment assignment + { + cur_pt->set_local_variable($2->first, $2->second); + } +; + +/* --------- Directives definitions parsing ----------- */ + +directive.options: T_DIRECTIVE_OPTIONS { $$ = cur_pt->register_directive(new OPTIONSDirective); } +; + +directive.nodeset: T_DIRECTIVE_NODESET { $$ = cur_pt->register_directive(new NODESETDirective); } + | directive.nodeset netval_assignment + { + static_cast<NODESETDirective *>(cur_pt->directives[$1])->net_assignments[$2->first].push_back($2->second); + $$ = $1; + } +; +subcircuit.with_ports: T_DIRECTIVE_SUBCKT T_STR + { + // Register a new subcircuit in current parse tree + $$ = cur_pt->register_subcircuit(*$2); + delete $2; + } + | subcircuit.with_ports port_name + { + if (!cur_pt->subcircuits[$1]->kwargs.empty()) + { + cerr << "Expected keyword assignment in subcircuit declaration but got: " << *$2 << endl; + exit(1); + } + // cout << *$2 << endl; + cur_pt->subcircuits[$1]->register_port(*$2); + $$ = $1; + delete $2; + } +; +subcircuit.with_assignments: + subcircuit.with_assignments assignment + { + cur_pt->subcircuits[$1]->kwargs[$2->first] = $2->second; + + $$ = $1; + delete $2; + } +| subcircuit.with_ports +; + +subcircuit: subcircuit.with_assignments T_DIRECTIVE_ENDS + { + // cout << "Parsed subcircuit " << cur_pt->subcircuits[$1]->name << endl; + cur_pt->subcircuits[$1]->netlist = *$2; + delete $2; + } +; + +/* --------- Elements definitions parsing ----------- */ + +element.wg: T_ELEM_WG net.oa.in net.oa.out + { + $$ = cur_pt->register_element(new WGElement(*$1, {*$2, *$3})); + delete $1; + delete $2; + delete $3; + } +; + +element.merger: T_ELEM_MERGER net.oa.in net.oa.in net.oa.out + { + $$ = cur_pt->register_element(new MergerElement(*$1, {*$2, *$3, *$4})); + delete $1; + delete $2; + delete $3; + delete $4; + } +; + +element.splitter: T_ELEM_SPLITTER net.oa.in net.oa.out net.oa.out + { + $$ = cur_pt->register_element(new SplitterElement(*$1, {*$2, *$3, *$4})); + delete $1; + delete $2; + delete $3; + delete $4; + } +; + +element.coupler: T_ELEM_COUPLER net.oa.in net.oa.in net.oa.out net.oa.out + { + $$ = cur_pt->register_element(new DCElement(*$1, {*$2, *$3, *$4, *$5})); + delete $1; + delete $2; + delete $3; + delete $4; + delete $5; + } +; + +element.pshift: T_ELEM_PSHIFT net.oa.in net.oa.out net.eanalog + { + $$ = cur_pt->register_element(new PhaseShifterElement(*$1, {*$2, *$3, *$4})); + delete $1; + delete $2; + delete $3; + delete $4; + } +; + +element.mzi: T_ELEM_MZI net.oa.in net.oa.in net.oa.out net.oa.out net.eanalog + { + $$ = cur_pt->register_element(new MZIElement(*$1, {*$2, *$3, *$4, *$5, *$6})); + delete $1; + delete $2; + delete $3; + delete $4; + delete $5; + delete $6; + } +; + +element.crossing: T_ELEM_CROSSING net.oa.in net.oa.in net.oa.out net.oa.out + { + $$ = cur_pt->register_element(new CrossingElement(*$1, {*$2, *$3, *$4, *$5})); + delete $1; + delete $2; + delete $3; + delete $4; + delete $5; + } +; + +element.pcm_cell: T_ELEM_PCMCELL net.oa.in net.oa.out + { + $$ = cur_pt->register_element(new PCMCellElement(*$1, {*$2, *$3})); + delete $1; + delete $2; + delete $3; + } +; + +element.cwsrc: T_ELEM_CWSRC net.oa.out + { + $$ = cur_pt->register_element(new CWSourceElement(*$1, {*$2})); + delete $1; + delete $2; + } +; + +element.vlsrc: T_ELEM_VLSRC net.oa.out + { + $$ = cur_pt->register_element(new VLSourceElement(*$1, {*$2})); + delete $1; + delete $2; + } +; + +element.evlsrc: T_ELEM_EVLSRC net.eanalog + { + $$ = cur_pt->register_element(new EVLSourceElement(*$1, {*$2})); + delete $1; + delete $2; + } +; + +element.probe: T_ELEM_PROBE net.oa.in + { + $$ = cur_pt->register_element(new ProbeElement(*$1, {*$2})); + delete $1; + delete $2; + } +; + +element.mlprobe: T_ELEM_MLPROBE net.oa.in + { + $$ = cur_pt->register_element(new MLProbeElement(*$1, {*$2})); + delete $1; + delete $2; + } +; + +element.pdet: T_ELEM_PDET net.oa.in net.eanalog + { + $$ = cur_pt->register_element(new PhotodetectorElement(*$1, {*$2, *$3})); + delete $1; + delete $2; + delete $3; + } +; + +element.x: T_ELEM_X + { + $$ = cur_pt->register_element(new XElement(*$1)); + delete $1; + } +; + +/* --------- Analyses definitions parsing ----------- */ + +analysis.op: T_ANALYSIS_OP + { $$ = cur_pt->register_analysis(new OPAnalysis()); } +; + +analysis.dc: T_ANALYSIS_DC + { $$ = cur_pt->register_analysis(new DCAnalysis()); } + | analysis.dc cw_sweep_order + { + auto ana = dynamic_cast<DCAnalysis *>(cur_pt->analyses[$1]); + if (ana->sweep_orders.size()) + { + cerr << "Registering more than one DC sweep is not supported yet." << endl; + exit(1); + } + ana->register_sweep_order(*$2); + delete $2; + } +; + +analysis.tran: T_ANALYSIS_TRAN + { $$ = cur_pt->register_analysis(new TRANAnalysis()); } +; + + +/* ---------- Directives arguments parsing ----------- */ + +atomdirective: directive.options { $$ = $1; } + | directive.nodeset { $$ = $1; } +; + +directive.with_args: + directive.with_args variable + { + // cout << "found positional arg: " << $2->get_str() << endl; + if (!cur_pt->directives[$1]->kwargs.empty()) + yyerror(scanner, pt, "positional arguments cannot follow keyword arguments"); + cur_pt->directives[$1]->args.emplace_back(*$2); + $$ = $1; + delete $2; + } +| atomdirective { $$ = $1; } +; + +directive.with_kwargs: + directive.with_kwargs assignment + { + // cout << "found keyword arg: " << $2->second.get_str() << endl; + cur_pt->directives[$1]->kwargs[$2->first] = $2->second; + $$ = $1; + delete $2; + } +| directive.with_args +; + +directive: directive.with_kwargs +; + +/* --------- Elements arguments parsing ----------- */ + +atomelement: element.wg { $$ = $1; } + | element.merger { $$ = $1; } + | element.splitter { $$ = $1; } + | element.coupler { $$ = $1; } + | element.pshift { $$ = $1; } + | element.mzi { $$ = $1; } + | element.crossing { $$ = $1; } + | element.pcm_cell { $$ = $1; } + | element.cwsrc { $$ = $1; } + | element.vlsrc { $$ = $1; } + | element.evlsrc { $$ = $1; } + | element.probe { $$ = $1; } + | element.mlprobe { $$ = $1; } + | element.pdet { $$ = $1; } +; + +element.with_args: + element.with_args variable + { + // cout << "found positional arg: " << $2->get_str() << endl; + if (!cur_pt->elements[$1]->kwargs.empty()) + yyerror(scanner, pt, "positional arguments cannot follow keyword arguments"); + cur_pt->elements[$1]->args.emplace_back(*$2); + $$ = $1; + + // TODO: for X element only, nets are stored as args + // Xnnnn n1 n2 n3 ... sub_name **sub_kwargs + // because the number of nets is not known when reading n1 n2 n3... + // [n1 n2 n3 ... subname] are also args + // when the time an arg is found, the previous one (if it exists), can be considered a net + // and therefore added to the element's nets array and discarded from args + // this will ensure that args will contain only [sub_name] + // for this to work, the X element cannot have args beyond sub_name (only kwargs) + if (cur_pt->elements[$1]->args.size() == 2) + { + // check if the args[0] is a valid net name + // create net with name args[0] (by default with type NONE) + // add args[0] to nets + // delete args[0] from args + } + + delete $2; + } +| atomelement { $$ = $1; } +; + +element.with_kwargs: + element.with_kwargs assignment + { + // cout << "found keyword arg: " << $2->second.get_str() << endl; + cur_pt->elements[$1]->kwargs[$2->first] = $2->second; + $$ = $1; + delete $2; + } +| element.with_args +; + +element.x.with_args: + element.x.with_args net_name_base + { + // cout << "found positional arg: " << $2->get_str() << endl; + if (!cur_pt->elements[$1]->kwargs.empty()) + yyerror(scanner, pt, "positional arguments cannot follow keyword arguments"); + cur_pt->elements[$1]->args.emplace_back(Variable(*$2)); + $$ = $1; + + // TODO: for X element only, nets are stored as args + // Xnnnn n1 n2 n3 ... sub_name **sub_kwargs + // because the number of nets is not known when reading n1 n2 n3... + // [n1 n2 n3 ... subname] are also args + // when the time an arg is found, the previous one (if it exists), can be considered a net + // and therefore added to the element's nets array and discarded from args + // this will ensure that args will contain only [sub_name] + // for this to work, the X element cannot have args beyond sub_name (only kwargs) + if (cur_pt->elements[$1]->args.size() == 2) + { + // check if the args[0] is a valid net name + // create net with name args[0] (by default with type NONE) + // add args[0] to nets + // delete args[0] from args + } + + delete $2; + } +| element.x { $$ = $1; } +; + +element.x.with_kwargs: + element.x.with_kwargs assignment + { + // cout << "found keyword arg: " << $2->second.get_str() << endl; + cur_pt->elements[$1]->kwargs[$2->first] = $2->second; + $$ = $1; + delete $2; + } +| element.x.with_args +; + +element: + element.with_kwargs +| element.x.with_kwargs +; + +/* ---------- Analysis arguments parsing ----------- */ + +atomanalysis: analysis.op { $$ = $1; } + | analysis.dc { $$ = $1; } + | analysis.tran { $$ = $1; } +; + +analysis.with_args: + analysis.with_args variable + { + // cout << "found positional arg: " << $2->get_str() << endl; + if (!cur_pt->analyses[$1]->kwargs.empty()) + yyerror(scanner, pt, "positional arguments cannot follow keyword arguments"); + cur_pt->analyses[$1]->args.emplace_back(*$2); + $$ = $1; + delete $2; + } +| atomanalysis { $$ = $1; } +; + +analysis.with_kwargs: + analysis.with_kwargs assignment + { + // cout << "found keyword arg: " << $2->second.get_str() << endl; + cur_pt->analyses[$1]->kwargs[$2->first] = $2->second; + $$ = $1; + delete $2; + } +| analysis.with_args +; + +analysis: analysis.with_kwargs + +/* --------- NET type parsing ----------- */ + +net.oanalog: net_name + { + bool ok = cur_pt->nets[*$1].setType(ParseNet::OANALOG); + if (!ok) + { + stringstream ret; + ret << "Error creating net '" + *$1 + "': net already exists with a different type" << endl; + ret << "\t (new type: " << "OANALOG" << ", old type: " << cur_pt->nets[*$1].type_str() << ")" << endl; + yyerror(scanner, pt, ret.str().c_str()); + } + cur_pt->nets[*$1].m_ports_count++; + $$ = $1; + } +; + +net.oa.explicit_bidir: + net.oanalog '&' + { + // this net will be both written to and read from by the new device + // so increment both reader and writer count + // and set the explicit "bidirectional" flag to true + cur_pt->nets[*$1].m_bidirectional = true; + cur_pt->nets[*$1].m_readers_count++; + cur_pt->nets[*$1].m_writers_count++; + $$ = $1; + } +; + +net.oa.bidir: + net.oa.explicit_bidir +| net.oanalog + { + // this net will be both written to and read from by the new device + // so increment both reader and writer count + cur_pt->nets[*$1].m_readers_count++; + cur_pt->nets[*$1].m_writers_count++; + $$ = $1; + } +; + +net.oa.in: + net.oanalog + { + // this net will only be read from by the new device + // so increment only reader count + cur_pt->nets[*$1].m_readers_count++; + $$ = $1; + } +| net.oa.explicit_bidir + { + // bidir already got a writer and reader increment, but + // this net will only be read from by the new device + // so decrement writer count + cur_pt->nets[*$1].m_writers_count--; + $$ = $1; + } +; + +net.oa.out: + net.oanalog + { + // this net will only be written to by the new device + // so increment only writer count + cur_pt->nets[*$1].m_writers_count++; + $$ = $1; + } +| net.oa.explicit_bidir + { + // bidir already got a writer and reader increment, but + // this net will only be written to by the new device + // so decrement reader count + cur_pt->nets[*$1].m_readers_count--; + $$ = $1; + } +; + +net.eanalog: net_name + { + bool ok = cur_pt->nets[*$1].setType(ParseNet::EANALOG); + if (!ok) + { + stringstream ret; + ret << "Error creating net '" + *$1 + "': net already exists with a different type" << endl; + ret << "\t (new type: " << "EANALOG" << ", old type: " << cur_pt->nets[*$1].type_str() << ")" << endl; + yyerror(scanner, pt, ret.str().c_str()); + } + $$ = $1; + } + +net.edigital: net_name + { + bool ok = cur_pt->nets[*$1].setType(ParseNet::EDIGITAL); + if (!ok) + { + stringstream ret; + ret << "Error creating net '" + *$1 + "': net already exists with a different type" << endl; + ret << "\t (new type: " << "EDIGITAL" << ", old type: " << cur_pt->nets[*$1].type_str() << ")"; + yyerror(scanner, pt, ret.str().c_str()); + } + $$ = $1; + } +; + +/* --------- BUS type parsing ----------- */ + +/* +bus.oanalog: bus_name + { + cur_pt->nets[*$1].m_type = ParseNet::OANALOG; + $$ = $1; + } +; + +bus.eanalog: bus_name + { + cur_pt->nets[*$1].m_type = ParseNet::EANALOG; + $$ = $1; + } +; + +bus.edigital: bus_name + { + cur_pt->nets[*$1].m_type = ParseNet::EDIGITAL; + $$ = $1; + } +; +bus: bus.oanalog { $$ = $1; } + | bus.eanalog { $$ = $1; } + | bus.edigital { $$ = $1; } +; +*/ +/* --------- NET and BUS name parsing ----------- */ + +net_name.base.str: + T_STR { $$ = $1; } + | '/' T_STR + { + $$ = $2; + *$2 = "/" + *$2; + } + | '/' T_INT + { + stringstream ss; + ss << "/" << $2; + $$ = new string(ss.str()); + } + | net_name.base.str '-' T_STR + { + $$ = $1; + *$1 += "-" + *$3; + delete $3; + } +; + +net_name_base: T_INT { $$ = new string(ParseNet::name_from_id($1)); } + | net_name.base.str { $$ = $1; } +; + +net_name: net_name_base + { + $$ = new string(cur_pt->get_or_create_net(*$1)); + delete $1; + } +; + +/* +bus_name: net_name { $$ = $1; } + | net_name_base '<' T_INT '>' + { + $$ = new string(cur_pt->get_or_create_net(*$1, $3)); + delete $1; + } +; +*/ +port_name: net_name_base { $$ = $1; } +; + +/* --------- Assignment and variable ----------- */ + +netval_assignment: '/' net_name '/' T_STR '=' variable.delimited_expr + { + $$ = new pair<string, pair<string, Variable>>( + *$2, + pair<string, Variable>(*$4, *$6) + ); + delete $2; + delete $4; + delete $6; + } +; + +cw_sweep_order: element_attribute variable_base variable_base variable_base + { + // cout << $1->first << "->" << $1->second; + // cout << " = [" << $2->as_double(); + // cout << ":" << $4->as_double(); + // cout << ":" << $3->as_double() << "]" << endl; + $$ = new pair<pair<string, string>, vector<double>>(*$1, {$2->as_double(), $3->as_double(), $4->as_double()}); + delete $1; + delete $2; + delete $3; + delete $4; + } +; + +element_attribute: '/' T_STR '/' T_STR + { + // cout << *$2 << "->" << *$4 << endl; + $$ = new pair<string, string>(*$2,*$4); + delete $2; + delete $4; + } +; + +assignment: T_ASSIGN_ID '=' variable + { + $$ = new pair<string, Variable>(*$1, *$3); + delete $1; + delete $3; + } +; + +variable_base: + T_INT + { + $$ = new Variable($1); + } + | T_NUM + { + $$ = new Variable($1); + } + | T_NONE + { + $$ = new Variable(Variable::NONE); + } + | '{' T_STR '}' + { + $$ = new Variable(cur_pt->get_variable(*$2)); + delete $2; + } + | '"' T_STR '"' + { + $$ = new Variable(*$2); + delete $2; + } + | listvar.bound + { + $$ = $1; + } +; + +variable.delimited_expr: + '{' expr '}' + { + $$ = $2; + } +| variable_base; +; + +variable.free_expr: + expr + { + $$ = $1; + } +; + +variable: + variable.free_expr +; + +/* +variable.str_without_quotes: + T_STR + { + if (*$1 == "None") + $$ = new Variable(Variable::NONE); + else + $$ = new Variable(*$1); + delete $1; + } +| variable; +; +*/ + +variable_or_empty: + variable + | %empty + { + $$ = new Variable(Variable::NONE); + } +; + +/* ------------ Expression parsing ------------- */ + +constant: variable_base { $$ = $1; } +; + +expr: + expr '+' term { $$ = $1; *$$ += *$3; delete $3; } +| expr '-' term { $$ = $1; *$$ -= *$3; delete $3; } +| term { $$ = $1; } +; + +term: + term '*' fact { $$ = $1; *$$ *= *$3; delete $3; } +| term '/' fact { $$ = $1; *$$ /= *$3; delete $3; } +| fact { $$ = $1; } +; + +fact: + fact '^' pow { $$ = $1; *$$ ^= *$3; delete $3; } +| pow { $$ = $1; } +; + +pow: + constant +| '(' expr ')' { $$ = $2; } +; + +// --------------- variables list (elements can have different types) +listvar.tail: variable_or_empty + { + $$ = new Variable(Variable::LIST); + $$->vec.insert($$->vec.begin(), *$1); + delete $1; + } +; + +listvar.unbound: variable_or_empty ',' listvar.tail + { + $3->vec.insert($3->vec.begin(), *$1); + $$ = $3; + delete $1; + } + | variable_or_empty ',' listvar.unbound + { + $3->vec.insert($3->vec.begin(), *$1); + $$ = $3; + delete $1; + } +; + +listvar.bound: '[' listvar.tail ']' { $$ = $2; } + | '[' listvar.unbound ']' { $$ = $2; } +; + +%% + +int yyerror(yyscan_t scanner, ParseTree *pt, const char *err) +{ + (void)pt; + (void)scanner; + string token = yyget_text(scanner); + stringstream ss; + for (char c : token) + { + switch (c) + { + case '\r': + ss << "\\r"; + break; + case '\n': + ss << "\\n"; + break; + case '\t': + ss << "\\t"; + break; + case '\b': + ss << "\\b"; + break; + default: + ss << c; + break; + } + } + string token_escaped = ss.str(); + printf("-- Error in the netlist (line %u): %s\n", yyget_lineno(scanner), err); + printf("-- \"%s\"\n", token_escaped.c_str()); + //cerr << err << endl; + exit(1); +} diff --git a/src/specs.cpp b/src/specs.cpp new file mode 100644 index 0000000..2b9727d --- /dev/null +++ b/src/specs.cpp @@ -0,0 +1,383 @@ +#include "bitstream_source.h" +#include "optical_signal.h" +#include "sysc_utils.h" +#include <specs.h> +#include "spx_module.h" +#include "value_list_source.h" +#include "electrical_value_list_source.h" + +#include <systemc.h> +#include <optical_output_port.h> +#include <spx_module.h> +#include <cw_source.h> +#include <probe.h> +#include <detector.h> +#include <generic_transmission_device.h> + +using std::string; + +SPECSConfig specsGlobalConfig { "SPX" }; + +SPECSConfig::SPECSConfig(sc_module_name name) + : sc_module(name) +{ + drop_all_events = false; + // Simulation options + engine_timescale = HUNDRED_FS; + simulation_mode = OpticalOutputPortMode::DEFAULT; + analysis_type = AnalysisType::TIME_DOMAIN; + + // Port options + default_abstol = 1e-8; + default_reltol = 1e-4; + default_resolution_multiplier = 1; + + // Trace options + trace_filename = "traces/delete_me"; + default_trace_file = nullptr; + trace_all_optical_nets = 1; +} + +void SPECSConfig::runAnalysis() +{ + applyEngineResolution(); + prepareSimulation(); + + switch (analysis_type) { + case CW_OPERATING_POINT: + runOPAnalysis(); + break; + case CW_SWEEP: + runDCAnalysis(); + break; + case TIME_DOMAIN: + runTRANAnalysis(); + break; + default: + cerr << "Undefined Analysis type"; + sc_stop(); + } +} + +void SPECSConfig::runOPAnalysis() +{ + auto all_probes = sc_get_all_module_by_type<Probe>(); + auto all_mlprobes = sc_get_all_module_by_type<MLambdaProbe>(); + auto all_photodetectors = sc_get_all_module_by_type<Detector>(); + auto all_oop = sc_get_all_module_by_type<OpticalOutputPort>(); + auto all_cws = sc_get_all_module_by_type<CWSource>(); + + // Run to initialize all threads and register first values + sc_start(); + + // Set values of signals according to NODESET directive + for (auto &nodeset_order : nodeset_orders) + { + nodeset_order.second.first->write(nodeset_order.second.second); + } + + // Disable probes for OP point + for (auto probe: all_probes) { + probe->enable = sc_logic(0); + } + + // Disable ML probes for OP point + for (auto mlprobe: all_mlprobes) { + mlprobe->enable = sc_logic(0); + } + + // Disable photodetectors + for (auto pdet: all_photodetectors) { + pdet->enable = sc_logic(0); + } + + // Set all ports mode to NO_DELAY + for (auto oop: all_oop) { + oop->m_mode = OpticalOutputPortMode::NO_DELAY; + } + + // Activate all CW sources + for (auto cws: all_cws) + cws->enable = sc_logic(1); + + // Run operating point simulation + sc_start(); + + // Print results on the command line + printOPAnalysisResult(); +} + +void SPECSConfig::runDCAnalysis() +{ + auto all_probes = sc_get_all_module_by_type<Probe>(); + auto all_mlprobes = sc_get_all_module_by_type<MLambdaProbe>(); + auto all_photodetectors = sc_get_all_module_by_type<Detector>(); + auto all_oop = sc_get_all_module_by_type<OpticalOutputPort>(); + auto all_sig = sc_get_all_object_by_type<sc_signal<OpticalSignal, SC_MANY_WRITERS>>(); + auto all_cws = sc_get_all_module_by_type<CWSource>(); + + // Run to initialize all threads and register first values + sc_start(); + + // Enable normal probes + for (auto probe: all_probes) { + probe->enable = sc_logic(1); + } + + // Disable ML probes + for (auto mlprobe: all_mlprobes) { + mlprobe->enable = sc_logic(0); + } + + // Enable photodetectors + for (auto pdet: all_photodetectors) { + // Remark: Photodetectors could in fact be left enabled ? + // Would that serve any purpose though...? + pdet->enable = sc_logic(0); + } + + // Set all ports mode to NO_DELAY + for (auto oop: all_oop) { + oop->m_mode = OpticalOutputPortMode::NO_DELAY; + } + + // Activate CW sources + for (auto cws: all_cws) { + cws->enable = sc_logic(1); + } + + const auto &order = *cw_sweep_orders.begin(); + wavelengths_vector.reserve(order.second.second.size()); + cout << "Starting sweep on " << order.first; + cout << " (" << order.second.second.size() << " points)" << endl; + for (const auto &val : order.second.second) + { + // Apply sweep param + order.second.first(val); + + //cout << order.first << " = " << val << endl; + + // Reset OOP and set internal signals to new wavelength + for (auto oop: all_oop) { + #if 1 // reset OOP + oop->reset(); + // TODO: also reset photodetectors? + #elif 0 // remove previous wavelengths from OOP but keep value + if (wavelengths_vector.size() >= 2) + { + oop->swap_wavelengths(wavelengths_vector.size()-1, wavelengths_vector.size()-2); + oop->delete_wavelength(wavelengths_vector.size()-2); + oop->m_skip_next_convergence_check = true; + } + #else + // do nothing + #endif + } + + // run simulation and advance one tick + sc_start(sc_time::from_value(1)); + + // Reset CW sources + for (auto cws: all_cws) + { + cws->reset.write(sc_logic(1)); + } + + //printOPAnalysisResult(); + } +} + +void SPECSConfig::runTRANAnalysis() +{ + auto all_probes = sc_get_all_module_by_type<Probe>(); + auto all_mlprobes = sc_get_all_module_by_type<MLambdaProbe>(); + auto all_photodetectors = sc_get_all_module_by_type<Detector>(); + auto all_oop = sc_get_all_module_by_type<OpticalOutputPort>(); + auto all_vl_src = sc_get_all_module_by_type<VLSource>(); + auto all_evl_src = sc_get_all_module_by_type<EVLSource>(); + + // Run OP analysis + runOPAnalysis(); + + // Set values of signals according to IC directive + for (auto &ic_order : ic_orders) + { + //ic_order.second.first->write(ic_order.second.second); + } + + // Enable probes + for (auto probe: all_probes) { + probe->enable = sc_logic(1); + } + + // Enable ML probes + for (auto mlprobe: all_mlprobes) { + mlprobe->enable = sc_logic(1); + } + + // Enable photodetectors + for (auto pdet: all_photodetectors) { + pdet->enable = sc_logic(1); + } + + // Re-apply configuration of all ports + for (auto oop: all_oop) { + oop->applyConfig(); + } + + // Activate TRAN sources + for (auto src: all_vl_src) + src->enable = sc_logic(1); + for (auto src: all_evl_src) + src->enable = sc_logic(1); + + // Strart TRAN simulation + if (isfinite(tran_duration)) + sc_start(tran_duration, SC_SEC); + else + sc_start(); + + cout << "Simulated " << sc_time_stamp() << endl; +} + +void SPECSConfig::applyDefaultOpticalOutputPortConfig() { + //assert(!oop_configs.empty()); + auto oop_default_config = make_shared<OpticalOutputPortConfig>(); + oop_default_config->m_mode = simulation_mode; + oop_default_config->m_abstol = default_abstol; + oop_default_config->m_reltol = default_reltol; + oop_default_config->m_timestep_value = default_resolution_multiplier; // relative to systemc timestep + + // apply default config to all optical output ports which don't have one + auto all_oop = sc_get_all_module_by_type<OpticalOutputPort>(); + for (auto oop: all_oop) { + if(!oop->getConfig().get()) + oop->setConfig(oop_default_config); + // FIXME: only works for first call to sc_start !! + } +} + +void SPECSConfig::applyDefaultTraceFileToAllSignals() { + if (!default_trace_file) + return; + + auto all_probes = sc_get_all_object_by_type<Probe>(); + for (auto p: all_probes) { + p->setTraceFile(default_trace_file); + } + + // auto all_mlprobes = sc_get_all_object_by_type<MLambdaProbe>(); + // for (auto p: all_mlprobes) { + // p->m_Tf = default_trace_file; + // p->prepare(); + // } + + auto all_mlambda_probes = sc_get_all_object_by_type<MLambdaProbe>(); + for (auto p: all_mlambda_probes) { + p->setTraceFile(default_trace_file); + } + + if (trace_all_optical_nets) + { + auto all_optical_sigs = sc_get_all_object_by_type<sc_signal<OpticalSignal, SC_MANY_WRITERS>>(); + for (auto &sig: all_optical_sigs) { + string signame = sig->name(); + + // Check if the signal is explicitly marked as uninteresting + stringstream ss (signame); + string base_signame; + while (getline (ss, base_signame, '/')) {} + if (base_signame.empty() || base_signame[0] == '_') + continue; + //cout << signame << endl; + + auto p = make_shared<Probe>(("PROBE{" + signame + "}").c_str(), true, true, true, true); + p->setTraceFile(default_trace_file); + p->p_in(*sig); + additional_objects.push_back(p); + } + } + // TODO: refactor ↓ + auto all_pdets = sc_get_all_object_by_type<Detector>(); + for (auto &pdet: all_pdets) { + string detname = pdet->name(); + cout << detname << endl; + pdet->trace(default_trace_file); + //sc_trace(default_trace_file, , (string(pdet->name()) + ".readout").c_str()); + } +} + +string SPECSConfig::analysisTypeDesc() const +{ + switch (analysis_type) { + case CW_OPERATING_POINT: + return "CW OPERATING POINT"; + case CW_SWEEP: + return "CW SWEEP"; + case TIME_DOMAIN: + return "TIME DOMAIN"; + default: + return "UNDEFINED"; + } +} + +void SPECSConfig::printConfig() const +{ + cout << "Current SPECS config: " << endl; + cout << "- simulation mode: " << oopPortMode2str(simulation_mode) << endl; + cout << "- analysis type: " << analysisTypeDesc() << endl; + cout << "- engine timescale (log10 of s): " << engine_timescale << endl; + cout << "- abstol: " << default_abstol << endl; + cout << "- default reltol: " << default_reltol << endl; + cout << "- resolution multiplier: " << default_resolution_multiplier << endl; + cout << "- trace all optical nets: " << trace_all_optical_nets << endl; +} + +void SPECSConfig::printOPAnalysisResult() const +{ + cout << "╔═══════════════════╗" << endl; + cout << "║ OPERATING POINT ║" << endl; + cout << "╠═══════════════════╣" << endl; + cout << "║ ╨───┄┄" << endl; + auto all_optical_sigs = sc_get_all_object_by_type<sc_signal<OpticalSignal, SC_MANY_WRITERS>>(); + for (auto &sig: all_optical_sigs) { + string signame = sig->name(); + cout << "║ "; + cout << "- " << signame << " (OPTICAL)" << " = " << sig->read() << endl; + } + cout << "║ ╥───┄┄" << endl; + cout << "╚═══════════════════╝" << endl; +} + +void SPECSConfig::prepareSimulation() { + auto all_spx_mod = sc_get_all_object_by_type<spx_module>(); + for (auto &mod : all_spx_mod) + mod->init(); + printConfig(); + verifyConfig(); + + { // open default trace_file + if (!default_trace_file && trace_filename.size()) + default_trace_file = sc_create_vcd_trace_file(trace_filename.c_str()); + + default_trace_file->set_time_unit(std::pow(10, 15 + engine_timescale), SC_FS); + } + + applyDefaultOpticalOutputPortConfig(); + applyDefaultTraceFileToAllSignals(); + if (default_trace_file) + sc_trace(default_trace_file, *this, ""); +} + +inline void sc_trace(sc_trace_file *tf, const SPECSConfig &s, string parent_tree) +{ + parent_tree += (parent_tree.size() ? "." : ""); + sc_trace(tf, s.default_abstol, parent_tree + "abstol"); + sc_trace(tf, s.default_reltol, parent_tree + "reltol"); + sc_trace(tf, s.default_resolution_multiplier, parent_tree + "resolution_multiplier"); + sc_trace(tf, s.engine_timescale, parent_tree + "engine_timescale"); + sc_trace(tf, s.simulation_mode, parent_tree + "simulation_mode"); + sc_trace(tf, s.analysis_type, parent_tree + "analysis_type"); + sc_trace(tf, s.trace_all_optical_nets, parent_tree + "trace_all_optical_nets"); + sc_trace(tf, s.verbose_component_initialization, parent_tree + "verbose_component_initialization"); +}
\ No newline at end of file diff --git a/src/specs.h b/src/specs.h new file mode 100644 index 0000000..fe56d6a --- /dev/null +++ b/src/specs.h @@ -0,0 +1,159 @@ +#pragma once + +#include <sysc_utils.h> +#include "optical_signal.h" +#include "optical_output_port.h" + +#include <systemc.h> +#include <vector> +#include <map> +#include <utility> +#include <functional> + +using std::vector; +using std::map; +using std::pair; +using std::make_shared; +using std::shared_ptr; +using std::string; +using std::function; + +namespace spx { + // Value types + typedef OpticalSignal oa_value_type; + typedef double ea_value_type; + typedef sc_logic ed_value_type; + + // Signal types + typedef sc_signal<oa_value_type, SC_MANY_WRITERS> oa_signal_type; + typedef sc_signal<ea_value_type, SC_MANY_WRITERS> ea_signal_type; + typedef sc_signal<ed_value_type, SC_MANY_WRITERS> ed_signal_type; + typedef sc_signal<sc_lv_base, SC_MANY_WRITERS> ed_bus_type; + + // Optical analog IF type + typedef sc_signal_in_if<oa_value_type> oa_if_in_type; + typedef sc_signal_out_if<oa_value_type> oa_if_out_type; + typedef sc_signal_inout_if<oa_value_type> oa_if_inout_type; + + // Electrical analog IF type + typedef sc_signal_in_if<ea_value_type> ea_if_in_type; + typedef sc_signal_out_if<ea_value_type> ea_if_out_type; + typedef sc_signal_inout_if<ea_value_type> ea_if_inout_type; + + // Optical analog ports + typedef sc_port<oa_if_in_type, 0, SC_ZERO_OR_MORE_BOUND> oa_port_in_type; + typedef sc_port<oa_if_out_type> oa_port_out_type; + typedef sc_port<oa_if_inout_type> oa_port_inout_type; + + // Electrical analog ports + typedef sc_port<ea_if_in_type, 0, SC_ZERO_OR_MORE_BOUND> ea_port_in_type; + typedef sc_port<ea_if_out_type> ea_port_out_type; + typedef sc_port<ea_if_inout_type> ea_port_inout_type; +}; + +class SPECSConfig : public sc_module { +public: + enum EngineTimescale { + ONE_SEC = 0, + HUNDRED_MS = -1, + TEN_MS = -2, + ONE_MS = -3, + HUNDRED_US = -4, + TEN_US = -5, + ONE_US = -6, + HUNDRED_NS = -7, + TEN_NS = -8, + ONE_NS = -9, + HUNDRED_PS = -10, + TEN_PS = -11, + ONE_PS = -12, + HUNDRED_FS = -13, + TEN_FS = -14, + ONE_FS = -15, + }; + + enum AnalysisType { + ANALYSIS_TYPE_MINVAL, + CW_OPERATING_POINT, + CW_SWEEP, + TIME_DOMAIN, + ANALYSIS_TYPE_MAXVAL, + + // aliases + DEFAULT = TIME_DOMAIN, + OP = CW_OPERATING_POINT, + DC = CW_SWEEP, + TRAN = TIME_DOMAIN, + UNDEFINED = ANALYSIS_TYPE_MAXVAL, + }; + + // Hold simulation objects + vector<shared_ptr<sc_object>> additional_objects; + map<string, pair<sc_signal<OpticalSignal, SC_MANY_WRITERS> *, OpticalSignal>> ic_orders; + map<string, pair<sc_signal<OpticalSignal, SC_MANY_WRITERS> *, OpticalSignal>> nodeset_orders; + + // Simulation options + EngineTimescale engine_timescale = ONE_FS; + OpticalOutputPortMode simulation_mode; + AnalysisType analysis_type; + map<string, pair<function<void(double)>, vector<double>>> cw_sweep_orders; + double tran_duration = std::numeric_limits<double>::infinity(); + + // Port options + double default_abstol = 1e-8; + double default_reltol = 1e-4; + sc_time::value_type default_resolution_multiplier = 1; + + // For multi-wavelength support + vector<double> wavelengths_vector; + + // Trace options + string trace_filename = ""; + sc_trace_file *default_trace_file = nullptr; + bool trace_all_optical_nets = 1; + + // other + sc_signal<bool, SC_MANY_WRITERS> drop_all_events; + bool verbose_component_initialization = true; + + SPECSConfig(sc_module_name name); + + ~SPECSConfig() {} + + virtual void before_end_of_elaboration() + {} + + void runAnalysis(); + void runOPAnalysis(); + void runDCAnalysis(); + void runTRANAnalysis(); + + void applyEngineResolution() { + // set engine time resolution + sc_set_time_resolution(std::pow(10, 15+engine_timescale), SC_FS); + } + void applyDefaultOpticalOutputPortConfig(); + void traceSettings(); + void applyDefaultTraceFileToAllSignals(); + void verifyConfig() + { + assert(default_abstol > 0); + assert(default_reltol > 0); + assert(default_resolution_multiplier >= 1); + assert(ONE_FS <= engine_timescale && engine_timescale <= ONE_SEC); + assert(PORT_MODE_MINVAL < simulation_mode && simulation_mode < PORT_MODE_MAXVAL); + assert(ANALYSIS_TYPE_MINVAL < analysis_type && analysis_type < ANALYSIS_TYPE_MAXVAL); + } + string analysisTypeDesc() const; + void printConfig() const; + void printOPAnalysisResult() const; + void prepareSimulation(); + inline void register_object(shared_ptr<sc_object> object) { + additional_objects.push_back(object); + } + + inline friend void + sc_trace(sc_trace_file *tf, const SPECSConfig &s, string parent_tree); +}; + +extern SPECSConfig specsGlobalConfig;
\ No newline at end of file diff --git a/src/tb/alltestbenches.cpp b/src/tb/alltestbenches.cpp new file mode 100644 index 0000000..107dfdc --- /dev/null +++ b/src/tb/alltestbenches.cpp @@ -0,0 +1,28 @@ +#include <map> +#include <tb/alltestbenches.h> + +#if defined(BUILD_TB) && BUILD_TB == 1 +std::map<std::string, tb_func_t> tb_map = { + { "wg", wg_tb_run }, + { "waveguide", wg_tb_run }, + { "merg", Merger_tb_run }, + { "merger", Merger_tb_run }, + { "dc", DirectionalCoupler_tb_run }, + { "directional_coupler", DirectionalCoupler_tb_run }, + { "spli", Splitter_tb_run }, + { "splitter", Splitter_tb_run }, + { "det", Detector_tb_run }, + { "detector", Detector_tb_run }, + { "pcm", PCMElement_tb_run }, + { "mzi", MZI_tb_run }, + { "ring", Ring_tb_run }, + { "ac_add_drop", freqsweep_tb_run_add_drop }, + { "ac_crow", crow_tb_run }, + { "lambda", lambda_tb_run }, + { "phaseshifter", ps_tb_run }, + { "ps", ps_tb_run }, + { "mesh", mesh_tb_run }, +}; +#else +std::map<std::string, tb_func_t> tb_map = {}; +#endif diff --git a/src/tb/alltestbenches.h b/src/tb/alltestbenches.h new file mode 100644 index 0000000..49043bb --- /dev/null +++ b/src/tb/alltestbenches.h @@ -0,0 +1,22 @@ +#pragma once + +#include <tb/detector_tb.h> +#include <tb/directional_coupler_tb.h> +#include <tb/merger_tb.h> +#include <tb/pcm_device_tb.h> +#include <tb/splitter_tb.h> +#include <tb/wg_tb.h> +#include "tb/mzi_tb.h" +#include "tb/ring_tb.h" +#include "tb/freqsweep_tb.h" +#include "tb/crow_tb.h" +#include "tb/lambda_tb.h" +#include "tb/phase_shifter_tb.h" +#include "mesh_tb.h" + +#include <map> +#include <string> + +typedef void (*tb_func_t)(); + +extern std::map<std::string, tb_func_t> tb_map; diff --git a/src/tb/crow_tb.cpp b/src/tb/crow_tb.cpp new file mode 100644 index 0000000..91a816c --- /dev/null +++ b/src/tb/crow_tb.cpp @@ -0,0 +1,216 @@ +#include <ctime> +#include <iomanip> +#include <tb/crow_tb.h> + +#include <cstdlib> +#include <unistd.h> +#include <chrono> + +#include <waveguide.h> +#include <directional_coupler.h> +#include <probe.h> +#include <crow.h> +#include <specs.h> +#include "time_monitor.h" + +#include "general_utils.h" + +using namespace std; +using namespace std::chrono; + + +/* ----------------------------------------------------------------------------- * + This testbench is called freqsweep because it is capable of this + type of simulation, but it is also possible to set it as a time-domain + simulation depending on the mode chosen when calling SPECS. Example: + + specs -t ac_add_drop -m fd -> will perform the frequency sweep + specs -t ac_add_drop -m td -> will perform the time domain simulation + +/ ----------------------------------------------------------------------------- */ + +// ---------------- Use this variable to change the size of the CROW ----------- + size_t nrings_crow = 3; +// ----------------------------------------------------------------------------- + +void crow_tb::run_td() +{ + bool verbose = true; + if (specsGlobalConfig.simulation_mode == OpticalOutputPortMode::TIME_DOMAIN) + { + int npulses = 4; + double lambda = 1554.3719e-9; + lambda = 1.561931948453715e-6; + lambda = 1538.3277504e-9; + lambda = 1543e-9; + lambda = 1556.5742279e-9; + lambda = 1556.32782563158025368466e-9; + lambda = 1556e-9; + lambda = 1553e-9; + //lambda = 1550e-9; + double tpulse = 1e-9; + double deadtime = tpulse; + + + // Wait one tick that all sc_threads are started and on their first `wait` call + wait(SC_ZERO_TIME); + + if (verbose) + { + cout << "----------------------------" <<endl; + cout << "Starting time-domain simulation" << endl; + } + for (int i = 0; i < npulses; ++i) + { + IN->write(OpticalSignal(1, lambda)); + wait(tpulse, SC_SEC); + // //ADD.write(OpticalSignal(polar<double>(1, M_PI_2), lambda)); + // //ADD.write(OpticalSignal(polar<double>(0,0), lambda)); + IN->write(OpticalSignal(0, lambda)); + // ADD.write(OpticalSignal(0, lambda)); + wait(deadtime, SC_SEC); + } + } + + while (true) { wait(); } +} + +void crow_tb::run_fd() +{ + bool verbose = true; + if (specsGlobalConfig.simulation_mode == OpticalOutputPortMode::FREQUENCY_DOMAIN) + { + auto lambda_center = 1550e-9; + auto lambda_span = 2e-9; + auto dlambda = 0.001e-9; + auto lambda_min = lambda_center - lambda_span/2; + auto lambda_max = lambda_center + lambda_span/2; + // lambda_min = 1545e-9; + // lambda_max = 1569e-9; + lambda_min = 299792458.0/195e12; + lambda_max = 299792458.0/190e12; + lambda_min = 1556e-9; + lambda_span = lambda_max - lambda_min; + dlambda = lambda_span / 10000; + + // Wait one tick that all sc_threads are started and on their first `wait` call + wait(SC_ZERO_TIME); + //wait(lambda_min, SC_SEC); + + auto tic = high_resolution_clock::now(); + auto toc = high_resolution_clock::now(); + + if (verbose) + { + cout << "----------------------------" <<endl; + cout << "Starting sweep" << endl; + } + int i = 0; + int n = ceil(lambda_span / dlambda); + for (auto lambda = lambda_min; lambda < lambda_max + dlambda; lambda += dlambda) + { + ++i; + if (true || (verbose && i % (int)(n/20) == 0)) + { + toc = high_resolution_clock::now(); + auto duration = duration_cast<microseconds>(toc - tic); + tic = toc; + cout << duration.count()/1000.0 << "ms" << endl; + cout << endl; + cout << fixed << setprecision(1) << (lambda-lambda_min)/lambda_span * 100.0 << "%" << endl; + cout << setprecision(20) << lambda * 1e9 << "nm" << endl; + } + IN->write(OpticalSignal(sqrt(1), lambda)); + ADD->write(OpticalSignal(0, lambda)); + //ADD.write(OpticalSignal(polar<double>(0, 0), lambda)); + //ADD.write(OpticalSignal(polar<double>(sqrt(0.5), -M_PI_2), lambda)); + wait(dlambda, SC_SEC); + } + if (verbose) + { + cout << "----------------------------" <<endl; + cout << "Sweep over (" << n << " points)" << endl; + } + } + while (true) { wait(); } +} + +void crow_tb::monitor() +{ + unsigned long long event_counter = 0; + while(true) + { + wait(); + continue; + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tADD: " << ADD->read() << std::endl + << "\tTHROUGH: " << THROUGH->read() << std::endl + << "\tDROP: " << DROP->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + } + +} + +void crow_tb_run() +{ + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN("IN"), THROUGH("THROUGH"), DROP("DROP"), ADD("ADD"); + + crow_tb tb1("tb1"); + tb1.IN(IN); + tb1.ADD(ADD); + tb1.THROUGH(THROUGH); + tb1.DROP(DROP); + + // pid_t pid = fork(); + CROW *pc; + // if(pid) + pc = new CROW("crow", nrings_crow); + // else + // pc = new Crow("crow", 5); + pc->p_in(IN); + pc->p_add(ADD); + pc->p_out_t(THROUGH); + pc->p_out_d(DROP); + + pc->setRingLength(2*30e-6); + pc->m_loss_db_cm = 2.0; + pc->m_coupling_through = 1 - pow(0.83645, 2.0); + // pc->m_coupling_through = 0.5; + pc->m_neff = 2.6391; + pc->m_ng = 4.3416; + + pc->m_ring_length = 500.0*1.55e-6 + 1.55e-6/2.0; + pc->m_loss_db_cm = 2.0; + pc->m_coupling_through = 1 - 0.2; + pc->m_neff = 1; + pc->m_ng = 2; + + pc->init(); //instantiating all nets + + Probe pthrough("pthrough", true, true, false, true); + pthrough.p_in(THROUGH); + // + Probe pcross("pcross", true, true, false, false); + pcross.p_in(DROP); + + specsGlobalConfig.trace_filename = "traces/crow_tb"; + + // Apply SPECS options specific to the testbench + // specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(50e-9, SC_SEC); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/crow_tb.h b/src/tb/crow_tb.h new file mode 100644 index 0000000..473708d --- /dev/null +++ b/src/tb/crow_tb.h @@ -0,0 +1,30 @@ +#pragma once + +#include <optical_signal.h> +#include <specs.h> +#include <systemc.h> + +class crow_tb : public sc_module { +public: + spx::oa_port_out_type IN; + spx::oa_port_out_type ADD; + spx::oa_port_in_type THROUGH; + spx::oa_port_in_type DROP; + + void run_fd(); + void run_td(); + void monitor(); + + SC_CTOR(crow_tb) + { + SC_THREAD(run_fd); + SC_THREAD(run_td); + SC_THREAD(monitor); + if (false) + sensitive << IN << ADD << THROUGH << DROP; + } +}; + +void crow_tb_run(); + +extern size_t nrings_crow; diff --git a/src/tb/detector_tb.cpp b/src/tb/detector_tb.cpp new file mode 100644 index 0000000..e296d26 --- /dev/null +++ b/src/tb/detector_tb.cpp @@ -0,0 +1,127 @@ +#include <ctime> +#include <iomanip> +#include <tb/detector_tb.h> + +#include "general_utils.h" + +void Detector_tb::run_1() +{ + IN->write(OpticalSignal(sqrt(1.0), 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(0, 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(sqrt(1.0), 1551e-9)); + + + + while (true) { wait(); } +} + +void Detector_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tREADOUT: " << READOUT.read() << std::endl + << "\tREADOUT2: " << READOUT2.read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + + if(event_counter == 2) + { + if ((is_close(READOUT.read(), 1, 1e-3)) && (is_close(READOUT2.read(), 1, 1e-3))) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 1A as both output currents!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 4) + { + if ((is_close(READOUT.read(), 0, 1e-4)) && (is_close(READOUT2.read(), 0, 1e-4))) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0A as output currents!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 6) + { + if (!is_close(READOUT.read(), READOUT2.read(), 1e-7)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected slightly different currents (different noise seed)!" << std::endl; + std::cout << "Is the noise ON?" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + } +} + +void Detector_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN; + sc_signal<double> READOUT, READOUT2; + + Detector uut("uut", 1, 100e-12, false); + uut.p_in(IN); + uut.p_readout(READOUT); + + Detector uut2("uut2", 1, 100e-12, false); + uut2.p_in(IN); + uut2.p_readout(READOUT2); + + Detector_tb tb("tb"); + tb.IN(IN); + tb.READOUT(READOUT); + tb.READOUT2(READOUT2); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "detector_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + Probe probe_detector("probe_detector",specsGlobalConfig.default_trace_file); + probe_detector.p_in(IN); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // custom traces should come after prepareSimulation !! + sc_trace(specsGlobalConfig.default_trace_file, READOUT, "READOUT"); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/detector_tb.h b/src/tb/detector_tb.h new file mode 100644 index 0000000..39b05dc --- /dev/null +++ b/src/tb/detector_tb.h @@ -0,0 +1,30 @@ +#pragma once + +#include <detector.h> +#include <optical_signal.h> +#include <systemc.h> +#include <probe.h> +#include <specs.h> +#include <waveguide.h> + +SC_MODULE(Detector_tb) +{ +public: + spx::oa_port_out_type IN; + sc_in<double> READOUT, READOUT2; + + void run_1(); + void monitor(); + SC_CTOR(Detector_tb) + { + SC_HAS_PROCESS(Detector_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << READOUT << READOUT2; + } +}; + +void Detector_tb_run(); + diff --git a/src/tb/directional_coupler_tb.cpp b/src/tb/directional_coupler_tb.cpp new file mode 100644 index 0000000..1954414 --- /dev/null +++ b/src/tb/directional_coupler_tb.cpp @@ -0,0 +1,150 @@ +#include <ctime> +#include <iomanip> +#include <tb/directional_coupler_tb.h> + +#include "general_utils.h" +#include "generic_2x2_coupler.h" + +void DirectionalCoupler_tb::run_1() +{ + IN1->write(OpticalSignal(1.0, 1550e-9)); + wait(100, SC_MS); + IN2->write(OpticalSignal(1.0, 1550e-9)); + wait(100, SC_MS); + + while (true) { wait(); } +} + +void DirectionalCoupler_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN1: " << IN1->read() << std::endl + << "\tIN2: " << IN2->read() << std::endl + << "\tOUT1: " << OUT1->read() << std::endl + << "\tOUT2: " << OUT2->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + + if(event_counter == 2) + { + if (is_close(norm(OUT1->read().m_field), 0.05, 1e-4) && is_close(norm(OUT2->read().m_field), 0.45, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.05W/0.45 as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + if (is_close(arg(OUT2->read().m_field), 1.5708, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected pi/2 as phase in OUT2!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 4) + { + if (is_close(arg(OUT1->read().m_field), 1.2490, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 1.2490 as phase in OUT1!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } +} + +void DirectionalCoupler_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + + spx::oa_signal_type IN1, IN2, IN3, IN4, OUT1, OUT2; + spx::oa_signal_type TERM_r, TERM_w; + + // Unidirectional variant + // DirectionalCoupler uut("uut", 0.5, 0); + // uut.m_dc_through_coupling_power = 0.1; + // uut.m_dc_loss = 3.0103; + + // uut.p_in1(IN1); + // uut.p_in2(IN2); + // uut.p_out1(OUT1); + // uut.p_out2(OUT2); + + // Bidirectional variant + DirectionalCouplerBi uut("uut", 0.5, 0); + uut.m_dc_through_coupling_power = 0.1; + uut.m_dc_loss = 3.0103; + + uut.p0_in(IN1); + uut.p0_out(TERM_w); + uut.p1_in(IN2); + uut.p1_out(TERM_w); + uut.p2_in(TERM_r); + uut.p2_out(OUT1); + uut.p3_in(TERM_r); + uut.p3_out(OUT2); + + // Generic bidirectional variant + // Generic2x2Coupler uut("uut", 1-0.1, 3.0103); + // uut.ports_in[0]->bind(IN1); + // uut.ports_in[1]->bind(IN2); + // uut.ports_in[2]->bind(TERM_r); + // uut.ports_in[3]->bind(TERM_r); + // uut.ports_out[0]->bind(TERM_w); + // uut.ports_out[1]->bind(TERM_w); + // uut.ports_out[2]->bind(OUT1); + // uut.ports_out[3]->bind(OUT2); + + DirectionalCoupler_tb tb("tb"); + tb.IN1(IN1); + tb.IN2(IN2); + tb.OUT1(OUT1); + tb.OUT2(OUT2); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "directional_coupler_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + Probe probe_dc_1("probe_dc_1",specsGlobalConfig.default_trace_file); + probe_dc_1.p_in(OUT1); + Probe probe_dc_2("probe_dc_2",specsGlobalConfig.default_trace_file); + probe_dc_2.p_in(OUT2); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/directional_coupler_tb.h b/src/tb/directional_coupler_tb.h new file mode 100644 index 0000000..c137b31 --- /dev/null +++ b/src/tb/directional_coupler_tb.h @@ -0,0 +1,31 @@ +#pragma once + +#include <directional_coupler.h> +#include <optical_signal.h> +#include <systemc.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(DirectionalCoupler_tb) +{ +public: + spx::oa_port_out_type IN1; + spx::oa_port_out_type IN2; + spx::oa_port_in_type OUT1; + spx::oa_port_in_type OUT2; + + void run_1(); + void monitor(); + SC_CTOR(DirectionalCoupler_tb) + { + SC_HAS_PROCESS(DirectionalCoupler_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN1 << IN2 << OUT1 << OUT2; + } +}; + +void DirectionalCoupler_tb_run(); + diff --git a/src/tb/freqsweep_tb.cpp b/src/tb/freqsweep_tb.cpp new file mode 100644 index 0000000..f44aa34 --- /dev/null +++ b/src/tb/freqsweep_tb.cpp @@ -0,0 +1,213 @@ +#include <ctime> +#include <iomanip> +#include <tb/freqsweep_tb.h> + +#include <cstdlib> +#include <unistd.h> + +#include "time_monitor.h" + +#include "general_utils.h" + +/* ----------------------------------------------------------------------------- * + This testbench is called freqsweep because it is capable of this + type of simulation, but it is also possible to set it as a time-domain + simulation depending on the mode chosen when calling SPECS. Example: + + specs -t ac_add_drop -m fd -> will perform the frequency sweep + specs -t ac_add_drop -m td -> will perform the time domain simulation + +/ ----------------------------------------------------------------------------- */ + +void freqsweep_tb::run_1() +{ + if (specsGlobalConfig.simulation_mode == OpticalOutputPortMode::FREQUENCY_DOMAIN) + { + auto lambda_center = 1550.3e-9; + auto lambda_span = 1e-9; + auto dlambda = 0.002e-9; + auto lambda_min = lambda_center - lambda_span/2; + auto lambda_max = lambda_center + lambda_span/2; + // lambda_min = 1550.250e-9; + // lambda_max = 1550.303e-9; + //wait(lambda_min * 1e9, SC_SEC); + + wait(SC_ZERO_TIME); + cout << "----------------------------" <<endl; + cout << "Starting sweep" << endl; + for (auto lambda = lambda_min; lambda < lambda_max + dlambda; lambda += dlambda) + { + cout << setprecision(7) << lambda * 1e9 << "nm" << endl; + IN->write(OpticalSignal(1, lambda)); + wait(dlambda, SC_SEC); + } + } else { + for (int i = 0; i < 1; ++i) + { + auto lambda = 1550.302e-9; + IN->write(OpticalSignal(1,lambda)); + wait(1, SC_NS); + IN->write(OpticalSignal(0, lambda)); + wait(1, SC_NS); + } + } + + while (true) { wait(); } +} + +void freqsweep_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + while(true) + { + wait(); + continue; + } +} + +void freqsweep_tb_run_add_drop() +{ + specsGlobalConfig.applyEngineResolution(); + //specsGlobalConfig.oop_configs[0]->m_mode = OpticalOutputPortMode::EVENT_DRIVEN; + //specsGlobalConfig.oop_configs[0]->m_mode = OpticalOutputPortMode::FREQUENCY_DOMAIN; + + // First test for the LBR paper to DAC + // Single ring resonator, compare the response to theoretical + // Also compare time of simulation wrt photontorch for same ring. + + // Characteristics: + // Add-drop ring + // Internal wg length (cm): + // Internal wg loss (dB/cm): + // Internal wg neff: + // Internal wg ng: + // DC ratio : 0.15 cross, 0.85 through + // DC coupling loss (dB) : 0 + // Total length for resonance: lambda/2neff + double neff = 1.0; + double loss_db_cm = 1.0; + double coupling_through = 0.85; + + spx::oa_signal_type IN, T_OUT, X_OUT, X_TERM; + spx::oa_signal_type INNER_RING[4]; + + freqsweep_tb tb1("tb1"); + tb1.IN(IN); + tb1.OUT(X_OUT); + + DirectionalCoupler dc1("dc1", coupling_through, 0); + dc1.p_in1(INNER_RING[0]); + dc1.p_out1(INNER_RING[1]); + dc1.p_in2(IN); + dc1.p_out2(T_OUT); + + Waveguide wg1("wg1", 100.0*1550.0e-6/(2*neff), loss_db_cm, neff, neff); + wg1.p_in(INNER_RING[1]); + wg1.p_out(INNER_RING[2]); + + Waveguide wg2("wg2", 100.0*1550.0e-6/(2*neff), loss_db_cm, neff, neff); + wg2.p_in(INNER_RING[3]); + wg2.p_out(INNER_RING[0]); + + DirectionalCoupler dc2("dc2", coupling_through, 0); + dc2.p_in1(X_TERM); + dc2.p_out1(X_OUT); + dc2.p_in2(INNER_RING[2]); + dc2.p_out2(INNER_RING[3]); + + Probe pthrough("ptrough"); + pthrough.p_in(T_OUT); + + Probe pcross("pcross"); + pcross.p_in(X_OUT); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "freqsweep_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + // could have forced frequency domain like this, but taking command line input instead + // specsGlobalConfig.simulation_mode = OpticalOutputPortMode::FREQUENCY_DOMAIN; + specsGlobalConfig.trace_all_optical_nets = 0; + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} + +// void freqsweep_tb_run_crow() +// { +// if (specsGlobalConfig.oop_configs[0]->m_mode == OpticalOutputPortMode::FREQUENCY_DOMAIN) +// specsGlobalConfig.engine_timescale = SPECSConfig::ONE_FS; + +// specsGlobalConfig.applyEngineResolution(); + +// sc_signal<OpticalSignal> IN("IN"), T_OUT("T_OUT"), X_OUT("X_OUT"), ADD("ADD"); + +// freqsweep_tb tb1("tb1"); +// tb1.IN(IN); +// tb1.IN(IN); +// tb1.OUT(T_OUT); + +// // pid_t pid = fork(); +// CROW *pc; +// // if(pid) +// pc = new CROW("crow", nrings); +// // else +// // pc = new CROW("crow", 5); +// pc->p_in(IN); +// pc->p_add(ADD); +// pc->p_out_t(T_OUT); +// pc->p_out_d(X_OUT); + +// Probe pthrough("ptrough"); +// pthrough.p_in(T_OUT); +// // +// Probe pcross("pcross"); +// pcross.p_in(X_OUT); + +// // shared_ptr<TimeMonitor> tm; +// // if (specsGlobalConfig.oop_configs[0]->m_mode == OpticalOutputPortMode::FREQUENCY_DOMAIN) +// // tm = make_shared<TimeMonitor>("TM", 0, 0.01); +// // else +// // tm = make_shared<TimeMonitor>("TM", 1e-14, 0.5); + +// // // Open Trace file +// // sc_trace_file *Tf; +// // std::time_t now = std::time(nullptr); +// // char mbstr[100]; +// // std::strftime(mbstr, sizeof(mbstr), "%F-%H-%M-%S-", std::localtime(&now)); +// // +// // std::string trace_filename = "traces/"; +// // //trace_filename += mbstr; +// // trace_filename += "freqsweep_tb"; + +// // auto engineTime = std::pow(10, 15+specsGlobalConfig.engine_timescale); +// // Tf = sc_create_vcd_trace_file(trace_filename.c_str()); +// // ((sc_trace_file *)Tf)->set_time_unit(engineTime, SC_FS); +// // sc_trace(Tf, IN, "IN"); +// // sc_trace(Tf, X_OUT, "X_OUT"); +// // sc_trace(Tf, T_OUT, "T_OUT"); + +// if (specsGlobalConfig.trace_filename.empty()) +// specsGlobalConfig.trace_filename = "traces/crow_tb"; + +// // Start simulation +// specsGlobalConfig.prepareSimulation(); +// sc_start(); // run until sc_stop() + +// std::cout << std::endl << std::endl; +// std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + +// sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +// } diff --git a/src/tb/freqsweep_tb.h b/src/tb/freqsweep_tb.h new file mode 100644 index 0000000..d5a328c --- /dev/null +++ b/src/tb/freqsweep_tb.h @@ -0,0 +1,33 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <waveguide.h> +#include <directional_coupler.h> +#include <probe.h> +#include <crow.h> +#include <specs.h> + +SC_MODULE(freqsweep_tb) +{ +public: + spx::oa_port_out_type IN; + spx::oa_port_in_type OUT; + + void run_1(); + void monitor(); + SC_CTOR(freqsweep_tb) + { + SC_HAS_PROCESS(freqsweep_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT; + } +}; + +//void freqsweep_tb_run(); +void freqsweep_tb_run_add_drop(); +void freqsweep_tb_run_crow(); + diff --git a/src/tb/lambda_tb.cpp b/src/tb/lambda_tb.cpp new file mode 100644 index 0000000..96a5084 --- /dev/null +++ b/src/tb/lambda_tb.cpp @@ -0,0 +1,102 @@ +#include <ctime> +#include <iomanip> +#include <tb/lambda_tb.h> + +#include "general_utils.h" +#include "devices/generic_waveguide.h" + +void lambda_tb::run_1() +{ + // IN1.write(OpticalSignal(sqrt(2.0), 1550e-9)); + // wait(0, SC_FS); + // IN2.write(OpticalSignal(sqrt(2.0), 1660e-9)); + // while(true) {wait();} + wait(1,SC_SEC); + sc_stop(); +} + +void lambda_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 0; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tOUT: " << OUT.read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + } + +} + +void lambda_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type I1, I2, YOUT, WGOUT; + spx::oa_signal_type DCO1, DCO2, DCI1, DCI2; + + CWSource cw1("cw1"); + cw1.setWavelength(1550e-9); + cw1.setPower(2); + cw1.enable.write(SC_LOGIC_1); + cw1.p_out(I1); + + CWSource cw2("cw2"); + cw2.setWavelength(1660e-9); + cw2.setPower(2); + cw2.enable.write(SC_LOGIC_1); + cw2.p_out(I2); + + Merger merg1("merg1"); + merg1.p_in1(I1); + merg1.p_in2(I2); + merg1.p_out(YOUT); + + Waveguide wg1("wg1", 0.1, 0, 1, 1); + wg1.m_attenuation_dB_cm = 0; + wg1.p_in(YOUT); + wg1.p_out(DCI1); + + DirectionalCoupler dc1("dc1"); + dc1.p_in1(DCI1); + dc1.p_in2(DCI2); + dc1.p_out1(DCO1); + dc1.p_out2(DCO2); + + Waveguide wg2("wg2", 100*1001*1550e-9/(2), 0, 1, 1); + wg2.p_in(DCO2); + wg2.p_out(DCI2); + + lambda_tb tb("tb"); + tb.OUT(DCO1); + // tb.IN1(I1); + // tb.IN2(I2); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "lambda_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + MLambdaProbe probe("probe_lambda", {1550e-9, 1650e-9, 1660e-9}); + // Probe probe("test_probe",specsGlobalConfig.default_trace_file); + probe.p_in(DCO1); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/lambda_tb.h b/src/tb/lambda_tb.h new file mode 100644 index 0000000..a5dc203 --- /dev/null +++ b/src/tb/lambda_tb.h @@ -0,0 +1,31 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <waveguide.h> +#include <merger.h> +#include <directional_coupler.h> +#include <cw_source.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(lambda_tb) +{ +public: + sc_in<OpticalSignal> OUT; + // sc_out<OpticalSignal> IN1, IN2; + + void run_1(); + void monitor(); + SC_CTOR(lambda_tb) + { + SC_HAS_PROCESS(lambda_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << OUT; + } +}; + +void lambda_tb_run(); diff --git a/src/tb/merger_tb.cpp b/src/tb/merger_tb.cpp new file mode 100644 index 0000000..1c86643 --- /dev/null +++ b/src/tb/merger_tb.cpp @@ -0,0 +1,126 @@ +#include <ctime> +#include <iomanip> +#include <tb/merger_tb.h> + +#include "general_utils.h" + +void Merger_tb::run_1() +{ + IN1->write(OpticalSignal(1.0, 1550e-9)); + wait(100, SC_MS); + IN2->write(OpticalSignal(1.0, 1550e-9)); + wait(100, SC_MS); + IN1->write(OpticalSignal(sqrt(2.0), 1550e-9)); + IN2->write(OpticalSignal(sqrt(2.0), 1550e-9)); + wait(100, SC_MS); +} + +void Merger_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 4; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN1: " << IN1->read() << std::endl + << "\tIN2: " << IN2->read() << std::endl + << "\tOUT: " << OUT->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + if(event_counter == 2) + { + if (is_close(norm(OUT->read().m_field), 0.5, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.5W as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + if (is_close(arg(OUT->read().m_field), 0, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0 as output phase!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 4) + { + if (is_close(norm(OUT->read().m_field), 2, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 2W as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 6) + { + if (is_close(norm(OUT->read().m_field), 4, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 2W as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } +} + +void Merger_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN1, IN2, OUT; + + Merger uut("uut", 3.0103); + uut.m_attenuation_dB = 0; + uut.p_in1(IN1); + uut.p_in2(IN2); + uut.p_out(OUT); + + Merger_tb tb("tb"); + tb.IN1(IN1); + tb.IN2(IN2); + tb.OUT(OUT); + + // Open Trace file + // sc_trace_file *Tf; + std::string trace_filename = "traces/"; + trace_filename += "merger_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + Probe probe_merger("probe_merger",specsGlobalConfig.default_trace_file); + probe_merger.p_in(OUT); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/merger_tb.h b/src/tb/merger_tb.h new file mode 100644 index 0000000..a71fd2a --- /dev/null +++ b/src/tb/merger_tb.h @@ -0,0 +1,30 @@ +#pragma once + +#include <merger.h> +#include <optical_signal.h> +#include <systemc.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(Merger_tb) +{ +public: + spx::oa_port_out_type IN1; + spx::oa_port_out_type IN2; + spx::oa_port_in_type OUT; + + void run_1(); + void monitor(); + SC_CTOR(Merger_tb) + { + SC_HAS_PROCESS(Merger_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN1 << IN2 << OUT; + } +}; + +void Merger_tb_run(); + diff --git a/src/tb/mesh_tb.cpp b/src/tb/mesh_tb.cpp new file mode 100644 index 0000000..9effd11 --- /dev/null +++ b/src/tb/mesh_tb.cpp @@ -0,0 +1,130 @@ +#include <ctime> +#include <iomanip> +#include <tb/mesh_tb.h> + +#include "general_utils.h" + +void mesh_tb::run_1() +{ + IN->write(OpticalSignal(sqrt(1.0), 1550e-9)); + vtheta.write(M_PI); + vphi.write(1); + wait(1, SC_NS); + // vtheta.write(M_PI_2); + // wait(1, SC_NS); + // vtheta.write(M_PI); + // wait(1, SC_NS); + // vphi.write(1); + // wait(1, SC_NS); + + while (true) { wait(); } +} + +void mesh_tb::monitor() +{ + while(true) + { + wait(); + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tPHI: " << vphi.read() << std::endl + << "\tTHETA: " << vtheta.read() << std::endl + << "\tOUT1: " << OUT1->read() << std::endl + << "\tOUT2: " << OUT2->read() << std::endl + << "\tOUT3: " << OUT3->read() << std::endl + << "\tOUT4: " << OUT4->read() << std::endl + << "\tOUT5: " << OUT5->read() << std::endl; + } + +} + +void mesh_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type SIG, ZERO, OUT1, OUT2, OUT3, OUT4, OUT5; + sc_signal<double> vphi,vtheta,e_zero; + + Clements mesh1("mesh1", 5, 1, 0, 0, 0, 0, 1); + mesh1.p_in[0]->bind(SIG); + mesh1.p_in[1]->bind(SIG); + mesh1.p_in[2]->bind(SIG); + mesh1.p_in[3]->bind(SIG); + mesh1.p_in[4]->bind(SIG); + mesh1.p_out[0]->bind(OUT1); + mesh1.p_out[1]->bind(OUT2); + mesh1.p_out[2]->bind(OUT3); + mesh1.p_out[3]->bind(OUT4); + mesh1.p_out[4]->bind(OUT5); + + mesh1.p_vphi[0]->bind(e_zero); + mesh1.p_vtheta[0]->bind(vtheta); + + mesh1.p_vphi[1]->bind(e_zero); + mesh1.p_vtheta[1]->bind(e_zero); + + mesh1.p_vphi[2]->bind(e_zero); + mesh1.p_vtheta[2]->bind(vtheta); + + mesh1.p_vphi[3]->bind(e_zero); + mesh1.p_vtheta[3]->bind(e_zero); + + mesh1.p_vphi[4]->bind(e_zero); + mesh1.p_vtheta[4]->bind(e_zero); + + mesh1.p_vphi[5]->bind(e_zero); + mesh1.p_vtheta[5]->bind(e_zero); + + mesh1.p_vphi[6]->bind(e_zero); + mesh1.p_vtheta[6]->bind(e_zero); + + mesh1.p_vphi[7]->bind(e_zero); + mesh1.p_vtheta[7]->bind(e_zero); + + mesh1.p_vphi[8]->bind(e_zero); + mesh1.p_vtheta[8]->bind(e_zero); + + mesh1.p_vphi[9]->bind(e_zero); + mesh1.p_vtheta[9]->bind(e_zero); + + mesh1.init(); + + mesh_tb tb("tb"); + tb.IN(SIG); + tb.OUT1(OUT1); + tb.OUT2(OUT2); + tb.OUT3(OUT3); + tb.OUT4(OUT4); + tb.OUT5(OUT5); + tb.vphi(vphi); + tb.vtheta(vtheta); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "mesh_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + + Probe probe_mzi_1("probe_mzi_1",specsGlobalConfig.default_trace_file); + probe_mzi_1.p_in(OUT1); + Probe probe_mzi_2("probe_mzi_2",specsGlobalConfig.default_trace_file); + probe_mzi_2.p_in(OUT2); + Probe probe_in("probe_in",specsGlobalConfig.default_trace_file); + probe_in.p_in(SIG); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/mesh_tb.h b/src/tb/mesh_tb.h new file mode 100644 index 0000000..1e7e3dd --- /dev/null +++ b/src/tb/mesh_tb.h @@ -0,0 +1,29 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <probe.h> +#include <specs.h> +#include <clements.h> + +SC_MODULE(mesh_tb) +{ +public: + spx::oa_port_out_type IN; + spx::oa_port_in_type OUT1, OUT2, OUT3, OUT4, OUT5; + sc_out<double> vphi,vtheta; + + void run_1(); + void monitor(); + SC_CTOR(mesh_tb) + { + SC_HAS_PROCESS(mesh_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT1 << OUT2 << OUT3 << OUT4 << OUT5 << vphi << vtheta; + } +}; + +void mesh_tb_run(); diff --git a/src/tb/mzi_tb.cpp b/src/tb/mzi_tb.cpp new file mode 100644 index 0000000..2b9905a --- /dev/null +++ b/src/tb/mzi_tb.cpp @@ -0,0 +1,86 @@ +#include <ctime> +#include <iomanip> +#include <tb/mzi_tb.h> + +#include "general_utils.h" + +void mzi_tb::run_1() +{ + IN->write(OpticalSignal(sqrt(1.0), 1550e-9)); + wait(1, SC_NS); + vtheta.write(M_PI_2); + wait(1, SC_NS); + vtheta.write(M_PI); + wait(1, SC_NS); + vphi.write(1); + wait(1, SC_NS); + + while (true) { wait(); } +} + +void mzi_tb::monitor() +{ + while(true) + { + wait(); + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tPHI: " << vphi.read() << std::endl + << "\tTHETA: " << vtheta.read() << std::endl + << "\tOUT1: " << OUT1->read() << std::endl + << "\tOUT2: " << OUT2->read() << std::endl; + } + +} + +void MZI_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN1, IN2, OUT1, OUT2; + spx::ea_signal_type vphi,vtheta; + + MZI mzi1("mzi1",0,0,0,0,0,1); + mzi1.p_in1(IN1); + mzi1.p_in2(IN2); + mzi1.p_out1(OUT1); + mzi1.p_out2(OUT2); + mzi1.p_vphi(vphi); + mzi1.p_vtheta(vtheta); + + mzi_tb tb("tb"); + tb.IN(IN1); + tb.OUT1(OUT1); + tb.OUT2(OUT2); + tb.vphi(vphi); + tb.vtheta(vtheta); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "mzi_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + + Probe probe_mzi_1("probe_mzi_1",specsGlobalConfig.default_trace_file); + probe_mzi_1.p_in(OUT1); + Probe probe_mzi_2("probe_mzi_2",specsGlobalConfig.default_trace_file); + probe_mzi_2.p_in(OUT2); + Probe probe_in("probe_in",specsGlobalConfig.default_trace_file); + probe_in.p_in(IN1); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/mzi_tb.h b/src/tb/mzi_tb.h new file mode 100644 index 0000000..16ed624 --- /dev/null +++ b/src/tb/mzi_tb.h @@ -0,0 +1,31 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <waveguide.h> +#include <directional_coupler.h> +#include <mzi.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(mzi_tb) +{ +public: + spx::oa_port_out_type IN; + spx::oa_port_in_type OUT1, OUT2; + sc_out<double> vphi,vtheta; + + void run_1(); + void monitor(); + SC_CTOR(mzi_tb) + { + SC_HAS_PROCESS(mzi_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT1 << OUT2 << vphi << vtheta; + } +}; + +void MZI_tb_run(); diff --git a/src/tb/pcm_device_tb.cpp b/src/tb/pcm_device_tb.cpp new file mode 100644 index 0000000..b279e6c --- /dev/null +++ b/src/tb/pcm_device_tb.cpp @@ -0,0 +1,129 @@ +#include <ctime> +#include <iomanip> +#include <tb/pcm_device_tb.h> + +#include "general_utils.h" + +void PCMElement_tb::run_1() +{ + IN->write(OpticalSignal(sqrt(1.0e-3), 1.55e-6)); + wait(10, SC_MS); + IN->write(OpticalSignal(sqrt(2*1e-3), 1.55e-6)); // to 2W + wait(10, SC_MS); + IN->write(OpticalSignal(0, 1.55e-6)); + wait(10, SC_MS); + IN->write(OpticalSignal(sqrt(1.0e-3), 1.55e-6)); + wait(10, SC_MS); + IN->write(OpticalSignal(sqrt(2*1.0e-3), 1.55e-6)); + wait(10, SC_MS); + IN->write(OpticalSignal(0, 1.55e-6)); + wait(10, SC_MS); + IN->write(OpticalSignal(sqrt(1.0e-3), 1.55e-6)); + + + while (true) { wait(); } +} + +void PCMElement_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tOUT: " << OUT->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + + if(event_counter == 2) + { + if (is_close(norm(OUT->read().m_field), 0.000850, 1e-8)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.850mW as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 8) + { + if (is_close(norm(OUT->read().m_field), 0.000854758, 1e-8)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.854mW as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 14) + { + if (is_close(norm(OUT->read().m_field), 0.000859495, 1e-8)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.859mW as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } +} + +void PCMElement_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN, OUT; + + PCMElement pcm("pcm", 25e-6, 63, 0); + pcm.p_in(IN); + pcm.p_out(OUT); + + PCMElement_tb tb("tb"); + tb.IN(IN); + tb.OUT(OUT); + + // Open Trace file + + std::string trace_filename = "traces/"; + trace_filename += "pcm_device_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + Probe probe_in("in",specsGlobalConfig.default_trace_file); + probe_in.p_in(IN); + + Probe probe_out("out",specsGlobalConfig.default_trace_file); + probe_out.p_in(OUT); + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // extra traces should come after prepareSimulation + sc_trace(specsGlobalConfig.default_trace_file, pcm.m_state, "STATE"); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/pcm_device_tb.h b/src/tb/pcm_device_tb.h new file mode 100644 index 0000000..a9b7195 --- /dev/null +++ b/src/tb/pcm_device_tb.h @@ -0,0 +1,29 @@ +#pragma once + +#include <systemc.h> + +#include <optical_signal.h> +#include <pcm_device.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(PCMElement_tb) +{ +public: + spx::oa_port_out_type IN; + spx::oa_port_in_type OUT; + + void run_1(); + void monitor(); + SC_CTOR(PCMElement_tb) + { + SC_HAS_PROCESS(PCMElement_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT; + } +}; + +void PCMElement_tb_run(); diff --git a/src/tb/phase_shifter_tb.cpp b/src/tb/phase_shifter_tb.cpp new file mode 100644 index 0000000..5369e7c --- /dev/null +++ b/src/tb/phase_shifter_tb.cpp @@ -0,0 +1,129 @@ +#include <ctime> +#include <iomanip> +#include <tb/phase_shifter_tb.h> + +#include "general_utils.h" +#include "specs.h" + +void ps_tb::run_1() +{ + V_PS.write(1.0); + wait(SC_ZERO_TIME); + IN1->write(OpticalSignal(sqrt(1.0), 1550e-9)); + IN2->write(OpticalSignal(sqrt(1.0), 1660e-9)); + wait(100,SC_MS); + V_PS.write(2.0); + wait(100, SC_MS); + + while (true) { wait(); } +} + +void ps_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN1: " << IN1->read() << std::endl + << "\tIN2: " << IN2->read() << std::endl + << "\tOUT: " << OUT->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + + if(event_counter == 2) + { + if (is_close(abs(OUT->read().m_field), 0.630210, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.630210W as output field!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 4) + { + if (is_close(arg(OUT->read().m_field), 2, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 2 rad as output phase!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 5) + { + if (is_close(arg(OUT->read().m_field), 2, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 2 as output phase!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + +} + +void ps_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN1, IN2, OUT, YOUT; + spx::ea_signal_type V_PS; + + Merger merg1("merg1"); + merg1.p_in1(IN1); + merg1.p_in2(IN2); + merg1.p_out(YOUT); + + PhaseShifter ps1("ps1", 1); + ps1.p_in(YOUT); + ps1.p_vin(V_PS); + ps1.p_out(OUT); + + // Connect testbench to uut + ps_tb tb("tb"); + tb.IN1(IN1); + tb.IN2(IN2); + tb.OUT(OUT); + tb.V_PS(V_PS); + + // Attach probes + MLambdaProbe probe_out("out", {1550e-9, 1660e-9}); + probe_out.p_in(OUT); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "ps_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/phase_shifter_tb.h b/src/tb/phase_shifter_tb.h new file mode 100644 index 0000000..a59538d --- /dev/null +++ b/src/tb/phase_shifter_tb.h @@ -0,0 +1,32 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <waveguide.h> +#include <phaseshifter.h> +#include <merger.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(ps_tb) +{ +public: + spx::oa_port_out_type IN1; + spx::oa_port_out_type IN2; + sc_out<double> V_PS; + spx::oa_port_in_type OUT; + + void run_1(); + void monitor(); + SC_CTOR(ps_tb) + { + SC_HAS_PROCESS(ps_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN1 << IN2 << OUT; + } +}; + +void ps_tb_run(); diff --git a/src/tb/ring_tb.cpp b/src/tb/ring_tb.cpp new file mode 100644 index 0000000..cc3aaf2 --- /dev/null +++ b/src/tb/ring_tb.cpp @@ -0,0 +1,85 @@ +#include <ctime> +#include <iomanip> +#include <tb/ring_tb.h> + +#include "general_utils.h" + +void ring_tb::run_1() +{ + IN.write(OpticalSignal(sqrt(1.0), 1550e-9)); + wait(10, SC_NS); + IN.write(OpticalSignal(0, 1550e-9)); + wait(10, SC_NS); + + IN.write(OpticalSignal(sqrt(1.0), 1550e-9)); + wait(10, SC_NS); + IN.write(OpticalSignal(0, 1550e-9)); + wait(10, SC_NS); + + while(true) + { + wait(); + } +} + +void ring_tb::monitor() +{ + while(true) + { + wait(); + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN.read() << std::endl + << "\tOUT: " << OUT.read() << std::endl; + } + +} + +void Ring_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + double neff = 1.0; + double loss_db_cm = 0; + double coupling_through = 0.85; + + spx::oa_signal_type IN, OUT; + spx::oa_signal_type RING1, RING2; + + DirectionalCoupler dc1("dc1", coupling_through, 0); + dc1.p_in1(IN); + dc1.p_out1(OUT); + dc1.p_in2(RING1); + dc1.p_out2(RING2); + + Waveguide wg1("wg1", 1*100.0*1550.0e-6/(2*neff), loss_db_cm, neff, neff); + wg1.p_in(RING2); + wg1.p_out(RING1); + + ring_tb tb("tb"); + tb.IN(IN); + tb.OUT(OUT); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "ring_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + Probe probe_ring("probe_ring",specsGlobalConfig.default_trace_file); + probe_ring.p_in(OUT); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/ring_tb.h b/src/tb/ring_tb.h new file mode 100644 index 0000000..b995513 --- /dev/null +++ b/src/tb/ring_tb.h @@ -0,0 +1,29 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <waveguide.h> +#include <directional_coupler.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(ring_tb) +{ +public: + sc_out<OpticalSignal> IN; + sc_in<OpticalSignal> OUT; + + void run_1(); + void monitor(); + SC_CTOR(ring_tb) + { + SC_HAS_PROCESS(ring_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT; + } +}; + +void Ring_tb_run(); diff --git a/src/tb/splitter_tb.cpp b/src/tb/splitter_tb.cpp new file mode 100644 index 0000000..eeb3420 --- /dev/null +++ b/src/tb/splitter_tb.cpp @@ -0,0 +1,123 @@ +#include <ctime> +#include <iomanip> +#include <tb/splitter_tb.h> + +#include "general_utils.h" + +void Splitter_tb::run_1() +{ + IN->write(OpticalSignal(sqrt(1.0), 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(-sqrt(1.0), 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(sqrt(2.0), 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(-sqrt(2.0), 1550e-9)); + wait(10, SC_PS); + IN->write(OpticalSignal(sqrt(3.0), 1550e-9)); + wait(100, SC_MS); + + wait(OUT1->value_changed_event()); + wait(1, SC_SEC); + sc_stop(); +} + +void Splitter_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tOUT1: " << OUT1->read() << std::endl + << "\tOUT2: " << OUT2->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + + if(event_counter == 10) + { + if (is_close(norm(OUT1->read().m_field), 0.75, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.75W as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + if (is_close(norm(OUT1->read().m_field), norm(OUT2->read().m_field), 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected same power in both ends!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + if (is_close(arg(OUT1->read().m_field), 0, 1e-4) && is_close(arg(OUT2->read().m_field), 0, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected zero phase in both ends!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } +} + +void Splitter_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN, OUT1, OUT2; + + Splitter uut("uut"); + uut.m_attenuation_dB = 3.0103; + uut.p_in(IN); + uut.p_out1(OUT1); + uut.p_out2(OUT2); + + Splitter_tb tb("tb"); + tb.IN(IN); + tb.OUT1(OUT1); + tb.OUT2(OUT2); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "splitter_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + Probe probe_splitter_1("probe_splitter_1",specsGlobalConfig.default_trace_file); + probe_splitter_1.p_in(OUT1); + + Probe probe_splitter_2("probe_splitter_2",specsGlobalConfig.default_trace_file); + probe_splitter_2.p_in(OUT2); + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/splitter_tb.h b/src/tb/splitter_tb.h new file mode 100644 index 0000000..68d2a8d --- /dev/null +++ b/src/tb/splitter_tb.h @@ -0,0 +1,29 @@ +#pragma once + +#include <optical_signal.h> +#include <splitter.h> +#include <systemc.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(Splitter_tb) +{ +public: + spx::oa_port_out_type IN; + spx::oa_port_in_type OUT1; + spx::oa_port_in_type OUT2; + + void run_1(); + void monitor(); + SC_CTOR(Splitter_tb) + { + SC_HAS_PROCESS(Splitter_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT1 << OUT2; + } +}; + +void Splitter_tb_run(); diff --git a/src/tb/wg_tb.cpp b/src/tb/wg_tb.cpp new file mode 100644 index 0000000..7ccebf5 --- /dev/null +++ b/src/tb/wg_tb.cpp @@ -0,0 +1,143 @@ +#include <ctime> +#include <iomanip> +#include <tb/wg_tb.h> + +#include "general_utils.h" +#include "devices/generic_waveguide.h" +#include "specs.h" + +void wg_tb::run_1() +{ + IN->write(OpticalSignal(sqrt(1.0), 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(0, 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(sqrt(2.0), 1550e-9)); + wait(100, SC_MS); + IN->write(OpticalSignal(0, 1550e-9)); + wait(10, SC_PS); + IN->write(OpticalSignal(sqrt(3.0), 1550e-9)); + wait(100, SC_MS); + + while (true) { wait(); } +} + +void wg_tb::monitor() +{ + unsigned int event_counter = 0; + unsigned int success_counter = 0; + const unsigned int test_number = 3; + while(true) + { + wait(); + event_counter++; + std::cout << sc_time_stamp() << ":" << std::endl + << "\tIN: " << IN->read() << std::endl + << "\tOUT: " << OUT->read() << std::endl + << "\tCOUNT: " << event_counter << std::endl; + + if(event_counter == 2) + { + if (is_close(norm(OUT->read().m_field), 0.5, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 0.5W as output power!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 6) + { + if (is_close(arg(OUT->read().m_field), -2.4322, 1e-4)) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected -2.4322 rad as output phase!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + if(event_counter == 10) + { + if (is_close(norm(OUT->read().m_field), 1.5, 1e-4) && (is_close(arg(OUT->read().m_field), -2.4322, 1e-4))) + success_counter++; + else + { + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Failure!" << std::endl; + std::cout << "Expected 1.5W as output power and -2.4322 as output phase!" << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + + std::cout << "-----------------/! \\---------------" << std::endl; + std::cout << "Test finished!" << std::endl; + std::cout << "Success rate: " << success_counter << "/" << test_number << std::endl; + std::cout << "-----------------/! \\---------------" << std::endl; + } + } + +} + +void wg_tb_run() +{ + // Apply SPECS resolution before creating any device + specsGlobalConfig.applyEngineResolution(); + + spx::oa_signal_type IN("sig_in"), OUT("sig_out"); + spx::oa_signal_type TERM_r, TERM_w; + + // Unidirectional variant + // Waveguide uut("uut", 1, 0, 1, 1); + // uut.m_attenuation_dB_cm = 3.0103; + // uut.p_in(IN); + // uut.p_out(OUT); + + // Bidirectional variant + WaveguideBi uut("uut", 1, 0, 1, 1); + uut.m_attenuation_dB_cm = 3.0103; + uut.p0_in(IN); + uut.p0_out(TERM_w); + uut.p1_in(TERM_r); + uut.p1_out(OUT); + + // GenericWaveguide uut("uut",3.0103*100,1,1,0.01); + // uut.ports_in[0]->bind(IN); + // uut.ports_in[1]->bind(TERM_r); + // uut.ports_out[0]->bind(TERM_w); + // uut.ports_out[1]->bind(OUT); + + // Connect testbench to uut + wg_tb tb("tb"); + tb.IN(IN); + tb.OUT(OUT); + + // Attach probes + Probe probe_in("in"); + probe_in.p_in(IN); + + Probe probe_out("out"); + probe_out.p_in(OUT); + + // Open Trace file + std::string trace_filename = "traces/"; + trace_filename += "waveguide_tb"; + specsGlobalConfig.trace_filename = trace_filename; + + // Apply SPECS options specific to the testbench + specsGlobalConfig.simulation_mode = OpticalOutputPortMode::EVENT_DRIVEN; + specsGlobalConfig.trace_all_optical_nets = 0; + + // Run SPECS pre-simulation code + specsGlobalConfig.prepareSimulation(); + + // Start simulation + sc_start(); + + std::cout << std::endl << std::endl; + std::cout << ".vcd trace file: " << specsGlobalConfig.trace_filename << std::endl; + + sc_close_vcd_trace_file(specsGlobalConfig.default_trace_file); +} diff --git a/src/tb/wg_tb.h b/src/tb/wg_tb.h new file mode 100644 index 0000000..5d0a84f --- /dev/null +++ b/src/tb/wg_tb.h @@ -0,0 +1,28 @@ +#pragma once + +#include <optical_signal.h> +#include <systemc.h> +#include <waveguide.h> +#include <probe.h> +#include <specs.h> + +SC_MODULE(wg_tb) +{ +public: + spx::oa_port_out_type IN; + spx::oa_port_in_type OUT; + + void run_1(); + void monitor(); + SC_CTOR(wg_tb) + { + SC_HAS_PROCESS(wg_tb); + + SC_THREAD(run_1); + + SC_THREAD(monitor); + sensitive << IN << OUT; + } +}; + +void wg_tb_run(); diff --git a/src/utils/general_utils.cpp b/src/utils/general_utils.cpp new file mode 100644 index 0000000..0ba55be --- /dev/null +++ b/src/utils/general_utils.cpp @@ -0,0 +1 @@ +#include "general_utils.h" diff --git a/src/utils/general_utils.h b/src/utils/general_utils.h new file mode 100644 index 0000000..14757a9 --- /dev/null +++ b/src/utils/general_utils.h @@ -0,0 +1,35 @@ +#pragma once + +#include <cmath> +#include <vector> +#include <iostream> + +using std::abs; +using std::vector; +using std::cerr; +using std::endl; + +template <typename T1, typename T2> +inline bool is_close(const T1& x1, const T2& x2, const double &precision = 1e-12) +{ + return abs(x1-x2) < precision; +} + +//double linspace(double minval, double maxval, double npoints); + +template <typename T> +vector<T> range(const T &minval, const T &maxval, const T &step) +{ + vector<T> ret; + if (maxval <= minval || step <= 0) + { + cerr << "Invalid range parameters" << endl; + // because i don't have time to cover all cases + exit(1); + } + int n = floor((maxval - minval) / step); + ret.reserve(n); + for (T val = minval; val < maxval; val += step) + ret.push_back(val); + return ret; +}
\ No newline at end of file diff --git a/src/utils/pqueue.h b/src/utils/pqueue.h new file mode 100644 index 0000000..4ec5dfd --- /dev/null +++ b/src/utils/pqueue.h @@ -0,0 +1,35 @@ +#pragma once + +#include <queue> +#include <vector> + +using std::priority_queue; +using std::vector; +using std::greater; +using std::size_t; + +template <class T> +class PQueue: public priority_queue<T, vector<T>, greater<T>>{ +public: + public: + typedef typename + std::priority_queue<T>::container_type::iterator iterator; + typedef typename + std::priority_queue<T>::container_type::const_iterator const_iterator; + + iterator begin() { + return this->c.begin(); + } + iterator end() { + return this->c.end(); + } + const_iterator cbegin() const { + return this->c.cbegin(); + } + const_iterator cend() const { + return this->c.cend(); + } + size_t size() const { + return this->c.size(); + } +}; diff --git a/src/utils/strutils.h b/src/utils/strutils.h new file mode 100644 index 0000000..94e7ab7 --- /dev/null +++ b/src/utils/strutils.h @@ -0,0 +1,79 @@ +#pragma once + +#include <algorithm> // std::transform +#include <string> + +namespace strutils { +// trim from start (in place) +inline void ltrim(std::string &s) +{ + s.erase(s.begin(), + std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); +} + +// trim from end (in place) +inline void rtrim(std::string &s) +{ + s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }) + .base(), + s.end()); +} + +// trim from both ends (in place) +inline void trim(std::string &s) +{ + ltrim(s); + rtrim(s); +} + +// trim from start (copying) +inline std::string ltrim_copy(std::string s) +{ + ltrim(s); + return s; +} + +// trim from end (copying) +inline std::string rtrim_copy(std::string s) +{ + rtrim(s); + return s; +} + +// trim from both ends (copying) +inline std::string trim_copy(std::string s) +{ + trim(s); + return s; +} +// trim from end (in place) +inline void rtrim_comments(std::string &s, const std::string &comment_tokens) +{ + size_t pos = s.find_first_of(comment_tokens); + if (pos != s.npos) + s.erase(pos); +} +inline void toupper(std::string &s) +{ + std::transform(s.begin(), s.end(), s.begin(), ::toupper); +} + +inline bool strcontains(const std::string &s, const std::string &sub) +{ + return s.find(sub) != std::string::npos; +} + +inline bool streq(const std::string &s1, const std::string &s2) +{ + return s1 == s2; +} + +inline bool iequals(const std::string& a, const std::string& b) +{ + return std::equal(a.begin(), a.end(), + b.begin(), b.end(), + [](char a, char b) { + return tolower(a) == tolower(b); + }); +} +}; diff --git a/src/utils/sysc_utils.cpp b/src/utils/sysc_utils.cpp new file mode 100644 index 0000000..9b63632 --- /dev/null +++ b/src/utils/sysc_utils.cpp @@ -0,0 +1,70 @@ +#include <sysc_utils.h> + +#include <string> + + +inline bool sc_object_is_module(const sc_object &obj) { + return strcmp(obj.kind(), "sc_module") == 0; +} + +// Return vector containing all children objects (expanded) of obj +set<sc_object *> sc_collect_children_object(sc_object* obj) +{ + auto v = obj->get_child_objects(); + auto children = set<sc_object *>(v.begin(), v.end()); + auto all_children = children; + for (auto child : children) + if ( child ) + { + auto children_children = sc_collect_children_object(child); + for (auto child_child : children_children) + all_children.insert(child_child); + } + return all_children; +} + +// Return vector containing all children objects (expanded) of obj +set<sc_module *> sc_collect_children_module(sc_module* obj) +{ + auto v = obj->get_child_objects(); + auto children = set<sc_object *>(v.begin(), v.end()); + set<sc_module *> all_children; + for (auto obj: children) + { + auto mod = dynamic_cast<sc_module *>(obj); + if(mod) { + all_children.insert(mod); + auto children2 = sc_collect_children_module(mod); + all_children.insert(children2.begin(), children2.end()); + } + } + return all_children; +} + +set<sc_module *> sc_get_all_module() { + set<sc_module *> all_modules; + + for ( auto obj : sc_get_top_level_objects() ) { + auto mod = dynamic_cast<sc_module *>(obj); + if (mod) + { + all_modules.insert(mod); + auto all_children = sc_collect_children_module(mod); + for (auto child : all_children) + all_modules.insert(child); + } + } + return all_modules; +} + +set<sc_object *> sc_get_all_object() { + set<sc_object *> all_objects; + + for ( auto obj : sc_get_top_level_objects() ) { + all_objects.insert(obj); + auto all_children = sc_collect_children_object(obj); + for (auto child : all_children) + all_objects.insert(child); + } + return all_objects; +}
\ No newline at end of file diff --git a/src/utils/sysc_utils.h b/src/utils/sysc_utils.h new file mode 100644 index 0000000..be275a0 --- /dev/null +++ b/src/utils/sysc_utils.h @@ -0,0 +1,67 @@ +#pragma once + +#include <systemc.h> + +#include <vector> +#include <set> + +using std::vector; +using std::set; + +bool sc_object_is_module(const sc_object &obj); + +// Return vector containing all children objects (expanded) of obj +set<sc_object *> sc_collect_children_object(sc_object* obj); + +// Return vector containing all children objects (expanded) of obj +set<sc_module *> sc_collect_children_module(sc_module* obj); + +// Return vector containing all sc_module registered with engine +set<sc_module *> sc_get_all_module(); + +// Return vector containing all sc_object registered with engine +set<sc_object *> sc_get_all_object(); + +// Return vector containing all sc_module of a certain type +template<typename T> +set<T *> sc_get_all_module_by_type(); + +// Return vector containing all sc_object of a certain type +template<typename T> +set<T *> sc_get_all_object_by_type(); + +//////////////////////////////////////// +// Definition of template functions +//////////////////////////////////////// + + +template<typename T> +set<T *> sc_get_all_module_by_type() { + set<sc_module *> all_modules = sc_get_all_module(); + set<T *> all_requested; + for (auto mod : all_modules) + { + // cout << mod->name() << endl; + auto requested = dynamic_cast<T *>(mod); + if (requested) + all_requested.insert(requested); + } + return all_requested; +} + +template<typename T> +set<T *> sc_get_all_object_by_type() { + set<sc_object *> all_objects = sc_get_all_object(); + set<T *> all_requested; + + for (auto obj : all_objects) + { + //cout << obj->name() << endl; + auto requested = dynamic_cast<T *>(obj); + if (requested) { + //cout << "\\__( WE WANT IT )" << endl; + all_requested.insert(requested); + } + } + return all_requested; +}
\ No newline at end of file diff --git a/thirdparty/args b/thirdparty/args new file mode 160000 +Subproject 78e27faf75ff7d20f232f11ffcef65cde43c449 diff --git a/thirdparty/systemc b/thirdparty/systemc new file mode 160000 +Subproject 39740075f47fedbce242808d357fcfb6d3d3395 diff --git a/todo.txt b/todo.txt new file mode 100644 index 0000000..f97a2cf --- /dev/null +++ b/todo.txt @@ -0,0 +1,52 @@ +Library: +- [ ] Finish implementing all elements + - [x] phase-shifter + - [ ] EO Modulator + - [ ] LFSR + - [ ] PWL source +- [ ] Add models for the pcm + - [ ] Sequential FDTD/HEAT/... + - [ ] Looped MATLAB model + - [x] Raphael's LUT model +- [ ] Rework the photodetector device into: + - [x] Single-ended photodetector (with noise) + - [ ] Opticall2 type photodetector + - [x] Oscilloscope probe +- [ ] Add a monitor device to keep track of simulation duration + - [x] Time + - [ ] Energy spent by sources + - [ ] Energy left within circuit + +Netlist: +- [ ] Finish parser for all elements (and settings) +- [ ] Document (keep up to date list of available components and commands) +- [ ] Implement hierarchy +- [ ] Implement named components + +Simulation features: +- [ ] Bundle all simulation parameters (timestep, precision)... into a class which can be used by devices +- [ ] Bundle all material parameters into a table to make it easier to track/replace default parameters ? +- [ ] Make a cmd line switch to run in CW mode +- [x] implement runtime monitoring (energy...) +- [ ] improve signals (use a more general "multidomain signal" class ?) +- [ ] handle multiple propagation modes +- [ ] handle bidirectionality in devices +- [ ] handle arbitrary waveforms +- [ ] handle non-linear effects +- [ ] handle GVD as well + +Utilities: +- [ ] Implement frequency sweeps (depends on CW availability for transmission) +- [ ] Improve plotting capabilities + - [x] GTKWave + - [ ] Python reading with pyDigitalWaveTools +- [ ] Link with a GUI for creating the circuits + - [ ] xschem + +Other: +- [ ] Write data into a db (e.g. hdf5) instead of within the file-system +- [ ] Logging features +- [ ] Refactor once design is established +- [ ] Implement a parallel job manager +- [ ] Make some more features available through the command line +- [ ] Readme and documentation diff --git a/utils/analyze_detector_trace.py b/utils/analyze_detector_trace.py new file mode 100644 index 0000000..80099a3 --- /dev/null +++ b/utils/analyze_detector_trace.py @@ -0,0 +1,444 @@ +import sys +import numpy as np +import pickle +import matplotlib.pyplot as plt +import csv +from queue import PriorityQueue +import heapq +from scipy.constants import c, pi, h + + +def waveguide_length_for_phase_shift(phi, wavelength, neff): + phi = np.mod(phi, 2*pi) + if phi == 0: + phi = 2*pi + + length_req = phi * wavelength / (2 * pi * neff) + + return length_req + + +class Pulse(): + max_id = 0 + def __init__(self, power, duration, phase, tstart, wavelength=1.55e-6, sig_id=0): + self.power = power + self.duration = duration + self.phase = phase + self.tstart = tstart + self.wavelength = wavelength + if sig_id != 0: + self.id = sig_id + if self.id >= Pulse.max_id: + Pulse.max_id = self.id + 1 + else: + self.id = Pulse.max_id + Pulse.max_id += 1 + + @property + def tend(self): + return self.tstart + self.duration + + @property + def energy(self): + return self.power * self.duration + + def __str__(self): + return f't={self.tstart}, P={self.power}, tau={self.duration}, phi={self.phase}, lambda={self.wavelength}, id={self.id}' + + def _cmp_key(self): + return (self.tstart, self.id) + + def __lt__(self, rhs): + return self._cmp_key() < rhs._cmp_key() + + # def __le__(self, rhs): + # return self.tstart <= rhs.tstart + # + # def __gt__(self, rhs): + # return rhs < self + # + # def __ge__(self, rhs): + # return rhs <= self + + def __eq__(self, rhs): + #return self.tstart == rhs.tstart + return self._cmp_key() == rhs._cmp_key() + # return (self.power == rhs.power + # and self.duration == rhs.duration + # and self.phase == rhs.phase + # and self.tstart == rhs.tstart + # and self.wavelength == rhs.wavelength + # ) + + # def __neq__(self, rhs): + # return not self == rhs + + def intersects(lhs, rhs): + # sort by tstart + #pulses = sorted([lhs, rhs], key=lambda x: x.tstart) + + # if they don't interfere + if lhs.tstart <= rhs.tstart and lhs.tend - rhs.tstart > 1e-20: + return True + if rhs.tstart <= lhs.tstart and rhs.tend - lhs.tstart > 1e-20: + return True + + return False + + def __add__(lhs, rhs): + # sort by tstart + pulses = sorted([lhs, rhs]) + + assert(pulses[0].tstart <= pulses[1].tstart) + + # if they don't interfere, return both pulses + if pulses[0].tend <= pulses[1].tstart: + return pulses + + if pulses[0].wavelength != pulses[1].wavelength: + raise ValueError('Cannot handle addition of pulses of different frequencies with this class') + + #print(f'Summing pulses with timestamps {pulses[0].tstart} and {pulses[1].tstart}') + wavelength = pulses[0].wavelength + + phi1 = pulses[0].phase + P1 = pulses[0].power + A1 = np.sqrt(P1) + + phi2 = pulses[1].phase + P2 = pulses[1].power + A2 = np.sqrt(P2) + + dphi = phi2 - phi1 + + #print(f'dphi = {np.mod(dphi,2*pi)/pi:.3f}*pi') + #print(f'dphi/2 = {np.mod(dphi/2,2*pi)/pi:.3f}*pi') + #print(f'cos(dphi/2) = {np.cos(dphi/2)}') + A_sum = (A1 + A2) * np.cos(dphi/2) - 1j * (A1 - A2) * np.sin(dphi/2) + #P_sum = np.real(A_sum * np.conj(A_sum)) + P_sum = np.abs(A_sum) ** 2 + phi_sum = (phi1 + phi2) / 2 + np.angle(A_sum) + + last_pulse = 1 + if pulses[0].tend > pulses[1].tend: + last_pulse = 0 + + tstart_pre = pulses[0].tstart + tstart_sum = pulses[1].tstart + tstart_post = pulses[not last_pulse].tend + + duration_pre = tstart_sum - tstart_pre + duration_sum = tstart_post - tstart_sum + duration_post = pulses[last_pulse].tend - tstart_post + + P_post = [P1, P2][last_pulse] + phi_post = [phi1, phi2][last_pulse] + + assert(duration_pre >= 0) + assert(duration_sum >= 0) + assert(duration_post >= 0) + + result = [] + if duration_pre > 0: + result.append(Pulse(P1, duration_pre, phi1, tstart_pre, wavelength)) + + result.append(Pulse(P_sum, duration_sum, phi_sum, tstart_sum, wavelength)) + + if duration_post > 0: + result.append(Pulse(P_post, duration_post, phi_post, tstart_post, wavelength)) + + return result + + @classmethod + def sort_by_tstart(cls, pulses): + return sorted(pulses) + + +class PulseAggreg(): + def __init__(self, pulses): + self.reduced = False + self.pulses = pulses + heapq.heapify(self.pulses) + self.sort_pulses_by_tstart() + # print(str(self)) + + def sort_pulses_by_tstart(self): + #heapq.heapify(self.pulses) + self.pulses = Pulse.sort_by_tstart(self.pulses) + pass + + @property + def has_intersections(self): + if self.reduced: + return False + + heapq.heapify(self.pulses) + for i,p in enumerate(self.pulses[:-1]): + p2 = self.pulses[i+1] + if p.intersects(p2): + return True + # for i,p in enumerate(self.pulses[:-1]): + # for i2,p2 in enumerate(self.pulses[i+1:]): + # if p.intersects(p2): + # return True + return False + + def reduce_pulses_coherent(self): + if not self.has_intersections: + self.reduced = True + return + + pulses = self.pulses + pulses_new = [] + + n = len(pulses) + i = 0 + print('Reducing to independent pulses...') + while len(pulses) > 1: + print(f'\r{100*(1-len(pulses)/n):.0f}% ({len(pulses)} pulses left)', end='') + #pulses = Pulse.sort_by_tstart(pulses) + p0 = heapq.heappop(pulses) + p1 = heapq.heappop(pulses) + + if p0.intersects(p1): + resulting_pulses = p0 + p1 + #heapq.heappop(pulses) + # print(p0) + # print(p1) + # print('-->') + for px in resulting_pulses: + heapq.heappush(pulses, px) + #heapq.heappush(pulses_new, resulting_pulses[0]) + # print(px) + # print(' ') + else: + heapq.heappush(pulses_new, p0) + heapq.heappush(pulses, p1) + + + if len(pulses) == 1: + heapq.heappush(pulses_new, heapq.heappop(pulses)) + + print(f'\r{100*(1-len(pulses)/n):.0f}% ({len(pulses)} pulses left)') + self.pulses = pulses_new + + print('Checking...') + if self.has_intersections: + raise RuntimeError('Impossible to reduce pulse list') + + with open('NonIntersectingPulses.obj', 'wb') as f: + pickle.dump(self, f) + + print('Done') + self.reduced = True + + def __str__(self): + ret = '\n'.join([str(p) for p in list(self.pulses)]) + return ret + + @property + def energy(self): + if self.has_intersections: + self.reduce_pulses_coherent() + return np.sum([p.energy for p in self.pulses]) + + + def to_waveform(self, dt, coherent=True, tmax=None): + if self.has_intersections: + self.reduce_pulses_coherent() + + #print(np.min([p.duration for p in self.pulses])) + #print(np.max([p.power for p in self.pulses])) + #print(np.min([p.power for p in self.pulses])) + #print(str(self)) + #print(self.energy) + + if tmax == None: + tmax = self.pulses[-1].tend + + t = np.arange(0, tmax, dt) + Pout = np.zeros(len(t)) + + for p in self.pulses: + # itmin = int(np.ceil(p.tstart / dt)) + # itmax = int(np.ceil(p.tend / dt) + 1) + Pout[np.logical_and(t >= p.tstart, t < p.tend)] = p.power + #Pout[itmin:itmax] = p.power + + return t, Pout + + def to_waveform_2(self, coherent=True): + if self.has_intersections: + self.reduce_pulses_coherent() + + #print(self.energy) + + t = [0] + Pout = [0] + + for p in self.pulses: + if p.duration < 1e-20: + continue + if p.tstart - t[-1] > 1e-20: + t.append(t[-1]) + Pout.append(0) + t.append(p.tstart) + Pout.append(0) + t.append(p.tstart) + Pout.append(p.power) + t.append(p.tend) + Pout.append(p.power) + + return np.array(t), np.array(Pout) + + def plot_waveform(self, dt, title=None, tmax=None): + print(f'Mapping to timeseries ({len(self.pulses)} pulses to process)') + #t, Pout = self.to_waveform(dt, tmax=tmax) + t, Pout = self.to_waveform_2() + print('Done') + + with open('Pout.obj', 'wb') as f: + pickle.dump((t,Pout), f) + + linespec='-' + if title is not None and '.bk' in title: + linespec='--' + plt.plot(1e9*t, 1e3*Pout, linespec, label=title) + if tmax is not None: + plt.xlim([0, 1e9*tmax]) + #plt.title(title) + plt.xlabel('t (ns)') + plt.ylabel('Pout (mW)') + plt.savefig('Pout.png', dpi=300) + plt.grid('major') + plt.grid('minor') + plt.legend() + + +def main(filename='detector_trace.txt', override_lambda=None): + pulses = [] + tmax = 0 + taumin = 1 + + with open(filename, 'r') as f: + print('Reading trace file...') + fieldnames = [h.strip() for h in next(csv.reader(f))] + + reader = csv.DictReader(f, fieldnames=fieldnames) + for (i, row) in enumerate(reader): + # if i > 470: + # break + #power = np.round(float(row['P (W)']), 12) + power = float(row['P (W)']) + #tau = np.round(float(row['tau (s)']), 16) + tau = float(row['tau (s)']) + phase = float(row['phi (rad)']) + #tstart = np.round(float(row['t (s)']), 16) + tstart = float(row['t (s)']) + wavelength = np.round(float(row['lambda (m)']), 12) + if override_lambda is not None: + wavelength = override_lambda + sig_id = int(row['id']) + + #if tau < 1e-16: continue + + #print(wavelength) + p = Pulse(power, tau, phase, tstart, wavelength, sig_id) + pulses.append(p) + #tmax = max(tmax, p.tend) + taumin = min(taumin, tau) + + print(f'Smallest pulse duration: {taumin}') + pulses = PulseAggreg(pulses) + print(f'Some pulses intersect: {pulses.has_intersections}') + pulses.reduce_pulses_coherent() + + #t = np.arange(0, tmax, 10e-12) + #dt = 10e-12 + dt = 20e-12 + print(f'Total energy: {pulses.energy}') + return pulses + +def create_bitstream(n): + rng = np.random.default_rng() + bitstream = rng.integers(low=0, high=2, size=n) + return bitstream + +def xor_bitstream(bitstream): + bitstream_a = bitstream + bitstream_b = [0, *bitstream_a] + bitstream = [a ^ b for a, b in zip(bitstream_a, bitstream_b)] + return bitstream + +def bitstream_as_values(bitstream, nbits_per_value=8, pad_with=0): + padding_length = nbits_per_value - (len(bitstream) % nbits_per_value) + bitstream = [*bitstream, *[pad_with for i in range(padding_length)]] + + values = [] + for i in range(len(bitstream) // nbits_per_value): + values.append(int(''.join([str(b) for b in bitstream[i:i+nbits_per_value]]), 2)) + return values + +def test_bitstreams(): + bs = create_bitstream(20) + bs_xor = xor_bitstream(bs) + values_1bit = bitstream_as_values(bs, 1) + values_2bit = bitstream_as_values(bs, 2) + + plt.figure() + plt.subplot(2,2,1) + plt.plot(bs) + plt.subplot(2,2,2) + plt.plot(bs_xor) + plt.subplot(2,2,3) + plt.plot(values_1bit) + plt.subplot(2,2,4) + plt.plot(values_2bit) + plt.show() + +def create_random_bitstream_file(filename, nbits=3000, nbits_per_value=8): + bs = create_bitstream(nbits) + #bs_xor = xor_bitstream(bs) + values = bitstream_as_values(bs, nbits_per_value) + with open(filename, 'w') as f: + f.write(' '.join([str(v) for v in values])) + +def compare_Pout_vecs(): + with open('Pout_nosort.obj', 'r') as f: + data = pickle.load(f) + t_sort, Pout_sort = pickle.load(open('Pout_sort.obj')) + + assert(len(Pout_sort) == len(Pout_nosort)) + for t, p1, p2 in zip(t_nosort, Pout_nosort, Pout): + assert(p1 == p2) + +if __name__ == '__main__': + print(waveguide_length_for_phase_shift(2*pi, 1550e-9, 2.2111)) + print(waveguide_length_for_phase_shift(pi, 1550e-9, 2.2111)) + print(waveguide_length_for_phase_shift(1, 1550e-9, 2.2111)) + + a = waveguide_length_for_phase_shift(2*pi, 1551e-9, 2.2111) + b = waveguide_length_for_phase_shift(pi, 1551e-9, 2.2111) + print(a) + print(b) + print(500*a+b) + #exit(0) + # print(700*waveguide_length_for_phase_shift(2*pi, 1550e-9, 2.2111)) + # compare_Pout_vecs() + if len(sys.argv) > 1: + P = [] + for fn in sys.argv[1:]: + P.append(main(filename=fn)) + P[-1].plot_waveform(1e-13,title=fn, tmax=2.5e-9) + + if len(sys.argv) > 2: + plt.figure() + f0 = P[0].to_waveform(1e-13, tmax=2.5e-9) + f1 = P[1].to_waveform(1e-13, tmax=2.5e-9) + plt.plot(f0[0], f1[1] - f0[1]) + plt.show() + else: + main() + plt.show() + #test_bitstreams() + #create_random_bitstream_file('bitstream.txt', 3000) diff --git a/utils/draw_graph_from_json.py b/utils/draw_graph_from_json.py new file mode 100644 index 0000000..78a3c64 --- /dev/null +++ b/utils/draw_graph_from_json.py @@ -0,0 +1,145 @@ +import sys +import json +import html +import graphviz + +def shorten(s, length=8): + if type(s) == list: + return "[...]" + s = str(s) + if len(s) > length: + return s[:length-3] + else: + return s + +def edge_label(name, net): + bgcolors = { + "default": "white", + "OANALOG": "turquoise", + "EANALOG": "orange", + } + try: + bgcolor = bgcolors[net["type"]] + except: + bgcolor = bgcolors["default"] + + short_name = name + if short_name.startswith('ROOT/'): + short_name = short_name[5:] + + attributes = [f'<table style="rounded" border="0" cellborder="1" cellspacing="10" bgcolor="{bgcolor}" cellpadding="4" align="center">'] + attributes.append(f'<tr><td bgcolor="grey91" port="head"><b>{html.escape(short_name)}</b></td></tr>') + + attributes.append(f'<tr><td bgcolor="{bgcolor}" port="middle" border="0"><table border="0" cellborder="1" cellspacing="0">') + # attributes.append(f'<tr><td bgcolor="{bgcolor}"><table border="0" cellborder="1" cellspacing="0" cellpadding="0">') + attributes.append(f'<tr><td bgcolor="grey91">Type</td><td bgcolor="white">{net["type"]}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Bidirectional</td><td bgcolor="white">{"true" if net["bidirectional"] else "false"}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Size</td><td bgcolor="white">{net["size"]}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Readers</td><td bgcolor="white">{net["readers"]}</td></tr>') + attributes.append(f'<tr><td bgcolor="grey91">Writers</td><td bgcolor="white">{net["writers"]}</td></tr>') + attributes.append(f'</table></td></tr>') + + attributes.append('</table>') + return f'"{name}" [label=<{"".join(attributes)}> shape=none fillcolor="{bgcolor}" margin="0.05"]' + + + +def node_label(element): + attributes = ['<table border="0" cellborder="1" cellspacing="0" cellpadding="4" align="center">'] + + short_name = element["name"] + if short_name.startswith('ROOT/'): + short_name = short_name[5:] + # Header + attributes.append(f'<tr><td bgcolor="grey91"><b>{html.escape(short_name)}</b></td></tr>') + + # Nets + attributes.append(f'<tr><td bgcolor="darkslategray2"><table border="0" cellborder="1" cellspacing="8">') + if 'nets' in element and element['nets']: + nets = ''.join(f'<tr><td bgcolor="white" cellpadding="4" port="{html.escape(str(i))}">{str(i)}</td></tr>' for i,net in enumerate(element['nets'])) + attributes.append(f'{nets}') + else: + attributes.append('<tr><td border="0" cellpadding="0">∅</td></tr>') + attributes.append(f'</table></td></tr>') + + # Args + attributes.append(f'<tr><td bgcolor="palegreen"><table border="0" cellborder="1" cellpadding="2" cellspacing="0">') + if 'args' in element and element['args']: + args = ''.join(f'<tr><td bgcolor="white" cellpadding="4">{html.escape(shorten(v["value"]))}</td></tr>' for v in element['args']) + attributes.append(f'{args}') + else: + attributes.append('<tr><td border="0" cellpadding="0">∅</td></tr>') + attributes.append(f'</table></td></tr>') + + # Kwargs + attributes.append(f'<tr><td bgcolor="wheat"><table border="0" cellborder="1" cellpadding="2" cellspacing="0">') + if 'kwargs' in element and element['kwargs']: + kwargs = ''.join(f'<tr><td bgcolor="grey91">{html.escape(k)}</td><td bgcolor="white">{html.escape(shorten(v["value"]))}</td></tr>' for k, v in element['kwargs'].items()) + attributes.append(f'{kwargs}') + else: + attributes.append('<tr><td border="0" cellpadding="0">∅</td></tr>') + attributes.append(f'</table></td></tr>') + + attributes.append('</table>') + return f'"{element["name"]}" [label=<{"".join(attributes)}> shape=none margin="0"]' + +def edge(element): + if 'nets' in element: + for i,net in enumerate(element['nets']): + # yield f'"{element["name"]}":"{str(i)}" -- "{net}":"head"' + yield f'"{element["name"]}":"{str(i)}" -> "{net}":"middle"[ arrowhead = none ]' + +def generate_graph(description): + result = [] + result.append('digraph G {') + # result.append(' fontname="Helvetica,Arial,sans-serif"') + # result.append(' node [fontname="Helvetica,Arial,sans-serif"]') + # result.append(' edge [fontname="Helvetica,Arial,sans-serif"]') + result.append(' fontname="Cascadia,Courrier,mono"') + result.append(' node [fontname="Cascadia,Courrier,mono"]') + result.append(' edge [fontname="Cascadia,Courrier,mono"]') + result.append(' layout="sfdp"') + result.append(' overlap=false') + result.append(' splines=curved') + + for name, net in description["nets"].items(): + result.append(' ' + edge_label(name, net)) + + for element in description["elements"]: + result.append(' ' + node_label(element)) + result.extend(' ' + e for e in edge(element)) + + result.append('}') + return '\n'.join(result) + +def draw_graph(json_file, out_file): + with open(json_file) as f: + description = json.load(f) + + dot_src = generate_graph(description) + # print(dot_src) + graph = graphviz.Source(dot_src) + graph.render(outfile=out_file) + print(f'Results written to {out_file}') + +def main(): + try: + json_file = sys.argv[1] + except IndexError: + print('First and only argument should be a JSON description of the circuit') + try: + out_file = sys.argv[2] + except IndexError: + out_file = json_file + ".png" + + with open(json_file) as f: + description = json.load(f) + + dot_src = generate_graph(description) + # print(dot_src) + graph = graphviz.Source(dot_src) + graph.render(outfile=out_file) + print(f'Results written to {out_file}') + +if __name__ == '__main__': + main() diff --git a/utils/openwave.sh b/utils/openwave.sh new file mode 100644 index 0000000..9c59d1a --- /dev/null +++ b/utils/openwave.sh @@ -0,0 +1,55 @@ +#!/bin/env bash + +trace_file=$1 +config_dir=$2 + +if [[ -d $config_dir && ! -z "$(ls $config_dir)" ]]; then + configs=("`find $config_dir -iname '*.gtkw' -printf '%p '`") + configs=(${configs[*]}) + + # Check number of config file found + if [ ${#configs[*]} -eq 1 ]; then + # Only one file: run with it + echo -e "Going with the only gtkwave config found: ${configs[0]}." + echo "gtkwave -a \"${configs[0]}\" \"$1\"" + gtkwave -a "${configs[0]}" "$1" + else + # Several configs found, ask which to use + echo "Found the following ${#configs[*]} gtkwave configs:" + let "i = 1" + echo -e "0:\tNone" + for config in ${configs[*]}; do + echo -e "$i:\t\"$config\"" + let "i = ++i" + done + + echo -n "Your choice ? [0]: " + + # declare the choice variable as an integer + declare -i choice + declare -i i_config + read choice + let "i_config = choice - 1" + + while [[ $choice -lt 0 || $i_config -ge ${#configs} ]]; do + echo -n "Out of bounds. Your choice ? [0]: " + read choice + let "i_config = choice - 1" + done + + if [[ $choice -eq 0 ]]; then + echo "Not using any config file." + echo "gtkwave \"$1\"" + gtkwave "$1" + else + echo "Going with ${configs[$i_config]} ($choice)." + echo "gtkwave -a \"${configs[$i_config]}\" \"$1\"" + gtkwave -a "${configs[$i_config]}" "$1" + fi + fi +else + #No config + echo "No gtkwave configs found." + echo "gtkwave \"$1\"" + gtkwave "$1" +fi diff --git a/utils/specs.kicad_sym b/utils/specs.kicad_sym new file mode 100644 index 0000000..3b84b6f --- /dev/null +++ b/utils/specs.kicad_sym @@ -0,0 +1,1986 @@ +(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)
+ (symbol "ADD_DROP_FILTER" (in_bom yes) (on_board yes)
+ (property "Reference" "ADROP" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 6.35 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at -1.524 6.858 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3 4=4" (at -0.254 6.858 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "neff=1 ng=1 k1=0.5 k2=0.5 radius=10e-6 att=0" (at 0 -5.08 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "ADD_DROP_FILTER_0_0"
+ (text "" (at -3.556 1.524 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ )
+ (symbol "ADD_DROP_FILTER_0_1"
+ (rectangle (start -3.81 -2.286) (end 3.81 -2.794)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -3.81 2.794) (end 3.81 2.286)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (circle (center 0 0) (radius 1.016)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (circle (center 0 0) (radius 1.524)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "ADD_DROP_FILTER_1_1"
+ (pin input line (at -6.35 2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at -6.35 -2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 -2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "4" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "ALL_PASS_FILTER" (in_bom yes) (on_board yes)
+ (property "Reference" "APASS" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 6.35 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "neff=1 ng=1 k=0.5 radius=10e-6 att=0" (at 0 -5.08 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "ALL_PASS_FILTER_0_1"
+ (rectangle (start -3.81 0.254) (end 3.81 -0.254)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (circle (center 0 2.032) (radius 1.016)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (circle (center 0 2.032) (radius 1.524)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "ALL_PASS_FILTER_1_1"
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "CROSSING" (in_bom yes) (on_board yes)
+ (property "Reference" "CROSSING" (at 5.334 4.826 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -0.254 6.858 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "att=0 crosstalk=0" (at 9.652 -4.826 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3 4=4" (at -0.762 0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "CROSSING_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "CROSSING_1_1"
+ (polyline
+ (pts
+ (xy -3.81 0.254)
+ (xy -0.254 0.254)
+ (xy -0.254 3.81)
+ (xy 0.254 3.81)
+ (xy 0.254 0.254)
+ (xy 3.81 0.254)
+ (xy 3.81 -0.254)
+ (xy 0.254 -0.254)
+ (xy 0.254 -3.81)
+ (xy -0.254 -3.81)
+ (xy -0.254 -0.254)
+ (xy -3.81 -0.254)
+ (xy -3.81 0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at 0 6.35 270) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 0 -6.35 90) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "4" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "CW_SOURCE" (in_bom yes) (on_board yes)
+ (property "Reference" "CWSRC" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "wl=1550e-9 power=1" (at -0.254 -5.588 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "CW_SOURCE_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.524 -1.27)
+ (xy 1.524 -1.27)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -1.27)
+ (xy 0 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 1.016)
+ (xy 0 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.778 1.524)
+ (xy 2.286 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.778 2.286)
+ (xy 2.286 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 2.032)
+ (xy 2.032 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 2.032)
+ (xy 2.286 1.778)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 2.794)
+ (xy 2.032 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 2.794)
+ (xy 2.286 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -1.27)
+ (xy -1.524 1.016)
+ (xy 1.524 1.016)
+ (xy 0 -1.27)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "CW_SOURCE_1_1"
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "DETECTOR" (in_bom yes) (on_board yes)
+ (property "Reference" "PDET" (at -6.35 3.048 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -0.508 3.556 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at -0.508 3.556 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -0.508 3.556 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "r=1 ts=1e-12" (at 0 -5.334 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (symbol "DETECTOR_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.286 0.254)
+ (xy -1.778 -0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.159 0.889)
+ (xy -1.651 0.381)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 -0.254)
+ (xy -2.032 -0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 -0.254)
+ (xy -1.778 0)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.651 0.381)
+ (xy -1.905 0.381)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.651 0.381)
+ (xy -1.651 0.635)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -3.048)
+ (xy 0.254 -3.048)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.127 -3.302)
+ (xy 0.127 -3.302)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -2.794)
+ (xy -0.508 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -2.794)
+ (xy 0.508 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -1.27)
+ (xy 0 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 1.016)
+ (xy 0 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 2.54)
+ (xy 0 3.81)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.524 1.016)
+ (xy -1.524 1.016)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 1.016)
+ (xy 1.524 -1.27)
+ (xy -1.524 -1.27)
+ (xy 0 1.016)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "DETECTOR_1_1"
+ (text "Electric" (at 2.032 6.35 0)
+ (effects (font (face "KiCad Font") (size 0.5 0.5)))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 0 6.35 270) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "DIRECTIONAL_COUPLER" (in_bom yes) (on_board yes)
+ (property "Reference" "COUPLER" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 6.35 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3 4=4" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "k=0.5" (at 0 -5.08 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (symbol "DIRECTIONAL_COUPLER_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.81 -2.286)
+ (xy -3.048 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.81 2.286)
+ (xy -3.048 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.81 2.794)
+ (xy -3.048 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.81 -2.286)
+ (xy 3.048 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.81 2.286)
+ (xy 3.048 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.81 2.794)
+ (xy 3.048 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.048 2.286)
+ (xy -1.016 0.254)
+ (xy 1.016 0.254)
+ (xy 3.048 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.048 -2.286)
+ (xy 1.016 -0.254)
+ (xy -1.016 -0.254)
+ (xy -3.048 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.81 2.794)
+ (xy -2.794 2.794)
+ (xy -0.762 0.762)
+ (xy 0 0.762)
+ (xy 0.762 0.762)
+ (xy 2.794 2.794)
+ (xy 3.81 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.81 -2.794)
+ (xy 2.794 -2.794)
+ (xy 0.762 -0.762)
+ (xy 0 -0.762)
+ (xy -0.762 -0.762)
+ (xy -2.794 -2.794)
+ (xy -3.81 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "DIRECTIONAL_COUPLER_1_1"
+ (pin input line (at -6.35 2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at -6.35 -2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 -2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "4" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "ELECTRIC_V_SOURCE_FILE" (in_bom yes) (on_board yes)
+ (property "Reference" "EVLSRC" (at -7.874 2.032 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "values=\"file.txt\"" (at -12.192 -0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "ELECTRIC_V_SOURCE_FILE_0_1"
+ (polyline
+ (pts
+ (xy -2.032 -1.524)
+ (xy 1.778 -1.524)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 1.778)
+ (xy -1.778 -1.778)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 -6.35)
+ (xy -0.762 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 -2.54)
+ (xy 0.508 -2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 2.54)
+ (xy 0.508 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -6.858)
+ (xy 0.254 -6.858)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -6.604)
+ (xy -0.508 -6.604)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -6.604)
+ (xy 0.254 -6.604)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.127 -6.858)
+ (xy 0.127 -6.858)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -6.35)
+ (xy -0.508 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -6.35)
+ (xy 0 -3.81)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -6.35)
+ (xy 0.508 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 3.048)
+ (xy 0 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0.254 -6.604)
+ (xy 0.508 -6.604)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0.508 -6.35)
+ (xy 0.762 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 1.27)
+ (xy -1.016 1.27)
+ (xy -1.016 0.254)
+ (xy -0.254 0.254)
+ (xy -0.254 -0.508)
+ (xy 0.508 -0.508)
+ (xy 0.508 1.016)
+ (xy 1.27 1.016)
+ (xy 1.27 -1.016)
+ (xy 1.778 -1.016)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (circle (center 0 0) (radius 3.776)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "ELECTRIC_V_SOURCE_FILE_1_1"
+ (text "Electric" (at 2.286 6.35 0)
+ (effects (font (face "KiCad Font") (size 0.5 0.5)))
+ )
+ (pin output line (at 0 6.35 270) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "ELECTRIC_V_SOURCE_LIST" (in_bom yes) (on_board yes)
+ (property "Reference" "EVLSRC" (at -7.874 2.032 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "values=[[t0,p0,1550e-9],[t1,p1,1550e-9]]" (at -25.146 0 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "ELECTRIC_V_SOURCE_LIST_0_1"
+ (polyline
+ (pts
+ (xy -2.032 -1.524)
+ (xy 1.778 -1.524)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 1.778)
+ (xy -1.778 -1.778)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 -6.35)
+ (xy -0.762 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 -2.54)
+ (xy 0.508 -2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 2.54)
+ (xy 0.508 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -6.858)
+ (xy 0.254 -6.858)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -6.604)
+ (xy -0.508 -6.604)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.254 -6.604)
+ (xy 0.254 -6.604)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.127 -6.858)
+ (xy 0.127 -6.858)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -6.35)
+ (xy -0.508 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -6.35)
+ (xy 0 -3.81)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 -6.35)
+ (xy 0.508 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 3.048)
+ (xy 0 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0.254 -6.604)
+ (xy 0.508 -6.604)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0.508 -6.35)
+ (xy 0.762 -6.35)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 1.27)
+ (xy -1.016 1.27)
+ (xy -1.016 0.254)
+ (xy -0.254 0.254)
+ (xy -0.254 -0.508)
+ (xy 0.508 -0.508)
+ (xy 0.508 1.016)
+ (xy 1.27 1.016)
+ (xy 1.27 -1.016)
+ (xy 1.778 -1.016)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (circle (center 0 0) (radius 3.776)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "ELECTRIC_V_SOURCE_LIST_1_1"
+ (text "Electric" (at 2.286 6.35 0)
+ (effects (font (face "KiCad Font") (size 0.5 0.5)))
+ )
+ (pin output line (at 0 6.35 270) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "MERGER" (in_bom yes) (on_board yes)
+ (property "Reference" "MERGER" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 6.35 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "il=0" (at 0 -5.08 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (symbol "MERGER_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -1.016 0.762) (end 0.762 -0.762)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.81 -2.794)
+ (xy -2.794 -2.794)
+ (xy -0.762 -0.762)
+ (xy 0.762 -0.762)
+ (xy 0.762 -0.254)
+ (xy 3.81 -0.254)
+ (xy 3.81 0.254)
+ (xy 0.762 0.254)
+ (xy 0.762 0.762)
+ (xy -0.762 0.762)
+ (xy -2.794 2.794)
+ (xy -3.81 2.794)
+ (xy -3.81 2.286)
+ (xy -3.048 2.286)
+ (xy -1.016 0.254)
+ (xy -1.016 -0.254)
+ (xy -3.048 -2.286)
+ (xy -3.81 -2.286)
+ (xy -3.81 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "MERGER_1_1"
+ (pin input line (at -6.35 2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at -6.35 -2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "MLPROBE" (in_bom yes) (on_board yes)
+ (property "Reference" "MLPROBE" (at 0 5.08 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "wl=[1550e-9, 1560e-9]" (at -0.508 -5.08 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (symbol "MLPROBE_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "MLPROBE_1_1"
+ (polyline
+ (pts
+ (xy -1.524 0.762)
+ (xy -1.27 1.016)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.27 0.508)
+ (xy -1.016 0.762)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.27 0.508)
+ (xy -2.794 2.032)
+ (xy -2.54 2.286)
+ (xy -1.016 0.762)
+ (xy -1.016 0.508)
+ (xy -1.27 0.508)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (text ".vcd" (at 1.016 0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (text "λ" (at 1.016 2.794 0)
+ (effects (font (size 1.27 1.27) (color 61 166 29 1)))
+ )
+ (text "λ" (at 2.032 2.794 0)
+ (effects (font (size 1.27 1.27) (color 255 87 139 1)))
+ )
+ (text "λ" (at 3.048 2.794 0)
+ (effects (font (size 1.27 1.27) (color 101 111 255 1)))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "MZI" (in_bom yes) (on_board yes)
+ (property "Reference" "MZI" (at 0 -5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 6.35 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3 4=4" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "length=1e-6 length_ref=1e-6 neff=2 ng=2 att=0 il_dc=0 il_phaseshifter=0" (at 0 -7.112 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "MZI_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.81 2.286)
+ (xy 3.556 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "MZI_1_1"
+ (rectangle (start -0.508 3.048) (end 0.508 2.032)
+ (stroke (width 0) (type default) (color 65 164 59 1))
+ (fill (type outline))
+ )
+ (polyline
+ (pts
+ (xy -3.556 -2.286)
+ (xy -3.81 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.302 -2.794)
+ (xy -3.81 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.302 2.794)
+ (xy -3.81 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.54 -0.254)
+ (xy -3.556 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.54 0.254)
+ (xy -1.778 0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.286 0.254)
+ (xy -2.032 0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.286 0.762)
+ (xy -3.302 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.032 -0.762)
+ (xy -1.016 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.032 -0.254)
+ (xy -2.286 -0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 -0.254)
+ (xy -2.54 -0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 0.254)
+ (xy -0.762 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.016 -2.794)
+ (xy -0.508 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.016 2.794)
+ (xy 1.016 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.508 -2.286)
+ (xy 0.762 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 0 3.048)
+ (xy 0 3.81)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.016 -2.794)
+ (xy -0.508 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.778 -0.254)
+ (xy 0.762 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.778 0.254)
+ (xy 2.54 0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.032 0.254)
+ (xy 2.286 0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.032 0.254)
+ (xy 2.286 0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.032 0.762)
+ (xy 1.016 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 -0.762)
+ (xy 3.302 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 -0.254)
+ (xy 2.032 -0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.54 -0.254)
+ (xy 1.778 -0.254)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.54 0.254)
+ (xy 3.556 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.302 -2.794)
+ (xy 3.81 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.302 2.794)
+ (xy 3.81 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -3.302 -2.794)
+ (xy -2.286 -0.762)
+ (xy -2.032 -0.762)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.54 0.254)
+ (xy -3.556 2.286)
+ (xy -3.81 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.778 -0.254)
+ (xy -0.762 -2.286)
+ (xy -0.508 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.016 2.794)
+ (xy -2.032 0.762)
+ (xy -2.286 0.762)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -0.762 2.286)
+ (xy 0.508 2.286)
+ (xy 0.762 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.016 -2.794)
+ (xy 2.032 -0.762)
+ (xy 2.286 -0.762)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 1.778 0.254)
+ (xy 0.762 2.286)
+ (xy 0.508 2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.54 -0.254)
+ (xy 3.556 -2.286)
+ (xy 3.81 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.302 2.794)
+ (xy 2.286 0.762)
+ (xy 2.032 0.762)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (text "Electric" (at 2.032 6.35 0)
+ (effects (font (face "KiCad Font") (size 0.5 0.5)))
+ )
+ (pin input line (at -6.35 2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at -6.35 -2.54 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 -2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "4" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at 0 6.35 270) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "5" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "PCM" (in_bom yes) (on_board yes)
+ (property "Reference" "PCM" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "levels=63" (at -0.254 -5.334 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "PCM_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "PCM_1_1"
+ (rectangle (start -3.81 0.254) (end 3.81 -0.254)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -1.27 0.508) (end 1.27 -0.508)
+ (stroke (width 0) (type default) (color 132 0 132 1))
+ (fill (type outline))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "PROBE" (in_bom yes) (on_board yes)
+ (property "Reference" "PROBE" (at 0 5.08 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "PROBE" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "PROBE_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "PROBE_1_1"
+ (polyline
+ (pts
+ (xy -1.524 0.762)
+ (xy -1.27 1.016)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.27 0.508)
+ (xy -1.016 0.762)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -1.27 0.508)
+ (xy -2.794 2.032)
+ (xy -2.54 2.286)
+ (xy -1.016 0.762)
+ (xy -1.016 0.508)
+ (xy -1.27 0.508)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (text ".vcd" (at 1.016 0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "PSHIFT" (in_bom yes) (on_board yes)
+ (property "Reference" "PSHIFT" (at 0 -4.826 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0.254 2.286 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at 0.254 2.286 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0.254 2.286 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "gain=1 att=0" (at 0 -6.604 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "PSHIFT_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "PSHIFT_1_1"
+ (rectangle (start -3.81 0.254) (end 3.81 -0.254)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -0.762 0.508) (end 0.762 -0.508)
+ (stroke (width 0) (type default) (color 65 164 59 1))
+ (fill (type outline))
+ )
+ (polyline
+ (pts
+ (xy 0 0.508)
+ (xy 0 3.81)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (text "Electric" (at 2.032 6.35 0)
+ (effects (font (face "KiCad Font") (size 0.5 0.5)))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin input line (at 0 6.35 270) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "SPLITTER" (in_bom yes) (on_board yes)
+ (property "Reference" "SPLITTER" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 6.35 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2 3=3" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "il=0 ratio=0.5" (at 0 -5.08 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (symbol "SPLITTER_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (rectangle (start -0.762 0.762) (end 1.016 -0.762)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 3.81 2.794)
+ (xy 2.794 2.794)
+ (xy 0.762 0.762)
+ (xy -0.762 0.762)
+ (xy -0.762 0.254)
+ (xy -3.81 0.254)
+ (xy -3.81 -0.254)
+ (xy -0.762 -0.254)
+ (xy -0.762 -0.762)
+ (xy 0.762 -0.762)
+ (xy 2.794 -2.794)
+ (xy 3.81 -2.794)
+ (xy 3.81 -2.286)
+ (xy 3.048 -2.286)
+ (xy 1.016 -0.254)
+ (xy 1.016 0.254)
+ (xy 3.048 2.286)
+ (xy 3.81 2.286)
+ (xy 3.81 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "SPLITTER_1_1"
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 -2.54 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "3" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "V_SOURCE_FILE" (in_bom yes) (on_board yes)
+ (property "Reference" "VLSRC" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "values=\"file.txt\"" (at -0.254 -5.588 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "V_SOURCE_FILE_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 1.524)
+ (xy 2.794 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 2.286)
+ (xy 2.794 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.032)
+ (xy 2.54 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.032)
+ (xy 2.794 1.778)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.794)
+ (xy 2.54 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.794)
+ (xy 2.794 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "V_SOURCE_FILE_1_1"
+ (polyline
+ (pts
+ (xy -3.302 -2.286)
+ (xy 2.794 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.794 2.794)
+ (xy -2.794 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.794 -0.508)
+ (xy -1.524 -0.508)
+ (xy -1.524 1.778)
+ (xy -0.508 1.778)
+ (xy -0.508 0.762)
+ (xy 0.762 0.762)
+ (xy 0.762 -1.524)
+ (xy 1.778 -1.524)
+ (xy 1.778 -0.762)
+ (xy 2.794 -0.762)
+ (xy 2.794 -2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "V_SOURCE_LIST" (in_bom yes) (on_board yes)
+ (property "Reference" "VLSRC" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at -19.812 -0.254 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "values=[[t0,p0,1550e-9],[t1,p1,1550e-9]]" (at -0.254 -5.588 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Pins" "1=1" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "V_SOURCE_LIST_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 1.524)
+ (xy 2.794 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.286 2.286)
+ (xy 2.794 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.032)
+ (xy 2.54 2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.032)
+ (xy 2.794 1.778)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.794)
+ (xy 2.54 2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy 2.794 2.794)
+ (xy 2.794 2.54)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "V_SOURCE_LIST_1_1"
+ (polyline
+ (pts
+ (xy -3.302 -2.286)
+ (xy 2.794 -2.286)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.794 2.794)
+ (xy -2.794 -2.794)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (polyline
+ (pts
+ (xy -2.794 -0.508)
+ (xy -1.524 -0.508)
+ (xy -1.524 1.778)
+ (xy -0.508 1.778)
+ (xy -0.508 0.762)
+ (xy 0.762 0.762)
+ (xy 0.762 -1.524)
+ (xy 1.778 -1.524)
+ (xy 1.778 -0.762)
+ (xy 2.794 -0.762)
+ (xy 2.794 -2.032)
+ )
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+ (symbol "WAVEGUIDE" (in_bom yes) (on_board yes)
+ (property "Reference" "WG" (at 0 5.08 0) (do_not_autoplace)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Value" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Footprint" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Datasheet" "" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Params" "length=1e-6 att=0 neff=2 ng=2 d=0" (at -0.254 -5.334 0)
+ (effects (font (size 1.27 1.27)))
+ )
+ (property "Sim.Device" "SPICE" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (property "Sim.Pins" "1=1 2=2" (at 0 0 0)
+ (effects (font (size 1.27 1.27)) hide)
+ )
+ (symbol "WAVEGUIDE_0_1"
+ (rectangle (start -3.81 3.81) (end 3.81 -3.81)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ )
+ (symbol "WAVEGUIDE_1_1"
+ (rectangle (start -3.81 0.254) (end 3.81 -0.254)
+ (stroke (width 0) (type default))
+ (fill (type none))
+ )
+ (pin input line (at -6.35 0 0) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "1" (effects (font (size 1.27 1.27))))
+ )
+ (pin output line (at 6.35 0 180) (length 2.54)
+ (name "" (effects (font (size 1.27 1.27))))
+ (number "2" (effects (font (size 1.27 1.27))))
+ )
+ )
+ )
+)
|
