Location: Gastrocnemius @ 1095891f214a / generate_argon_document.py

Author:
vickieshim <v.shim@auckland.ac.nz>
Date:
2022-11-10 14:20:34+13:00
Desc:
gastroc files
Permanent Source URI:
https://models.cellml.org/workspace/972/rawfile/1095891f214a452736db5ba269104784631909e3/generate_argon_document.py

import copy
import json
import os

EXPORT_RELATIVE_PATH = True

#Change this to match the root directory to generate the new file
DIR_2 = '.'

#The name of the newly generated argon document
EXPORT_NAME = 'generated.neon'

VERSION_INFO = {
    "OpenCMISS-Argon Version": [
        "0",
        "2",
        "2"
    ],
}


#Settings for scene viewport, not used a this moment
SCENEVIEWER = {
  "Sceneviewer": {
    "AntialiasSampling": 0,
    "BackgroundColourRGB": [
      1,
      1,
      1
    ],
    "EyePosition": [
      295.78381273359287,
      2742.141219539055,
      -486.04315158466096
    ],
    "FarClippingPlane": 6485.082381619184,
    "LightingLocalViewer": False,
    "LightingTwoSided": True,
    "LookatPosition": [
      133.9595184326172,
      128.9081916809082,
      -829.2242584228516
    ],
    "NearClippingPlane": 132.03169346983802,
    "PerturbLinesFlag": False,
    "ProjectionMode": "PERSPECTIVE",
    "Scene": "",
    "Scenefilter": "default",
    "TranslationRate": 1,
    "TransparencyMode": "FAST",
    "TumbleRate": 1.5,
    "UpVector": [
      0,
      0,
      1
    ],
    "ViewAngle": 0.6981317007976229,
    "ZoomRate": 1
  }
}

SCENE_GRAPHICS = {
    "Scene": {
        "Graphics": [
            {
                "BoundaryMode": "ALL",
                "CoordinateField": "coordinates",
                "ElementFaceType": "ALL",
                "FieldDomainType": "MESH2D",
                "Material": "black",
                "RenderLineWidth": 1,
                "RenderPointSize": 1,
                "RenderPolygonMode": "SHADED",
                "Scenecoordinatesystem": "LOCAL",
                "SelectMode": "ON", 
                "SelectedMaterial": "default_selected",
                "Surfaces": {},
                "Tessellation": "default",
                "Type": "SURFACES",
                "VisibilityFlag": True
            }
        ],
        "VisibilityFlag": True
    }
}

TESSELLATION = {
    "Tessellations": {
    "DefaultPointsTessellation": "default_points",
    "DefaultTessellation": "default",
    "Tessellations": [
      {
        "CircleDivisions": 12,
        "MinimumDivisions": [
          1
        ],
        "Name": "default",
        "RefinementFactors": [
          12
        ]
      },
      {
        "CircleDivisions": 12,
        "MinimumDivisions": [
          1
        ],
        "Name": "default_points",
        "RefinementFactors": [
          1
        ]
      },
      {
        "CircleDivisions": 48,
        "MinimumDivisions": [
          1
        ],
        "Name": "material_preview",
        "RefinementFactors": [
          1
        ]
      },
      {
        "CircleDivisions": 12,
        "MinimumDivisions": [
          16
        ],
        "Name": "update_vis",
        "RefinementFactors": [
          1
        ]
      }
    ]
  }
}

FIELD_MODULE = {
    "Fieldmodule": {
        "Fields": [
            {
                "CoordinateSystemType": "RECTANGULAR_CARTESIAN",
                "FieldFiniteElement": {
                    "ComponentNames": [
                        "x",
                        "y",
                        "z"
                    ],
                    "NumberOfComponents": 3
                },
                "IsManaged": True,
                "IsTypeCoordinate": True,
                "Name": "coordinates"
            },
            {
                "CoordinateSystemType": "FIBRE",
                "FieldFiniteElement": {
                    "ComponentNames": [
                        "fibre angle",
                        "imbrication angle",
                        "sheet angle"
                    ],
                    "NumberOfComponents": 3
                },
                "IsManaged": True,
                "IsTypeCoordinate": False,
                "Name": "fibres"
            }
        ]
    },
}

EMPTY_REGION = {
    "Fieldmodule": None,
    "Scene": {
        "Graphics": None,
        "VisibilityFlag": True
    }
}

SKIP_REGIONS = ['maxilla', ]

def generate_output(currentDir):
    data_files = []
    for root, dirs, files in os.walk(currentDir, topdown=True):
        transformedFound = False
        current_dir = {
            'node_files': [],
            'elem_files': []
        }

        for file in files:
            # print(file)
            if file.endswith('_transformed.exnode'):
                transformedFound = True
                current_dir['node_files'].append(file)
            if file.endswith('_transformed.exelem'):
                current_dir['elem_files'].append(file)

        if transformedFound == False:
            for file in files:
                if file.endswith('.EXNODE'):
                    current_dir['node_files'].append(file)
                if file.endswith('.EXELEM'):
                    current_dir['elem_files'].append(file)

        if len(current_dir["node_files"]):
            data_files.append(current_dir)

    argon_document = {
        **VERSION_INFO,
        #**SCENEVIEWER,
        **TESSELLATION
    }

    root_region = copy.deepcopy(EMPTY_REGION)

    bits = []
    for index, data in enumerate(data_files):

        exnode_file = data["node_files"][0]
        region_path = exnode_file

        region_parts = region_path.split('/')
        region_parts.pop(0)
        base_region = root_region
        for i in range(len(region_parts) - 1):
            current_region = region_parts[i].lower()

            if "ChildRegions" not in base_region:
                base_region["ChildRegions"] = []

            child_region_names = []
            for region_info in base_region["ChildRegions"]:
                child_region_names.append(region_info["Name"])

            if current_region not in child_region_names:
                new_child = copy.deepcopy(EMPTY_REGION)
                new_child['Name'] = current_region
                base_region["ChildRegions"].append(new_child)
                child_region_names.append(current_region)

            j = child_region_names.index(current_region)

            base_region = base_region["ChildRegions"][j]

        # base_region["Fieldmodule"] = copy.deepcopy(FIELD_MODULE["Fieldmodule"])
        base_region["Scene"] = copy.deepcopy(SCENE_GRAPHICS["Scene"])

        #bit = f"'{region_parts[-2].lower()}',"
        # if bit not in bits:
        #     bits.append(bit)
        if len(region_parts) > 2 and region_parts[-2].lower() in SKIP_REGIONS:
            continue

        if "Model" not in base_region:
            base_region["Model"] = {"Sources": []}


        for node_file in data['node_files']:
            exnode_path = node_file  # .replace(common_path, '')[1:]

            regionName = os.path.dirname(region_path).lower()
            if regionName == "":
                regionName = exnode_path.replace('_transformed.exnode', '')

            base_region["Model"]["Sources"].insert(
                0,
                {
                    "FileName": exnode_path,
                    "RegionName": regionName,
                    "Type": "FILE"
                }
            )
        for elem_file in data['elem_files']:
            exelem_path = elem_file  # .replace(common_path, '')[1:]
            regionName = os.path.dirname(region_path).lower()
            if regionName == "":
                regionName = exelem_path.replace('_transformed.exelem', '')
            base_region["Model"]["Sources"].append(
                {
                    "FileName": exelem_path,
                    "RegionName": regionName,
                    "Type": "FILE"
                }
            )

        #Pick one of the colors below
        #if 'MUSCLES' in region_path or 'NECK' in region_path:
        #    base_region["Scene"]["Graphics"][0]["Material"] = "muscle"
        #if 'BONE' in region_path:
        #    base_region["Scene"]["Graphics"][0]["Material"] = "bone"
        #if 'LIGAMENT' in region_path:
        #    base_region["Scene"]["Graphics"][0]["Material"] = "white"
        #if 'SKIN' in region_path:
        base_region["Scene"]["Graphics"][0]["Material"] = "brown"

    argon_document["RootRegion"] = root_region

    #print('\n'.join(bits))
    output = os.path.join(currentDir, EXPORT_NAME)
    with open(output, 'w') as f:
        f.write(json.dumps(argon_document, default=lambda o: o.__dict__, sort_keys=True, indent=2))
        print('Generated ' + output)


def main():
    data_files = []
    print(os.listdir(DIR_2))
    for path in os.listdir(DIR_2):
        workingDir = DIR_2 + "/" + path
        if os.path.isdir(workingDir):
            generate_output(workingDir)

if __name__ == "__main__":
    main()

model_sources = {
    "Model": {
        "Sources": [
            {
                "FileName": "FEMUR.EXNODE",
                "RegionName": "/left_lower_limb/bones/femur",
                "Type": "FILE"
            },
            {
                "FileName": "FEMUR.EXELEM",
                "RegionName": "/left_lower_limb/bones/femur",
                "Type": "FILE"
            }
        ]
    },
}