<commit_before>"""
I/O for Nastran bulk data.

See <http://help.autodesk.com/view/NSTRN/2019/ENU/?guid=GUID-42B54ACB-FBE3-47CA-B8FE-475E7AD91A00>
"""
import logging

import numpy as np

from ..__about__ import __version__
from .._common import num_nodes_per_cell
from .._files import open_file
from .._helpers import register
from .._mesh import CellBlock, Mesh

nastran_to_meshio_type = {
    "CELAS1": "vertex",
    "CBEAM": "line",
    "CBUSH": "line",
    "CBUSH1D": "line",
    "CROD": "line",
    "CGAP": "line",
    "CBAR": "line",
    "CTRIAR": "triangle",
    "CTRIA3": "triangle",
    "CTRAX6": "triangle6",
    "CTRIAX6": "triangle6",
    "CTRIA6": "triangle6",
    "CQUADR": "quad",
    "CSHEAR": "quad",
    "CQUAD4": "quad",
    "CQUAD8": "quad8",
    "CQUAD9": "quad9",
    "CTETRA": "tetra",
    "CTETRA_": "tetra10",  # fictive
    "CPYRAM": "pyramid",
    "CPYRA": "pyramid",
    "CPYRA_": "pyramid13",  # fictive
    "CPENTA": "wedge",
    "CPENTA_": "wedge15",  # fictive
    "CHEXA": "hexahedron",
    "CHEXA_": "hexahedron20",  # fictive
}
nastran_solid_types = ["CTETRA", "CPYRA", "CPENTA", "CHEXA"]
meshio_to_nastran_type = {v: k for k, v in nastran_to_meshio_type.items()}

def read(filename):
    with open_file(filename, "r") as f:
        out = read_buffer(f)
    return out

def read_buffer(f):
    # Skip until BEGIN BULK
    while True:
        line = f.readline()
        if not line:
            raise RuntimeError('"BEGIN BULK" statement not found')
        if line.strip().startswith("BEGIN BULK"):
            break

    # Reading data
    points = []
    points_id = []
    cells = []
    cells_id = []
    cell = None
    cell_type = None
    point_refs = []
    cell_refs = []
    cell_ref = None

    def add_cell(nastran_type, cell, cell_type, cell_ref):
        cell_type = nastran_to_meshio_type[keyword]
        cell = list(map(int, cell))
        cell = _convert_to_vtk_ordering(cell, nastran_type)

        # Treat 2nd order CTETRA, CPYRA, CPENTA, CHEXA elements
        if len(cell) > num_nodes_per_cell[cell_type]:
            assert cell_type in ["tetra", "pyramid", "wedge", "hexahedron"]
            if cell_type == "tetra":
                cell_type = "tetra10"
            elif cell_type == "pyramid":
                cell_type = "pyramid13"
            elif cell_type == "wedge":
                cell_type = "wedge15"
            elif cell_type == "hexahedron":
                cell_type = "hexahedron20"

        if len(cells) > 0 and cells[-1].type == cell_type:
            cells[-1].data.append(cell)
            cells_id[-1].append(cell_id)
            if cell_ref is not None:
                cell_refs[-1].append(cell_ref)
        else:
            cells.append(CellBlock(cell_type, [cell]))
            cells_id.append([cell_id])
            if cell_ref is not None:
                cell_refs.append([cell_ref])

    while True:
        next_line = f.readline()
        # Blank lines or comments
        if len(next_line) < 4 or next_line.startswith(("$", "//", "#")):
            continue
        else:
            break

    while True:
        # End loop when ENDDATA detected
        if next_line.startswith("ENDDATA"):
            break

        # read line and merge with all continuation lines (starting with `+`)
        chunks = _chunk_line(next_line)
        while True:
            next_line = f.readline()
            if not next_line:
                exit(1)
            next_line = next_line.rstrip()
            # Blank lines or comments
            if len(next_line) < 4 or next_line.startswith(("$", "//", "#")):
                continue
            elif next_line[0] == "+":
                # skip the continuation chunk
                chunks += _chunk_line(next_line)[1:]
            else:
                break

        chunks = [chunk.strip() for chunk in chunks]

        keyword = chunks[0]

        # Points
        if keyword == "GRID":
            point_id = int(chunks[1])
            pref = chunks[2].strip()
            if len(pref) > 0:
                point_refs.append(int(pref))
            points_id.append(point_id)
            points.append([_nastran_string_to_float(i) for i in chunks[3:6]])
        elif keyword == "GRID*":  # large field format: 8 + 16*4 + 8
            point_id = int(chunks[1] + chunks[2])
            pref = (chunks[3] + chunks[4]).strip()
            if len(pref) > 0:
                point_refs.append(int(pref))
            points_id.append(point_id)
            chunks2 = _chunk_line(next_line)
            next_line = f.readline()
            points.append(
                [
                    _nastran_string_to_float(i + j)
                    for i, j in [chunks[5:7], chunks[7:9], chunks2[1:3]]
                ]
            )

        # CellBlock
        elif keyword in nastran_to_meshio_type:
            cell_id = int(chunks[1])
            cell_ref = chunks[2].strip()
            cell_ref = int(cell_ref) if len(cell_ref) > 0 else None

            if keyword == "CBAR":
                # A CBAR line can be
                # ```
                # CBAR          37               3       11.0     0.0     0.0
                # ```
                # No idea what the last three floats are. Just remove them.
                cell = chunks[3:5]
            else:
                cell = chunks[3:]

            # remove empty chunks
            cell = [item for item in cell if item != ""]

            if cell is not None:
                add_cell(keyword, cell, cell_type, cell_ref)

    # Convert to numpy arrays
    points = np.array(points)
    points_id = np.array(points_id, dtype=int)
    for k, (c, cid) in enumerate(zip(cells, cells_id)):
        cells[k] = CellBlock(c.type, np.array(c.data, dtype=int))
        cells_id[k] = np.array(cid, dtype=int)

    # Convert to natural point ordering
    # https://stackoverflow.com/questions/16992713/translate-every-element-in-numpy-array-according-to-key
    points_id_dict = dict(zip(points_id, np.arange(len(points), dtype=int)))
    points_id_get = np.vectorize(points_id_dict.__getitem__)
    for k, c in enumerate(cells):
        cells[k] = CellBlock(c.type, points_id_get(c.data))

    # Construct the mesh object
    mesh = Mesh(points, cells)
    mesh.points_id = points_id
    mesh.cells_id = cells_id
    if len(point_refs) > 0:
        mesh.point_data["nastran:ref"] = np.array(point_refs)
    if len(cell_refs) > 0:
        mesh.cell_data["nastran:ref"] = [np.array(i) for i in cell_refs]
    return mesh

# There are two basic categories of input data formats in NX Nastran:
#
#     "Free" format data, in which the data fields are simply separated by commas. This type of data is known as free field data.
#     "Fixed" format data, in which your data must be aligned in columns of specific width. There are two subcategories of fixed format data that differ based on the size of the fixed column width:
#         Small field format, in which a single line of data is divided into 10 fields that can contain eight characters each.
#         Large field format, in which a single line of input is expanded into two lines The first and last fields on each line are eight columns wide, while the intermediate fields are sixteen columns wide. The large field format is useful when you need greater numerical accuracy.
#
# See: https://docs.plm.automation.siemens.com/data_services/resources/nxnastran/10/help/en_US/tdocExt/pdf/User.pdf

def write(filename, mesh, point_format="fixed-large", cell_format="fixed-small"):
    if point_format == "free":
        grid_fmt = "GRID,{:d},{:s},{:s},{:s},{:s}\n"
        float_fmt = _float_to_nastran_string
    elif point_format == "fixed-small":
        grid_fmt = "GRID    {:<8d}{:<8s}{:>8s}{:>8s}{:>8s}\n"
        float_fmt = _float_rstrip
    elif point_format == "fixed-large":
        grid_fmt = "GRID*   {:<16d}{:<16s}{:>16s}{:>16s}\n*       {:>16s}\n"
        float_fmt = _float_to_nastran_string
    else:
        raise RuntimeError(f'unknown "{format}" format')

    if cell_format == "free":
        int_fmt, cell_info_fmt = "{:d}", "{:s},{:d},{:s},"
        sjoin = ","
    elif cell_format == "fixed-small":
        int_fmt, cell_info_fmt = "{:<8d}", "{:<8s}{:<8d}{:<8s}"
        sjoin, cchar = "", "+"
        nipl1, nipl2 = 6, 14
    elif cell_format == "fixed-large":
        int_fmt, cell_info_fmt = "{:<16d}", "{:<8s}{:<16d}{:<16s}"
        sjoin, cchar = "", "*"
        nipl1, nipl2 = 2, 6
    else:
        raise RuntimeError(f'unknown "{format}" format')

    if mesh.points.shape[1] == 2:
        logging.warning(
            "Nastran requires 3D points, but 2D points given. "
            "Appending 0 third component."
        )
        points = np.column_stack([mesh.points, np.zeros(mesh.points.shape[0])])
    else:
        points = mesh.points

    with open_file(filename, "w") as f:
        f.write(f"$ Nastran file written by meshio v{__version__}\n")
        f.write("BEGIN BULK\n")

        # Points
        point_refs = mesh.point_data.get("nastran:ref", None)
        for point_id, x in enumerate(points):
            fx = [float_fmt(k) for k in x]
            pref = str(point_refs[point_id]) if point_refs is not None else ""
            f.write(grid_fmt.format(point_id + 1, pref, fx[0], fx[1], fx[2]))

        # CellBlock
        cell_id = 0
        cell_refs = mesh.cell_data.get("nastran:ref", None)
        for ict, (cell_type, cells) in enumerate(mesh.cells):
            nastran_type = meshio_to_nastran_type[cell_type].replace("_", "")
            if cell_format.endswith("-large"):
                nastran_type += "*"
            if cell_refs is not None:
                cell_refs_t = cell_refs[ict]
            else:
                cell_ref = ""
            for ic, cell in enumerate(cells):
                if cell_refs is not None:
                    cell_ref = str(int(cell_refs_t[ic]))
                cell_id += 1
                cell_info = cell_info_fmt.format(nastran_type, cell_id, cell_ref)
                cell1 = cell + 1
                cell1 = _convert_to_nastran_ordering(cell1, nastran_type)
                conn = sjoin.join(int_fmt.format(nid) for nid in cell1[:nipl1])
                if len(cell1) > nipl1:
                    if cell_format == "free":
                        cflag1 = cflag3 = ""
                        cflag2 = cflag4 = "+,"
                    else:
                        cflag1 = cflag2 = f"{cchar}1{cell_id:<6x}"
                        cflag3 = cflag4 = f"{cchar}2{cell_id:<6x}"
                    f.write(cell_info + conn + cflag1 + "\n")
                    conn = sjoin.join(int_fmt.format(nid) for nid in cell1[nipl1:nipl2])
                    if len(cell1) > nipl2:
                        f.write(cflag2 + conn + cflag3 + "\n")
                        conn = sjoin.join(int_fmt.format(nid) for nid in cell1[nipl2:])
                        f.write(cflag4 + conn + "\n")
                    else:
                        f.write(cflag2 + conn + "\n")
                else:
                    f.write(cell_info + conn + "\n")

        f.write("ENDDATA\n")

def _float_rstrip(x, n=8):
    return f"{x:f}".rstrip("0")[:n]

def _float_to_nastran_string(value, length=16):
    """
    Return a value in NASTRAN scientific notation.
    Examples:
        1234.56789 --> "1.23456789+3"
        -0.1234 --> "-1.234-1"
        3.1415926535897932 --> "3.14159265359+0"
    """
    aux = length - 2
    # sfmt = "{" + f":{length}s" + "}"
    sfmt = "{" + ":s" + "}"
    pv_fmt = "{" + f":{length}.{aux}e" + "}"

    if value == 0.0:
        return sfmt.format("0.")

    python_value = pv_fmt.format(value)  # -1.e-2
    svalue, sexponent = python_value.strip().split("e")
    exponent = int(sexponent)  # removes 0s

    sign = "-" if abs(value) < 1.0 else "+"

    # the exponent will be added later...
    sexp2 = str(exponent).strip("-+")
    value2 = float(svalue)

    # the plus 1 is for the sign
    len_sexp = len(sexp2) + 1
    leftover = length - len_sexp
    leftover = leftover - 3 if value < 0 else leftover - 2
    fmt = "{" + f":1.{leftover:d}f" + "}"

    svalue3 = fmt.format(value2)
    svalue4 = svalue3.strip("0")
    field = sfmt.format(svalue4 + sign + sexp2)
    return field

def _nastran_string_to_float(string):
    try:
        return float(string)
    except ValueError:
        string = string.strip()
        return float(string[0] + string[1:].replace("+", "e+").replace("-", "e-"))

def _chunk_line(line):
    if "," in line:  # free format
        chunks = line.split(",")
    else:  # fixed format
        CHUNK_SIZE = 8
        chunks = [line[i : CHUNK_SIZE + i] for i in range(0, len(line), CHUNK_SIZE)]
    # everything after the 9th chunk is ignored
    return chunks[:9]

def _convert_to_vtk_ordering(cell, nastran_type):
    if nastran_type in ["CTRAX6", "CTRIAX6"]:
        cell = [cell[i] for i in [0, 2, 4, 1, 3, 5]]
    return cell

def _convert_to_nastran_ordering(cell, nastran_type):
    if nastran_type in ["CTRAX6", "CTRIAX6"]:
        cell = [cell[i] for i in [0, 3, 1, 4, 2, 5]]
    return cell

register("nastran", [".bdf", ".fem", ".nas"], read, {"nastran": write})
<commit_msg>nastran: exit -> raise<commit_after>"""
I/O for Nastran bulk data.
"""
import logging

import numpy as np

from ..__about__ import __version__
from .._common import num_nodes_per_cell
from .._exceptions import ReadError
from .._files import open_file
from .._helpers import register
from .._mesh import CellBlock, Mesh

nastran_to_meshio_type = {
    "CELAS1": "vertex",
    "CBEAM": "line",
    "CBUSH": "line",
    "CBUSH1D": "line",
    "CROD": "line",
    "CGAP": "line",
    "CBAR": "line",
    "CTRIAR": "triangle",
    "CTRIA3": "triangle",
    "CTRAX6": "triangle6",
    "CTRIAX6": "triangle6",
    "CTRIA6": "triangle6",
    "CQUADR": "quad",
    "CSHEAR": "quad",
    "CQUAD4": "quad",
    "CQUAD8": "quad8",
    "CQUAD9": "quad9",
    "CTETRA": "tetra",
    "CTETRA_": "tetra10",  # fictive
    "CPYRAM": "pyramid",
    "CPYRA": "pyramid",
    "CPYRA_": "pyramid13",  # fictive
    "CPENTA": "wedge",
    "CPENTA_": "wedge15",  # fictive
    "CHEXA": "hexahedron",
    "CHEXA_": "hexahedron20",  # fictive
}
nastran_solid_types = ["CTETRA", "CPYRA", "CPENTA", "CHEXA"]
meshio_to_nastran_type = {v: k for k, v in nastran_to_meshio_type.items()}

def read(filename):
    with open_file(filename, "r") as f:
        out = read_buffer(f)
    return out

def read_buffer(f):
    # Skip until BEGIN BULK
    while True:
        line = f.readline()
        if not line:
            raise RuntimeError('"BEGIN BULK" statement not found')
        if line.strip().startswith("BEGIN BULK"):
            break

    # Reading data
    points = []
    points_id = []
    cells = []
    cells_id = []
    cell = None
    cell_type = None
    point_refs = []
    cell_refs = []
    cell_ref = None

    def add_cell(nastran_type, cell, cell_type, cell_ref):
        cell_type = nastran_to_meshio_type[keyword]
        cell = list(map(int, cell))
        cell = _convert_to_vtk_ordering(cell, nastran_type)

        # Treat 2nd order CTETRA, CPYRA, CPENTA, CHEXA elements
        if len(cell) > num_nodes_per_cell[cell_type]:
            assert cell_type in ["tetra", "pyramid", "wedge", "hexahedron"]
            if cell_type == "tetra":
                cell_type = "tetra10"
            elif cell_type == "pyramid":
                cell_type = "pyramid13"
            elif cell_type == "wedge":
                cell_type = "wedge15"
            elif cell_type == "hexahedron":
                cell_type = "hexahedron20"

        if len(cells) > 0 and cells[-1].type == cell_type:
            cells[-1].data.append(cell)
            cells_id[-1].append(cell_id)
            if cell_ref is not None:
                cell_refs[-1].append(cell_ref)
        else:
            cells.append(CellBlock(cell_type, [cell]))
            cells_id.append([cell_id])
            if cell_ref is not None:
                cell_refs.append([cell_ref])

    while True:
        next_line = f.readline()
        # Blank lines or comments
        if len(next_line) < 4 or next_line.startswith(("$", "//", "#")):
            continue
        else:
            break

    while True:
        # End loop when ENDDATA detected
        if next_line.startswith("ENDDATA"):
            break

        # read line and merge with all continuation lines (starting with `+`)
        chunks = _chunk_line(next_line)
        while True:
            next_line = f.readline()
            if not next_line:
                raise ReadError("Premature EOF")
            next_line = next_line.rstrip()
            # Blank lines or comments
            if len(next_line) < 4 or next_line.startswith(("$", "//", "#")):
                continue
            elif next_line[0] == "+":
                # skip the continuation chunk
                chunks += _chunk_line(next_line)[1:]
            else:
                break

        chunks = [chunk.strip() for chunk in chunks]

        keyword = chunks[0]

        # Points
        if keyword == "GRID":
            point_id = int(chunks[1])
            pref = chunks[2].strip()
            if len(pref) > 0:
                point_refs.append(int(pref))
            points_id.append(point_id)
            points.append([_nastran_string_to_float(i) for i in chunks[3:6]])
        elif keyword == "GRID*":  # large field format: 8 + 16*4 + 8
            point_id = int(chunks[1] + chunks[2])
            pref = (chunks[3] + chunks[4]).strip()
            if len(pref) > 0:
                point_refs.append(int(pref))
            points_id.append(point_id)
            chunks2 = _chunk_line(next_line)
            next_line = f.readline()
            points.append(
                [
                    _nastran_string_to_float(i + j)
                    for i, j in [chunks[5:7], chunks[7:9], chunks2[1:3]]
                ]
            )

        # CellBlock
        elif keyword in nastran_to_meshio_type:
            cell_id = int(chunks[1])
            cell_ref = chunks[2].strip()
            cell_ref = int(cell_ref) if len(cell_ref) > 0 else None

            if keyword == "CBAR":
                # A CBAR line can be
                # ```
                # CBAR          37               3       11.0     0.0     0.0
                # ```
                # No idea what the last three floats are. Just remove them.
                cell = chunks[3:5]
            else:
                cell = chunks[3:]

            # remove empty chunks
            cell = [item for item in cell if item != ""]

            if cell is not None:
                add_cell(keyword, cell, cell_type, cell_ref)

    # Convert to numpy arrays
    points = np.array(points)
    points_id = np.array(points_id, dtype=int)
    for k, (c, cid) in enumerate(zip(cells, cells_id)):
        cells[k] = CellBlock(c.type, np.array(c.data, dtype=int))
        cells_id[k] = np.array(cid, dtype=int)

    # Convert to natural point ordering
    # https://stackoverflow.com/questions/16992713/translate-every-element-in-numpy-array-according-to-key
    points_id_dict = dict(zip(points_id, np.arange(len(points), dtype=int)))
    points_id_get = np.vectorize(points_id_dict.__getitem__)
    for k, c in enumerate(cells):
        cells[k] = CellBlock(c.type, points_id_get(c.data))

    # Construct the mesh object
    mesh = Mesh(points, cells)
    mesh.points_id = points_id
    mesh.cells_id = cells_id
    if len(point_refs) > 0:
        mesh.point_data["nastran:ref"] = np.array(point_refs)
    if len(cell_refs) > 0:
        mesh.cell_data["nastran:ref"] = [np.array(i) for i in cell_refs]
    return mesh

# There are two basic categories of input data formats in NX Nastran:
#
#     "Free" format data, in which the data fields are simply separated by commas. This type of data is known as free field data.
#     "Fixed" format data, in which your data must be aligned in columns of specific width. There are two subcategories of fixed format data that differ based on the size of the fixed column width:
#         Small field format, in which a single line of data is divided into 10 fields that can contain eight characters each.
#         Large field format, in which a single line of input is expanded into two lines The first and last fields on each line are eight columns wide, while the intermediate fields are sixteen columns wide. The large field format is useful when you need greater numerical accuracy.
#
# See: https://docs.plm.automation.siemens.com/data_services/resources/nxnastran/10/help/en_US/tdocExt/pdf/User.pdf

def write(filename, mesh, point_format="fixed-large", cell_format="fixed-small"):
    if point_format == "free":
        grid_fmt = "GRID,{:d},{:s},{:s},{:s},{:s}\n"
        float_fmt = _float_to_nastran_string
    elif point_format == "fixed-small":
        grid_fmt = "GRID    {:<8d}{:<8s}{:>8s}{:>8s}{:>8s}\n"
        float_fmt = _float_rstrip
    elif point_format == "fixed-large":
        grid_fmt = "GRID*   {:<16d}{:<16s}{:>16s}{:>16s}\n*       {:>16s}\n"
        float_fmt = _float_to_nastran_string
    else:
        raise RuntimeError(f'unknown "{format}" format')

    if cell_format == "free":
        int_fmt, cell_info_fmt = "{:d}", "{:s},{:d},{:s},"
        sjoin = ","
    elif cell_format == "fixed-small":
        int_fmt, cell_info_fmt = "{:<8d}", "{:<8s}{:<8d}{:<8s}"
        sjoin, cchar = "", "+"
        nipl1, nipl2 = 6, 14
    elif cell_format == "fixed-large":
        int_fmt, cell_info_fmt = "{:<16d}", "{:<8s}{:<16d}{:<16s}"
        sjoin, cchar = "", "*"
        nipl1, nipl2 = 2, 6
    else:
        raise RuntimeError(f'unknown "{format}" format')

    if mesh.points.shape[1] == 2:
        logging.warning(
            "Nastran requires 3D points, but 2D points given. "
            "Appending 0 third component."
        )
        points = np.column_stack([mesh.points, np.zeros(mesh.points.shape[0])])
    else:
        points = mesh.points

    with open_file(filename, "w") as f:
        f.write(f"$ Nastran file written by meshio v{__version__}\n")
        f.write("BEGIN BULK\n")

        # Points
        point_refs = mesh.point_data.get("nastran:ref", None)
        for point_id, x in enumerate(points):
            fx = [float_fmt(k) for k in x]
            pref = str(point_refs[point_id]) if point_refs is not None else ""
            f.write(grid_fmt.format(point_id + 1, pref, fx[0], fx[1], fx[2]))

        # CellBlock
        cell_id = 0
        cell_refs = mesh.cell_data.get("nastran:ref", None)
        for ict, (cell_type, cells) in enumerate(mesh.cells):
            nastran_type = meshio_to_nastran_type[cell_type].replace("_", "")
            if cell_format.endswith("-large"):
                nastran_type += "*"
            if cell_refs is not None:
                cell_refs_t = cell_refs[ict]
            else:
                cell_ref = ""
            for ic, cell in enumerate(cells):
                if cell_refs is not None:
                    cell_ref = str(int(cell_refs_t[ic]))
                cell_id += 1
                cell_info = cell_info_fmt.format(nastran_type, cell_id, cell_ref)
                cell1 = cell + 1
                cell1 = _convert_to_nastran_ordering(cell1, nastran_type)
                conn = sjoin.join(int_fmt.format(nid) for nid in cell1[:nipl1])
                if len(cell1) > nipl1:
                    if cell_format == "free":
                        cflag1 = cflag3 = ""
                        cflag2 = cflag4 = "+,"
                    else:
                        cflag1 = cflag2 = f"{cchar}1{cell_id:<6x}"
                        cflag3 = cflag4 = f"{cchar}2{cell_id:<6x}"
                    f.write(cell_info + conn + cflag1 + "\n")
                    conn = sjoin.join(int_fmt.format(nid) for nid in cell1[nipl1:nipl2])
                    if len(cell1) > nipl2:
                        f.write(cflag2 + conn + cflag3 + "\n")
                        conn = sjoin.join(int_fmt.format(nid) for nid in cell1[nipl2:])
                        f.write(cflag4 + conn + "\n")
                    else:
                        f.write(cflag2 + conn + "\n")
                else:
                    f.write(cell_info + conn + "\n")

        f.write("ENDDATA\n")

def _float_rstrip(x, n=8):
    return f"{x:f}".rstrip("0")[:n]

def _float_to_nastran_string(value, length=16):
    """
    Return a value in NASTRAN scientific notation.
    Examples:
        1234.56789 --> "1.23456789+3"
        -0.1234 --> "-1.234-1"
        3.1415926535897932 --> "3.14159265359+0"
    """
    aux = length - 2
    # sfmt = "{" + f":{length}s" + "}"
    sfmt = "{" + ":s" + "}"
    pv_fmt = "{" + f":{length}.{aux}e" + "}"

    if value == 0.0:
        return sfmt.format("0.")

    python_value = pv_fmt.format(value)  # -1.e-2
    svalue, sexponent = python_value.strip().split("e")
    exponent = int(sexponent)  # removes 0s

    sign = "-" if abs(value) < 1.0 else "+"

    # the exponent will be added later...
    sexp2 = str(exponent).strip("-+")
    value2 = float(svalue)

    # the plus 1 is for the sign
    len_sexp = len(sexp2) + 1
    leftover = length - len_sexp
    leftover = leftover - 3 if value < 0 else leftover - 2
    fmt = "{" + f":1.{leftover:d}f" + "}"

    svalue3 = fmt.format(value2)
    svalue4 = svalue3.strip("0")
    field = sfmt.format(svalue4 + sign + sexp2)
    return field

def _nastran_string_to_float(string):
    try:
        return float(string)
    except ValueError:
        string = string.strip()
        return float(string[0] + string[1:].replace("+", "e+").replace("-", "e-"))

def _chunk_line(line):
    if "," in line:  # free format
        chunks = line.split(",")
    else:  # fixed format
        CHUNK_SIZE = 8
        chunks = [line[i : CHUNK_SIZE + i] for i in range(0, len(line), CHUNK_SIZE)]
    # everything after the 9th chunk is ignored
    return chunks[:9]

def _convert_to_vtk_ordering(cell, nastran_type):
    if nastran_type in ["CTRAX6", "CTRIAX6"]:
        cell = [cell[i] for i in [0, 2, 4, 1, 3, 5]]
    return cell

def _convert_to_nastran_ordering(cell, nastran_type):
    if nastran_type in ["CTRAX6", "CTRIAX6"]:
        cell = [cell[i] for i in [0, 3, 1, 4, 2, 5]]
    return cell

register("nastran", [".bdf", ".fem", ".nas"], read, {"nastran": write})
<|endoftext|>


<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Charliecloud(AutotoolsPackage):
    """Lightweight user-defined software stacks for HPC."""

    maintainers = ['j-ogas', 'reidpr']
    homepage = "https://hpc.github.io/charliecloud"
    url      = "https://github.com/hpc/charliecloud/releases/download/v0.18/charliecloud-0.18.tar.gz"
    git      = "https://github.com/hpc/charliecloud.git"

    version('master', branch='master')
    version('0.21',   sha256='024884074d283c4a0387d899161610fa4ae739ac1efcc9e53d7d626ddc20359f')
    version('0.19',   sha256='99619fd86860cda18f7f7a7cf7391f702ec9ebd3193791320dea647769996447')
    version('0.18',   sha256='15ce63353afe1fc6bcc10979496a54fcd5628f997cb13c827c9fc7afb795bdc5')

    depends_on('m4',       type='build')
    depends_on('autoconf', type='build')
    depends_on('automake', type='build')
    depends_on('libtool',  type='build')

    depends_on('python@3.5:',    type='run')
    depends_on('py-lark-parser', type='run')
    depends_on('py-requests',    type='run')

    # Man pages and html docs variant.
    variant('docs', default=False, description='Build man pages and html docs')
    depends_on('rsync',               type='build', when='+docs')
    depends_on('py-sphinx',           type='build', when='+docs')
    depends_on('py-sphinx-rtd-theme', type='build', when='+docs')

    # See https://github.com/spack/spack/pull/16049.
    conflicts('platform=darwin', msg='This package does not build on macOS')

    # Bash automated testing harness (bats).
    depends_on('bats@0.4.0', type='test')

    def configure_args(self):

        args = []
        py_path = self.spec['python'].command.path
        args.append('--with-python={0}'.format(py_path))

        if '+docs' in self.spec:
            sphinx_bin = '{0}'.format(self.spec['py-sphinx'].prefix.bin)
            args.append('--enable-html')
            args.append('--with-sphinx-build={0}'.format(sphinx_bin.join(
                                                         'sphinx-build')))
        else:
            args.append('--disable-html')

        return args
<commit_msg>add charliecloud 0.22 (#21574)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Charliecloud(AutotoolsPackage):
    """Lightweight user-defined software stacks for HPC."""

    maintainers = ['j-ogas', 'reidpr']
    homepage = "https://hpc.github.io/charliecloud"
    url      = "https://github.com/hpc/charliecloud/releases/download/v0.18/charliecloud-0.18.tar.gz"
    git      = "https://github.com/hpc/charliecloud.git"

    version('master', branch='master')
    version('0.22',   sha256='f65e4111ce87e449c656032da69f3b1cfc70a5a416a5e410329c1b0b2e953907')
    version('0.21',   sha256='024884074d283c4a0387d899161610fa4ae739ac1efcc9e53d7d626ddc20359f')
    version('0.19',   sha256='99619fd86860cda18f7f7a7cf7391f702ec9ebd3193791320dea647769996447')
    version('0.18',   sha256='15ce63353afe1fc6bcc10979496a54fcd5628f997cb13c827c9fc7afb795bdc5')

    depends_on('m4',       type='build')
    depends_on('autoconf', type='build')
    depends_on('automake', type='build')
    depends_on('libtool',  type='build')

    depends_on('python@3.5:',    type='run')
    depends_on('py-lark-parser', type='run')
    depends_on('py-requests',    type='run')

    # Man pages and html docs variant.
    variant('docs', default=False, description='Build man pages and html docs')
    depends_on('rsync',               type='build', when='+docs')
    depends_on('py-sphinx',           type='build', when='+docs')
    depends_on('py-sphinx-rtd-theme', type='build', when='+docs')

    # See https://github.com/spack/spack/pull/16049.
    conflicts('platform=darwin', msg='This package does not build on macOS')

    # Bash automated testing harness (bats).
    depends_on('bats@0.4.0', type='test')

    def configure_args(self):

        args = []
        py_path = self.spec['python'].command.path
        args.append('--with-python={0}'.format(py_path))

        if '+docs' in self.spec:
            sphinx_bin = '{0}'.format(self.spec['py-sphinx'].prefix.bin)
            args.append('--enable-html')
            args.append('--with-sphinx-build={0}'.format(sphinx_bin.join(
                                                         'sphinx-build')))
        else:
            args.append('--disable-html')

        return args
<|endoftext|>


<commit_before>#!/usr/bin/env python

#-------------------------------------------------------------------------
# Copyright (c) Microsoft.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------

from codecs import open
from setuptools import setup

VERSION = '0.0.5'

# The full list of classifiers is available at
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Intended Audience :: Developers',
    'Intended Audience :: System Administrators',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    #'License :: OSI Approved :: Apache Software License',
    #'License :: OSI Approved :: MIT License',
]

DEPENDENCIES = [
    'azure==2.0.0rc1',
]

with open('README.rst', 'r', encoding='utf-8') as f:
    README = f.read()

setup(
    name='azure-cli-network',
    version=VERSION,
    description='Microsoft Azure Command-Line Tools',
    long_description=README,
    license='TBD',
    author='Microsoft Corporation',
    author_email='azpycli@microsoft.com',
    url='https://github.com/Azure/azure-cli',
    classifiers=CLASSIFIERS,
    namespace_packages = [
        'azure',
        'azure.cli',
        'azure.cli.command_modules',
    ],
    packages=[
        'azure.cli.command_modules.network',
        'azure.cli.command_modules.network.mgmt',
        'azure.cli.command_modules.network.mgmt.lib',
    ],
    install_requires=DEPENDENCIES,
)
<commit_msg>annotate all modules<commit_after>#!/usr/bin/env python

#-------------------------------------------------------------------------
# Copyright (c) Microsoft.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------

from codecs import open
from setuptools import setup

VERSION = '0.0.5'

# The full list of classifiers is available at
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Intended Audience :: Developers',
    'Intended Audience :: System Administrators',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    #'License :: OSI Approved :: Apache Software License',
    #'License :: OSI Approved :: MIT License',
]

DEPENDENCIES = [
    'azure==2.0.0rc1',
]

with open('README.rst', 'r', encoding='utf-8') as f:
    README = f.read()

setup(
    name='azure-cli-network',
    version=VERSION,
    description='Microsoft Azure Command-Line Tools',
    long_description=README,
    license='TBD',
    author='Microsoft Corporation',
    author_email='azpycli@microsoft.com',
    url='https://github.com/Azure/azure-cli',
    classifiers=CLASSIFIERS,
    namespace_packages = [
        'azure',
        'azure.cli',
        'azure.cli.command_modules',
    ],
    packages=[
        'azure.cli.command_modules.network',
        'azure.cli.command_modules.network.mgmt',
        'azure.cli.command_modules.network.mgmt.lib',
        'azure.cli.command_modules.network.mgmt.lib.models',
        'azure.cli.command_modules.network.mgmt.lib.operations',
    ],
    install_requires=DEPENDENCIES,
)
<|endoftext|>


<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class DarshanUtil(Package):
    """Darshan (util) is collection of tools for parsing and summarizing log
    files produced by Darshan (runtime) instrumentation. This package is
    typically installed on systems (front-end) where you intend to analyze
    log files produced by Darshan (runtime)."""

    homepage = "http://www.mcs.anl.gov/research/projects/darshan/"
    url = "http://ftp.mcs.anl.gov/pub/darshan/releases/darshan-3.1.0.tar.gz"
    git      = "https://xgitlab.cels.anl.gov/darshan/darshan.git"

    maintainers = ['shanedsnyder', 'carns']

    version('develop', branch='master')
    version('3.2.1', sha256='d63048b7a3d1c4de939875943e3e7a2468a9034fcb68585edbc87f57f622e7f7')
    version('3.2.0', sha256='4035435bdc0fa2a678247fbf8d5a31dfeb3a133baf06577786b1fe8d00a31b7e')
    version('3.1.8', sha256='3ed51c8d5d93b4a8cbb7d53d13052140a9dffe0bc1a3e1ebfc44a36a184b5c82')
    version('3.1.7', sha256='9ba535df292727ac1e8025bdf2dc42942715205cad8319d925723fd88709e8d6')
    version('3.1.6', sha256='21cb24e2a971c45e04476e00441b7fbea63d2afa727a5cf8b7a4a9d9004dd856')
    version('3.1.0', sha256='b847047c76759054577823fbe21075cfabb478cdafad341d480274fb1cef861c')
    version('3.0.0', sha256='95232710f5631bbf665964c0650df729c48104494e887442596128d189da43e0')

    variant('bzip2', default=False, description="Enable bzip2 compression")
    depends_on('zlib')
    depends_on('bzip2', when="+bzip2", type=("build", "link", "run"))

    patch('retvoid.patch', when='@3.2.0:3.2.1')

    def install(self, spec, prefix):

        options = ['CC=%s' % self.compiler.cc,
                   '--with-zlib=%s' % spec['zlib'].prefix]

        with working_dir('spack-build', create=True):
            configure = Executable('../darshan-util/configure')
            configure('--prefix=%s' % prefix, *options)
            make()
            make('install')
<commit_msg>darshan-util" add "shared" variant (#21640)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class DarshanUtil(Package):
    """Darshan (util) is collection of tools for parsing and summarizing log
    files produced by Darshan (runtime) instrumentation. This package is
    typically installed on systems (front-end) where you intend to analyze
    log files produced by Darshan (runtime)."""

    homepage = "http://www.mcs.anl.gov/research/projects/darshan/"
    url = "http://ftp.mcs.anl.gov/pub/darshan/releases/darshan-3.1.0.tar.gz"
    git      = "https://xgitlab.cels.anl.gov/darshan/darshan.git"

    maintainers = ['shanedsnyder', 'carns']

    version('develop', branch='master')
    version('3.2.1', sha256='d63048b7a3d1c4de939875943e3e7a2468a9034fcb68585edbc87f57f622e7f7')
    version('3.2.0', sha256='4035435bdc0fa2a678247fbf8d5a31dfeb3a133baf06577786b1fe8d00a31b7e')
    version('3.1.8', sha256='3ed51c8d5d93b4a8cbb7d53d13052140a9dffe0bc1a3e1ebfc44a36a184b5c82')
    version('3.1.7', sha256='9ba535df292727ac1e8025bdf2dc42942715205cad8319d925723fd88709e8d6')
    version('3.1.6', sha256='21cb24e2a971c45e04476e00441b7fbea63d2afa727a5cf8b7a4a9d9004dd856')
    version('3.1.0', sha256='b847047c76759054577823fbe21075cfabb478cdafad341d480274fb1cef861c')
    version('3.0.0', sha256='95232710f5631bbf665964c0650df729c48104494e887442596128d189da43e0')

    variant('bzip2', default=False, description="Enable bzip2 compression")
    variant('shared', default=True, description='Build shared libraries')

    depends_on('zlib')
    depends_on('bzip2', when="+bzip2", type=("build", "link", "run"))

    patch('retvoid.patch', when='@3.2.0:3.2.1')

    def install(self, spec, prefix):

        options = ['CC=%s' % self.compiler.cc,
                   '--with-zlib=%s' % spec['zlib'].prefix]
        if '+shared' in spec:
            options.extend(['--enable-shared'])

        with working_dir('spack-build', create=True):
            configure = Executable('../darshan-util/configure')
            configure('--prefix=%s' % prefix, *options)
            make()
            make('install')
<|endoftext|>


<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

class PyIpykernel(PythonPackage):
    """IPython Kernel for Jupyter"""

    pypi = "ipykernel/ipykernel-5.3.4.tar.gz"

    version('6.2.0',  sha256='4439459f171d77f35b7f7e72dace5d7c2dd10a5c9e2c22b173ad9048fbfe7656')
    version('5.5.5',  sha256='e976751336b51082a89fc2099fb7f96ef20f535837c398df6eab1283c2070884')
    version('5.3.4',  sha256='9b2652af1607986a1b231c62302d070bc0534f564c393a5d9d130db9abbbe89d')
    version('5.1.1',  sha256='f0e962052718068ad3b1d8bcc703794660858f58803c3798628817f492a8769c')
    version('5.1.0',  sha256='0fc0bf97920d454102168ec2008620066878848fcfca06c22b669696212e292f')
    version('4.10.0', sha256='699103c8e64886e3ec7053f2a6aa83bb90426063526f63a818732ff385202bad')
    version('4.5.0',  sha256='245a798edb8fd751b95750d8645d736dd739a020e7fc7d5627dac4d1c35d8295')
    version('4.4.1',  sha256='6d48398b3112efb733b254edede4b7f3262c28bd19f665b64ef1acf6ec5cd74f')
    version('4.4.0',  sha256='d516427c3bd689205e6693c9616302ef34017b91ada3c9ea3fca6e90702b7ffe')
    version('4.3.1',  sha256='8219d3eaa3e4d4efc5f349114e41a40f0986c91a960846bb81d5da817fb7cc3f')
    version('4.3.0',  sha256='f214c661328c836e02b6f185f98f3eccd7ce396791937493ffa1babf5e3267ab')
    version('4.2.2',  sha256='a876da43e01acec2c305abdd8e6aa55f052bab1196171ccf1cb9a6aa230298b0')
    version('4.2.1',  sha256='081a5d4db33db58697be2d682b92f79b2c239493445f13dd457c15bc3e52c874')
    version('4.2.0',  sha256='723b3d4baac20f0c9cd91fc75c3e813636ecb6c6e303fb34d628c3df078985a7')
    version('4.1.1',  sha256='d8c5555386d0f18f1336dea9800f9f0fe96dcecc9757c0f980e11fdfadb661ff')
    version('4.1.0',  sha256='e0e150ad55e487e49054efc9a4b0e2e17f27e1de77444b26760789077b146d86')

    depends_on('python@2.7:2.8,3.3:', type=('build', 'run'))
    depends_on('python@3.4:', when='@5.0:', type=('build', 'run'))
    depends_on('python@3.5:', when='@5.2:', type=('build', 'run'))
    depends_on('python@3.7:', when='@6.0:', type=('build', 'run'))
    depends_on('py-setuptools', type='build', when='@5:')
    depends_on('py-importlib-metadata@:4', when='@6:^python@:3.7', type=('build', 'run'))
    depends_on('py-argcomplete@1.12.3:', when='@6:^python@:3.7', type=('build', 'run'))
    depends_on('py-debugpy@1.0:1', when='@6:', type=('build', 'run'))
    depends_on('py-ipython@4.0:', when='@:4', type=('build', 'run'))
    depends_on('py-ipython@5.0:', when='@5', type=('build', 'run'))
    depends_on('py-ipython@7.23.1:7', when='@6:', type=('build', 'run'))
    depends_on('py-traitlets@4.1.0:', type=('build', 'run'))
    depends_on('py-traitlets@4.1.0:5', when='@6:', type=('build', 'run'))
    depends_on('py-jupyter-client', type=('build', 'run'))
    depends_on('py-jupyter-client@:7', when='@6:', type=('build', 'run'))
    depends_on('py-tornado@4.0:', when='@:4', type=('build', 'run'))
    depends_on('py-tornado@4.2:', when='@5', type=('build', 'run'))
    depends_on('py-tornado@4.2:6', when='@6:', type=('build', 'run'))
    depends_on('py-appnope', when='platform=darwin', type=('build', 'run'))

    phases = ['build', 'install', 'install_data']

    def install_data(self, spec, prefix):
        """ install the Jupyter kernel spec """
        self.spec['python'].command(
            '-m', 'ipykernel', 'install', '--prefix=' + prefix)
<commit_msg>Add 6.0.2 (#26501)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

class PyIpykernel(PythonPackage):
    """IPython Kernel for Jupyter"""

    pypi = "ipykernel/ipykernel-5.3.4.tar.gz"

    version('6.2.0',  sha256='4439459f171d77f35b7f7e72dace5d7c2dd10a5c9e2c22b173ad9048fbfe7656')
    version('6.0.2',  sha256='7fb3e370dbb481b012b74bed4e794d2d16eb2a83930b31e6d8d030b9fdb4d5b4')
    version('5.5.5',  sha256='e976751336b51082a89fc2099fb7f96ef20f535837c398df6eab1283c2070884')
    version('5.3.4',  sha256='9b2652af1607986a1b231c62302d070bc0534f564c393a5d9d130db9abbbe89d')
    version('5.1.1',  sha256='f0e962052718068ad3b1d8bcc703794660858f58803c3798628817f492a8769c')
    version('5.1.0',  sha256='0fc0bf97920d454102168ec2008620066878848fcfca06c22b669696212e292f')
    version('4.10.0', sha256='699103c8e64886e3ec7053f2a6aa83bb90426063526f63a818732ff385202bad')
    version('4.5.0',  sha256='245a798edb8fd751b95750d8645d736dd739a020e7fc7d5627dac4d1c35d8295')
    version('4.4.1',  sha256='6d48398b3112efb733b254edede4b7f3262c28bd19f665b64ef1acf6ec5cd74f')
    version('4.4.0',  sha256='d516427c3bd689205e6693c9616302ef34017b91ada3c9ea3fca6e90702b7ffe')
    version('4.3.1',  sha256='8219d3eaa3e4d4efc5f349114e41a40f0986c91a960846bb81d5da817fb7cc3f')
    version('4.3.0',  sha256='f214c661328c836e02b6f185f98f3eccd7ce396791937493ffa1babf5e3267ab')
    version('4.2.2',  sha256='a876da43e01acec2c305abdd8e6aa55f052bab1196171ccf1cb9a6aa230298b0')
    version('4.2.1',  sha256='081a5d4db33db58697be2d682b92f79b2c239493445f13dd457c15bc3e52c874')
    version('4.2.0',  sha256='723b3d4baac20f0c9cd91fc75c3e813636ecb6c6e303fb34d628c3df078985a7')
    version('4.1.1',  sha256='d8c5555386d0f18f1336dea9800f9f0fe96dcecc9757c0f980e11fdfadb661ff')
    version('4.1.0',  sha256='e0e150ad55e487e49054efc9a4b0e2e17f27e1de77444b26760789077b146d86')

    depends_on('python@2.7:2.8,3.3:', type=('build', 'run'))
    depends_on('python@3.4:', when='@5.0:', type=('build', 'run'))
    depends_on('python@3.5:', when='@5.2:', type=('build', 'run'))
    depends_on('python@3.7:', when='@6.0:', type=('build', 'run'))
    depends_on('py-setuptools', type='build', when='@5:')
    depends_on('py-importlib-metadata@:4', when='@6:^python@:3.7', type=('build', 'run'))
    depends_on('py-argcomplete@1.12.3:', when='@6:^python@:3.7', type=('build', 'run'))
    depends_on('py-debugpy@1.0:1', when='@6:', type=('build', 'run'))
    depends_on('py-ipython@4.0:', when='@:4', type=('build', 'run'))
    depends_on('py-ipython@5.0:', when='@5', type=('build', 'run'))
    depends_on('py-ipython@7.23.1:7', when='@6:', type=('build', 'run'))
    depends_on('py-traitlets@4.1.0:', type=('build', 'run'))
    depends_on('py-traitlets@4.1.0:5', when='@6:', type=('build', 'run'))
    depends_on('py-jupyter-client', type=('build', 'run'))
    depends_on('py-jupyter-client@:7', when='@6:', type=('build', 'run'))
    depends_on('py-tornado@4.0:', when='@:4', type=('build', 'run'))
    depends_on('py-tornado@4.2:', when='@5', type=('build', 'run'))
    depends_on('py-tornado@4.2:6', when='@6:', type=('build', 'run'))
    depends_on('py-appnope', when='platform=darwin', type=('build', 'run'))

    phases = ['build', 'install', 'install_data']

    def install_data(self, spec, prefix):
        """ install the Jupyter kernel spec """
        self.spec['python'].command(
            '-m', 'ipykernel', 'install', '--prefix=' + prefix)
<|endoftext|>


<commit_before># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

import os
from spack import *

class PyNbconvert(PythonPackage):
    """Jupyter Notebook Conversion"""

    homepage = "https://github.com/jupyter/nbconvert"
    url      = "https://github.com/jupyter/nbconvert/archive/4.2.0.tar.gz"

    version('5.6.0', sha256='21a69fe5756a3af8e76dcc105217cc3bea4d8f23dbff5727d9fd1e4388b53beb')
    version('4.2.0', sha256='32394be5a20f39f99fabfb9b2f2625df17f1c2a6699182ca41598e98e7cc9610')
    version('4.1.0', sha256='459f23381411fd1ff9ec5ed71fcd56b8c080d97b3a1e47dae1c5c391f9a47266')
    version('4.0.0', sha256='00e25eeca90523ba6b774b289073631ef5ac65bb2de9774e9b7f29604516265c')

    variant('execute', default=True, description='Include jupyter-client')
    variant('serve', default=True, description='Include a webserver')

    depends_on('py-pycurl', type='build',                         when='^python@2.7:2.8')
    depends_on('py-setuptools', type='build',                     when='@5:')
    depends_on('python@2.7:2.8,3.3:', type=('build', 'run'))
    depends_on('python@2.7:2.8,3.5:', type=('build', 'run'),      when='@5:')
    depends_on('py-mistune@0.8.1:1.999', type=('build', 'run'))
    depends_on('py-jinja2', type=('build', 'run'))
    depends_on('py-jinja2@2.4:', type=('build', 'run'),           when='@5:')
    depends_on('py-pygments', type=('build', 'run'))
    depends_on('py-traitlets', type=('build', 'run'))
    depends_on('py-traitlets@4.2:', type=('build', 'run'),        when='@5:')
    depends_on('py-jupyter-core', type=('build', 'run'))
    depends_on('py-nbformat', type=('build', 'run'))
    depends_on('py-nbformat@4.4.0:', type=('build', 'run'),       when='@5:')
    depends_on('py-entrypoints', type=('build', 'run'))
    depends_on('py-entrypoints@0.2.2:', type=('build', 'run'),    when='@5:')
    depends_on('py-tornado@4.0:', type=('build', 'run'),          when='+serve')
    depends_on('py-jupyter-client', type=('build', 'run'),        when='+execute')
    depends_on('py-jupyter-client@5.3.1:', type=('build', 'run'), when='@5:+execute')
    depends_on('py-defusedxml', type=('build', 'run'),            when='@5:')
    depends_on('py-testpath', type=('build', 'run'),              when='@5:')
    depends_on('py-bleach', type=('build', 'run'),                when='@5:')
    depends_on('py-pandocfilters@1.4.1:', type=('build', 'run'),  when='@5:')

    def patch(self):
        # We bundle this with the spack package so that the installer
        # doesn't try to download it.
        install(os.path.join(self.package_dir, 'style.min.css'),
                os.path.join('nbconvert', 'resources', 'style.min.css'))
<commit_msg>Fix py-jupyter-client version ranges (#14126)<commit_after># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

import os
from spack import *

class PyNbconvert(PythonPackage):
    """Jupyter Notebook Conversion"""

    homepage = "https://github.com/jupyter/nbconvert"
    url      = "https://github.com/jupyter/nbconvert/archive/4.2.0.tar.gz"

    version('5.6.0', sha256='21a69fe5756a3af8e76dcc105217cc3bea4d8f23dbff5727d9fd1e4388b53beb')
    version('4.2.0', sha256='32394be5a20f39f99fabfb9b2f2625df17f1c2a6699182ca41598e98e7cc9610')
    version('4.1.0', sha256='459f23381411fd1ff9ec5ed71fcd56b8c080d97b3a1e47dae1c5c391f9a47266')
    version('4.0.0', sha256='00e25eeca90523ba6b774b289073631ef5ac65bb2de9774e9b7f29604516265c')

    variant('execute', default=True, description='Include jupyter-client')
    variant('serve', default=True, description='Include a webserver')

    depends_on('py-pycurl', type='build',                         when='^python@2.7:2.8')
    depends_on('py-setuptools', type='build',                     when='@5:')
    depends_on('python@2.7:2.8,3.3:', type=('build', 'run'))
    depends_on('python@2.7:2.8,3.5:', type=('build', 'run'),      when='@5:')
    depends_on('py-mistune@0.8.1:1.999', type=('build', 'run'))
    depends_on('py-jinja2', type=('build', 'run'))
    depends_on('py-jinja2@2.4:', type=('build', 'run'),           when='@5:')
    depends_on('py-pygments', type=('build', 'run'))
    depends_on('py-traitlets', type=('build', 'run'))
    depends_on('py-traitlets@4.2:', type=('build', 'run'),        when='@5:')
    depends_on('py-jupyter-core', type=('build', 'run'))
    depends_on('py-nbformat', type=('build', 'run'))
    depends_on('py-nbformat@4.4.0:', type=('build', 'run'),       when='@5:')
    depends_on('py-entrypoints', type=('build', 'run'))
    depends_on('py-entrypoints@0.2.2:', type=('build', 'run'),    when='@5:')
    depends_on('py-tornado@4.0:', type=('build', 'run'),          when='+serve')
    depends_on('py-jupyter-client', type=('build', 'run'),        when='+execute')
    depends_on('py-jupyter-client@4.2:', type=('build', 'run'),   when='@5.2.1:+execute')
    depends_on('py-jupyter-client@5.3.1:', type=('build', 'run'), when='@5.6.0:+execute')
    depends_on('py-defusedxml', type=('build', 'run'),            when='@5:')
    depends_on('py-testpath', type=('build', 'run'),              when='@5:')
    depends_on('py-bleach', type=('build', 'run'),                when='@5:')
    depends_on('py-pandocfilters@1.4.1:', type=('build', 'run'),  when='@5:')

    def patch(self):
        # We bundle this with the spack package so that the installer
        # doesn't try to download it.
        install(os.path.join(self.package_dir, 'style.min.css'),
                os.path.join('nbconvert', 'resources', 'style.min.css'))
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 23:25:33 2017

@author: asadm2
"""

from __future__ import division, print_function, absolute_import
from glob import glob
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
import subprocess

eco_repo_path = '/fs1/masad/Research/Repositories/ECO_Globular_Clusters/'

goodObj = '../../../data/interim/goodObj.txt'
good_Obj = pd.read_csv(goodObj,header=None)
good_Obj.columns = ['ECOID']

ECOnew  = '../../../data/interim/ECO_formatted.txt'
ECO_new  = pd.read_csv(ECOnew, delimiter='\t')

ECOphotcat = '../../../data/interim/ECOphot_final.txt'
ECO_phot_cat  = pd.read_csv(ECOphotcat, delim_whitespace=True,header=None,\
                            skiprows=1,names=['ECOID','RA','DEC','VLG','umag',\
                                              'gmag','rmag','imag','zmag',\
                                              'Jmag','Hmag','Kmag'])

good_Obj_new = good_Obj.ECOID[:4].append(good_Obj.ECOID[5:11].append(good_Obj\
                             .ECOID[104:105]))

#good_Obj_new = ['ECO12028']

sdssr_calc = []
sdssr_cat = []
for obj in good_Obj_new:
    print(obj)
    dir_path = os.getcwd()
    if os.path.basename(dir_path) == 'main':
        os.chdir('../../../data/interim/'+obj)
    elif os.path.basename(dir_path) != obj:
        os.chdir('../interim/'+obj)

    comb_coadd = glob(obj+'comb_coadd.fits')[0]
    f814_coadd = glob(obj+'_acs_wfc_f814w_coadd.fits')[0]

    print('Starting source extractor')
    subprocess.call(['sex',comb_coadd+","+f814_coadd,'-ANALYSIS_THRESH','1.5',\
    '-BACK_SIZE','128','-DEBLEND_MINCONT','0.0025', '-DETECT_THRESH','1.5',\
    '-DETECT_MINAREA','9','-SEEING_FWHM','0.1',\
    '-CATALOG_NAME',obj+'acs_wfc_f814w.cat'])
    print('Finished running source extractor')

    hdu_f814w_coadd = fits.open(f814_coadd)
    prihdr = hdu_f814w_coadd[0].header
    photflam814 = prihdr['PHOTFLAM']
    photzpt814 = prihdr['PHOTZPT']
    print('Calculating zeropoint')
    zpt814 = -2.5*np.log10(photflam814) + photzpt814

    ra = np.unique(ECO_new.RA.loc[ECO_new.ECOID==obj])[0]
    dec = np.unique(ECO_new.DEC.loc[ECO_new.ECOID==obj])[0]

    print('Converting to pixel coordinates')
    wcs = WCS(prihdr)
    print(wcs)
    xx,yy = wcs.wcs_world2pix(ra,dec,1)
    print(xx,yy)

#remember to copy already uncommented default.param file and remove other one
#remember to copy all default files to last obj in contents_new

#glob comb_coadd and store as image1
#glob f814 coadd and store as image2
#use subprocess to pass parameters
#open filter image and get necessary keywords for finding zeropoint
#get RA and DEC of galaxy from ECO catalog
#open filter image and get WCS info to find world2pix transformation for RA and
#DEC of galaxy
#open catalog that sextractor generated and get petro mag in f814 at
#calculated x and y pixel values
#Apply zeropoint to magnitude
#Use conversion to change to r band
#Get r band mag from photometry catalog
#Plot both points for each galaxy

#need to use WCS

    print('Reading test.cat')
    f814w_cat = pd.read_csv(obj+'acs_wfc_f814w.cat',header=None,\
                            delim_whitespace=True,skiprows=7,\
                            names=['petro_mag','petro_magerr','petro_radius',\
                                  'x_image','y_image','a_image','class_star'])

    print('Getting petro mag from test.cat')
#    print(f814w_cat.x_image==xx)
#    print(f814w_cat.y_image==yy)
    f814mag = f814w_cat.petro_mag.loc[(np.abs(f814w_cat.x_image-xx)<0.0001)&\
                                      (np.abs(f814w_cat.y_image-yy)<0.0001)]\
                                      .values[0]

    print('Calculating rmag')
    f814mag += zpt814
    sdss_r = f814mag - 1

    print('Retrieving rmag from catalog')
    sdss_r_cat = ECO_phot_cat.rmag.loc[ECO_phot_cat.ECOID==obj].values[0]

    sdssr_calc.append(sdss_r)
    sdssr_cat.append(sdss_r_cat)
    hdu_f814w_coadd.close()

print('Plotting')
x = np.linspace(0,len(good_Obj_new.values)+1,len(good_Obj_new.values))
my_xticks = good_Obj_new.values
fig1 = plt.figure(figsize=(10,8))
plt.xticks(x, my_xticks,rotation=90)
plt.scatter(x,sdssr_calc, c='r',label='calculated rmag')
plt.scatter(x,sdssr_cat, c='g',label='catalog rmag')
plt.xlabel('ECOID')
plt.ylabel('rmag')
plt.gca().invert_yaxis()
plt.title('Comparison of calculated rmag and rmag from ECO photometric table')
plt.savefig('calcrmag_catrmag.png')

    <commit_msg>Checking pixel scale addition to swarp with ECO00026<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 23:25:33 2017

@author: asadm2
"""

from __future__ import division, print_function, absolute_import
from glob import glob
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
import subprocess

eco_repo_path = '/fs1/masad/Research/Repositories/ECO_Globular_Clusters/'

goodObj = '../../../data/interim/goodObj.txt'
good_Obj = pd.read_csv(goodObj,header=None)
good_Obj.columns = ['ECOID']

ECOnew  = '../../../data/interim/ECO_formatted.txt'
ECO_new  = pd.read_csv(ECOnew, delimiter='\t')

ECOphotcat = '../../../data/interim/ECOphot_final.txt'
ECO_phot_cat  = pd.read_csv(ECOphotcat, delim_whitespace=True,header=None,\
                            skiprows=1,names=['ECOID','RA','DEC','VLG','umag',\
                                              'gmag','rmag','imag','zmag',\
                                              'Jmag','Hmag','Kmag'])

#good_Obj_new = good_Obj.ECOID[:4].append(good_Obj.ECOID[5:11].append(good_Obj\
#                             .ECOID[104:105]))

good_Obj_new = ['ECO00026'] #REMOVE THIS

sdssr_calc = []
sdssr_cat = []
for obj in good_Obj_new:
    print(obj)
    dir_path = os.getcwd()
    if os.path.basename(dir_path) == 'main':
        os.chdir('../../../data/interim/'+obj)
    elif os.path.basename(dir_path) != obj:
        os.chdir('../interim/'+obj)

    comb_coadd = glob(obj+'_comb_coadd.fits')[0]
    f814_coadd = glob(obj+'_acs_wfc_f814w_coadd.fits')[0]

    print('Starting source extractor')
    subprocess.call(['sex',comb_coadd+","+f814_coadd,'-ANALYSIS_THRESH','1.5',\
    '-BACK_SIZE','128','-DEBLEND_MINCONT','0.0025', '-DETECT_THRESH','1.5',\
    '-DETECT_MINAREA','9','-SEEING_FWHM','0.1',\
    '-CATALOG_NAME',obj+'acs_wfc_f814w_scaletest.cat']) #CHANGE THIS
    print('Finished running source extractor')

    hdu_f814w_coadd = fits.open(f814_coadd)
    prihdr = hdu_f814w_coadd[0].header
    photflam814 = prihdr['PHOTFLAM']
    photzpt814 = prihdr['PHOTZPT']
    print('Calculating zeropoint')
    zpt814 = -2.5*np.log10(photflam814) + photzpt814

    ra = np.unique(ECO_new.RA.loc[ECO_new.ECOID==obj])[0]
    dec = np.unique(ECO_new.DEC.loc[ECO_new.ECOID==obj])[0]

    print('Converting to pixel coordinates')
    wcs = WCS(prihdr)
    print(wcs)
    xx,yy = wcs.wcs_world2pix(ra,dec,1)
    print(xx,yy)

#remember to copy already uncommented default.param file and remove other one
#remember to copy all default files to last obj in contents_new

#glob comb_coadd and store as image1
#glob f814 coadd and store as image2
#use subprocess to pass parameters
#open filter image and get necessary keywords for finding zeropoint
#get RA and DEC of galaxy from ECO catalog
#open filter image and get WCS info to find world2pix transformation for RA and
#DEC of galaxy
#open catalog that sextractor generated and get petro mag in f814 at
#calculated x and y pixel values
#Apply zeropoint to magnitude
#Use conversion to change to r band
#Get r band mag from photometry catalog
#Plot both points for each galaxy

#need to use WCS

    print('Reading test.cat')
    #CHANGE NAME
    f814w_cat = pd.read_csv(obj+'acs_wfc_f814w_scaletest.cat',header=None,\
                            delim_whitespace=True,skiprows=7,\
                            names=['petro_mag','petro_magerr','petro_radius',\
                                  'x_image','y_image','a_image','class_star'])

    print('Getting petro mag from test.cat')
#    print(f814w_cat.x_image==xx)
#    print(f814w_cat.y_image==yy)
    f814mag = f814w_cat.petro_mag.loc[(np.abs(f814w_cat.x_image-xx)<0.0001)&\
                                      (np.abs(f814w_cat.y_image-yy)<0.0001)]\
                                      .values[0]

    print('Calculating rmag')
    f814mag += zpt814
    sdss_r = f814mag - 1

    print('Retrieving rmag from catalog')
    sdss_r_cat = ECO_phot_cat.rmag.loc[ECO_phot_cat.ECOID==obj].values[0]

    sdssr_calc.append(sdss_r)
    sdssr_cat.append(sdss_r_cat)
    hdu_f814w_coadd.close()

print('Plotting')
x = np.linspace(0,len(good_Obj_new.values)+1,len(good_Obj_new.values))
my_xticks = good_Obj_new.values
fig1 = plt.figure(figsize=(10,8))
plt.xticks(x, my_xticks,rotation=90)
plt.scatter(x,sdssr_calc, c='r',label='calculated rmag')
plt.scatter(x,sdssr_cat, c='g',label='catalog rmag')
plt.xlabel('ECOID')
plt.ylabel('rmag')
plt.gca().invert_yaxis()
plt.title('Comparison of calculated rmag and rmag from ECO photometric table')
plt.savefig('calcrmag_catrmag.png')

    <|endoftext|>


<commit_before>from spack import *

class SuiteSparse(Package):
    """
    SuiteSparse is a suite of sparse matrix algorithms
    """
    homepage = 'http://faculty.cse.tamu.edu/davis/suitesparse.html'
    url = 'http://faculty.cse.tamu.edu/davis/SuiteSparse/SuiteSparse-4.5.1.tar.gz'

    version('4.5.1', 'f0ea9aad8d2d1ffec66a5b6bfeff5319')

    depends_on('blas')
    depends_on('lapack')

    depends_on('metis@5.1.0', when='@4.5.1')

    def install(self, spec, prefix):
        # The build system of SuiteSparse is quite old-fashioned
        # It's basically a plain Makefile which include an header (SuiteSparse_config/SuiteSparse_config.mk)
        # with a lot of convoluted logic in it.
        # Any kind of customization will need to go through filtering of that file

        # FIXME : this actually uses the current workaround
        # FIXME : (blas / lapack always provide libblas and liblapack as aliases)
        make('install', 'INSTALL=%s' % prefix, 'BLAS=-lblas', 'LAPACK=-llapack')
<commit_msg>Make suite-sparse use spack compilers.<commit_after>from spack import *

class SuiteSparse(Package):
    """
    SuiteSparse is a suite of sparse matrix algorithms
    """
    homepage = 'http://faculty.cse.tamu.edu/davis/suitesparse.html'
    url = 'http://faculty.cse.tamu.edu/davis/SuiteSparse/SuiteSparse-4.5.1.tar.gz'

    version('4.5.1', 'f0ea9aad8d2d1ffec66a5b6bfeff5319')

    depends_on('blas')
    depends_on('lapack')

    depends_on('metis@5.1.0', when='@4.5.1')

    def install(self, spec, prefix):
        # The build system of SuiteSparse is quite old-fashioned
        # It's basically a plain Makefile which include an header (SuiteSparse_config/SuiteSparse_config.mk)
        # with a lot of convoluted logic in it.
        # Any kind of customization will need to go through filtering of that file

        # FIXME : this actually uses the current workaround
        # FIXME : (blas / lapack always provide libblas and liblapack as aliases)
        make('install', 'INSTALL=%s' % prefix,

             # inject Spack compiler wrappers
             'AUTOCC=no',
             'CC=cc',
             'CXX=c++',
             'F77=f77',

             # BLAS arguments require path to libraries
             'BLAS=-lblas',
             'LAPACK=-llapack')
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# dials.reflection_viewer.py
#
#  Copyright (C) 2014 Diamond Light Source
#
#  Author: Luis Fuentes-Montero (Luiso)
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division
import wx
import numpy as np
# set backend before importing pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

class wxbmp_from_np_array(object):

  def get_bmp(self, data_3d_in):
    print "data_3d_in =\n", data_3d_in

    print "data_3d_in[0:1, :, 0:1] =\n", data_3d_in[0:1, :, 0:1]
    print "data_3d_in[0:1, 0:1, :] =\n", data_3d_in[0:1, 0:1, :]

    print "data_3d_in.shape[0] =\n", data_3d_in.shape[0]
    print "data_3d_in.shape[1] =\n", data_3d_in.shape[1]
    print "data_3d_in.shape[2] =\n", data_3d_in.shape[2]

    z_dp = data_3d_in.shape[0]
    self.xmax = data_3d_in.shape[1]
    self.ymax = data_3d_in.shape[2]

    self.np_slice_lst = []
    tmp_data2d = np.zeros( (self.xmax, self.ymax), 'double')

    for z in range(z_dp):
      tmp_data2d[:, :] = data_3d_in[z:z + 1, :, :]
      self.np_slice_lst.append(tmp_data2d)

    self.vl_max = np.amax(data_3d_in)
    self.vl_min = np.amin(data_3d_in)
    wx_bmp_lst = []
    for single_np_2d in self.np_slice_lst:
      wx_bmp_lst.append(self.wxbmp(single_np_2d))

    return wx_bmp_lst

  def wxbmp(self, np_2d_tmp):

    d = self.vl_max - self.vl_min
    vl_mid_low = self.vl_min + d / 3.0
    vl_mid_hig = self.vl_max - d / 3.0
    lc_fig = plt.figure(frameon=False)
    lc_fig.set_size_inches(self.xmax * .6, self.ymax * .6)
    ax = plt.Axes(lc_fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    lc_fig.add_axes(ax)
    plt.imshow(np.transpose(np_2d_tmp), interpolation = "nearest", cmap = 'hot')

    for xpos in range(self.xmax):
      for ypos in range(self.ymax):
        f_num = np_2d_tmp[xpos,ypos]
        g = float("{0:.2f}".format(float(f_num)))

        txt_dat = str(g)
        if( g < vl_mid_low ):
          clr_chr = 'yellow'
        elif(g > vl_mid_hig):
          clr_chr = 'black'
        else:
          clr_chr = 'blue'
        plt.annotate(txt_dat, xy = (xpos - 0.3, ypos + 0.3), xycoords = 'data'
                     , color = clr_chr, size = 12.)

    lc_fig.canvas.draw()
    width, height = lc_fig.canvas.get_width_height()
    np_buf = np.fromstring (lc_fig.canvas.tostring_rgb(), dtype=np.uint8)
    np_buf.shape = (width, height, 3)
    np_buf = np.roll(np_buf, 3, axis = 2)
    wx_image = wx.EmptyImage(width, height)
    wx_image.SetData(np_buf )
    wxBitmap = wx_image.ConvertToBitmap()

    plt.close(lc_fig)

    return wxBitmap<commit_msg>starting to organise MY mess<commit_after>#!/usr/bin/env python
#
# dials.reflection_viewer.py
#
#  Copyright (C) 2014 Diamond Light Source
#
#  Author: Luis Fuentes-Montero (Luiso)
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division
import wx
import numpy as np
# set backend before importing pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

class wxbmp_from_np_array(object):

  def get_bmp(self, data_3d_in):
    print "data_3d_in =\n", data_3d_in

    print "data_3d_in[0:1, :, 0:1] =\n", data_3d_in[0:1, :, 0:1]
    print "data_3d_in[0:1, 0:1, :] =\n", data_3d_in[0:1, 0:1, :]

    print "data_3d_in.shape[0] =\n", data_3d_in.shape[0]
    print "data_3d_in.shape[1] =\n", data_3d_in.shape[1]
    print "data_3d_in.shape[2] =\n", data_3d_in.shape[2]

    z_dp = data_3d_in.shape[0]
    self.xmax = data_3d_in.shape[1]
    self.ymax = data_3d_in.shape[2]

    self.vl_max = np.amax(data_3d_in)
    self.vl_min = np.amin(data_3d_in)

    wx_bmp_lst = []
    tmp_data2d = np.zeros( (self.xmax, self.ymax), 'double')
    for z in range(z_dp):
      tmp_data2d[:, :] = data_3d_in[z:z + 1, :, :]
      wx_bmp_lst.append(self.wxbmp(tmp_data2d))

    return wx_bmp_lst

  def wxbmp(self, np_2d_tmp):

    d = self.vl_max - self.vl_min
    vl_mid_low = self.vl_min + d / 3.0
    vl_mid_hig = self.vl_max - d / 3.0
    lc_fig = plt.figure(frameon=False)
    lc_fig.set_size_inches(self.xmax * .6, self.ymax * .6)
    ax = plt.Axes(lc_fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    lc_fig.add_axes(ax)
    plt.imshow(np.transpose(np_2d_tmp), interpolation = "nearest", cmap = 'hot')

    for xpos in range(self.xmax):
      for ypos in range(self.ymax):
        f_num = np_2d_tmp[xpos,ypos]
        g = float("{0:.2f}".format(float(f_num)))

        txt_dat = str(g)
        if( g < vl_mid_low ):
          clr_chr = 'yellow'
        elif(g > vl_mid_hig):
          clr_chr = 'black'
        else:
          clr_chr = 'blue'
        plt.annotate(txt_dat, xy = (xpos - 0.3, ypos + 0.3), xycoords = 'data'
                     , color = clr_chr, size = 12.)

    lc_fig.canvas.draw()
    width, height = lc_fig.canvas.get_width_height()
    np_buf = np.fromstring (lc_fig.canvas.tostring_rgb(), dtype=np.uint8)
    np_buf.shape = (width, height, 3)
    np_buf = np.roll(np_buf, 3, axis = 2)
    wx_image = wx.EmptyImage(width, height)
    wx_image.SetData(np_buf )
    wxBitmap = wx_image.ConvertToBitmap()

    plt.close(lc_fig)

    return wxBitmap<|endoftext|>


<commit_before># !/usr/bin/env python

#    Copyright (c) 2014 Max Beloborodko.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

__author__ = 'f1ashhimself@gmail.com'

from ..interfaces.i_element import IElement
import atomac
from ..utils.mac_utils import MacUtils
from .. import TooSaltyUISoupException
from .mouse import MacMouse

class MacElement(IElement):

    _acc_role_name_map = {
        'AXWindow': u'frm',
        'AXTextArea': u'txt',
        'AXTextField': u'txt',
        'AXButton': u'btn',
        'AXStaticText': u'lbl',
        'AXRadioButton': u'rbtn',
        'AXSlider': u'sldr',
        'AXCell': u'tblc',
        'AXImage': u'img',
        'AXToolbar': u'tbar',
        'AXScrollBar': u'scbr',
        'AXMenuItem': u'mnu',
        'AXMenu': u'mnu',
        'AXMenuBar': u'mnu',
        'AXMenuBarItem': u'mnu',
        'AXCheckBox': u'chk',
        'AXTabGroup': u'ptl',
        'AXList': u'lst',
        'AXMenuButton': u'cbo',
        'AXRow': u'tblc',
        'AXColumn': u'col',
        'AXTable': u'tbl',
        'AXScrollArea': u'sar',
        'AXOutline': u'otl',
        'AXValueIndicator': u'val',
        'AXDisclosureTriangle': u'dct',
        'AXGroup': u'grp',
        'AXPopUpButton': u'pubtn',
        'AXApplication': u'app',
        'AXDocItem': u'doc',
        'AXHeading': u'tch',
        'AXGenericElement': u'gen',
        'AXLink': u'lnk'
    }

    _mouse = MacMouse()

    def __init__(self, atomac_object, process_name, process_id):
        """
        Constructor.

        Arguments:
            - atomac_object: string, object selector.
        """

        self._element = atomac_object
        self._proc_name = process_name
        self._proc_id = process_id
        self._cached_children = set()
        self._cached_properties = None

    @property
    def _properties(self):
        """
        Property for element properties.
        """

        if not self._cached_properties:
            self._cached_properties = \
                MacUtils.ApplescriptExecutor.get_element_properties(self._element)

        return self._cached_properties

    @property
    def _role(self):
        """
        Property for element role.
        """

        return self._properties.get('AXRole', None)

    def _find_windows_by_same_proc(self):
        """
        Find window by same process id.

        Arguments:
            - None

        Returns:
            - list of windows.
        """

        app = atomac.getAppRefByPid(self.proc_id)
        app.activate()
        return app.windowsR()

    def click(self, x_offset=None, y_offset=None):
        x, y, w, h = self.acc_location
        x += x_offset if x_offset is not None else int(w / 2)
        y += y_offset if y_offset is not None else int(h / 2)

        self._mouse.click(x, y)
        self._cached_properties = None

    def right_click(self, x_offset=0, y_offset=0):
        x, y, w, h = self.acc_location
        x += x_offset if x_offset is not None else w / 2
        y += y_offset if y_offset is not None else h / 2

        self._mouse.click(x, y, self._mouse.RIGHT_BUTTON)
        self._cached_properties = None

    def double_click(self, x_offset=0, y_offset=0, click_interval=0.5):
        x, y, w, h = self.acc_location
        x += x_offset if x_offset is not None else w / 2
        y += y_offset if y_offset is not None else h / 2

        self._mouse.double_click(x, y, click_interval=click_interval)
        self._cached_properties = None

    def drag_to(self, x, y, x_offset=None, y_offset=None, smooth=True):
        el_x, el_y, el_w, el_h = self.acc_location
        el_x += x_offset if x_offset is not None else el_w / 2
        el_y += y_offset if y_offset is not None else el_h / 2

        self._mouse.drag(el_x, el_y, x, y, smooth)
        self._cached_properties = None

    @property
    def proc_id(self):
        return self._proc_id

    @property
    def is_top_level_window(self):
        return self._properties.get('AXParent', 'false') == 'false'

    @property
    def is_selected(self):
        result = False
        if self.acc_role_name == self._acc_role_name_map['AXRadioButton'] and \
                self._properties.get('AXValue', 'false') == 'true':
            result = True

        return result

    @property
    def is_checked(self):
        result = False
        if self.acc_role_name == self._acc_role_name_map['AXCheckBox'] and \
                self._properties.get('AXValue', 'false') == 'true':
            result = True

        return result

    @property
    def is_visible(self):
        return True  # We can't work with invisible elements under Mac OS.

    @property
    def is_enabled(self):
        return bool(self._properties.get('AXEnabled', False))

    @property
    def acc_parent_count(self):
        return 0

    @property
    def acc_child_count(self):
        return len(self._properties.get('AXChildren'))

    @property
    def acc_name(self):
        result = self._properties.get('AXDescription') or \
            self._properties.get('AXTitle') or \
            self._properties.get('AXValue')

        return MacUtils.replace_inappropriate_symbols(result or '')

    def set_focus(self):
        # TODO:
        MacUtils.ApplescriptExecutor.set_element_attribute_value(
            self._object_selector, 'AXFocused', 'true', self._proc_name, False)

    @property
    def acc_c_name(self):
        return self.acc_role_name + self.acc_name if self.acc_name else ''

    @property
    def acc_location(self):
        x, y = self._element.AXPosition
        w, h = self._element.AXSize

        return map(int, [x, y, w, h])

    @property
    def acc_value(self):
        return self._properties.get('AXValue', None)

    def set_value(self, value):
        # TODO:
        MacUtils.ApplescriptExecutor.set_element_attribute_value(
            self._object_selector, 'AXValue', value, self._proc_name)
        self._cached_properties = None

    @property
    def acc_description(self):
        return self._properties.get('AXDescription', None)

    @property
    def acc_parent(self):
        result = None
        if self.acc_parent_count > 0:
            result = \
                MacElement(self._element.AXParent,
                           self._proc_name,
                           self._proc_id)

        return result

    @property
    def acc_selection(self):
        return self._properties.get('AXSelectedText', None)

    @property
    def acc_focused_element(self):
        childs = self.findall()

        result = None
        for element in childs:
            if self._properties.get('AXFocused', 'false') == 'true':
                result = element
                break

        return result

    @property
    def acc_role_name(self):
        return self._acc_role_name_map.get(self._role, 'unknown')

    def __iter__(self):
        children_elements = self._properties.get('AXChildren', [])

        # children = children_elements[0]

        if not len(children_elements):
            raise StopIteration()

        for element in children_elements:
            yield MacElement(element.AXChildren,
                             self._proc_name, self.proc_id)

    def __findcacheiter(self, only_visible, **kwargs):
        """
        Find child element in the cache.

        Arguments:
            - only_visible: bool, flag that indicates will we search only

        Returns:
            - Yield found element.
        """

        for obj_element in self._cached_children:
            if obj_element._match(only_visible, **kwargs):
                yield obj_element

    def _finditer(self, only_visible, **kwargs):
        """
        Find child element.

        Arguments:
            - only_visible: bool, flag that indicates will we search only

        Returns:
            - Yield found element.
        """

        lst_queue = list(self)

        if self.is_top_level_window:
            lst_queue.extend(self._find_windows_by_same_proc())

        while lst_queue:
            obj_element = lst_queue.pop(0)
            self._cached_children.add(obj_element)

            if obj_element._match(only_visible, **kwargs):
                yield obj_element

            if obj_element.acc_child_count:
                childs = [el for el in list(obj_element)]
                lst_queue[:0] = childs

    def find(self, **kwargs):
        result = self._element.findFirstR(**kwargs)

        if not result:
            attrs = ['%s=%s' % (k, v) for k, v in kwargs.iteritems()]
            raise TooSaltyUISoupException(
                'Can\'t find object with attributes "%s".' %
                '; '.join(attrs))
        return MacElement(result, self._proc_name, self.proc_id)

    def findall(self, only_visible=True, **kwargs):
        result = self._element.findAllR(**kwargs)

        if not result:
            attrs = ['%s=%s' % (k, v) for k, v in kwargs.iteritems()]
            raise TooSaltyUISoupException(
                'Can\'t find object with attributes "%s".' %
                '; '.join(attrs))
        return MacElement(result, self._proc_name, self.proc_id)

    def is_object_exists(self, **kwargs):
        try:
            self.find(**kwargs)
            return True
        except TooSaltyUISoupException:
            return False
<commit_msg>back compatibility with c_name<commit_after># !/usr/bin/env python

#    Copyright (c) 2014 Max Beloborodko.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

__author__ = 'f1ashhimself@gmail.com'

from ..interfaces.i_element import IElement
import atomac
from ..utils.mac_utils import MacUtils
from .. import TooSaltyUISoupException
from .mouse import MacMouse

class MacElement(IElement):

    _acc_role_name_map = {
        'AXWindow': u'frm',
        'AXTextArea': u'txt',
        'AXTextField': u'txt',
        'AXButton': u'btn',
        'AXStaticText': u'lbl',
        'AXRadioButton': u'rbtn',
        'AXSlider': u'sldr',
        'AXCell': u'tblc',
        'AXImage': u'img',
        'AXToolbar': u'tbar',
        'AXScrollBar': u'scbr',
        'AXMenuItem': u'mnu',
        'AXMenu': u'mnu',
        'AXMenuBar': u'mnu',
        'AXMenuBarItem': u'mnu',
        'AXCheckBox': u'chk',
        'AXTabGroup': u'ptl',
        'AXList': u'lst',
        'AXMenuButton': u'cbo',
        'AXRow': u'tblc',
        'AXColumn': u'col',
        'AXTable': u'tbl',
        'AXScrollArea': u'sar',
        'AXOutline': u'otl',
        'AXValueIndicator': u'val',
        'AXDisclosureTriangle': u'dct',
        'AXGroup': u'grp',
        'AXPopUpButton': u'pubtn',
        'AXApplication': u'app',
        'AXDocItem': u'doc',
        'AXHeading': u'tch',
        'AXGenericElement': u'gen',
        'AXLink': u'lnk'
    }

    _mouse = MacMouse()

    def __init__(self, atomac_object, process_name, process_id):
        """
        Constructor.

        Arguments:
            - atomac_object: string, object selector.
        """

        self._element = atomac_object
        self._proc_name = process_name
        self._proc_id = process_id
        self._cached_children = set()
        self._cached_properties = None

    def _parse_c_name(self, **kwargs):
        """
        Used for back compatibility if 'find' or 'finall' method calls
        witn c_name parameter like 'typeTitle' ('btnOpen')
        :param c_name: input c_name
        :return: strings, AXRole and AXTitle
        """
        axrole = axtitle = None
        c_name = kwargs.pop('c_name', '')
        for k, rolename in enumerate(self._acc_role_name_map):
            if c_name.startswith(self._acc_role_name_map[rolename]):
                axrole = rolename
                axtitle = c_name[len(self._acc_role_name_map[rolename]):]
                break
        if axrole:
            kwargs['AXRole'] = axrole
        if axtitle:
            kwargs['AXTitle'] = axtitle
        return kwargs

    @property
    def _properties(self):
        """
        Property for element properties.
        """

        if not self._cached_properties:
            self._cached_properties = \
                MacUtils.ApplescriptExecutor.get_element_properties(self._element)

        return self._cached_properties

    @property
    def _role(self):
        """
        Property for element role.
        """

        return self._properties.get('AXRole', None)

    def _find_windows_by_same_proc(self):
        """
        Find window by same process id.

        Arguments:
            - None

        Returns:
            - list of windows.
        """

        app = atomac.getAppRefByPid(self.proc_id)
        app.activate()
        return app.windowsR()

    def click(self, x_offset=None, y_offset=None):
        x, y, w, h = self.acc_location
        x += x_offset if x_offset is not None else int(w / 2)
        y += y_offset if y_offset is not None else int(h / 2)

        self._mouse.click(x, y)
        self._cached_properties = None

    def right_click(self, x_offset=None, y_offset=None):
        x, y, w, h = self.acc_location
        x += x_offset if x_offset is not None else w / 2
        y += y_offset if y_offset is not None else h / 2

        self._mouse.click(x, y, self._mouse.RIGHT_BUTTON)
        self._cached_properties = None

    def double_click(self, x_offset=None, y_offset=None, click_interval=0.5):
        x, y, w, h = self.acc_location
        x += x_offset if x_offset is not None else w / 2
        y += y_offset if y_offset is not None else h / 2

        self._mouse.double_click(x, y, click_interval=click_interval)
        self._cached_properties = None

    def drag_to(self, x, y, x_offset=None, y_offset=None, smooth=True):
        el_x, el_y, el_w, el_h = self.acc_location
        el_x += x_offset if x_offset is not None else el_w / 2
        el_y += y_offset if y_offset is not None else el_h / 2

        self._mouse.drag(el_x, el_y, x, y, smooth)
        self._cached_properties = None

    @property
    def proc_id(self):
        return self._proc_id

    @property
    def is_top_level_window(self):
        return self._properties.get('AXParent', 'false') == 'false'

    @property
    def is_selected(self):
        result = False
        if self.acc_role_name == self._acc_role_name_map['AXRadioButton'] and \
                self._properties.get('AXValue', 'false') == 'true':
            result = True

        return result

    @property
    def is_checked(self):
        result = False
        if self.acc_role_name == self._acc_role_name_map['AXCheckBox'] and \
                self._properties.get('AXValue', 'false') == 'true':
            result = True

        return result

    @property
    def is_visible(self):
        return True  # We can't work with invisible elements under Mac OS.

    @property
    def is_enabled(self):
        return bool(self._properties.get('AXEnabled', False))

    @property
    def acc_parent_count(self):
        return 0

    @property
    def acc_child_count(self):
        return len(self._properties.get('AXChildren'))

    @property
    def acc_name(self):
        result = self._properties.get('AXDescription') or \
            self._properties.get('AXTitle') or \
            self._properties.get('AXValue')

        return MacUtils.replace_inappropriate_symbols(result or '')

    def set_focus(self):
        # TODO:
        MacUtils.ApplescriptExecutor.set_element_attribute_value(
            self._object_selector, 'AXFocused', 'true', self._proc_name, False)

    @property
    def acc_c_name(self):
        return self.acc_role_name + self.acc_name if self.acc_name else ''

    @property
    def acc_location(self):
        x, y = self._element.AXPosition
        w, h = self._element.AXSize

        return map(int, [x, y, w, h])

    @property
    def acc_value(self):
        return self._properties.get('AXValue', None)

    def set_value(self, value):
        # TODO:
        MacUtils.ApplescriptExecutor.set_element_attribute_value(
            self._object_selector, 'AXValue', value, self._proc_name)
        self._cached_properties = None

    @property
    def acc_description(self):
        return self._properties.get('AXDescription', None)

    @property
    def acc_parent(self):
        result = None
        if self.acc_parent_count > 0:
            result = \
                MacElement(self._element.AXParent,
                           self._proc_name,
                           self._proc_id)

        return result

    @property
    def acc_selection(self):
        return self._properties.get('AXSelectedText', None)

    @property
    def acc_focused_element(self):
        childs = self.findall()

        result = None
        for element in childs:
            if self._properties.get('AXFocused', 'false') == 'true':
                result = element
                break

        return result

    def __iter__(self):
        pass

    @property
    def acc_role_name(self):
        return self._acc_role_name_map.get(self._role, 'unknown')

    def find(self, **kwargs):
        kwargs = self._parse_c_name(**kwargs)
        result = self._element.findFirstR(**kwargs)

        if not result:
            attrs = ['%s=%s' % (k, v) for k, v in kwargs.iteritems()]
            raise TooSaltyUISoupException(
                'Can\'t find object with attributes "%s".' %
                '; '.join(attrs))
        return MacElement(result, self._proc_name, self.proc_id)

    def findall(self, only_visible=True, **kwargs):
        kwargs = self._parse_c_name(**kwargs)
        result = self._element.findAllR(**kwargs)

        if not result:
            attrs = ['%s=%s' % (k, v) for k, v in kwargs.iteritems()]
            raise TooSaltyUISoupException(
                'Can\'t find object with attributes "%s".' %
                '; '.join(attrs))
        if not isinstance(result, list):
            result = [result]
        return [MacElement(r, self._proc_name, self.proc_id) for r in result]

    def is_object_exists(self, **kwargs):
        try:
            self.find(**kwargs)
            return True
        except TooSaltyUISoupException:
            return False
<|endoftext|>


<commit_before>import logging

import sqlalchemy
from flask import Flask
from celery import Celery
from jsonschema import validate, ValidationError

from radar.models.patients import Patient
from radar.models.patient_locks import PatientLock
from radar.database import db

from radar_ukrdc.aliases import import_aliases
from radar_ukrdc.medications import import_medications
from radar_ukrdc.addresses import import_addresses
from radar_ukrdc.demographics import import_demographics
from radar_ukrdc.patient_numbers import import_patient_numbers
from radar_ukrdc.results import import_results
from radar_ukrdc.utils import load_schema

logger = logging.getLogger(__name__)

def create_app():
    app = Flask(__name__)
    app.config.from_envvar('RADAR_SETTINGS')

    # noinspection PyUnresolvedReferences
    from radar import models  # noqa

    db.init_app(app)

    return app

def create_celery():
    app = create_app()

    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)

    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask

    return celery

celery = create_celery()

def find_patient_id(sda_patient_numbers):
    """Find RaDaR number in patient numbers"""

    for sda_patient_number in sda_patient_numbers:
        if sda_patient_number['organization']['code'] == 'RADAR':
            return sda_patient_number['number']

    return None

def parse_patient_id(value):
    if isinstance(value, basestring):
        value = int(value)

    return value

def get_patient(patient_id):
    return Patient.query.get(patient_id)

def lock_patient(patient):
    while True:
        patient_lock = PatientLock.query.filter(PatientLock.patient == patient).with_for_update().first()

        if patient_lock is not None:
            return patient_lock
        else:
            try:
                session = db.session.session_factory()
                patient_lock = PatientLock()
                patient_lock.patient = session.merge(patient)
                session.add(patient_lock)
                session.commit()
            except sqlalchemy.exc.IntegrityError:
                pass

@celery.task
def import_sda(sda_container, sequence_number):
    schema = load_schema('schema.json')

    try:
        validate(sda_container, schema)
    except ValidationError:
        logger.error('Container is invalid')
        return False

    sda_patient = sda_container['patient']
    sda_patient_numbers = sda_patient['patient_numbers']

    patient_id = find_patient_id(sda_patient_numbers)

    if patient_id is None:
        logger.error('Patient ID is missing')
        return False

    try:
        patient_id = parse_patient_id(patient_id)
    except ValueError:
        logger.error('Patient ID is invalid id={id}'.format(id=patient_id))
        return False

    patient = get_patient(patient_id)

    if patient is None:
        logger.error('Patient not found id={id}'.format(id=patient_id))
        return False

    patient_lock = lock_patient(patient)

    if patient_lock.sequence_number is not None and sequence_number < patient_lock.sequence_number:
        logger.error('Skipping old sequence number {0} < {1}'.format(sequence_number, patient_lock.sequence_number))
        return False

    patient_lock.sequence_number = sequence_number

    sda_medications = sda_container.get('medications', list())
    sda_names = sda_container.get('aliases', list())
    sda_addresses = sda_container.get('addresses', list())
    sda_lab_orders = sda_container.get('lab_orders', list())

    import_demographics(patient, sda_patient)
    import_patient_numbers(patient, sda_patient_numbers)
    import_aliases(patient, sda_names)
    import_addresses(patient, sda_addresses)
    import_medications(patient, sda_medications)
    import_results(patient, sda_lab_orders)

    db.session.commit()

    return True
<commit_msg>Fix typos<commit_after>import logging

import sqlalchemy
from flask import Flask
from celery import Celery
from jsonschema import validate, ValidationError

from radar.models.patients import Patient
from radar.models.patient_locks import PatientLock
from radar.database import db

from radar_ukrdc.aliases import import_aliases
from radar_ukrdc.medications import import_medications
from radar_ukrdc.addresses import import_addresses
from radar_ukrdc.demographics import import_demographics
from radar_ukrdc.patient_numbers import import_patient_numbers
from radar_ukrdc.results import import_results
from radar_ukrdc.utils import load_schema

logger = logging.getLogger(__name__)

def create_app():
    app = Flask(__name__)
    app.config.from_envvar('RADAR_SETTINGS')

    # noinspection PyUnresolvedReferences
    from radar import models  # noqa

    db.init_app(app)

    return app

def create_celery():
    app = create_app()

    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)

    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask

    return celery

celery = create_celery()

def find_patient_id(sda_patient_numbers):
    """Find RaDaR number in patient numbers"""

    for sda_patient_number in sda_patient_numbers:
        if sda_patient_number['organization']['code'] == 'RADAR':
            return sda_patient_number['number']

    return None

def parse_patient_id(value):
    if isinstance(value, basestring):
        value = int(value)

    return value

def get_patient(patient_id):
    return Patient.query.get(patient_id)

def lock_patient(patient):
    while True:
        patient_lock = PatientLock.query.filter(PatientLock.patient == patient).with_for_update().first()

        if patient_lock is not None:
            return patient_lock
        else:
            try:
                session = db.session.session_factory()
                patient_lock = PatientLock()
                patient_lock.patient = session.merge(patient)
                session.add(patient_lock)
                session.commit()
            except sqlalchemy.exc.IntegrityError:
                pass

@celery.task
def import_sda(sda_container, sequence_number):
    schema = load_schema('schema.json')

    try:
        validate(sda_container, schema)
    except ValidationError:
        logger.error('Container is invalid')
        return False

    sda_patient = sda_container['patient']
    sda_patient_numbers = sda_patient['patient_numbers']

    patient_id = find_patient_id(sda_patient_numbers)

    if patient_id is None:
        logger.error('Patient ID is missing')
        return False

    try:
        patient_id = parse_patient_id(patient_id)
    except ValueError:
        logger.error('Patient ID is invalid id={id}'.format(id=patient_id))
        return False

    patient = get_patient(patient_id)

    if patient is None:
        logger.error('Patient not found id={id}'.format(id=patient_id))
        return False

    patient_lock = lock_patient(patient)

    if patient_lock.sequence_number is not None and sequence_number < patient_lock.sequence_number:
        logger.info('Skipping old sequence number {0} < {1}'.format(sequence_number, patient_lock.sequence_number))
        return False

    patient_lock.sequence_number = sequence_number

    sda_names = sda_patient.get('aliases', list())
    sda_addresses = sda_patient.get('addresses', list())
    sda_medications = sda_container.get('medications', list())
    sda_lab_orders = sda_container.get('lab_orders', list())

    import_demographics(patient, sda_patient)
    import_patient_numbers(patient, sda_patient_numbers)
    import_aliases(patient, sda_names)
    import_addresses(patient, sda_addresses)
    import_medications(patient, sda_medications)
    import_results(patient, sda_lab_orders)

    db.session.commit()

    return True
<|endoftext|>