Skip to content

synthesis

Full documentation pages are generated for docstring reference only and may contain symbols imported from other modules. Imported symbols are not distinguished from locally defined symbols and will appear in any module that they are imported into. For better information on where symbols should be imported from, review the sourcecode on the github.

FoSpy.blocks.synthesis

_debug module-attribute

_debug = Debug()

Debug

Source code in FoSpy/_debug.py
class Debug:
    def __init__(self):
        self.on = False

        frame = inspect.currentframe().f_back
        self.module_name = frame.f_globals.get("__name__", "<unknown>")
        self.label = f"|(Debug message from {self.module_name})"
        self.label_width = len(self.label)

    def _get_text_width(self, module=None):
        if module:
            label = f"|(Debug message from {module} via {self.module_name})"
            label_width = len(label)
        else:
            label = self.label
            label_width = self.label_width

        text_width = DEBUG_WIDTH - label_width
        return text_width, label, label_width


    def msg(self,msg, module=None):
        if not self.on:
            return

        text_width, label, label_width = self._get_text_width(module)

        wrapped = textwrap.fill(str(msg), width=text_width)

        for line in wrapped.splitlines():
            print(f'{line:<{text_width}}{label:>{label_width}}')

    def pmsg(self,msg,module=None,**kwargs):
        if not self.on:
            return

        text_width, label, label_width = self._get_text_width(module)

        buf = io.StringIO()
        pprint(msg,stream=buf, width=text_width,**kwargs)
        txt = buf.getvalue()
        for line in txt.splitlines():
            print(f'{line:<{text_width}}{label:>{label_width}}')

label instance-attribute

label = f'|(Debug message from {self.module_name})'

label_width instance-attribute

label_width = len(self.label)

module_name instance-attribute

module_name = frame.f_globals.get('__name__', '<unknown>')

on instance-attribute

on = False

__init__

__init__()
Source code in FoSpy/_debug.py
def __init__(self):
    self.on = False

    frame = inspect.currentframe().f_back
    self.module_name = frame.f_globals.get("__name__", "<unknown>")
    self.label = f"|(Debug message from {self.module_name})"
    self.label_width = len(self.label)

_get_text_width

_get_text_width(module=None)
Source code in FoSpy/_debug.py
def _get_text_width(self, module=None):
    if module:
        label = f"|(Debug message from {module} via {self.module_name})"
        label_width = len(label)
    else:
        label = self.label
        label_width = self.label_width

    text_width = DEBUG_WIDTH - label_width
    return text_width, label, label_width

msg

msg(msg, module=None)
Source code in FoSpy/_debug.py
def msg(self,msg, module=None):
    if not self.on:
        return

    text_width, label, label_width = self._get_text_width(module)

    wrapped = textwrap.fill(str(msg), width=text_width)

    for line in wrapped.splitlines():
        print(f'{line:<{text_width}}{label:>{label_width}}')

pmsg

pmsg(msg, module=None, **kwargs)
Source code in FoSpy/_debug.py
def pmsg(self,msg,module=None,**kwargs):
    if not self.on:
        return

    text_width, label, label_width = self._get_text_width(module)

    buf = io.StringIO()
    pprint(msg,stream=buf, width=text_width,**kwargs)
    txt = buf.getvalue()
    for line in txt.splitlines():
        print(f'{line:<{text_width}}{label:>{label_width}}')

FileBlock

Bases: SingleBlock

Represents a set of blocks loaded from a file.

All public attributes of FileBlock objects are either SingleBlock or ListBlock objects. Attributes without a header at the start of the file are parsed into {"metadata": blockDict} before passing to FileBlock.

Noteable Subclasses:

Synthesis(FileBlock)
TemplateSet(FileBlock)

Source code in FoSpy/blocks/files.py
class FileBlock(SingleBlock):
    """
    Represents a set of blocks loaded from a file.

    All public attributes of `FileBlock` objects are either `SingleBlock` or
    `ListBlock` objects. Attributes without a header at the start of the file
    are parsed into `{"metadata": blockDict}` before passing to `FileBlock`.

    Noteable Subclasses:
    ```
    Synthesis(FileBlock)
    TemplateSet(FileBlock)
    ```
    """

    def __init__(self, blockDict, _sourceFile=None, _dispatched=True):
        """
        Optionally specify _sourceFile before constructing from blockDict using parent `SingleBlock` constructor.
        """
        self._sourceFile = _sourceFile

        self._tempdir = tempfile.TemporaryDirectory()
        self._temppath = Path(self._tempdir.name)
        atexit.register(self.cleanup)

        super().__init__(blockDict, _dispatched=_dispatched)
        self.refresh_attachments()

    def cleanup(self):
        if self._tempdir is not None:
            self._tempdir.cleanup()

    @classmethod
    def fromFile(cls, filepath):
        from .metadata import MetaData
        from ._blockUtils import _unwrap_block
        abspath = os.path.abspath(filepath)
        pathstr = str(abspath)
        try:
            ext = pathstr.lower().split(".")[-1]
        except IndexError:
            raise ValueError(f"Could not determine extension for filepath: {pathstr}")

        ext_map = {
            "fos": dict_from_file,
            "json": lambda fp: json.load(open(fp, "r"))
        }

        if ext not in ext_map:
            raise ValueError(f"Unrecognized file extension '{ext}'. Supported extensions are: {list(ext_map.keys())}")

        blockDict = ext_map[ext](abspath)
        if "metadata" not in blockDict:
            raise ValueError(f"Could not find metadata block in file {abspath}")

        metadata = _unwrap_block(blockDict["metadata"])
        if "fos_type" not in metadata:
            raise ValueError(f"Could not find fos_type in metadata block in file {abspath}")

        typ = metadata.get("fos_type","").lower()
        subcls = MetaData.dispatch.get(typ, ("", cls))[1]

        if not issubclass(subcls, cls):
            raise ValueError(f"Cannot construct {cls.__name__} from file '{abspath}' with incompatible fos_type '{typ}'.")

        return subcls.dispatch_subclass(blockDict, _sourceFile = abspath)

    def save(self, filepath:str=None, json_indent=4, **kwargs):
        """
        Sends a serialized dict to be written to file.

        Args:
            filepath:
                If specified, writes serialized dict to filepath. ks to `self._sourceFile`.
            json_indent:
                Indent to use for json.dump when saving as json
            **kwargs:
                Optional kwargs to pass to saving routine (unique to each file extension)

        Raises:
            ValueError:
                If _sourceFile is not specified (if `FileBlock` was copied from
                another object or constructed directly from a blockDict),
                filepath must be specified.
        """
        from warnings import warn
        saving_as = filepath is not None
        try:
            if not saving_as:
                if self._sourceFile is None:
                    raise ValueError("Synthesis object was constructed without a sourceFile. A save destination must be specified.")
                else:
                    filepath = self._sourceFile
            self._sourceFile = os.path.abspath(filepath)
            self.refresh_attachments()
            pathstr = str(self._sourceFile)
            try:
                ext = pathstr.lower().split(".")[-1]
            except IndexError:
                raise ValueError(f"Could not determine extension for filepath: {pathstr}")

            ext_map = {
                "fos": write_dict_to_file,
                "json": lambda blockDict, fp, **kwargs: json.dump(blockDict, open(fp, "w"), indent=json_indent, **kwargs)
            }

            ext = str(filepath).lower().split(".")[-1]

            if ext not in ext_map:
                raise ValueError(f"Unrecognized file extension '{ext}'. Supported extensions are: {list(ext_map.keys())}")

            blockDict = self.serialize(clean=ext!="fos")

            ext_map[ext](blockDict, self._sourceFile, **kwargs)

        except Exception as e:
            if not saving_as:
                warn(f"Could not save file. Disconnected from source file for safety. Exception: {e}", RuntimeWarning)
                self._sourceFile = None
                return e
            else:
                raise e
        return True

    def check_attachments(self):
        pass

    def matches_file(self):
        reloaded = self.fromFile(self._sourceFile)

        return self.__eq__(reloaded, suppress_routine_paths=True)

_sourceFile instance-attribute

_sourceFile = _sourceFile

_tempdir instance-attribute

_tempdir = tempfile.TemporaryDirectory()

_temppath instance-attribute

_temppath = Path(self._tempdir.name)

__init__

__init__(blockDict, _sourceFile=None, _dispatched=True)

Optionally specify _sourceFile before constructing from blockDict using parent SingleBlock constructor.

Source code in FoSpy/blocks/files.py
def __init__(self, blockDict, _sourceFile=None, _dispatched=True):
    """
    Optionally specify _sourceFile before constructing from blockDict using parent `SingleBlock` constructor.
    """
    self._sourceFile = _sourceFile

    self._tempdir = tempfile.TemporaryDirectory()
    self._temppath = Path(self._tempdir.name)
    atexit.register(self.cleanup)

    super().__init__(blockDict, _dispatched=_dispatched)
    self.refresh_attachments()

check_attachments

check_attachments()
Source code in FoSpy/blocks/files.py
def check_attachments(self):
    pass

cleanup

cleanup()
Source code in FoSpy/blocks/files.py
def cleanup(self):
    if self._tempdir is not None:
        self._tempdir.cleanup()

fromFile classmethod

fromFile(filepath)
Source code in FoSpy/blocks/files.py
@classmethod
def fromFile(cls, filepath):
    from .metadata import MetaData
    from ._blockUtils import _unwrap_block
    abspath = os.path.abspath(filepath)
    pathstr = str(abspath)
    try:
        ext = pathstr.lower().split(".")[-1]
    except IndexError:
        raise ValueError(f"Could not determine extension for filepath: {pathstr}")

    ext_map = {
        "fos": dict_from_file,
        "json": lambda fp: json.load(open(fp, "r"))
    }

    if ext not in ext_map:
        raise ValueError(f"Unrecognized file extension '{ext}'. Supported extensions are: {list(ext_map.keys())}")

    blockDict = ext_map[ext](abspath)
    if "metadata" not in blockDict:
        raise ValueError(f"Could not find metadata block in file {abspath}")

    metadata = _unwrap_block(blockDict["metadata"])
    if "fos_type" not in metadata:
        raise ValueError(f"Could not find fos_type in metadata block in file {abspath}")

    typ = metadata.get("fos_type","").lower()
    subcls = MetaData.dispatch.get(typ, ("", cls))[1]

    if not issubclass(subcls, cls):
        raise ValueError(f"Cannot construct {cls.__name__} from file '{abspath}' with incompatible fos_type '{typ}'.")

    return subcls.dispatch_subclass(blockDict, _sourceFile = abspath)

matches_file

matches_file()
Source code in FoSpy/blocks/files.py
def matches_file(self):
    reloaded = self.fromFile(self._sourceFile)

    return self.__eq__(reloaded, suppress_routine_paths=True)

save

save(filepath=None, json_indent=4, **kwargs)

Sends a serialized dict to be written to file.

Parameters:

Name Type Description Default
filepath str

If specified, writes serialized dict to filepath. ks to self._sourceFile.

None
json_indent

Indent to use for json.dump when saving as json

4
**kwargs

Optional kwargs to pass to saving routine (unique to each file extension)

{}

Raises:

Type Description
ValueError

If _sourceFile is not specified (if FileBlock was copied from another object or constructed directly from a blockDict), filepath must be specified.

Source code in FoSpy/blocks/files.py
def save(self, filepath:str=None, json_indent=4, **kwargs):
    """
    Sends a serialized dict to be written to file.

    Args:
        filepath:
            If specified, writes serialized dict to filepath. ks to `self._sourceFile`.
        json_indent:
            Indent to use for json.dump when saving as json
        **kwargs:
            Optional kwargs to pass to saving routine (unique to each file extension)

    Raises:
        ValueError:
            If _sourceFile is not specified (if `FileBlock` was copied from
            another object or constructed directly from a blockDict),
            filepath must be specified.
    """
    from warnings import warn
    saving_as = filepath is not None
    try:
        if not saving_as:
            if self._sourceFile is None:
                raise ValueError("Synthesis object was constructed without a sourceFile. A save destination must be specified.")
            else:
                filepath = self._sourceFile
        self._sourceFile = os.path.abspath(filepath)
        self.refresh_attachments()
        pathstr = str(self._sourceFile)
        try:
            ext = pathstr.lower().split(".")[-1]
        except IndexError:
            raise ValueError(f"Could not determine extension for filepath: {pathstr}")

        ext_map = {
            "fos": write_dict_to_file,
            "json": lambda blockDict, fp, **kwargs: json.dump(blockDict, open(fp, "w"), indent=json_indent, **kwargs)
        }

        ext = str(filepath).lower().split(".")[-1]

        if ext not in ext_map:
            raise ValueError(f"Unrecognized file extension '{ext}'. Supported extensions are: {list(ext_map.keys())}")

        blockDict = self.serialize(clean=ext!="fos")

        ext_map[ext](blockDict, self._sourceFile, **kwargs)

    except Exception as e:
        if not saving_as:
            warn(f"Could not save file. Disconnected from source file for safety. Exception: {e}", RuntimeWarning)
            self._sourceFile = None
            return e
        else:
            raise e
    return True

Synthesis

Bases: FileBlock

Represents a Synthesis loaded from a FOS file.

Source code in FoSpy/blocks/synthesis.py
class Synthesis(FileBlock):
    """
    Represents a Synthesis loaded from a FOS file.
    """

    def insert_material(self, mat, idx=-1):
        # placeholder. modify for insertion at idx
        self.materials.append(mat)

    def insert_treatment(self, treat, idx=-1):
        # placeholder. modify for insertion at idx
        self.treatments.append(treat)

insert_material

insert_material(mat, idx=-1)
Source code in FoSpy/blocks/synthesis.py
def insert_material(self, mat, idx=-1):
    # placeholder. modify for insertion at idx
    self.materials.append(mat)

insert_treatment

insert_treatment(treat, idx=-1)
Source code in FoSpy/blocks/synthesis.py
def insert_treatment(self, treat, idx=-1):
    # placeholder. modify for insertion at idx
    self.treatments.append(treat)