Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • da/B-ASIC
  • lukja239/B-ASIC
  • robal695/B-ASIC
3 results
Show changes
Commits on Source (45)
AccessModifierOffset: -4
AlignAfterOpenBracket: DontAlign
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: true
AlignEscapedNewlines: DontAlign
AlignOperands: false
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: Inline
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: true
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: BeforeComma
BreakInheritanceList: BeforeComma
BreakStringLiterals: true
ColumnLimit: 140
CommentPragmas: ''
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
FixNamespaceComments: true
ForEachMacros:
- Q_FOREACH
- BOOST_FOREACH
- FOREACH
- FOR_EACH
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<'
Priority: 2
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(_test)?$'
IndentCaseLabels: true
IndentGotoLabels: false
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
Language: Cpp
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
NamespaceMacros:
- NAMESPACE
PenaltyBreakAssignment: 100
PenaltyBreakBeforeFirstCallParameter: 10
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 100
PenaltyBreakString: 10
PenaltyBreakTemplateDeclaration: 10000
PenaltyExcessCharacter: 999999
PenaltyReturnTypeOnItsOwnLine: 10000
PointerAlignment: Left
ReflowComments: false
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
StatementMacros:
- Q_UNUSED
TabWidth: 4
TypenameMacros:
- STACK_OF
- LIST
- LIST_ENTRY
UseTab: ForContinuationAndIndentation
\ No newline at end of file
.vs/
.vscode/
build*/
bin*/
logs/
dist/
CMakeLists.txt.user*
*.autosave
*.creator
*.creator.user*
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*
*~
.fuse_hudden*
.directory
.Trash-*
.nfs*
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
$RECYCLE.BIN/
*.stackdump
[Dd]esktop.ini
*.egg-info
__pycache__/
env/
venv/
\ No newline at end of file
......@@ -6,5 +6,4 @@ PythonBuild:
artifacts:
untracked: true
script:
- apt-get update && apt-get install python3 -y
- bash build.sh
\ No newline at end of file
- apt-get update && apt-get install python3 -y
\ No newline at end of file
cmake_minimum_required(VERSION 3.8)
project(
"B-ASIC"
VERSION 0.0.1
DESCRIPTION "Better ASIC Toolbox for python3"
LANGUAGES C CXX
)
find_package(fmt 6.1.2 REQUIRED)
find_package(pybind11 CONFIG REQUIRED)
set(LIBRARY_NAME "b_asic")
set(TARGET_NAME "_${LIBRARY_NAME}")
if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY)
include(GNUInstallDirs)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_INSTALL_LIBDIR}")
endif()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_PDB_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_PDB_OUTPUT_DIRECTORY_DEBUG "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_PDB_OUTPUT_DIRECTORY_RELEASE "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
pybind11_add_module(
"${TARGET_NAME}"
"${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp"
)
target_include_directories(
"${TARGET_NAME}"
PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/src"
)
target_compile_features(
"${TARGET_NAME}"
PRIVATE
cxx_std_17
)
target_compile_options(
"${TARGET_NAME}"
PRIVATE
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:
-W -Wall -Wextra -Werror -Wno-psabi
$<$<CONFIG:Debug>:-g>
$<$<NOT:$<CONFIG:Debug>>:-O3>
>
$<$<CXX_COMPILER_ID:MSVC>:
/W3 /WX /permissive- /utf-8
$<$<CONFIG:Debug>:/Od>
$<$<NOT:$<CONFIG:Debug>>:/Ot>
>
)
target_link_libraries(
"${TARGET_NAME}"
PRIVATE
fmt::fmt-header-only
)
add_custom_target(
remove_old_python_dir ALL
COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${LIBRARY_NAME}"
COMMENT "Removing old python directory ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${LIBRARY_NAME}"
)
add_custom_target(
copy_python_dir ALL
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_LIST_DIR}/${LIBRARY_NAME}" "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${LIBRARY_NAME}"
COMMENT "Copying python files to ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${LIBRARY_NAME}"
DEPENDS "${TARGET_NAME}" remove_old_python_dir
)
\ No newline at end of file
MIT License
Copyright (c) 2020 TDDD96
Copyright (c) 2020 TDDD96 PUM4
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
include README.md
include LICENSE
include CMakeLists.txt
recursive-include src *.cpp *.h
<img src="https://files.slack.com/files-pri/TSHPRJY83-FTTRW9MQ8/b-asic-logo-opaque.png" width="318" height="100">
<br>
<h3>The leading company in circuit design<h3>
\ No newline at end of file
<img src="logo.png" width="278" height="100">
# B-ASIC - Better ASIC Toolbox
B-ASIC is an ASIC toolbox for Python 3 that simplifies circuit design and optimization.
## Development
How to build and debug the library during development.
### Prerequisites
The following packages are required in order to build the library:
* cmake 3.8+
* gcc 7+/clang 7+/msvc 16+
* fmtlib 6.1.2+
* pybind11 2.3.0+
* python 3.6+
* setuptools
* wheel
* pybind11
* numpy
* pyside2/pyqt5
### Using CMake directly
How to build using CMake.
#### Configuring
In `B-ASIC`:
```
mkdir build
cd build
cmake ..
```
#### Building (Debug)
In `B-ASIC/build`:
```
cmake --build .
```
The output gets written to `B-ASIC/build/lib`.
#### Building (Release)
In `B-ASIC/build`:
```
cmake --build . --config Release
```
The output gets written to `B-ASIC/build/lib`.
### Using setuptools to create a package
How to create a package using setuptools that can be installed using pip.
#### Setup (Binary distribution)
In `B-ASIC`:
```
python3 setup.py bdist_wheel
```
The output gets written to `B-ASIC/dist/b_asic-<version>-<python_tag>-<abi_tag>-<platform_tag>.whl`.
#### Setup (Source distribution)
In `B-ASIC`:
```
python3 setup.py sdist
```
The output gets written to `B-ASIC/dist/b-asic-<version>.tar.gz`.
#### Installation (Binary distribution)
In `B-ASIC/dist`:
```
pip install b_asic-<version>-<python_tag>-<abi_tag>-<platform_tag>.whl
```
#### Installation (Source distribution)
In `B-ASIC/dist`:
```
pip install b-asic-<version>.tar.gz
```
### Running tests
How to run the tests using pytest in a virtual environment.
#### Linux/OS X
In `B-ASIC`:
```
python3 -m venv env
source env/bin/activate
pip install .
pytest
```
#### Windows
In `B-ASIC` (as admin):
```
python3 -m venv env
.\env\Scripts\activate.bat
pip install .
pytest
```
#### Test with coverage
```
pytest --cov=b_asic --cov-report html test
```
## Usage
How to build and use the library as a user.
### Installation
```
pip install b_asic
```
### Importing
```
python3
>>> import b_asic as asic
>>> help(asic)
```
## License
B-ASIC is distributed under the MIT license.
See the included LICENSE file for more information.
"""
Better ASIC Toolbox.
TODO: More info.
"""
from _b_asic import *
from b_asic.basic_operation import *
from b_asic.core_operations import *
from b_asic.operation import *
from b_asic.precedence_chart import *
from b_asic.port import *
from b_asic.schema import *
from b_asic.signal_flow_graph import *
from b_asic.signal import *
from b_asic.simulation import *
\ No newline at end of file
"""
B-ASIC Basic Operation Module.
TODO: More info.
"""
from b_asic.port import InputPort, OutputPort
from b_asic.signal import SignalSource, SignalDestination
from b_asic.operation import Operation
from b_asic.simulation import SimulationState, OperationState
from abc import ABC, abstractmethod
from typing import List, Dict, Optional, Any
from numbers import Number
class BasicOperation(Operation):
"""
Generic abstract operation class which most implementations will derive from.
TODO: More info.
"""
_input_ports: List[InputPort]
_output_ports: List[OutputPort]
_parameters: Dict[str, Optional[Any]]
def __init__(self):
"""
Construct a BasicOperation.
"""
self._input_ports = []
self._output_ports = []
self._parameters = {}
@abstractmethod
def evaluate(self, inputs: list) -> list:
"""
Evaluate the operation and generate a list of output values given a list of input values.
"""
pass
def inputs(self) -> List[InputPort]:
return self._input_ports.copy()
def outputs(self) -> List[OutputPort]:
return self._output_ports.copy()
def input_count(self) -> int:
return len(self._input_ports)
def output_count(self) -> int:
return len(self._output_ports)
def input(self, i: int) -> InputPort:
return self._input_ports[i]
def output(self, i: int) -> OutputPort:
return self._output_ports[i]
def params(self) -> Dict[str, Optional[Any]]:
return self._parameters.copy()
def param(self, name: str) -> Optional[Any]:
return self._parameters.get(name)
def set_param(self, name: str, value: Any) -> None:
assert name in self._parameters # TODO: Error message.
self._parameters[name] = value
def evaluate_outputs(self, state: SimulationState) -> List[Number]:
# TODO: Check implementation.
input_count: int = self.input_count()
output_count: int = self.output_count()
assert input_count == len(self._input_ports) # TODO: Error message.
assert output_count == len(self._output_ports) # TODO: Error message.
self_state: OperationState = state.operation_states[self.identifier()]
while self_state.iteration < state.iteration:
input_values: List[Number] = [0] * input_count
for i in range(input_count):
source: SignalSource = self._input_ports[i].signal().source
input_values[i] = source.operation.evaluate_outputs(state)[source.port_index]
self_state.output_values = self.evaluate(input_values)
assert len(self_state.output_values) == output_count # TODO: Error message.
self_state.iteration += 1
for i in range(output_count):
for signal in self._output_ports[i].signals():
destination: SignalDestination = signal.destination
destination.evaluate_outputs(state)
return self_state.output_values
def split(self) -> List[Operation]:
# TODO: Check implementation.
results = self.evaluate(self._input_ports)
if all(isinstance(e, Operation) for e in results):
return results
return [self]
# TODO: More stuff.
"""
B-ASIC Core Operations Module.
TODO: More info.
"""
from b_asic.port import InputPort, OutputPort
from b_asic.operation import Operation
from b_asic.basic_operation import BasicOperation
from b_asic.graph_id import GraphIDType
from numbers import Number
class Input(Operation):
"""
Input operation.
TODO: More info.
"""
# TODO: Implement all functions.
pass
class Constant(BasicOperation):
"""
Constant value operation.
TODO: More info.
"""
def __init__(self, value: Number):
"""
Construct a Constant.
"""
super().__init__(identifier)
self._output_ports = [OutputPort()] # TODO: Generate appropriate ID for ports.
self._parameters["value"] = value
def evaluate(self, inputs: list) -> list:
return [self.param("value")]
def get_op_name(self) -> GraphIDType:
return "const"
class Addition(BasicOperation):
"""
Binary addition operation.
TODO: More info.
"""
def __init__(self):
"""
Construct an Addition.
"""
super().__init__(self)
self._input_ports = [InputPort(1), InputPort(1)] # TODO: Generate appropriate ID for ports.
self._output_ports = [OutputPort(1)] # TODO: Generate appropriate ID for ports.
def evaluate(self, inputs: list) -> list:
return [inputs[0] + inputs[1]]
def get_op_name(self) -> GraphIDType:
return "add"
class ConstantMultiplication(BasicOperation):
"""
Unary constant multiplication operation.
TODO: More info.
"""
def __init__(self, coefficient: Number):
"""
Construct a ConstantMultiplication.
"""
super().__init__(identifier)
self._input_ports = [InputPort(1)] # TODO: Generate appropriate ID for ports.
self._output_ports = [OutputPort(1)] # TODO: Generate appropriate ID for ports.
self._parameters["coefficient"] = coefficient
def evaluate(self, inputs: list) -> list:
return [inputs[0] * self.param("coefficient")]
def get_op_name(self) -> GraphIDType:
return "const_mul"
# TODO: More operations.
"""
B-ASIC Graph ID module for handling IDs of different objects in a graph.
TODO: More info
"""
from collections import defaultdict
from typing import NewType, Union, DefaultDict
GraphID = NewType("GraphID", str)
GraphIDType = NewType("GraphIDType", str)
GraphIDNumber = NewType("GraphIDNumber", int)
class GraphIDGenerator:
"""
A class that generates Graph IDs for objects.
"""
_next_id_number: DefaultDict[GraphIDType, GraphIDNumber]
def __init__(self):
self._next_id_number = defaultdict(lambda: 1) # Initalises every key element to 1
def get_next_id(self, graph_id_type: GraphIDType) -> GraphID:
"""
Returns the next graph id for a certain graph id type.
"""
graph_id = graph_id_type + str(self._next_id_number[graph_id_type])
self._next_id_number[graph_id_type] += 1 # Increase the current id number
return graph_id
"""
B-ASIC Operation Module.
TODO: More info.
"""
from abc import ABC, abstractmethod
from numbers import Number
from typing import NewType, List, Dict, Optional, Any, TYPE_CHECKING
if TYPE_CHECKING:
from b_asic.port import InputPort, OutputPort
from b_asic.simulation import SimulationState
from b_asic.graph_id import GraphIDType
class Operation(ABC):
"""
Operation interface.
TODO: More info.
"""
@abstractmethod
def inputs(self) -> "List[InputPort]":
"""
Get a list of all input ports.
"""
pass
@abstractmethod
def outputs(self) -> "List[OutputPort]":
"""
Get a list of all output ports.
"""
pass
@abstractmethod
def input_count(self) -> int:
"""
Get the number of input ports.
"""
pass
@abstractmethod
def output_count(self) -> int:
"""
Get the number of output ports.
"""
pass
@abstractmethod
def input(self, i: int) -> "InputPort":
"""
Get the input port at index i.
"""
pass
@abstractmethod
def output(self, i: int) -> "OutputPort":
"""
Get the output port at index i.
"""
pass
@abstractmethod
def params(self) -> Dict[str, Optional[Any]]:
"""
Get a dictionary of all parameter values.
"""
pass
@abstractmethod
def param(self, name: str) -> Optional[Any]:
"""
Get the value of a parameter.
Returns None if the parameter is not defined.
"""
pass
@abstractmethod
def set_param(self, name: str, value: Any) -> None:
"""
Set the value of a parameter.
The parameter must be defined.
"""
pass
@abstractmethod
def evaluate_outputs(self, state: "SimulationState") -> List[Number]:
"""
Simulate the circuit until its iteration count matches that of the simulation state,
then return the resulting output vector.
"""
pass
@abstractmethod
def split(self) -> "List[Operation]":
"""
Split the operation into multiple operations.
If splitting is not possible, this may return a list containing only the operation itself.
"""
pass
@abstractmethod
def get_op_name(self) -> "GraphIDType":
"""Returns a string representing the operation name of the operation."""
pass
# TODO: More stuff.
"""
B-ASIC Port Module.
TODO: More info.
"""
from b_asic.signal import Signal
from abc import ABC, abstractmethod
from typing import NewType, Optional, List, Dict
PortId = NewType("PortId", int)
class Port(ABC):
"""
Abstract port class.
TODO: More info.
"""
_identifier: PortId
def __init__(self, identifier: PortId):
"""
Construct a Port.
"""
self._identifier = identifier
def identifier(self) -> PortId:
"""
Get the unique identifier.
"""
return self._identifier
@abstractmethod
def signals(self) -> List[Signal]:
"""
Get a list of all connected signals.
"""
pass
@abstractmethod
def signal_count(self) -> int:
"""
Get the number of connected signals.
"""
pass
@abstractmethod
def signal(self, i: int = 0) -> Signal:
"""
Get the connected signal at index i.
"""
pass
@abstractmethod
def connect(self, signal: Signal) -> None:
"""
Connect a signal.
"""
pass
@abstractmethod
def disconnect(self, i: int = 0) -> None:
"""
Disconnect a signal.
"""
pass
# TODO: More stuff.
class InputPort(Port):
"""
Input port.
TODO: More info.
"""
_source_signal: Optional[Signal]
def __init__(self, identifier: PortId):
"""
Construct an InputPort.
"""
super().__init__(identifier)
self._source_signal = None
def signals(self) -> List[Signal]:
return [] if self._source_signal == None else [self._source_signal]
def signal_count(self) -> int:
return 0 if self._source_signal == None else 1
def signal(self, i: int = 0) -> Signal:
assert i >= 0 and i < self.signal_count() # TODO: Error message.
assert self._source_signal != None # TODO: Error message.
return self._source_signal
def connect(self, signal: Signal) -> None:
self._source_signal = signal
def disconnect(self, i: int = 0) -> None:
assert i >= 0 and i < self.signal_count() # TODO: Error message.
self._source_signal = None
# TODO: More stuff.
class OutputPort(Port):
"""
Output port.
TODO: More info.
"""
_destination_signals: List[Signal]
def __init__(self, identifier: PortId):
"""
Construct an OutputPort.
"""
super().__init__(identifier)
self._destination_signals = []
def signals(self) -> List[Signal]:
return self._destination_signals.copy()
def signal_count(self) -> int:
return len(self._destination_signals)
def signal(self, i: int = 0) -> Signal:
assert i >= 0 and i < self.signal_count() # TODO: Error message.
return self._destination_signals[i]
def connect(self, signal: Signal) -> None:
assert signal not in self._destination_signals # TODO: Error message.
self._destination_signals.append(signal)
def disconnect(self, i: int = 0) -> None:
assert i >= 0 and i < self.signal_count() # TODO: Error message.
del self._destination_signals[i]
# TODO: More stuff.
"""
B-ASIC Precedence Chart Module.
TODO: More info.
"""
from b_asic.signal_flow_graph import SFG
class PrecedenceChart:
"""
Precedence chart constructed from a signal flow graph.
TODO: More info.
"""
sfg: SFG
# TODO: More members.
def __init__(self, sfg: SFG):
"""
Construct a PrecedenceChart.
"""
self.sfg = sfg
# TODO: Implement.
# TODO: More stuff.
"""
B-ASIC Schema Module.
TODO: More info.
"""
from b_asic.precedence_chart import PrecedenceChart
class Schema:
"""
Schema constructed from a precedence chart.
TODO: More info.
"""
pc: PrecedenceChart
# TODO: More members.
def __init__(self, pc: PrecedenceChart):
"""
Construct a Schema.
"""
self.pc = pc
# TODO: Implement.
# TODO: More stuff.
"""
B-ASIC Signal Module.
TODO: More info.
"""
from b_asic.operation import Operation
from typing import NewType
class SignalSource:
"""
Handle to a signal source.
TODO: More info.
"""
operation: Operation
port_index: int
def __init__(self, operation: Operation, port_index: int):
"""
Construct a SignalSource.
"""
self.operation = operation
self.port_index = port_index
# TODO: More stuff.
class SignalDestination:
"""
Handle to a signal destination.
TODO: More info.
"""
operation: Operation
port_index: int
def __init__(self, operation: Operation, port_index: int):
"""
Construct a SignalDestination.
"""
self.operation = operation
self.port_index = port_index
# TODO: More stuff.
class Signal:
"""
A connection between two operations consisting of a source and destination handle.
TODO: More info.
"""
source: SignalSource
destination: SignalDestination
def __init__(self, source: SignalSource, destination: SignalDestination):
"""
Construct a Signal.
"""
self.source = source
self.destination = destination
# TODO: More stuff.
"""
B-ASIC Signal Flow Graph Module.
TODO: More info.
"""
from b_asic.operation import Operation
from b_asic.basic_operation import BasicOperation
from b_asic.signal import Signal, SignalSource, SignalDestination
from b_asic.simulation import SimulationState, OperationState
from b_asic.graph_id import GraphIDGenerator, GraphID
from typing import List, Dict, Union, Optional
class SFG(BasicOperation):
"""
Signal flow graph.
TODO: More info.
"""
_graph_objects_by_id: Dict[GraphID, Union[Operation, Signal]]
_graph_id_generator: GraphIDGenerator
def __init__(self, input_destinations: List[SignalDestination], output_sources: List[SignalSource]):
"""Constructs an SFG."""
super().__init__()
# TODO: Allocate input/output ports with appropriate IDs.
self._graph_objects_by_id = dict # Map Operation ID to Operation objects
self._graph_id_generator = GraphIDGenerator()
# TODO: Traverse the graph between the inputs/outputs and add to self._operations.
# TODO: Connect ports with signals with appropriate IDs.
def evaluate(self, inputs: list) -> list:
return [] # TODO: Implement
def add_operation(self, operation: Operation) -> GraphID:
"""Adds the entered operation to the SFG's dictionary of graph objects and
returns a generated GraphID for it.
Keyword arguments:
operation: Operation to add to the graph.
"""
return self._add_graph_obj(operation, operation.get_op_name())
def add_signal(self, signal: Signal) -> GraphID:
"""Adds the entered signal to the SFG's dictionary of graph objects and returns
a generated GraphID for it.
Keyword argumentst:
signal: Signal to add to the graph.
"""
return self._add_graph_obj(signal, 'sig')
def find_by_id(self, graph_id: GraphID) -> Optional[Operation]:
"""Finds a graph object based on the entered Graph ID and returns it. If no graph
object with the entered ID was found then returns None.
Keyword arguments:
graph_id: Graph ID of the wanted object.
"""
if graph_id in self._graph_objects_by_id:
return self._graph_objects_by_id[graph_id]
else:
return None
def _add_graph_obj(self, obj: Union[Operation, Signal], operation_id_type: str):
graph_id = self._graph_id_generator.get_next_id(operation_id_type)
self._graph_objects_by_id[graph_id] = obj
return graph_id
"""
B-ASIC Simulation Module.
TODO: More info.
"""
from numbers import Number
from typing import List, Dict
class OperationState:
"""
Simulation state of an operation.
TODO: More info.
"""
output_values: List[Number]
iteration: int
def __init__(self):
"""
Construct an OperationState.
"""
self.output_values = []
self.iteration = 0
class SimulationState:
"""
Simulation state.
TODO: More info.
"""
# operation_states: Dict[OperationId, OperationState]
iteration: int
def __init__(self):
"""
Construct a SimulationState.
"""
self.operation_states = {}
self.iteration = 0
# TODO: More stuff.
#! bin/sh
for n in `find . -name "*.py"`
do
python3 $n
done
\ No newline at end of file
print("Hello world")
\ No newline at end of file