Beispiel #1
0
    def emit_initialization(self, source_file):
        source_file.add(configure_serial(self.cfg, self.serial.baudrate))

        if self.serial.stdio:
            source_file.add(cgen.Line())
            source_file.add(cgen.LineComment(f"Setup stdio"))
            source_file.add(cgen.Statement(f"stdout = &uart_stdout"))
Beispiel #2
0
    def declaration(self, pos):
        """Generates the declarative instructions for the optimizations over
        sites nr. `pos`

        :param pos: The local tensor to copy (should be `< len(X)`)
        :returns: List containing cgen Statements
        """
        max_ltens_size = max(self._ltens_sizes)
        max_left_size = 1 if pos == 0 else max(self._ranks[:pos])
        max_right_size = 1 if pos == self._sites - 1 else max(
            self._ranks[pos:])
        max_tmat_size = max(self._ranks[i] * self._ranks[i + 1]
                            for i in range(self._sites - 2))

        init_statements = [
            c.LineComment(
                "Define the row number the current thread is operating on"),
            c.Initializer(c.Const(c.POD(np.int32, 'mid')),
                          'threadIdx.x + blockIdx.x * blockDim.x'),
            c.LineComment("Allocate shared memory for the local tensors"),
            ccu.CudaShared(
                c.ArrayOf(c.POD(self._dtype, 'x_shared'), max_ltens_size)),
            c.LineComment(
                "Allocate the left-, right-, and transfer contractions"),
            c.ArrayOf(c.POD(self._dtype, 'left_c'), max_left_size),
            c.ArrayOf(c.POD(self._dtype, 'right_c'), max_right_size),
            c.ArrayOf(c.POD(self._dtype, 'tmat_c'), max_tmat_size),
            c.ArrayOf(c.POD(self._dtype, 'buf_c'),
                      max(max_right_size, max_left_size)),
            c.LineComment("Shortcut for current row of design matrix"),
            c.LineComment("Carefull, current_row might be out of bounds!"),
            ConstPointerToConst(self._dtype, 'current_row',
                                'A + (mid * %i)' % sum(self._dims))
        ]

        return init_statements
Beispiel #3
0
 def map_Comment(self, node):
     if node.content:
         return cgen.LineComment(node.content.strip())
     else:
         return []
Beispiel #4
0
def main():
    import argparse

    argparser = argparse.ArgumentParser()
    argparser.add_argument('-c', '--config', type=str, metavar="PATH", required=True)
    argparser.add_argument('-o', '--output-dir', type=str, metavar="PATH", required=True)

    args = argparser.parse_args()

    cfg = load_config(args.config)

    components = []

    serial: Optional[SerialComponent] = None
    systick: Optional[SysTickComponent] = None

    if cfg.components.serial is not None:
        serial = SerialComponent(cfg)
        components.append(serial)

    if cfg.components.systick is not None:
        systick = SysTickComponent(cfg)
        components.append(systick)

    if cfg.components.gpio is not None:
        gpio = GPIOComponent(cfg)
        components.append(gpio)

    if cfg.components.modbus is not None:
        assert systick is not None
        assert serial is not None

        modbus = ModbusComponent(cfg)
        systick.register_systimer(SysTimerDef(name="modbusTimer", repeat=False, handler=True, required_accuracy=1))
        components.append(modbus)

    ### SOURCE
    source_file = SourceFile(is_header=False)

    # source_file.add_include("stdint.h", True)

    for component in components:
        if not component.verify():
            exit(1)
        for path in component.get_source_includes():
            if path is not None:
                source_file.add_include(path, True)

    source_file.add_include("ksystem.h", system=False)

    for component in components:
        component.emit_global_variables(source_file)

    source_file.add(cgen.Statement("extern void setup()"))
    source_file.add(cgen.Statement("extern void loop()"))
    source_file.add(cgen.Line())

    for component in components:
        source_file.add(cgen.LineComment(f"Component: {type(component).__name__}"))
        component.emit_helper_functions(source_file)
        source_file.add_blank()

    with source_file.function("int", "main") as f:

        for component in components:
            f.add(cgen.LineComment(f"Component: {type(component).__name__}"))
            component.emit_initialization(f)
            f.add_blank()

        f.add(cgen.Statement("setup()"))

        f.add(cgen.Statement("sei()"))

        loop_statements = StatementsContainer()
        loop_statements.add("loop()")

        for component in components:
            loop_statements.add_blank()
            loop_statements.add(cgen.LineComment(f"Component: {type(component).__name__}"))
            component.emit_loop(loop_statements)

        f.add(cgen.For("", "", "", cgen.Block(loop_statements.statements)))

    ksystem_cpp_path = os.path.join(args.output_dir, "ksystem.cpp")
    source_file.save(ksystem_cpp_path)

    ### HEADER
    header_file = SourceFile(is_header=True)

    for component in components:
        for path in component.get_header_includes():
            if path is not None:
                header_file.add_include(path, True)

    for component in components:
        header_file.add(cgen.LineComment(f"Component: {type(component).__name__}"))
        component.emit_extern_global_variables(header_file)
        header_file.add_blank()

    header_file.save(os.path.join(args.output_dir, "ksystem.h"))

    ### INTERNAL HEADER
    internal_header_file = SourceFile(is_header=True)

    for component in components:
        internal_header_file.add(cgen.LineComment(f"Component: {type(component).__name__}"))
        component.emit_internal_header(internal_header_file)
        internal_header_file.add_blank()

    internal_header_file.save(os.path.join(args.output_dir, "ksystem_internal.h"))

    ### CMAKE
    sources = []
    include_dirs = []

    for component in components:
        sources += component.get_additional_source_files()
        include_dirs += component.get_additional_header_directories()

    sources = [os.path.join(script_dir, x) for x in sources]
    include_dirs = [os.path.join(script_dir, x) for x in include_dirs]

    nl = "\n  "

    cmake_content = f"""
add_definitions(-DF_CPU={cfg.frequency})

include_directories(generated)
include_directories({os.path.join(script_dir, "library")})

add_avr_library(ksystem STATIC
  ${{CMAKE_CURRENT_LIST_DIR}}/ksystem.cpp
  {nl.join(sources)}
)

avr_target_include_directories(ksystem PUBLIC
  {nl.join(include_dirs)}
)
""".lstrip()

    write_text_file(os.path.join(args.output_dir, "ksystem.cmake"), cmake_content)
Beispiel #5
0
    def finish(self, cgvis):
        graph = self._node
        setup = graph.setup
        insp = graph.inspector
        exec = graph.executor

        cgvis.finish(graph)             # Finish up the graph (write main)

        indent = cgvis.indent
        (srcname, destname) = graph.name.split('_')

        # 1) Call the setup function (graph)
        mid = ['%s%s' % (indent, cg.LineComment('1) Call the setup function'))]
        args = ['argv[%d]' % (i + 1) for i in range(len(setup.params))]
        retval = ''
        if len(setup.returntype) > 0:
            retval = '%s %s' % (setup.returntype, srcname)
        stmt = CGenHelper.functionCall(setup.name, args, retval)
        mid.append("%s%s\n" % (indent, stmt))

        # 2) Call the inspector...
        mid.append('%s%s' % (indent, '// 2) Call the inspector'))
        retval = ''
        if len(insp.returntype) > 0:
            retval = '%s %s' % (insp.returntype, destname)

        # Time the inspector:
        if cgvis.profile:
            mid.append('%s%s' % (indent, 'double tinsp = get_time();'))

        # Assume 1st arg is struct from inspector, and remaining parameters are command line args
        args = [srcname]
        for i in range(1, len(insp.params)):
            argval = 'argv[%d]' % (i + 1)
            argtype = insp.params[i].type
            if 'char' not in argtype:
                argval = 'ato%s(%s)' % (argtype[0], argval)
            args.append(argval)
        stmt = CGenHelper.functionCall(insp.name, args, retval)
        mid.append("%s%s" % (indent, stmt))

        if cgvis.profile:
            mid.append(indent + 'fprintf(stderr,"' + insp.name + '::%.6lf seconds elapsed\\n", (get_time() - tinsp));')

        # 3) Call the executor...
        mid.append("\n%s%s" % (indent, '// 3) Call the executor'))
        # Time the executor:
        if cgvis.profile:
            mid.append('%s%s' % (indent, 'double texec = get_time();'))

        stmt = CGenHelper.functionCall(exec.name, [destname], '')
        mid.append('%s%s' % (indent, stmt))
        if cgvis.profile:
            mid.append(indent + 'fprintf(stderr,"' + exec.name + '::%.6lf seconds elapsed\\n", (get_time() - texec));')

        # Insert the middle code in between the top and bottom
        ndx = cgvis.lines.index('%s%s();' % (indent, graph.name))
        top = cgvis.lines[0:ndx]
        bot = cgvis.lines[ndx+1:]

        lines = []
        for list in (top, mid, bot):
            for line in list:
                lines.append(line)

        cgvis.lines = lines
        print(cgvis)
Beispiel #6
0
import cgen as c

code = c.Module([
    c.Include('iostream'),
    c.Include('stdlib.h'),
    c.Include('math.h'),
    c.Line(),
    c.LineComment('Necessary to declare constant for OPS.'),
    c.Value('double', 'dx, dy, dt'),
    c.LineComment('Step for each dimension and time.'),
    c.Value('double', 'nx, ny'),
    c.Line(),
    c.Define('PREVIOUS', '0'),
    c.Define('CURRENT', '1'),
    c.Define('NEXT', '2'),
    c.Define('M_PI', '3.14159265358979323846'),
    c.Define('BORDER_SIZE', '20'),
    c.Define('CPML', '20'),
    c.Define('SOURCE_LOCATION_X', '0'),
    c.Define('SOURCE_LOCATION_Y', '0'),
    c.Define('RICKER_PEAK_FREQUENCY', '5'),
    c.Define('MAX_VELOCITY', '5000'),
    c.Line(),
    c.Define('OPS_2D', ''),
    c.Include('ops_seq.h'),
    c.Include('ops_lib_cpp.h'),
    c.Include('sources.cpp'),
    c.Include('velocity-model.cpp'),
    c.Include('wave-propagation-ops.h'),
    c.Line(),
    c.Statement('using namespace std'),