├── .Rhistory ├── Deformetrica ├── .ipynb_checkpoints │ ├── ssm_estimation-checkpoint.ipynb │ └── ssm_new_shape_generation-checkpoint.ipynb ├── ssm_estimation.ipynb └── ssm_new_shape_generation.ipynb ├── Envs ├── env_deformetrica.yml ├── env_keras.yml └── env_vmtk.yml ├── Fluent ├── autofluent_template.jou └── cfd_prepare.py ├── Keras ├── .ipynb_checkpoints │ ├── cfd_dnn_testing-checkpoint.ipynb │ └── cfd_dnn_training-checkpoint.ipynb ├── cfd_dnn_testing.ipynb └── cfd_dnn_training.ipynb ├── LICENSE ├── Paraview └── pview_resample_cfd2vtu.py ├── Postprocessing ├── README.md ├── pview_sampling_planes.py ├── vmtk_cfdpointcloud2vtu.py └── vtk_distance.py ├── README.md ├── VMTK ├── __pycache__ │ └── custom_vmtkflowextensions.cpython-36.pyc ├── custom_vmtkflowextensions.py ├── vmtk_centerlines_open_profiles.py ├── vmtk_cfdmesher.py ├── vmtk_clipper.py ├── vmtk_extension.py ├── vmtk_idfix_inlet.py ├── vmtk_registration.py ├── vmtk_remesher.py └── vmtk_vtu2msh.py ├── coverpic.jpg └── widget.gif /.Rhistory: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndritPJ/CFD_Machine_Learning/566caec994e437fe8d79af447aca93229efd2294/.Rhistory -------------------------------------------------------------------------------- /Deformetrica/.ipynb_checkpoints/ssm_estimation-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Building a statistical shape model (Deformetrica)" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# uses DFCA 4.3\n", 17 | "import sys, glob, importlib\n", 18 | "import matplotlib.pyplot as plt\n", 19 | "import matplotlib\n", 20 | "import numpy as np" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "import logging\n", 30 | "mpl_logger = logging.getLogger('matplotlib')\n", 31 | "mpl_logger.setLevel(logging.WARNING) " 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "# append scripts from https://github.com/ClinicalCardiovascEngGroup/SSM/tree/master/python (credit: Raphael Sivera)\n", 41 | "sys.path.append(\"/Scripts/SSM/python/\")\n", 42 | "\n", 43 | "import ssm.tools, ssm.iovtk, ssm.atlas, ssm.initialize_controlpoints" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "%matplotlib inline" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "Approach:\n", 60 | "\n", 61 | "1) first initialise control points (basic grid) \n", 62 | "2) freeze control points and compute template \n", 63 | "3) then freeze the template and optimise the control points \n", 64 | "4) then freeze control points and recompute template " 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "base_dir = \"SSM/\"" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "## Initialise control points (do once)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": {}, 86 | "source": [ 87 | "Files are assumed to be in millimetres" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "datadir = \"/my_folder_of_surface_meshes/\"" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [ 105 | "# defining params\n", 106 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 107 | " idir=datadir,\n", 108 | " odir=base_dir + \"r0/\",\n", 109 | " name=\"Aorta\",\n", 110 | " initial_guess=base_dir + \"my_initial_template.vtk\",\n", 111 | " kwd=20.,\n", 112 | " kwg=15.,\n", 113 | " noise=10.)\n", 114 | "\n", 115 | "# init control points first before setting in params\n", 116 | "params = {'convergence_tolerance': 0.01, 'max_iterations': 50,\n", 117 | " 'initial_control_points': ae.odir+\"initial_controlpoints.txt\",\n", 118 | " \"freeze_control_points\":True, \"freeze_template\":False}\n", 119 | "\n", 120 | "ae.save_parameters(True)" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "#################################### SKIP IF CONTROL POINTS ALREADY INITIALISED #####################################\n", 130 | "\n", 131 | "b,p = ssm.initialize_controlpoints.initialize_controlpoints(ae.lf, spacing=ae.p_kernel_width_deformation, margin=1, \n", 132 | " output_dir=ae.odir, name=\"initial_controlpoints.txt\")\n", 133 | "\n", 134 | "ssm.iovtk.controlpoints_to_vtkPoints_files(ae.odir+\"initial_controlpoints.txt\", ae.odir+\"initial_controlpoints.vtk\")" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "**FIRST ROUND OF ATLAS ESTIMATION**" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": { 148 | "scrolled": true 149 | }, 150 | "outputs": [], 151 | "source": [ 152 | "ae.estimate(params)" 153 | ] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "metadata": {}, 158 | "source": [ 159 | "Check control point variance" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "M = ae.read_momenta()\n", 169 | "C = ae.read_ctrlpoints()\n", 170 | "varM = np.var(M, axis=0).sum(axis=1)" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "# plot variance vs control points\n", 180 | "idx = varM.argsort()\n", 181 | "\n", 182 | "fig, (ax0, ax1) = plt.subplots(1,2, figsize=(10,4))\n", 183 | "\n", 184 | "ax0.plot(varM, \".\", label=\"variance\")\n", 185 | "ax0.semilogy()\n", 186 | "\n", 187 | "ax1.plot((np.log(varM[idx])-np.log(varM.max())) / np.log(10), label=\"log10 variance\")\n", 188 | "#ax1.set_xticks([0, 50, 100, 200])\n", 189 | "ax0.legend()\n", 190 | "ax1.legend()\n", 191 | "ax0.grid(True)\n", 192 | "ax1.grid(True)" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [ 201 | "# truncating bad control points\n", 202 | "Ncp = int(np.sum(varM < 0.001*varM.max()))\n", 203 | "\n", 204 | "# keep remaining ctrl points\n", 205 | "C0 = C[varM > varM[idx][Ncp], :]\n", 206 | "print(C0.shape)" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "# writing the txt array and vtk point cloud\n", 216 | "import deformetrica\n", 217 | "deformetrica.in_out.array_readers_and_writers.write_2D_array(C0, ae.odir, \"sel_controlpoints.txt\")\n", 218 | "\n", 219 | "ssm.iovtk.controlpoints_to_vtkPoints_files(ae.odir + \"sel_controlpoints.txt\",\n", 220 | " ae.odir + \"sel_controlpoints.vtk\")" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "metadata": {}, 226 | "source": [ 227 | "**SECOND ROUND OF ATLAS ESTIMATION**" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": null, 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 237 | " idir=datadir,\n", 238 | " odir=base_dir + \"r1/\",\n", 239 | " name=\"Aorta\",\n", 240 | " initial_guess=base_dir + \"r0/output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk\",\n", 241 | " kwd=20.,\n", 242 | " kwg=15.,\n", 243 | " noise=10.)\n", 244 | "\n", 245 | "# freeze template this time, to optimise ctrl points\n", 246 | "params = {'convergence_tolerance': 0.001, 'max_iterations': 100,\n", 247 | " \"initial_control_points\":base_dir + \"r0/sel_controlpoints.txt\",\n", 248 | " \"freeze_control_points\":False, \"freeze_template\":True}\n", 249 | "\n", 250 | "ae.save_parameters(True)" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": { 257 | "scrolled": true 258 | }, 259 | "outputs": [], 260 | "source": [ 261 | "ae.estimate(params)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "ae.save_controlpoints_vtk()" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "metadata": {}, 276 | "source": [ 277 | "**THIRD AND FINAL ROUND OF ATLAS ESTIMATION**" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": null, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 287 | " idir=datadir,\n", 288 | " odir=base_dir + \"r2/\",\n", 289 | " name=\"Aorta\",\n", 290 | " initial_guess=base_dir + \"r1/output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk\",\n", 291 | " kwd=20.,\n", 292 | " kwg=15.,\n", 293 | " noise=5.)\n", 294 | "\n", 295 | "params = {'convergence_tolerance': 0.001,\n", 296 | " \"initial_control_points\":base_dir + \"r1/output/DeterministicAtlas__EstimatedParameters__ControlPoints.txt\",\n", 297 | " \"freeze_control_points\":True, \"freeze_template\":False}\n", 298 | "\n", 299 | "ae.save_parameters(True)" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": null, 305 | "metadata": { 306 | "scrolled": true 307 | }, 308 | "outputs": [], 309 | "source": [ 310 | "ae.estimate(params)" 311 | ] 312 | } 313 | ], 314 | "metadata": { 315 | "kernelspec": { 316 | "display_name": "dfca-env-4.3", 317 | "language": "python", 318 | "name": "dfca-env-4.3" 319 | }, 320 | "language_info": { 321 | "codemirror_mode": { 322 | "name": "ipython", 323 | "version": 3 324 | }, 325 | "file_extension": ".py", 326 | "mimetype": "text/x-python", 327 | "name": "python", 328 | "nbconvert_exporter": "python", 329 | "pygments_lexer": "ipython3", 330 | "version": "3.8.13" 331 | } 332 | }, 333 | "nbformat": 4, 334 | "nbformat_minor": 4 335 | } 336 | -------------------------------------------------------------------------------- /Deformetrica/.ipynb_checkpoints/ssm_new_shape_generation-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Generate Synthetic Cohort" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# dfca 4.3 needed\n", 17 | "import subprocess as sp\n", 18 | "import statistics, sys, os, shutil, re\n", 19 | "import numpy as np\n", 20 | "import deformetrica" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "import matplotlib.pyplot as plt\n", 30 | "import matplotlib\n", 31 | "import logging\n", 32 | "mpl_logger = logging.getLogger('matplotlib')\n", 33 | "mpl_logger.setLevel(logging.WARNING)\n", 34 | "%matplotlib inline" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "# append scripts from https://github.com/ClinicalCardiovascEngGroup/SSM/tree/master/python (credit: Raphael Sivera)\n", 44 | "sys.path.append(\"/home/endrit/Documents/Scripts/SSM-V2/python/\")\n", 45 | "\n", 46 | "import ssm.pca, ssm.volumetric_meshes, ssm.atlas" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "# New Surfaces" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "List directories" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "ssm_dir = \"my_final_SSM_folder/\"" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "odir = \"new_surfaces/\"" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "**COMPUTE PCA**" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "ao = ssm.pca.DeformetricaAtlasPCA(\n", 95 | " idir = ssm_dir + \"output/\",\n", 96 | " odir = ssm_dir + \"pca/\")\n", 97 | "\n", 98 | "ao.compute_pca(with_plots=True)" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "# Reshape into U, S, Vt matrices\n", 108 | "momenta = ao.momenta\n", 109 | "nsbj = momenta.shape[0]\n", 110 | "ndim = momenta.shape[1] * momenta.shape[2]\n", 111 | "x = ao.momenta.reshape((nsbj, ndim))\n", 112 | "pca_u = ao.pca_u\n", 113 | "pca_s = ao.pca_s\n", 114 | "pca_v = ao.pca_v" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "# print cumsum of PCA\n", 124 | "cumsum_pca = np.concatenate((np.zeros(1), (pca_s**2).cumsum()/(pca_s**2).sum()))\n", 125 | "print(cumsum_pca)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "# keep adding modes until 99% variance captured\n", 135 | "print(cumsum_pca[:35])" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "# save pca matrices of training set\n", 145 | "np.savetxt(odir + \"pca_u.csv\", pca_u, delimiter=',')\n", 146 | "np.savetxt(odir + \"pca_s.csv\", pca_s, delimiter=\",\")\n", 147 | "np.savetxt(odir + \"pca_v.csv\", pca_v, delimiter=\",\")" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "**FUNCTIONS**" 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "metadata": {}, 160 | "source": [ 161 | "Get standard deviation" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "def get_mean_stdev(n_subjects, n_modes, pca_matrix):\n", 171 | " \"\"\"\n", 172 | " build matrix of mean and stdev per mode:\n", 173 | " output: rows=modes, col_0 = mean score per mode, col_1 = stdev of scores per mode\n", 174 | " \n", 175 | " Modes that are excluded given 0 mean and 0 stdev.\n", 176 | " \"\"\"\n", 177 | " matrix = np.zeros(shape=(n_subjects, 2))\n", 178 | "\n", 179 | " for i in range(n_subjects):\n", 180 | " if i < n_modes:\n", 181 | " matrix[i][0] = statistics.mean(pca_matrix[:,i])\n", 182 | " matrix[i][1] = statistics.stdev(pca_matrix[:,i])\n", 183 | " else:\n", 184 | " matrix[i][0] = 0\n", 185 | " matrix[i][1] = 0\n", 186 | " return matrix" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "Sample Gaussian" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": null, 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [ 202 | "def sample_gaussian(new_subjects, n_subjects, stats_arr):\n", 203 | " \"\"\"\n", 204 | " make new pca u [subjects, modes]\n", 205 | " sample within 2 stdev (limit extreme deformations)\n", 206 | " \"\"\"\n", 207 | " new_shapes = np.zeros(shape=(new_subjects, n_subjects))\n", 208 | " for i in range(new_subjects):\n", 209 | " for j in range(n_subjects):\n", 210 | " mu = stats_arr[j][0]\n", 211 | " sigma = stats_arr[j][1]\n", 212 | " x = np.random.normal(mu, sigma)\n", 213 | " if x < mu - 2*sigma:\n", 214 | " x = mu - 2*sigma\n", 215 | " if x > mu + 2*sigma:\n", 216 | " x = mu + 2*sigma\n", 217 | " new_shapes[i][j] = x\n", 218 | " return new_shapes" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": {}, 224 | "source": [ 225 | "Create Momenta txt file" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "def generate_momenta(new_subjects, batch_size, pca_new, ofile):\n", 235 | " \"\"\"\n", 236 | " reverse svd to get momenta u@s@v = momenta \n", 237 | " \"\"\"\n", 238 | " s = np.dot(np.diag(pca_s), pca_v[0:batch_size, :])\n", 239 | " \n", 240 | " with open(ofile, 'w') as outfile:\n", 241 | " # start writing momenta file\n", 242 | " outfile.write(str(new_subjects)+' '+str(momenta.shape[1])+' '+str(momenta.shape[2])+'\\n')\n", 243 | " outfile.write('\\n')\n", 244 | " for i in range(0, new_subjects, batch_size):\n", 245 | " \"\"\"\n", 246 | " calculate momenta for each batch\n", 247 | " \"\"\"\n", 248 | " b = max(new_subjects, i + batch_size)\n", 249 | " usv = np.dot(pca_new[i:b, :], s)\n", 250 | " M = usv.reshape((-1, momenta.shape[1], 3))\n", 251 | " # write each subject from batch into momenta file\n", 252 | " for subject in M:\n", 253 | " np.savetxt(outfile, subject, fmt='%-3.20f')\n", 254 | " outfile.write('\\n')" 255 | ] 256 | }, 257 | { 258 | "cell_type": "markdown", 259 | "metadata": {}, 260 | "source": [ 261 | "Shooting" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "def shoot(idir, odir, kw, noise):\n", 271 | "\n", 272 | " ftemplate = idir + \"output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk\"\n", 273 | " fctrlpts = idir + \"output/DeterministicAtlas__EstimatedParameters__ControlPoints.txt\"\n", 274 | " # new momenta file\n", 275 | " fmoments = odir + \"pca_u_new_shapes_momenta.txt\"\n", 276 | "\n", 277 | " sp.call([\"mkdir\", \"-p\", odir+\"new_shapes/\"])\n", 278 | "\n", 279 | " # warping polydata\n", 280 | " template_specifications = {\n", 281 | " 'new_shape': {'deformable_object_type': 'surfacemesh', \n", 282 | " 'noise_std': noise,\n", 283 | " 'kernel_type':'torch', 'kernel_width':kw,\n", 284 | " 'filename': ftemplate}}\n", 285 | " \n", 286 | " model_options={\n", 287 | " 'dimension': 3,\n", 288 | " 'deformation_kernel_type': 'torch',\n", 289 | " 'deformation_kernel_width': kw,\n", 290 | " 'tmin':0,\n", 291 | " 'tmax':1,\n", 292 | " \"initial_control_points\": fctrlpts,\n", 293 | " \"initial_momenta\": fmoments}\n", 294 | " \n", 295 | " Deformetrica = deformetrica.api.Deformetrica(verbosity=\"INFO\", output_dir=odir+\"new_shapes/\")\n", 296 | " Deformetrica.compute_shooting(template_specifications, model_options=model_options)" 297 | ] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": {}, 302 | "source": [ 303 | "**DEFINE VARIABLES**" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [ 312 | "# number of original shapes\n", 313 | "n_subjects = 67" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "# number of modes to use\n", 323 | "n_modes = 35" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": {}, 330 | "outputs": [], 331 | "source": [ 332 | "# number of subjects to generate\n", 333 | "n_new_subjects = 3000" 334 | ] 335 | }, 336 | { 337 | "cell_type": "markdown", 338 | "metadata": {}, 339 | "source": [ 340 | "**GENERATE SHAPES**" 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": {}, 347 | "outputs": [], 348 | "source": [ 349 | "mean_stdev = get_mean_stdev(n_subjects, n_modes, pca_u)" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "metadata": {}, 356 | "outputs": [], 357 | "source": [ 358 | "# sample gaussian\n", 359 | "pca_u_new = sample_gaussian(n_new_subjects, n_subjects, mean_stdev)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": null, 365 | "metadata": {}, 366 | "outputs": [], 367 | "source": [ 368 | "# write concat pca_u file (for ML)\n", 369 | "np.savetxt(odir + \"pca_u_new_shapes_concat.csv\", pca_u_new, delimiter=\",\")" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": null, 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "# write momenta (for shooting)\n", 379 | "generate_momenta(n_new_subjects, n_subjects, pca_u_new, odir + \"pca_u_new_shapes_momenta.txt\")" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": null, 385 | "metadata": {}, 386 | "outputs": [], 387 | "source": [ 388 | "kw = 20.\n", 389 | "noise = 5.\n", 390 | "\n", 391 | "shoot(ssm_dir, odir, kw, noise)" 392 | ] 393 | }, 394 | { 395 | "cell_type": "markdown", 396 | "metadata": {}, 397 | "source": [ 398 | "**GENERATE VOLUMES**" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": null, 404 | "metadata": {}, 405 | "outputs": [], 406 | "source": [ 407 | "vol_dir = \"new_volumes/\"" 408 | ] 409 | }, 410 | { 411 | "cell_type": "code", 412 | "execution_count": null, 413 | "metadata": {}, 414 | "outputs": [], 415 | "source": [ 416 | "# make sure template and directories are correct\n", 417 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 418 | " idir=ssm_dir,\n", 419 | " odir=vol_dir,\n", 420 | " initial_guess=ssm_dir + '/output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk',\n", 421 | " kwd=20.,\n", 422 | " kwg=15.,\n", 423 | " noise=5.)" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": null, 429 | "metadata": {}, 430 | "outputs": [], 431 | "source": [ 432 | "# new template\n", 433 | "template_vtu = ssm_dir + \"DeterministicAtlas__EstimatedParameters__Template_Aorta.vtu\"" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": null, 439 | "metadata": {}, 440 | "outputs": [], 441 | "source": [ 442 | "# new momenta file\n", 443 | "fmmt = odir + \"pca_u_new_shapes_momenta.txt\"" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": null, 449 | "metadata": {}, 450 | "outputs": [], 451 | "source": [ 452 | "# ctrl points\n", 453 | "fctp = ssm_dir + \"output/DeterministicAtlas__EstimatedParameters__ControlPoints.txt\"" 454 | ] 455 | }, 456 | { 457 | "cell_type": "code", 458 | "execution_count": null, 459 | "metadata": {}, 460 | "outputs": [], 461 | "source": [ 462 | "ssm.volumetric_meshes.shoot_vtu(fin=template_vtu, \n", 463 | " fvtk=ae.odir+\"vtu/points.vtk\", \n", 464 | " fmoments=fmmt, \n", 465 | " fctrlpts=fctp, \n", 466 | " odir=ae.odir+\"vtu/\",\n", 467 | " fout=ae.odir+\"vtu/vol_mesh.vtu\", \n", 468 | " kw=ae.p_kernel_width_deformation, \n", 469 | " noise=ae.p_noise, \n", 470 | " name=ae.id)" 471 | ] 472 | } 473 | ], 474 | "metadata": { 475 | "kernelspec": { 476 | "display_name": "dfca-env-4.3", 477 | "language": "python", 478 | "name": "dfca-env-4.3" 479 | }, 480 | "language_info": { 481 | "codemirror_mode": { 482 | "name": "ipython", 483 | "version": 3 484 | }, 485 | "file_extension": ".py", 486 | "mimetype": "text/x-python", 487 | "name": "python", 488 | "nbconvert_exporter": "python", 489 | "pygments_lexer": "ipython3", 490 | "version": "3.8.13" 491 | } 492 | }, 493 | "nbformat": 4, 494 | "nbformat_minor": 4 495 | } 496 | -------------------------------------------------------------------------------- /Deformetrica/ssm_estimation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Building a statistical shape model (Deformetrica)" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# uses DFCA 4.3\n", 17 | "import sys, glob, importlib\n", 18 | "import matplotlib.pyplot as plt\n", 19 | "import matplotlib\n", 20 | "import numpy as np" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "import logging\n", 30 | "mpl_logger = logging.getLogger('matplotlib')\n", 31 | "mpl_logger.setLevel(logging.WARNING) " 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "# append scripts from https://github.com/ClinicalCardiovascEngGroup/SSM/tree/master/python (credit: Raphael Sivera)\n", 41 | "sys.path.append(\"/Scripts/SSM/python/\")\n", 42 | "\n", 43 | "import ssm.tools, ssm.iovtk, ssm.atlas, ssm.initialize_controlpoints" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "%matplotlib inline" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "Approach:\n", 60 | "\n", 61 | "1) first initialise control points (basic grid) \n", 62 | "2) freeze control points and compute template \n", 63 | "3) then freeze the template and optimise the control points \n", 64 | "4) then freeze control points and recompute template " 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "base_dir = \"SSM/\"" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "## Initialise control points (do once)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": {}, 86 | "source": [ 87 | "Files are assumed to be in millimetres" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "datadir = \"/my_folder_of_surface_meshes/\"" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [ 105 | "# defining params\n", 106 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 107 | " idir=datadir,\n", 108 | " odir=base_dir + \"r0/\",\n", 109 | " name=\"Aorta\",\n", 110 | " initial_guess=base_dir + \"my_initial_template.vtk\",\n", 111 | " kwd=20.,\n", 112 | " kwg=15.,\n", 113 | " noise=10.)\n", 114 | "\n", 115 | "# init control points first before setting in params\n", 116 | "params = {'convergence_tolerance': 0.01, 'max_iterations': 50,\n", 117 | " 'initial_control_points': ae.odir+\"initial_controlpoints.txt\",\n", 118 | " \"freeze_control_points\":True, \"freeze_template\":False}\n", 119 | "\n", 120 | "ae.save_parameters(True)" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "#################################### SKIP IF CONTROL POINTS ALREADY INITIALISED #####################################\n", 130 | "\n", 131 | "b,p = ssm.initialize_controlpoints.initialize_controlpoints(ae.lf, spacing=ae.p_kernel_width_deformation, margin=1, \n", 132 | " output_dir=ae.odir, name=\"initial_controlpoints.txt\")\n", 133 | "\n", 134 | "ssm.iovtk.controlpoints_to_vtkPoints_files(ae.odir+\"initial_controlpoints.txt\", ae.odir+\"initial_controlpoints.vtk\")" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "**FIRST ROUND OF ATLAS ESTIMATION**" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": { 148 | "scrolled": true 149 | }, 150 | "outputs": [], 151 | "source": [ 152 | "ae.estimate(params)" 153 | ] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "metadata": {}, 158 | "source": [ 159 | "Check control point variance" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "M = ae.read_momenta()\n", 169 | "C = ae.read_ctrlpoints()\n", 170 | "varM = np.var(M, axis=0).sum(axis=1)" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "# plot variance vs control points\n", 180 | "idx = varM.argsort()\n", 181 | "\n", 182 | "fig, (ax0, ax1) = plt.subplots(1,2, figsize=(10,4))\n", 183 | "\n", 184 | "ax0.plot(varM, \".\", label=\"variance\")\n", 185 | "ax0.semilogy()\n", 186 | "\n", 187 | "ax1.plot((np.log(varM[idx])-np.log(varM.max())) / np.log(10), label=\"log10 variance\")\n", 188 | "#ax1.set_xticks([0, 50, 100, 200])\n", 189 | "ax0.legend()\n", 190 | "ax1.legend()\n", 191 | "ax0.grid(True)\n", 192 | "ax1.grid(True)" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [ 201 | "# truncating bad control points\n", 202 | "Ncp = int(np.sum(varM < 0.001*varM.max()))\n", 203 | "\n", 204 | "# keep remaining ctrl points\n", 205 | "C0 = C[varM > varM[idx][Ncp], :]\n", 206 | "print(C0.shape)" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "# writing the txt array and vtk point cloud\n", 216 | "import deformetrica\n", 217 | "deformetrica.in_out.array_readers_and_writers.write_2D_array(C0, ae.odir, \"sel_controlpoints.txt\")\n", 218 | "\n", 219 | "ssm.iovtk.controlpoints_to_vtkPoints_files(ae.odir + \"sel_controlpoints.txt\",\n", 220 | " ae.odir + \"sel_controlpoints.vtk\")" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "metadata": {}, 226 | "source": [ 227 | "**SECOND ROUND OF ATLAS ESTIMATION**" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": null, 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 237 | " idir=datadir,\n", 238 | " odir=base_dir + \"r1/\",\n", 239 | " name=\"Aorta\",\n", 240 | " initial_guess=base_dir + \"r0/output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk\",\n", 241 | " kwd=20.,\n", 242 | " kwg=15.,\n", 243 | " noise=10.)\n", 244 | "\n", 245 | "# freeze template this time, to optimise ctrl points\n", 246 | "params = {'convergence_tolerance': 0.001, 'max_iterations': 100,\n", 247 | " \"initial_control_points\":base_dir + \"r0/sel_controlpoints.txt\",\n", 248 | " \"freeze_control_points\":False, \"freeze_template\":True}\n", 249 | "\n", 250 | "ae.save_parameters(True)" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": { 257 | "scrolled": true 258 | }, 259 | "outputs": [], 260 | "source": [ 261 | "ae.estimate(params)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "ae.save_controlpoints_vtk()" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "metadata": {}, 276 | "source": [ 277 | "**THIRD AND FINAL ROUND OF ATLAS ESTIMATION**" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": null, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 287 | " idir=datadir,\n", 288 | " odir=base_dir + \"r2/\",\n", 289 | " name=\"Aorta\",\n", 290 | " initial_guess=base_dir + \"r1/output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk\",\n", 291 | " kwd=20.,\n", 292 | " kwg=15.,\n", 293 | " noise=5.)\n", 294 | "\n", 295 | "params = {'convergence_tolerance': 0.001,\n", 296 | " \"initial_control_points\":base_dir + \"r1/output/DeterministicAtlas__EstimatedParameters__ControlPoints.txt\",\n", 297 | " \"freeze_control_points\":True, \"freeze_template\":False}\n", 298 | "\n", 299 | "ae.save_parameters(True)" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": null, 305 | "metadata": { 306 | "scrolled": true 307 | }, 308 | "outputs": [], 309 | "source": [ 310 | "ae.estimate(params)" 311 | ] 312 | } 313 | ], 314 | "metadata": { 315 | "kernelspec": { 316 | "display_name": "dfca-env-4.3", 317 | "language": "python", 318 | "name": "dfca-env-4.3" 319 | }, 320 | "language_info": { 321 | "codemirror_mode": { 322 | "name": "ipython", 323 | "version": 3 324 | }, 325 | "file_extension": ".py", 326 | "mimetype": "text/x-python", 327 | "name": "python", 328 | "nbconvert_exporter": "python", 329 | "pygments_lexer": "ipython3", 330 | "version": "3.8.13" 331 | } 332 | }, 333 | "nbformat": 4, 334 | "nbformat_minor": 4 335 | } 336 | -------------------------------------------------------------------------------- /Deformetrica/ssm_new_shape_generation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Generate Synthetic Cohort" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# dfca 4.3 needed\n", 17 | "import subprocess as sp\n", 18 | "import statistics, sys, os, shutil, re\n", 19 | "import numpy as np\n", 20 | "import deformetrica" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "import matplotlib.pyplot as plt\n", 30 | "import matplotlib\n", 31 | "import logging\n", 32 | "mpl_logger = logging.getLogger('matplotlib')\n", 33 | "mpl_logger.setLevel(logging.WARNING)\n", 34 | "%matplotlib inline" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "# append scripts from https://github.com/ClinicalCardiovascEngGroup/SSM/tree/master/python (credit: Raphael Sivera)\n", 44 | "sys.path.append(\"/home/endrit/Documents/Scripts/SSM-V2/python/\")\n", 45 | "\n", 46 | "import ssm.pca, ssm.volumetric_meshes, ssm.atlas" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "# New Surfaces" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "List directories" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "ssm_dir = \"my_final_SSM_folder/\"" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "odir = \"new_surfaces/\"" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "**COMPUTE PCA**" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "ao = ssm.pca.DeformetricaAtlasPCA(\n", 95 | " idir = ssm_dir + \"output/\",\n", 96 | " odir = ssm_dir + \"pca/\")\n", 97 | "\n", 98 | "ao.compute_pca(with_plots=True)" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "# Reshape into U, S, Vt matrices\n", 108 | "momenta = ao.momenta\n", 109 | "nsbj = momenta.shape[0]\n", 110 | "ndim = momenta.shape[1] * momenta.shape[2]\n", 111 | "x = ao.momenta.reshape((nsbj, ndim))\n", 112 | "pca_u = ao.pca_u\n", 113 | "pca_s = ao.pca_s\n", 114 | "pca_v = ao.pca_v" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "# print cumsum of PCA\n", 124 | "cumsum_pca = np.concatenate((np.zeros(1), (pca_s**2).cumsum()/(pca_s**2).sum()))\n", 125 | "print(cumsum_pca)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "# keep adding modes until 99% variance captured\n", 135 | "print(cumsum_pca[:35])" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "# save pca matrices of training set\n", 145 | "np.savetxt(odir + \"pca_u.csv\", pca_u, delimiter=',')\n", 146 | "np.savetxt(odir + \"pca_s.csv\", pca_s, delimiter=\",\")\n", 147 | "np.savetxt(odir + \"pca_v.csv\", pca_v, delimiter=\",\")" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "**FUNCTIONS**" 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "metadata": {}, 160 | "source": [ 161 | "Get standard deviation" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "def get_mean_stdev(n_subjects, n_modes, pca_matrix):\n", 171 | " \"\"\"\n", 172 | " build matrix of mean and stdev per mode:\n", 173 | " output: rows=modes, col_0 = mean score per mode, col_1 = stdev of scores per mode\n", 174 | " \n", 175 | " Modes that are excluded given 0 mean and 0 stdev.\n", 176 | " \"\"\"\n", 177 | " matrix = np.zeros(shape=(n_subjects, 2))\n", 178 | "\n", 179 | " for i in range(n_subjects):\n", 180 | " if i < n_modes:\n", 181 | " matrix[i][0] = statistics.mean(pca_matrix[:,i])\n", 182 | " matrix[i][1] = statistics.stdev(pca_matrix[:,i])\n", 183 | " else:\n", 184 | " matrix[i][0] = 0\n", 185 | " matrix[i][1] = 0\n", 186 | " return matrix" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "Sample Gaussian" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": null, 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [ 202 | "def sample_gaussian(new_subjects, n_subjects, stats_arr):\n", 203 | " \"\"\"\n", 204 | " make new pca u [subjects, modes]\n", 205 | " sample within 2 stdev (limit extreme deformations)\n", 206 | " \"\"\"\n", 207 | " new_shapes = np.zeros(shape=(new_subjects, n_subjects))\n", 208 | " for i in range(new_subjects):\n", 209 | " for j in range(n_subjects):\n", 210 | " mu = stats_arr[j][0]\n", 211 | " sigma = stats_arr[j][1]\n", 212 | " x = np.random.normal(mu, sigma)\n", 213 | " if x < mu - 2*sigma:\n", 214 | " x = mu - 2*sigma\n", 215 | " if x > mu + 2*sigma:\n", 216 | " x = mu + 2*sigma\n", 217 | " new_shapes[i][j] = x\n", 218 | " return new_shapes" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": {}, 224 | "source": [ 225 | "Create Momenta txt file" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "def generate_momenta(new_subjects, batch_size, pca_new, ofile):\n", 235 | " \"\"\"\n", 236 | " reverse svd to get momenta u@s@v = momenta \n", 237 | " \"\"\"\n", 238 | " s = np.dot(np.diag(pca_s), pca_v[0:batch_size, :])\n", 239 | " \n", 240 | " with open(ofile, 'w') as outfile:\n", 241 | " # start writing momenta file\n", 242 | " outfile.write(str(new_subjects)+' '+str(momenta.shape[1])+' '+str(momenta.shape[2])+'\\n')\n", 243 | " outfile.write('\\n')\n", 244 | " for i in range(0, new_subjects, batch_size):\n", 245 | " \"\"\"\n", 246 | " calculate momenta for each batch\n", 247 | " \"\"\"\n", 248 | " b = max(new_subjects, i + batch_size)\n", 249 | " usv = np.dot(pca_new[i:b, :], s)\n", 250 | " M = usv.reshape((-1, momenta.shape[1], 3))\n", 251 | " # write each subject from batch into momenta file\n", 252 | " for subject in M:\n", 253 | " np.savetxt(outfile, subject, fmt='%-3.20f')\n", 254 | " outfile.write('\\n')" 255 | ] 256 | }, 257 | { 258 | "cell_type": "markdown", 259 | "metadata": {}, 260 | "source": [ 261 | "Shooting" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "def shoot(idir, odir, kw, noise):\n", 271 | "\n", 272 | " ftemplate = idir + \"output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk\"\n", 273 | " fctrlpts = idir + \"output/DeterministicAtlas__EstimatedParameters__ControlPoints.txt\"\n", 274 | " # new momenta file\n", 275 | " fmoments = odir + \"pca_u_new_shapes_momenta.txt\"\n", 276 | "\n", 277 | " sp.call([\"mkdir\", \"-p\", odir+\"new_shapes/\"])\n", 278 | "\n", 279 | " # warping polydata\n", 280 | " template_specifications = {\n", 281 | " 'new_shape': {'deformable_object_type': 'surfacemesh', \n", 282 | " 'noise_std': noise,\n", 283 | " 'kernel_type':'torch', 'kernel_width':kw,\n", 284 | " 'filename': ftemplate}}\n", 285 | " \n", 286 | " model_options={\n", 287 | " 'dimension': 3,\n", 288 | " 'deformation_kernel_type': 'torch',\n", 289 | " 'deformation_kernel_width': kw,\n", 290 | " 'tmin':0,\n", 291 | " 'tmax':1,\n", 292 | " \"initial_control_points\": fctrlpts,\n", 293 | " \"initial_momenta\": fmoments}\n", 294 | " \n", 295 | " Deformetrica = deformetrica.api.Deformetrica(verbosity=\"INFO\", output_dir=odir+\"new_shapes/\")\n", 296 | " Deformetrica.compute_shooting(template_specifications, model_options=model_options)" 297 | ] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": {}, 302 | "source": [ 303 | "**DEFINE VARIABLES**" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [ 312 | "# number of original shapes\n", 313 | "n_subjects = 67" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "# number of modes to use\n", 323 | "n_modes = 35" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": {}, 330 | "outputs": [], 331 | "source": [ 332 | "# number of subjects to generate\n", 333 | "n_new_subjects = 3000" 334 | ] 335 | }, 336 | { 337 | "cell_type": "markdown", 338 | "metadata": {}, 339 | "source": [ 340 | "**GENERATE SHAPES**" 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": {}, 347 | "outputs": [], 348 | "source": [ 349 | "mean_stdev = get_mean_stdev(n_subjects, n_modes, pca_u)" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "metadata": {}, 356 | "outputs": [], 357 | "source": [ 358 | "# sample gaussian\n", 359 | "pca_u_new = sample_gaussian(n_new_subjects, n_subjects, mean_stdev)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": null, 365 | "metadata": {}, 366 | "outputs": [], 367 | "source": [ 368 | "# write concat pca_u file (for ML)\n", 369 | "np.savetxt(odir + \"pca_u_new_shapes_concat.csv\", pca_u_new, delimiter=\",\")" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": null, 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "# write momenta (for shooting)\n", 379 | "generate_momenta(n_new_subjects, n_subjects, pca_u_new, odir + \"pca_u_new_shapes_momenta.txt\")" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": null, 385 | "metadata": {}, 386 | "outputs": [], 387 | "source": [ 388 | "kw = 20.\n", 389 | "noise = 5.\n", 390 | "\n", 391 | "shoot(ssm_dir, odir, kw, noise)" 392 | ] 393 | }, 394 | { 395 | "cell_type": "markdown", 396 | "metadata": {}, 397 | "source": [ 398 | "**GENERATE VOLUMES**" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": null, 404 | "metadata": {}, 405 | "outputs": [], 406 | "source": [ 407 | "vol_dir = \"new_volumes/\"" 408 | ] 409 | }, 410 | { 411 | "cell_type": "code", 412 | "execution_count": null, 413 | "metadata": {}, 414 | "outputs": [], 415 | "source": [ 416 | "# make sure template and directories are correct\n", 417 | "ae = ssm.atlas.DeformetricaAtlasEstimation(\n", 418 | " idir=ssm_dir,\n", 419 | " odir=vol_dir,\n", 420 | " initial_guess=ssm_dir + '/output/DeterministicAtlas__EstimatedParameters__Template_Aorta.vtk',\n", 421 | " kwd=20.,\n", 422 | " kwg=15.,\n", 423 | " noise=5.)" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": null, 429 | "metadata": {}, 430 | "outputs": [], 431 | "source": [ 432 | "# new template\n", 433 | "template_vtu = ssm_dir + \"DeterministicAtlas__EstimatedParameters__Template_Aorta.vtu\"" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": null, 439 | "metadata": {}, 440 | "outputs": [], 441 | "source": [ 442 | "# new momenta file\n", 443 | "fmmt = odir + \"pca_u_new_shapes_momenta.txt\"" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": null, 449 | "metadata": {}, 450 | "outputs": [], 451 | "source": [ 452 | "# ctrl points\n", 453 | "fctp = ssm_dir + \"output/DeterministicAtlas__EstimatedParameters__ControlPoints.txt\"" 454 | ] 455 | }, 456 | { 457 | "cell_type": "code", 458 | "execution_count": null, 459 | "metadata": {}, 460 | "outputs": [], 461 | "source": [ 462 | "ssm.volumetric_meshes.shoot_vtu(fin=template_vtu, \n", 463 | " fvtk=ae.odir+\"vtu/points.vtk\", \n", 464 | " fmoments=fmmt, \n", 465 | " fctrlpts=fctp, \n", 466 | " odir=ae.odir+\"vtu/\",\n", 467 | " fout=ae.odir+\"vtu/vol_mesh.vtu\", \n", 468 | " kw=ae.p_kernel_width_deformation, \n", 469 | " noise=ae.p_noise, \n", 470 | " name=ae.id)" 471 | ] 472 | } 473 | ], 474 | "metadata": { 475 | "kernelspec": { 476 | "display_name": "dfca-env-4.3", 477 | "language": "python", 478 | "name": "dfca-env-4.3" 479 | }, 480 | "language_info": { 481 | "codemirror_mode": { 482 | "name": "ipython", 483 | "version": 3 484 | }, 485 | "file_extension": ".py", 486 | "mimetype": "text/x-python", 487 | "name": "python", 488 | "nbconvert_exporter": "python", 489 | "pygments_lexer": "ipython3", 490 | "version": "3.8.13" 491 | } 492 | }, 493 | "nbformat": 4, 494 | "nbformat_minor": 4 495 | } 496 | -------------------------------------------------------------------------------- /Envs/env_deformetrica.yml: -------------------------------------------------------------------------------- 1 | name: dfca-env-4.3 2 | channels: 3 | - ngsolve 4 | - conda-forge 5 | - defaults 6 | dependencies: 7 | - _libgcc_mutex=0.1=conda_forge 8 | - _openmp_mutex=4.5=2_gnu 9 | - asttokens=2.0.5=pyhd8ed1ab_0 10 | - backcall=0.2.0=pyh9f0ad1d_0 11 | - backports=1.0=py_2 12 | - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0 13 | - bzip2=1.0.8=h7f98852_4 14 | - ca-certificates=2022.6.15=ha878542_0 15 | - debugpy=1.6.0=py38hfa26641_0 16 | - decorator=5.1.1=pyhd8ed1ab_0 17 | - entrypoints=0.4=pyhd8ed1ab_0 18 | - executing=0.8.3=pyhd8ed1ab_0 19 | - ipykernel=6.14.0=py38h7f3c49e_0 20 | - ipython=8.4.0=py38h578d9bd_0 21 | - jedi=0.18.1=py38h578d9bd_1 22 | - jupyter_client=7.3.4=pyhd8ed1ab_0 23 | - jupyter_core=4.10.0=py38h578d9bd_0 24 | - ld_impl_linux-64=2.36.1=hea4e1c9_2 25 | - libblas=3.9.0=15_linux64_openblas 26 | - libcblas=3.9.0=15_linux64_openblas 27 | - libffi=3.4.2=h7f98852_5 28 | - libgcc-ng=12.1.0=h8d9b700_16 29 | - libgfortran-ng=12.1.0=h69a702a_16 30 | - libgfortran5=12.1.0=hdcd56e2_16 31 | - libgomp=12.1.0=h8d9b700_16 32 | - liblapack=3.9.0=15_linux64_openblas 33 | - libnsl=2.0.0=h7f98852_0 34 | - libopenblas=0.3.20=pthreads_h78a6416_0 35 | - libsodium=1.0.18=h36c2ea0_1 36 | - libstdcxx-ng=12.1.0=ha89aaad_16 37 | - libuuid=2.32.1=h7f98852_1000 38 | - libzlib=1.2.12=h166bdaf_1 39 | - matplotlib-inline=0.1.3=pyhd8ed1ab_0 40 | - ncurses=6.3=h27087fc_1 41 | - nest-asyncio=1.5.5=pyhd8ed1ab_0 42 | - numpy=1.22.4=py38h99721a1_0 43 | - openssl=3.0.3=h166bdaf_0 44 | - packaging=21.3=pyhd8ed1ab_0 45 | - parso=0.8.3=pyhd8ed1ab_0 46 | - pexpect=4.8.0=pyh9f0ad1d_2 47 | - pickleshare=0.7.5=py_1003 48 | - pip=22.1.2=pyhd8ed1ab_0 49 | - prompt-toolkit=3.0.29=pyha770c72_0 50 | - psutil=5.9.1=py38h0a891b7_0 51 | - ptyprocess=0.7.0=pyhd3deb0d_0 52 | - pure_eval=0.2.2=pyhd8ed1ab_0 53 | - pygments=2.12.0=pyhd8ed1ab_0 54 | - pyparsing=3.0.9=pyhd8ed1ab_0 55 | - python=3.8.13=ha86cf86_0_cpython 56 | - python-dateutil=2.8.2=pyhd8ed1ab_0 57 | - python_abi=3.8=2_cp38 58 | - pyzmq=23.1.0=py38hfc09fa9_0 59 | - readline=8.1.2=h0f457ee_0 60 | - setuptools=62.6.0=py38h578d9bd_0 61 | - six=1.16.0=pyh6c4a22f_0 62 | - sqlite=3.38.5=h4ff8645_0 63 | - stack_data=0.3.0=pyhd8ed1ab_0 64 | - tk=8.6.12=h27826a3_0 65 | - tornado=6.1=py38h0a891b7_3 66 | - traitlets=5.3.0=pyhd8ed1ab_0 67 | - wcwidth=0.2.5=pyh9f0ad1d_2 68 | - wheel=0.37.1=pyhd8ed1ab_0 69 | - xz=5.2.5=h516909a_1 70 | - zeromq=4.3.4=h9c3ff4c_1 71 | - zlib=1.2.12=h166bdaf_1 72 | - pip: 73 | - aiohttp==3.8.1 74 | - aiosignal==1.2.0 75 | - async-timeout==4.0.2 76 | - attrs==21.4.0 77 | - charset-normalizer==2.1.0 78 | - cycler==0.11.0 79 | - deformetrica==4.3.0 80 | - docopt==0.6.2 81 | - fonttools==4.33.3 82 | - frozenlist==1.3.0 83 | - future==0.18.2 84 | - gputil==1.4.0 85 | - idna==3.3 86 | - joblib==1.1.0 87 | - kiwisolver==1.4.3 88 | - matplotlib==3.5.2 89 | - multidict==6.0.2 90 | - nibabel==4.0.1 91 | - pillow==9.1.1 92 | - pykeops==1.4.1 93 | - pyqt5==5.15.7 94 | - pyqt5-qt5==5.15.2 95 | - pyqt5-sip==12.11.0 96 | - scikit-learn==1.1.1 97 | - scipy==1.8.1 98 | - threadpoolctl==3.1.0 99 | - torch==1.6.0 100 | - torchvision==0.7.0 101 | - vtk==9.1.0 102 | - wslink==1.6.5 103 | - yarl==1.7.2 104 | prefix: /home/endrit/anaconda3/envs/dfca-env-4.3 105 | 106 | -------------------------------------------------------------------------------- /Envs/env_keras.yml: -------------------------------------------------------------------------------- 1 | name: keras-env 2 | channels: 3 | - plotly 4 | - anaconda 5 | - ngsolve 6 | - conda-forge 7 | - defaults 8 | dependencies: 9 | - _libgcc_mutex=0.1=conda_forge 10 | - _openmp_mutex=4.5=1_gnu 11 | - _tflow_select=2.1.0=gpu 12 | - absl-py=0.12.0=pyhd8ed1ab_0 13 | - adjusttext=0.7.3.1=py_1 14 | - aiohttp=3.7.4=py39h3811e60_0 15 | - alembic=1.7.5=pyhd8ed1ab_0 16 | - anyio=3.5.0=py39hf3d152e_0 17 | - argon2-cffi=20.1.0=py39h3811e60_2 18 | - astunparse=1.6.3=py_0 19 | - async-timeout=3.0.1=py_1000 20 | - async_generator=1.10=py_0 21 | - attrs=20.3.0=pyhd3deb0d_0 22 | - autopage=0.4.0=pyhd8ed1ab_0 23 | - babel=2.9.1=pyh44b312d_0 24 | - backcall=0.2.0=pyh9f0ad1d_0 25 | - backports=1.0=py_2 26 | - backports.functools_lru_cache=1.6.3=pyhd8ed1ab_0 27 | - bleach=3.3.0=pyh44b312d_0 28 | - blinker=1.4=py_1 29 | - brotli-python=1.0.9=py39he80948d_5 30 | - brotlipy=0.7.0=py39h3811e60_1001 31 | - c-ares=1.17.1=h7f98852_1 32 | - ca-certificates=2021.10.8=ha878542_0 33 | - cachetools=4.1.1=py_0 34 | - certifi=2021.10.8=py39hf3d152e_2 35 | - cffi=1.14.5=py39he32792d_0 36 | - chardet=3.0.4=py39h079e4ff_1008 37 | - click=7.1.2=py_0 38 | - cliff=3.10.0=pyhd8ed1ab_0 39 | - cmaes=0.8.2=pyh44b312d_0 40 | - cmd2=2.3.3=py39hf3d152e_1 41 | - colorama=0.4.4=pyh9f0ad1d_0 42 | - colorlog=6.6.0=py39hf3d152e_0 43 | - cryptography=3.4.7=py39hbca0aa6_0 44 | - cudatoolkit=10.1.243=h6bb024c_0 45 | - cudnn=7.6.5=cuda10.1_0 46 | - cupti=10.1.168=0 47 | - cycler=0.10.0=py_2 48 | - dash=2.3.1=pyhd8ed1ab_0 49 | - dbus=1.13.6=h48d8840_2 50 | - decorator=5.0.5=pyhd8ed1ab_0 51 | - defusedxml=0.7.1=pyhd8ed1ab_0 52 | - entrypoints=0.3=pyhd8ed1ab_1003 53 | - et_xmlfile=1.0.1=py_1001 54 | - expat=2.3.0=h9c3ff4c_0 55 | - flask=1.1.2=pyh9f0ad1d_0 56 | - flask-compress=1.11=pyhd8ed1ab_0 57 | - fontconfig=2.13.1=hba837de_1004 58 | - freetype=2.10.4=h0708190_1 59 | - future=0.18.2=py39hf3d152e_4 60 | - gast=0.4.0=py_0 61 | - gettext=0.19.8.1=h0b5b191_1005 62 | - glib=2.68.0=h9c3ff4c_2 63 | - glib-tools=2.68.0=h9c3ff4c_2 64 | - google-auth=1.22.1=py_0 65 | - google-auth-oauthlib=0.4.1=py_2 66 | - google-pasta=0.2.0=py_0 67 | - grpcio=1.36.1=py39hff7568b_0 68 | - gst-plugins-base=1.18.4=h29181c9_0 69 | - gstreamer=1.18.4=h76c114f_0 70 | - h5py=2.10.0=nompi_py39h25020de_105 71 | - hdf5=1.10.6=nompi_h6a2412b_1114 72 | - icu=68.1=h58526e2_0 73 | - idna=2.10=py_0 74 | - importlib-metadata=3.10.0=py39hf3d152e_0 75 | - importlib_resources=5.4.0=pyhd8ed1ab_0 76 | - ipykernel=5.5.3=py39hef51801_0 77 | - ipython=7.22.0=py39hef51801_0 78 | - ipython_genutils=0.2.0=py_1 79 | - ipywidgets=7.6.3=pyhd3deb0d_0 80 | - itsdangerous=2.1.2=pyhd8ed1ab_0 81 | - jdcal=1.4.1=py_0 82 | - jedi=0.18.0=py39hf3d152e_2 83 | - jinja2=2.11.3=pyh44b312d_0 84 | - joblib=1.0.1=pyhd8ed1ab_0 85 | - jpeg=9d=h36c2ea0_0 86 | - json5=0.9.5=pyh9f0ad1d_0 87 | - jsonschema=3.2.0=pyhd8ed1ab_3 88 | - jupyter=1.0.0=py39hf3d152e_6 89 | - jupyter_client=6.1.12=pyhd8ed1ab_0 90 | - jupyter_console=6.4.0=pyhd8ed1ab_0 91 | - jupyter_core=4.7.1=py39hf3d152e_0 92 | - jupyter_server=1.13.5=pyhd3eb1b0_0 93 | - jupyterlab=3.3.4=pyhd8ed1ab_0 94 | - jupyterlab_pygments=0.1.2=pyh9f0ad1d_0 95 | - jupyterlab_server=2.10.3=pyhd3eb1b0_1 96 | - jupyterlab_widgets=1.0.0=pyhd8ed1ab_1 97 | - keras=2.4.3=py_0 98 | - keras-preprocessing=1.1.2=pyhd8ed1ab_0 99 | - keras-tuner=1.0.3=pyhd8ed1ab_0 100 | - kiwisolver=1.3.1=py39h1a9c180_1 101 | - krb5=1.17.2=h926e7f8_0 102 | - lcms2=2.12=hddcbb42_0 103 | - ld_impl_linux-64=2.35.1=hea4e1c9_2 104 | - libblas=3.9.0=8_openblas 105 | - libcblas=3.9.0=8_openblas 106 | - libclang=11.1.0=default_ha53f305_0 107 | - libcurl=7.76.0=hc4aaa36_0 108 | - libedit=3.1.20191231=he28a2e2_2 109 | - libev=4.33=h7b6447c_0 110 | - libevent=2.1.10=hcdb4288_3 111 | - libffi=3.3=h58526e2_2 112 | - libgcc-ng=9.3.0=h2828fa1_18 113 | - libgfortran-ng=9.3.0=hff62375_18 114 | - libgfortran5=9.3.0=hff62375_18 115 | - libglib=2.68.0=h3e27bee_2 116 | - libgomp=9.3.0=h2828fa1_18 117 | - libiconv=1.16=h516909a_0 118 | - liblapack=3.9.0=8_openblas 119 | - libllvm11=11.1.0=hf817b99_2 120 | - libnghttp2=1.43.0=h812cca2_0 121 | - libopenblas=0.3.12=pthreads_h4812303_1 122 | - libpng=1.6.37=h21135ba_2 123 | - libpq=13.1=hfd2b0eb_2 124 | - libprotobuf=3.15.7=h780b84a_0 125 | - libsodium=1.0.18=h36c2ea0_1 126 | - libssh2=1.9.0=h1ba5d50_1 127 | - libstdcxx-ng=9.3.0=h6de172a_18 128 | - libtiff=4.2.0=hdc55705_0 129 | - libuuid=2.32.1=h7f98852_1000 130 | - libwebp-base=1.2.0=h7f98852_2 131 | - libxcb=1.13=h7f98852_1003 132 | - libxkbcommon=1.0.3=he3ba5ed_0 133 | - libxml2=2.9.10=h72842e0_3 134 | - lz4-c=1.9.3=h9c3ff4c_0 135 | - mako=1.1.6=pyhd8ed1ab_0 136 | - markdown=3.3.4=pyhd8ed1ab_0 137 | - markupsafe=1.1.1=py39h3811e60_3 138 | - matplotlib=3.4.1=py39hf3d152e_0 139 | - matplotlib-base=3.4.1=py39h2fa2bec_0 140 | - mistune=0.8.4=py39h3811e60_1003 141 | - multidict=5.1.0=py39h3811e60_1 142 | - mysql-common=8.0.23=ha770c72_1 143 | - mysql-libs=8.0.23=h935591d_1 144 | - nbclassic=0.3.7=pyhd8ed1ab_0 145 | - nbclient=0.5.3=pyhd8ed1ab_0 146 | - nbconvert=6.0.7=py39hf3d152e_3 147 | - nbformat=5.1.3=pyhd8ed1ab_0 148 | - ncurses=6.2=h58526e2_4 149 | - nest-asyncio=1.5.1=pyhd8ed1ab_0 150 | - notebook=6.3.0=py39hf3d152e_0 151 | - notebook-shim=0.1.0=pyhd8ed1ab_0 152 | - nspr=4.30=h9c3ff4c_0 153 | - nss=3.63=hb5efdd6_0 154 | - numpy=1.20.2=py39hdbf815f_0 155 | - oauthlib=3.1.0=py_0 156 | - olefile=0.46=pyh9f0ad1d_1 157 | - openpyxl=3.0.7=pyhd8ed1ab_0 158 | - openssl=1.1.1k=h7f98852_0 159 | - opt_einsum=3.1.0=py_0 160 | - optuna=2.10.0=pyhd8ed1ab_0 161 | - packaging=20.9=pyh44b312d_0 162 | - pandas=1.2.3=py39hde0f152_0 163 | - pandoc=2.12=h7f98852_0 164 | - pandocfilters=1.4.2=py_1 165 | - parso=0.8.2=pyhd8ed1ab_0 166 | - patsy=0.5.1=py_0 167 | - pbr=5.8.0=pyhd8ed1ab_1 168 | - pcre=8.44=he1b5a44_0 169 | - pexpect=4.8.0=pyh9f0ad1d_2 170 | - pickleshare=0.7.5=py_1003 171 | - pillow=8.1.2=py39hf95b381_0 172 | - pip=21.0.1=pyhd8ed1ab_0 173 | - plotly=5.3.1=py_0 174 | - prettytable=3.0.0=pyhd8ed1ab_0 175 | - prometheus_client=0.10.0=pyhd8ed1ab_0 176 | - prompt-toolkit=3.0.18=pyha770c72_0 177 | - prompt_toolkit=3.0.18=hd8ed1ab_0 178 | - protobuf=3.15.7=py39he80948d_0 179 | - pthread-stubs=0.4=h36c2ea0_1001 180 | - ptyprocess=0.7.0=pyhd3deb0d_0 181 | - pyasn1=0.4.8=py_0 182 | - pyasn1-modules=0.2.8=py_0 183 | - pycparser=2.20=pyh9f0ad1d_2 184 | - pygments=2.8.1=pyhd8ed1ab_0 185 | - pyjwt=2.0.1=pyhd8ed1ab_1 186 | - pyopengl=3.1.6=pyh6c4a22f_0 187 | - pyopenssl=19.1.0=py_1 188 | - pyparsing=2.4.7=pyh9f0ad1d_0 189 | - pyperclip=1.8.2=pyhd8ed1ab_2 190 | - pyqt=5.12.3=py39hf3d152e_7 191 | - pyqt-impl=5.12.3=py39h0fcd23e_7 192 | - pyqt5-sip=4.19.18=py39he80948d_7 193 | - pyqtchart=5.12=py39h0fcd23e_7 194 | - pyqtgraph=0.12.4=pyhd8ed1ab_0 195 | - pyqtwebengine=5.12.1=py39h0fcd23e_7 196 | - pyrsistent=0.17.3=py39h3811e60_2 197 | - pysocks=1.7.1=py39hf3d152e_3 198 | - python=3.9.2=hffdb5ce_0_cpython 199 | - python-dateutil=2.8.1=py_0 200 | - python-flatbuffers=1.12=pyhd8ed1ab_1 201 | - python_abi=3.9=1_cp39 202 | - pytz=2021.1=pyhd8ed1ab_0 203 | - pyyaml=5.4.1=py39h3811e60_0 204 | - pyzmq=22.0.3=py39h37b5a0c_1 205 | - qt=5.12.9=hda022c4_4 206 | - qtconsole=5.0.3=pyhd8ed1ab_0 207 | - qtpy=1.9.0=py_0 208 | - readline=8.0=he28a2e2_2 209 | - requests=2.24.0=py_0 210 | - requests-oauthlib=1.3.0=py_0 211 | - rsa=4.6=py_0 212 | - scikit-learn=0.24.1=py39h4dfa638_0 213 | - scipy=1.6.2=py39hee8e79c_0 214 | - seaborn=0.11.1=hd8ed1ab_1 215 | - seaborn-base=0.11.1=pyhd8ed1ab_1 216 | - send2trash=1.5.0=py_0 217 | - setuptools=49.6.0=py39hf3d152e_3 218 | - six=1.15.0=pyh9f0ad1d_0 219 | - sniffio=1.2.0=py39hf3d152e_3 220 | - sqlalchemy=1.3.23=py39h3811e60_0 221 | - sqlite=3.35.4=h74cdb3f_0 222 | - statsmodels=0.12.2=py39hce5d2b2_0 223 | - stevedore=3.5.0=py39hf3d152e_2 224 | - tabulate=0.8.9=pyhd8ed1ab_0 225 | - tenacity=8.0.1=pyhd8ed1ab_0 226 | - tensorboard=2.4.1=pyhd8ed1ab_0 227 | - tensorboard-plugin-wit=1.6.0=py_0 228 | - tensorflow=2.4.1=gpu_py39h8236f22_0 229 | - tensorflow-base=2.4.1=gpu_py39h29c2da4_0 230 | - tensorflow-estimator=2.4.1=pyheb71bc4_0 231 | - tensorflow-gpu=2.4.1=h30adc30_0 232 | - termcolor=1.1.0=py_2 233 | - terminado=0.9.4=py39hf3d152e_0 234 | - terminaltables=3.1.10=pyhd8ed1ab_0 235 | - testpath=0.4.4=py_0 236 | - threadpoolctl=2.1.0=pyh5ca1d4c_0 237 | - tk=8.6.10=h21135ba_1 238 | - tornado=6.1=py39h3811e60_1 239 | - tqdm=4.62.3=pyhd8ed1ab_0 240 | - traitlets=5.0.5=py_0 241 | - typing-extensions=3.7.4.3=0 242 | - typing_extensions=3.7.4.3=py_0 243 | - tzdata=2021a=he74cb21_0 244 | - urllib3=1.25.11=py_0 245 | - wcwidth=0.2.5=pyh9f0ad1d_2 246 | - webencodings=0.5.1=py_1 247 | - websocket-client=1.3.2=pyhd8ed1ab_0 248 | - werkzeug=1.0.1=py_0 249 | - wheel=0.36.2=pyhd3deb0d_0 250 | - widgetsnbextension=3.5.1=py39hf3d152e_4 251 | - wrapt=1.12.1=py39h3811e60_3 252 | - xlrd=2.0.1=pyhd8ed1ab_3 253 | - xorg-libxau=1.0.9=h7f98852_0 254 | - xorg-libxdmcp=1.1.3=h7f98852_0 255 | - xz=5.2.5=h516909a_1 256 | - yaml=0.2.5=h516909a_0 257 | - yarl=1.6.3=py39h3811e60_1 258 | - zeromq=4.3.4=h9c3ff4c_0 259 | - zipp=3.4.1=pyhd8ed1ab_0 260 | - zlib=1.2.11=h516909a_1010 261 | - zstd=1.4.9=ha95c52a_0 262 | prefix: /home/endrit/anaconda3/envs/keras-env 263 | 264 | -------------------------------------------------------------------------------- /Envs/env_vmtk.yml: -------------------------------------------------------------------------------- 1 | name: vmtk-env 2 | channels: 3 | - vmtk 4 | - anaconda 5 | - ngsolve 6 | - conda-forge 7 | - defaults 8 | dependencies: 9 | - _libgcc_mutex=0.1=conda_forge 10 | - _openmp_mutex=4.5=1_gnu 11 | - arrow=0.15.8=py36h9f0ad1d_0 12 | - asn1crypto=1.4.0=pyh9f0ad1d_0 13 | - backcall=0.2.0=py_0 14 | - binaryornot=0.4.4=py_1 15 | - brotlipy=0.7.0=py36h8c4c3a4_1000 16 | - ca-certificates=2020.10.14=0 17 | - certifi=2020.6.20=py36_0 18 | - cffi=1.14.1=py36h0ff685e_0 19 | - chardet=3.0.4=py36h9f0ad1d_1006 20 | - click=7.1.2=pyh9f0ad1d_0 21 | - cookiecutter=1.7.2=pyh9f0ad1d_0 22 | - cryptography=2.5=py36hb7f436b_1 23 | - decorator=4.4.2=py_0 24 | - expat=2.2.9=he1b5a44_2 25 | - freetype=2.8.1=hfa320df_1 26 | - future=0.18.2=py36h9f0ad1d_1 27 | - h5py=2.8.0=py36h470a237_0 28 | - hdf5=1.10.1=2 29 | - icu=67.1=he1b5a44_0 30 | - idna=2.10=pyh9f0ad1d_0 31 | - ipykernel=5.3.4=py36h5ca1d4c_0 32 | - ipython=7.16.1=py36h5ca1d4c_0 33 | - ipython_genutils=0.2.0=py36_0 34 | - itk=4.13.0=h2f4ac57_1 35 | - jedi=0.10.2=py36_2 36 | - jinja2=2.11.2=pyh9f0ad1d_0 37 | - jinja2-time=0.2.0=py_2 38 | - jpeg=9d=h516909a_0 39 | - jsoncpp=1.8.4=hc9558a2_1002 40 | - jupyter_client=6.1.7=py_0 41 | - jupyter_core=4.6.3=py36_0 42 | - libblas=3.8.0=17_openblas 43 | - libcblas=3.8.0=17_openblas 44 | - libffi=3.2.1=he1b5a44_1007 45 | - libgcc-ng=9.3.0=h24d8f2e_14 46 | - libgfortran=3.0.0=1 47 | - libgfortran-ng=7.5.0=hdf63c60_14 48 | - libgomp=9.3.0=h24d8f2e_14 49 | - libiconv=1.15=h516909a_1006 50 | - liblapack=3.8.0=17_openblas 51 | - libopenblas=0.3.10=pthreads_hb3c22a3_4 52 | - libpng=1.6.37=hed695b0_2 53 | - libsodium=1.0.18=h7b6447c_0 54 | - libstdcxx-ng=9.3.0=hdf63c60_14 55 | - libtiff=4.1.0=hc7e4089_6 56 | - libwebp-base=1.1.0=h516909a_3 57 | - libxml2=2.9.10=h72b56ed_2 58 | - lz4-c=1.9.2=he1b5a44_1 59 | - markupsafe=1.1.1=py36h8c4c3a4_1 60 | - mesa=0.8.7=py_0 61 | - ncurses=5.9=10 62 | - networkx=2.4=py_1 63 | - openssl=1.0.2u=h7b6447c_0 64 | - pandas=0.23.4=py36h637b7d7_1000 65 | - pexpect=4.8.0=py36_0 66 | - pickleshare=0.7.5=py36_0 67 | - pip=20.2.2=py_0 68 | - poyo=0.5.0=py_0 69 | - prompt-toolkit=3.0.8=py_0 70 | - ptyprocess=0.6.0=py36_0 71 | - pycparser=2.20=pyh9f0ad1d_2 72 | - pygments=2.7.1=py_0 73 | - pyopenssl=19.0.0=py36_0 74 | - pysocks=1.7.1=py36h9f0ad1d_1 75 | - python=3.6.1=2 76 | - python-dateutil=2.8.1=py_0 77 | - python-slugify=4.0.1=pyh9f0ad1d_0 78 | - python_abi=3.6=1_cp36m 79 | - pytz=2020.1=pyh9f0ad1d_0 80 | - pyzmq=19.0.2=py36he6710b0_1 81 | - readline=6.2=0 82 | - requests=2.24.0=pyh9f0ad1d_0 83 | - setuptools=49.6.0=py36h9f0ad1d_0 84 | - six=1.15.0=pyh9f0ad1d_0 85 | - sqlite=3.13.0=1 86 | - tbb=2020.1=hc9558a2_0 87 | - text-unidecode=1.3=py_0 88 | - tk=8.5.18=0 89 | - tornado=6.0.4=py36h8c4c3a4_1 90 | - tqdm=4.48.2=pyh9f0ad1d_0 91 | - traitlets=4.3.3=py36_0 92 | - unidecode=1.1.1=py_0 93 | - urllib3=1.25.10=py_0 94 | - vmtk=1.4.0=py36hfe14cac_1 95 | - vtk=8.1.0=py36h969b564_201 96 | - wcwidth=0.2.5=py_0 97 | - wheel=0.34.2=py_1 98 | - whichcraft=0.6.1=py_0 99 | - xz=5.2.5=h516909a_1 100 | - zeromq=4.3.3=he6710b0_3 101 | - zlib=1.2.11=h516909a_1007 102 | - zstd=1.4.5=h6597ccf_2 103 | - pip: 104 | - gmsh==4.6.0 105 | - nibabel==3.2.1 106 | - numpy==1.19.4 107 | - packaging==20.7 108 | - pyparsing==2.4.7 109 | prefix: /home/endrit/anaconda3/envs/vmtk-env 110 | 111 | -------------------------------------------------------------------------------- /Fluent/autofluent_template.jou: -------------------------------------------------------------------------------- 1 | ; to run: fluent 3ddp -t 18 -g -cflush simulation_report.log 2 | 3 | ; ********************************************************* 4 | ; Variables 5 | ; ********************************************************* 6 | 7 | ; inlet (m/s) can also do flow rate m3/s 8 | (define velocityInlet 1.3) 9 | (define pressureOutlet 0) 10 | 11 | ; material properties 12 | (define viscosityBlood 0.004) 13 | (define densityBlood 1060) 14 | 15 | ; calculation settings 16 | (define itnNumber 250) 17 | (define convCriterion 0.001) 18 | 19 | ; file directories 20 | (define filedir "") 21 | (define cgnsdir "") 22 | (define csvdir "") 23 | 24 | ; ********************************************************* 25 | ; Loop 26 | ; ********************************************************* 27 | (for-each (lambda (i) 28 | 29 | ; load in mesh 30 | (ti-menu-load-string (format #f "file rc ~a~a.msh OK" filedir i)) 31 | 32 | ; improve quality 33 | (ti-menu-load-string (format #f "/mesh/repair-improve/improve-quality")) 34 | 35 | ; make mesh polyhedral 36 | (ti-menu-load-string (format #f "/mesh/polyhedra/convert-domain")) 37 | 38 | ; **********SCALE MESH TO METRES********** 39 | (ti-menu-load-string (format #f "mesh/scale 0.001 0.001 0.001")) 40 | 41 | 42 | ; create blood material 43 | (ti-menu-load-string (format #f "define/materials/change-create air blood y constant densityBlood n n y constant viscosityBlood n n n n")) 44 | 45 | ; set cell zone conditions to blood (interior, id=2) 46 | (ti-menu-load-string (format #f "define/boundary-conditions/fluid 2 y blood n n n n 0 n 0 n 0 n 0 n 0 n 1 n n n n")) 47 | 48 | ; assign inlet/outlet 49 | (ti-menu-load-string (format #f "define/boundary-conditions/zone-type 4 velocity-inlet")) 50 | (ti-menu-load-string (format #f "define/boundary-conditions/zone-type 5 pressure-outlet")) 51 | 52 | ; set BCs 53 | (ti-menu-load-string (format #f "define/boundary-conditions/velocity-inlet 4 n n y y n velocityInlet n 0")) 54 | (ti-menu-load-string (format #f "define/boundary-conditions/pressure-outlet 5 y n pressureOutlet n y y n n n")) 55 | 56 | ; set convergence criteria 57 | (ti-menu-load-string (format #f "solve/monitors/residual/convergence-criteria convCriterion convCriterion convCriterion convCriterion")) 58 | 59 | ; init 60 | (ti-menu-load-string (format #f "solve/initialize/hyb-initialization")) 61 | 62 | ; solve 63 | (ti-menu-load-string (format #f "solve/iterate ~a" itnNumber)) 64 | 65 | 66 | ; **********SCALE MESH BACK TO MM********** 67 | (ti-menu-load-string (format #f "mesh/scale 1000 1000 1000")) 68 | 69 | 70 | ; write ascii results file 71 | (ti-menu-load-string (format #f "file/export ascii ~a~a.csv default-interior , y cell-id x-coordinate y-coordinate z-coordinate pressure velocity-magnitude () n" csvdir i)) 72 | 73 | 74 | 75 | ) 76 | 77 | (list 78 | ) 79 | ) 80 | 81 | (exit) 82 | -------------------------------------------------------------------------------- /Fluent/cfd_prepare.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | from shutil import copyfile 3 | 4 | def prepare_cfd(idir, odir, jpath): 5 | ''' 6 | - copies journal template to jou_path 7 | - populates it with the mesh filenames in idir 8 | ''' 9 | if not os.path.exists(odir): 10 | os.makedirs(odir) 11 | 12 | template_dir = os.path.join(os.getcwd(), 'autofluent_template.jou') 13 | copyfile(template_dir, jpath + 'autofluent.jou') 14 | 15 | if not os.path.exists(odir + 'CGNS/'): 16 | os.makedirs(odir + 'CGNS/') 17 | if not os.path.exists(odir + 'Point_Cloud/'): 18 | os.makedirs(odir + 'Point_Cloud/') 19 | 20 | jou = open(jpath + 'autofluent.jou', 'r') 21 | lines = jou.readlines() 22 | jou.close() 23 | 24 | fnames = sorted(os.listdir(idir)) 25 | for i, fname in enumerate(fnames): 26 | fnames[i] = fname.replace('.msh','') 27 | # add filepaths and filenames 28 | for i in range(0, len(lines)): 29 | if 'define filedir' in lines[i]: 30 | lines[i] = '(define filedir ' + '"' + idir + '")\n' 31 | if 'define cgnsdir' in lines[i]: 32 | lines[i] = '(define cgnsdir ' + '"' + odir + 'CGNS/")\n' 33 | if 'define csvdir' in lines[i]: 34 | lines[i] = '(define csvdir ' + '"' + odir + 'Point_Cloud/")\n' 35 | if '(list' in lines[i]: 36 | for j, fname in enumerate(fnames): 37 | lines.insert(i+j+1, ' "' + fname + '"\n') 38 | break 39 | 40 | jou = open(jpath + '/autofluent.jou', 'w') 41 | jou.writelines(lines) 42 | jou.close() 43 | 44 | if __name__=="__main__": 45 | readline.set_completer_delims(" \t\n=") 46 | readline.parse_and_bind("tab: complete") 47 | idir = input("Enter Fluent meshes directory: ") 48 | odir = input("Enter the desired CFD results directory: ") 49 | jpath = input("Enter directory where journal file will be saved: ") 50 | prepare_cfd(idir, odir, jpath) -------------------------------------------------------------------------------- /Keras/.ipynb_checkpoints/cfd_dnn_testing-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "b2196f2e", 6 | "metadata": {}, 7 | "source": [ 8 | "# Testing ML models for predicting CFD\n" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "id": "22ad3281", 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import os, glob, re, time, random\n", 19 | "import copy as cp\n", 20 | "import numpy as np\n", 21 | "import statistics, scipy\n", 22 | "import statsmodels.api as sm\n", 23 | "import pandas as pd\n", 24 | "from sklearn.preprocessing import StandardScaler\n", 25 | "from sklearn.decomposition import PCA\n", 26 | "%matplotlib inline\n", 27 | "import matplotlib.pyplot as plt\n", 28 | "import matplotlib\n", 29 | "import matplotlib.patheffects as PathEffects\n", 30 | "matplotlib.rcParams['figure.dpi']= 200\n", 31 | "matplotlib.rcParams.update({'font.size': 5})" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "id": "fa2bbf07", 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "import tensorflow as tf\n", 42 | "from tensorflow import keras\n", 43 | "import keras.backend as K\n", 44 | "from sklearn.pipeline import Pipeline\n", 45 | "from sklearn.metrics import mean_absolute_error, median_absolute_error, mean_squared_error\n", 46 | "import joblib" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "id": "0b060521", 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "from __future__ import print_function" 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "id": "9c27607e", 62 | "metadata": {}, 63 | "source": [ 64 | "## Import Shape Modelling PCA Data " 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "id": "3096523d", 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "# path to .csv with shape mode csvs\n", 75 | "ssm_pca_path = \"\"" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "id": "98c10be9", 82 | "metadata": { 83 | "scrolled": true 84 | }, 85 | "outputs": [], 86 | "source": [ 87 | "ssm_file = open(ssm_pca_path, \"r\")\n", 88 | "ssm_df = pd.read_csv(ssm_file, header=None, index_col=False)\n", 89 | "ssm_pca_u = ssm_df.to_numpy()\n", 90 | "print(np.shape(ssm_pca_u))" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "id": "3f67092a", 96 | "metadata": {}, 97 | "source": [ 98 | "**keep only first X modes (99% cumvar)**" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "d163604c", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "ssm_pca_u = ssm_pca_u[:, :35]\n", 109 | "print(np.shape(ssm_pca_u))" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "id": "4096f1ae", 115 | "metadata": {}, 116 | "source": [ 117 | "## Import CFD Data " 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "id": "7a8fc7ff", 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "# human sorting function\n", 128 | "\n", 129 | "def tryint(s):\n", 130 | " try:\n", 131 | " return int(s)\n", 132 | " except:\n", 133 | " return s\n", 134 | "\n", 135 | "def alphanum_key(s):\n", 136 | " return [ tryint(c) for c in re.split('([0-9]+)', s) ]\n", 137 | "\n", 138 | "def sort_nicely(l):\n", 139 | " l.sort(key=alphanum_key)\n", 140 | " return l" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "id": "30ca91b6", 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "# path to folder with cfd point cloud csvs in point correspondence\n", 151 | "cfd_path = \"\"" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "id": "d9b75172", 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "fnames = sort_nicely(os.listdir(cfd_path))" 162 | ] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "id": "4d94ff5d", 167 | "metadata": {}, 168 | "source": [ 169 | "**import all csv flow fields (keep columns 1: pressure, 3: velocity)**" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "id": "ff4f896a", 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "# build array of csv files\n", 180 | "cfd_files = sort_nicely(os.listdir(cfd_path))\n", 181 | "cfd_data = []\n", 182 | "cfd_empty = [] # only x,y,z\n", 183 | "\n", 184 | "for fn in cfd_files:\n", 185 | " file = open(cfd_path + fn, \"r\")\n", 186 | " df = pd.read_csv(file, index_col=False)\n", 187 | " df.columns = df.columns.str.replace(' ', '')\n", 188 | " # build list of cfd or empty dataframes\n", 189 | " df_cfd = df.drop(df.columns[[2, 3, 4]], axis=1)\n", 190 | " df_empty = df.drop(df.columns[[0, 1]], axis=1)\n", 191 | " cfd_data.append(df_cfd.values)\n", 192 | " cfd_empty.append(df_empty.values)" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "id": "f7a2a980", 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [ 202 | "# cfd_data[subject][node][pressure/velocity]\n", 203 | "cfd_data = np.array(cfd_data)\n", 204 | "\n", 205 | "# p_data[subject][node_pressure]\n", 206 | "p_data = np.squeeze(cfd_data[:, :, :1])\n", 207 | "v_data = np.squeeze(cfd_data[:, :, 1:])" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "id": "64f25544", 214 | "metadata": {}, 215 | "outputs": [], 216 | "source": [ 217 | "# no. of subjects, no. of pressure nodes (features)\n", 218 | "np.shape(p_data)" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "id": "2c45b94c", 224 | "metadata": {}, 225 | "source": [ 226 | "### SPLIT DATASET " 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": null, 232 | "id": "73c1f8a5", 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "train_n = 2800\n", 237 | "test_n = 200" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "id": "89cf1fc2", 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "p_data_test = p_data[train_n:]\n", 248 | "v_data_test = v_data[train_n:]" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": null, 254 | "id": "9dcef537", 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "X_train = ssm_pca_u[:train_n]\n", 259 | "X_test = ssm_pca_u[train_n:]\n", 260 | "X_test.shape" 261 | ] 262 | }, 263 | { 264 | "cell_type": "markdown", 265 | "id": "03038cfb", 266 | "metadata": {}, 267 | "source": [ 268 | "# DNN PREDICTION " 269 | ] 270 | }, 271 | { 272 | "cell_type": "markdown", 273 | "id": "6cc8768c", 274 | "metadata": {}, 275 | "source": [ 276 | "**Import models**" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "id": "a4f74620", 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "run_attempt = 1" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "id": "84e370f4", 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "model_dir = os.getcwd() + \"/Run_\" + str(run_attempt) + \"/model/\"\n", 297 | "\n", 298 | "# load S and Vt matrices (needed for estimators)\n", 299 | "S_p_tensor = tf.convert_to_tensor(np.load(model_dir + 'S_p.npy'))\n", 300 | "S_v_tensor = tf.convert_to_tensor(np.load(model_dir + 'S_v.npy'))\n", 301 | "Vt_p_tensor = tf.convert_to_tensor(np.load(model_dir + 'Vt_p.npy'))\n", 302 | "Vt_v_tensor = tf.convert_to_tensor(np.load(model_dir + 'Vt_v.npy'))\n", 303 | "\n", 304 | "# load pipeline\n", 305 | "pipeline_loaded = joblib.load(model_dir + 'pipeline.pkl')\n", 306 | "scaler_p = pipeline_loaded[0]\n", 307 | "scaler_v = pipeline_loaded[1]\n", 308 | "\n", 309 | "# load estimators\n", 310 | "dnn_p = keras.models.load_model(model_dir + \"dnn_p.h5\")\n", 311 | "dnn_v = keras.models.load_model(model_dir + \"dnn_v.h5\")" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": null, 317 | "id": "76f7b1fb-4500-443d-a0e1-a1ea81bf652d", 318 | "metadata": {}, 319 | "outputs": [], 320 | "source": [ 321 | "# output save directory\n", 322 | "\n", 323 | "data_dir = model_dir.replace(\"model/\", \"predictions/\")\n", 324 | "if not os.path.exists(data_dir):\n", 325 | " os.makedirs(data_dir)\n", 326 | "\n", 327 | "print(data_dir)" 328 | ] 329 | }, 330 | { 331 | "cell_type": "markdown", 332 | "id": "4af8c13b", 333 | "metadata": {}, 334 | "source": [ 335 | "**Pressure** " 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "id": "3a74f97d", 342 | "metadata": {}, 343 | "outputs": [], 344 | "source": [ 345 | "# predict standardised data\n", 346 | "P_pred = dnn_p.predict(X_test)\n", 347 | "\n", 348 | "# reverse standardisation\n", 349 | "P_pred_inv_scaling = scaler_p.inverse_transform(P_pred)" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "id": "de3ca26a", 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "np.shape(P_pred)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "markdown", 364 | "id": "b8e02599", 365 | "metadata": {}, 366 | "source": [ 367 | "**Velocity**" 368 | ] 369 | }, 370 | { 371 | "cell_type": "code", 372 | "execution_count": null, 373 | "id": "1e00770c", 374 | "metadata": {}, 375 | "outputs": [], 376 | "source": [ 377 | "# predict standardised data\n", 378 | "V_pred = dnn_v.predict(X_test)\n", 379 | "\n", 380 | "# inverse standardisation \n", 381 | "V_pred_inv_scaling = scaler_v.inverse_transform(V_pred)\n", 382 | "# make all negatives = 0\n", 383 | "V_pred_inv_scaling_no_negatives = np.clip(V_pred_inv_scaling, a_min=0, a_max=None)" 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": null, 389 | "id": "c7affe2b", 390 | "metadata": {}, 391 | "outputs": [], 392 | "source": [ 393 | "np.shape(V_pred_inv_scaling)" 394 | ] 395 | }, 396 | { 397 | "cell_type": "markdown", 398 | "id": "f91844d7", 399 | "metadata": {}, 400 | "source": [ 401 | "**Stack together prediction results**" 402 | ] 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": null, 407 | "id": "5024aa0a", 408 | "metadata": {}, 409 | "outputs": [], 410 | "source": [ 411 | "pred_empty_csv = cfd_empty[train_n:]" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": null, 417 | "id": "09a40c8c", 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [ 421 | "# add predictions to csv\n", 422 | "pred_csv = np.dstack((pred_empty_csv, P_pred_inv_scaling))\n", 423 | "pred_csv = np.dstack((pred_csv, V_pred_inv_scaling_no_negatives))\n", 424 | "\n", 425 | "# calculate P and V errors and add them to csv\n", 426 | "errors_p, errors_v = [], []\n", 427 | "for i in range(len(pred_csv)):\n", 428 | " err_p = abs(np.subtract(pred_csv[i, :, 3], p_data[i+train_n, :]))\n", 429 | " err_v = abs(np.subtract(pred_csv[i, :, 4], v_data[i+train_n, :]))\n", 430 | " errors_p.append(err_p)\n", 431 | " errors_v.append(err_v)\n", 432 | " \n", 433 | "pred_csv = np.dstack((pred_csv, errors_p))\n", 434 | "pred_csv = np.dstack((pred_csv, errors_v))" 435 | ] 436 | }, 437 | { 438 | "cell_type": "code", 439 | "execution_count": null, 440 | "id": "cf32d070", 441 | "metadata": {}, 442 | "outputs": [], 443 | "source": [ 444 | "np.shape(pred_csv)" 445 | ] 446 | }, 447 | { 448 | "cell_type": "markdown", 449 | "id": "4aef50b2", 450 | "metadata": {}, 451 | "source": [ 452 | "## Inspecting Errors " 453 | ] 454 | }, 455 | { 456 | "cell_type": "code", 457 | "execution_count": null, 458 | "id": "defa0481", 459 | "metadata": {}, 460 | "outputs": [], 461 | "source": [ 462 | "test_filenames = fnames[train_n:]\n", 463 | "test_filenames = [s.replace(\"_ext.csv\", \"\") for s in test_filenames]" 464 | ] 465 | }, 466 | { 467 | "cell_type": "markdown", 468 | "id": "13506c69-1021-4c56-ae67-0af43092b049", 469 | "metadata": {}, 470 | "source": [ 471 | "**get matrix of subject errors (rows=subjects)**" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": null, 477 | "id": "8f3ffda8", 478 | "metadata": { 479 | "scrolled": true 480 | }, 481 | "outputs": [], 482 | "source": [ 483 | "pressure_pred_evaluation = pd.DataFrame(columns=['filename', 'range_true (Pa)', 'MAE (Pa)', 'NMAE (%)'])\n", 484 | "for i in range(p_data_test.shape[0]):\n", 485 | " MAE = mean_absolute_error(p_data_test[i], P_pred_inv_scaling[i])\n", 486 | " p_range = max(p_data_test[i]) - min(p_data_test[i])\n", 487 | " pressure_pred_evaluation.loc[i] = [test_filenames[i], p_range, MAE, MAE*100/p_range]\n", 488 | " \n", 489 | "velocity_pred_evaluation = pd.DataFrame(columns=['filename', 'range_true (m/s)', 'MAE (m/s)', 'NMAE (%)'])\n", 490 | "for i in range(v_data_test.shape[0]):\n", 491 | " MAE = mean_absolute_error(v_data_test[i], V_pred_inv_scaling_no_negatives[i])\n", 492 | " v_range = max(v_data_test[i]) - min(v_data_test[i])\n", 493 | " velocity_pred_evaluation.loc[i] = [test_filenames[i], v_range, MAE, MAE*100/v_range]" 494 | ] 495 | }, 496 | { 497 | "cell_type": "markdown", 498 | "id": "da793fe4", 499 | "metadata": {}, 500 | "source": [ 501 | "**MAE**" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": null, 507 | "id": "4901e2eb", 508 | "metadata": {}, 509 | "outputs": [], 510 | "source": [ 511 | "print(\"average MAE = \" + \"{:.2f}\".format(np.mean(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 512 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 513 | "print(\"\")\n", 514 | "print(\"average MAE = \" + \"{:.2f}\".format(np.mean(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")\n", 515 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")" 516 | ] 517 | }, 518 | { 519 | "cell_type": "code", 520 | "execution_count": null, 521 | "id": "c011bae8", 522 | "metadata": {}, 523 | "outputs": [], 524 | "source": [ 525 | "print(\"value of max MAE = \" + \"{:.2f}\".format(max(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 526 | "print(\"index of max MAE = \" + str(np.argmax(pressure_pred_evaluation['MAE (Pa)'])))\n", 527 | "print(\"value of min MAE = \" + \"{:.2f}\".format(min(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 528 | "print(\"index of min MAE = \" + str(np.argmin(pressure_pred_evaluation['MAE (Pa)'])))\n", 529 | "print(\"\")\n", 530 | "print(\"value of max MAE = \" + \"{:.2f}\".format(max(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")\n", 531 | "print(\"index of max MAE = \" + str(np.argmax(velocity_pred_evaluation['MAE (m/s)'])))\n", 532 | "print(\"value of min MAE = \" + \"{:.2f}\".format(min(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")\n", 533 | "print(\"index of min MAE = \" + str(np.argmin(velocity_pred_evaluation['MAE (m/s)'])))" 534 | ] 535 | }, 536 | { 537 | "cell_type": "markdown", 538 | "id": "1098bbd4", 539 | "metadata": {}, 540 | "source": [ 541 | "**NMAE**" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": null, 547 | "id": "0c985545", 548 | "metadata": {}, 549 | "outputs": [], 550 | "source": [ 551 | "print(\"average NMAE = \" + \"{:.2f}\".format(np.mean(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 552 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 553 | "print(\"\")\n", 554 | "print(\"average NMAE = \" + \"{:.2f}\".format(np.mean(velocity_pred_evaluation['NMAE (%)'])) + \" %\")\n", 555 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(velocity_pred_evaluation['NMAE (%)'])) + \" %\")" 556 | ] 557 | }, 558 | { 559 | "cell_type": "code", 560 | "execution_count": null, 561 | "id": "fd5ff201", 562 | "metadata": {}, 563 | "outputs": [], 564 | "source": [ 565 | "print(\"value of max NMAE = \" + \"{:.2f}\".format(max(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 566 | "print(\"index of max NMAE = \" + str(np.argmax(pressure_pred_evaluation['NMAE (%)'])))\n", 567 | "print(\"value of min NMAE = \" + \"{:.2f}\".format(min(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 568 | "print(\"index of min NMAE = \" + str(np.argmin(pressure_pred_evaluation['NMAE (%)'])))\n", 569 | "print(\"\")\n", 570 | "print(\"value of max NMAE = \" + \"{:.2f}\".format(max(velocity_pred_evaluation['NMAE (%)'])) + \" %\")\n", 571 | "print(\"index of max NMAE = \" + str(np.argmax(velocity_pred_evaluation['NMAE (%)'])))\n", 572 | "print(\"value of min NMAE = \" + \"{:.2f}\".format(min(velocity_pred_evaluation['NMAE (%)'])) + \" %\")\n", 573 | "print(\"index of min NMAE = \" + str(np.argmin(velocity_pred_evaluation['NMAE (%)'])))" 574 | ] 575 | }, 576 | { 577 | "cell_type": "markdown", 578 | "id": "38ff1291-a4bf-4808-8aa6-7fece287d0d1", 579 | "metadata": {}, 580 | "source": [ 581 | "## Box Plots " 582 | ] 583 | }, 584 | { 585 | "cell_type": "markdown", 586 | "id": "a553c3ed-6ae5-47dc-beea-737fecbfefbe", 587 | "metadata": {}, 588 | "source": [ 589 | "Subject-wise errors (SE)" 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "id": "c7640b80", 596 | "metadata": {}, 597 | "outputs": [], 598 | "source": [ 599 | "fig, ax = plt.subplots(1, 1, figsize=(3, 2))\n", 600 | "\n", 601 | "ax.boxplot([pressure_pred_evaluation['NMAE (%)'], \n", 602 | " velocity_pred_evaluation['NMAE (%)']], \n", 603 | " labels=[\"Pressure\", \"Velocity Magnitude\"],\n", 604 | " flierprops=dict(marker='.'),\n", 605 | " medianprops=dict(color='r'),\n", 606 | " showfliers=False)\n", 607 | "ax.set(title=\"Pressure and Velocity DNN errors (NMAE)\", ylabel = \"NMAE (%)\")\n", 608 | "\n", 609 | "fig.tight_layout()\n", 610 | "plt.show()" 611 | ] 612 | }, 613 | { 614 | "cell_type": "markdown", 615 | "id": "5e9111da-8094-4104-8314-4368b2156402", 616 | "metadata": {}, 617 | "source": [ 618 | "Node-wise errors (NE)" 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "execution_count": null, 624 | "id": "368108ae-4df1-4184-98cc-638bbc9504f8", 625 | "metadata": {}, 626 | "outputs": [], 627 | "source": [ 628 | "fig, ax = plt.subplots(1, 1, figsize=(2, 3))\n", 629 | "\n", 630 | "# compute range of pressure/velocity values per subject\n", 631 | "# use OVERALL ao range for each node\n", 632 | "ranges_p = np.ptp(p_data_test, axis=1)\n", 633 | "ranges_v = np.ptp(v_data_test, axis=1)\n", 634 | "\n", 635 | "p_data_flatten_errors = abs(p_data_test.flatten() - P_pred_inv_scaling.flatten())\n", 636 | "v_data_flatten_errors = abs(v_data_test.flatten() - V_pred_inv_scaling.flatten())\n", 637 | "\n", 638 | "p_data_flatten_errors = p_data_flatten_errors * 100 / np.repeat(ranges_p, p_data_test[0].shape[0])\n", 639 | "v_data_flatten_errors = v_data_flatten_errors * 100 / np.repeat(ranges_v, v_data_test[0].shape[0])\n", 640 | "\n", 641 | "p_data_flatten_errors = p_data_flatten_errors.reshape((p_data_test.shape[0], p_data_test.shape[1]))\n", 642 | "v_data_flatten_errors = v_data_flatten_errors.reshape((v_data_test.shape[0], v_data_test.shape[1]))\n", 643 | "\n", 644 | "p_data_flatten_errors = np.mean(p_data_flatten_errors, axis=0)\n", 645 | "v_data_flatten_errors = np.mean(v_data_flatten_errors, axis=0)\n", 646 | "\n", 647 | "ax.boxplot([p_data_flatten_errors, \n", 648 | " v_data_flatten_errors], \n", 649 | " labels=[\"Pressure\", \"Velocity Magnitude\"],\n", 650 | " showfliers=False,\n", 651 | " widths=0.3,\n", 652 | " flierprops=dict(marker='.'),\n", 653 | " medianprops=dict(color='r'))\n", 654 | "ax.set(title=\"Pressure and Velocity DNN errors (NMAE)\", ylabel = \"NMAE (%)\")\n", 655 | "\n", 656 | "print(np.median(p_data_flatten_errors))\n", 657 | "print(np.median(v_data_flatten_errors))\n", 658 | "print(np.percentile(p_data_flatten_errors, [25, 75])[1] - np.percentile(p_data_flatten_errors, [25, 75])[0])\n", 659 | "print(np.percentile(v_data_flatten_errors, [25, 75])[1] - np.percentile(v_data_flatten_errors, [25, 75])[0])\n", 660 | "\n", 661 | "fig.tight_layout()\n", 662 | "plt.show()" 663 | ] 664 | }, 665 | { 666 | "cell_type": "markdown", 667 | "id": "ac7d5923-c9a6-4d20-898f-565cee98bf97", 668 | "metadata": {}, 669 | "source": [ 670 | "Node-wise errors (NE) with no averaging" 671 | ] 672 | }, 673 | { 674 | "cell_type": "code", 675 | "execution_count": null, 676 | "id": "9971d88b-5fe8-458c-b370-22a87bbb3b2c", 677 | "metadata": {}, 678 | "outputs": [], 679 | "source": [ 680 | "# NO averaging, concat all subjects then do pred vs true errors and plot\n", 681 | "\n", 682 | "fig, ax = plt.subplots(1, 1, figsize=(3, 2))\n", 683 | "\n", 684 | "p_data_flatten_errors = abs(p_data_test.flatten() - P_pred_inv_scaling.flatten())\n", 685 | "v_data_flatten_errors = abs(v_data_test.flatten() - V_pred_inv_scaling.flatten())\n", 686 | "\n", 687 | "p_data_flatten_errors = p_data_flatten_errors * 100 / np.repeat(ranges_p, p_data_test[0].shape[0])\n", 688 | "v_data_flatten_errors = v_data_flatten_errors * 100 / np.repeat(ranges_v, v_data_test[0].shape[0])\n", 689 | "\n", 690 | "ax.boxplot([p_data_flatten_errors, \n", 691 | " v_data_flatten_errors], \n", 692 | " labels=[\"Pressure\", \"Velocity Magnitude\"],\n", 693 | " showfliers=False,\n", 694 | " flierprops=dict(marker='.'),\n", 695 | " medianprops=dict(color='r'))\n", 696 | "ax.set(title=\"Pressure and Velocity DNN errors (NMAE)\", ylabel = \"NMAE (%)\")\n", 697 | "\n", 698 | "fig.tight_layout()\n", 699 | "plt.show()" 700 | ] 701 | }, 702 | { 703 | "cell_type": "markdown", 704 | "id": "abc1e8bf", 705 | "metadata": {}, 706 | "source": [ 707 | "## Shape mode vs Subject Error " 708 | ] 709 | }, 710 | { 711 | "cell_type": "code", 712 | "execution_count": null, 713 | "id": "3d950b0c", 714 | "metadata": {}, 715 | "outputs": [], 716 | "source": [ 717 | "R_0vsP = scipy.stats.pearsonr(X_test[:, 0], pressure_pred_evaluation['NMAE (%)'])\n", 718 | "R_1vsP = scipy.stats.pearsonr(X_test[:, 1], pressure_pred_evaluation['NMAE (%)'])\n", 719 | "R_2vsP = scipy.stats.pearsonr(X_test[:, 2], pressure_pred_evaluation['NMAE (%)'])\n", 720 | "R_0vsV = scipy.stats.pearsonr(X_test[:, 0], velocity_pred_evaluation['NMAE (%)'])\n", 721 | "R_1vsV = scipy.stats.pearsonr(X_test[:, 1], velocity_pred_evaluation['NMAE (%)'])\n", 722 | "R_2vsV = scipy.stats.pearsonr(X_test[:, 2], velocity_pred_evaluation['NMAE (%)'])" 723 | ] 724 | }, 725 | { 726 | "cell_type": "code", 727 | "execution_count": null, 728 | "id": "0d0a16d2", 729 | "metadata": {}, 730 | "outputs": [], 731 | "source": [ 732 | "fig, ax = plt.subplots(2, 3, figsize=(4.5, 3))\n", 733 | "\n", 734 | "ax[0][0].scatter(X_test[:, 0]*8, pressure_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\", marker=\"o\")\n", 735 | "ax[0][0].set_ylabel(\"Pressure SE (%)\")\n", 736 | "ax[0][0].set_title(\"R = \"+\"{:.2f}\".format(R_0vsP[0])+\" p = \"+\"{:.2f}\".format(R_0vsP[1]), fontsize=6, pad=0.2, y=1.02)\n", 737 | "ax[0][0].set_xlim(left=-2, right=2)\n", 738 | "\n", 739 | "ax[0][1].scatter(X_test[:, 1]*8, pressure_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 740 | "ax[0][1].set_title(\"R = \"+\"{:.2f}\".format(R_1vsP[0])+\" p = \"+\"{:.2f}\".format(R_1vsP[1]), fontsize=6, pad=0.2, y=1.02)\n", 741 | "ax[0][1].set_xlim(left=-2, right=2)\n", 742 | "\n", 743 | "ax[0][2].scatter(X_test[:, 2]*8, pressure_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 744 | "ax[0][2].set_title(\"R = \"+\"{:.2f}\".format(R_2vsP[0])+\" p = \"+\"{:.2f}\".format(R_2vsP[1]), fontsize=6, pad=0.2, y=1.02)\n", 745 | "ax[0][2].set_xlim(left=-2, right=2)\n", 746 | "\n", 747 | "ax[1][0].scatter(X_test[:, 0]*8, velocity_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 748 | "ax[1][0].set(xlabel=\"Shape mode 1\"+\"\\n\"+\"Standard deviations\")\n", 749 | "ax[1][0].set_ylabel(\"Velocity SE (%)\")\n", 750 | "ax[1][0].set_title(\"R = \"+\"{:.2f}\".format(R_0vsV[0])+\" p = \"+\"{:.0e}\".format(R_0vsV[1]), fontsize=6, pad=0.2, y=1.02)\n", 751 | "ax[1][0].set_xlim(left=-2, right=2)\n", 752 | "\n", 753 | "ax[1][1].scatter(X_test[:, 1]*8, velocity_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 754 | "ax[1][1].set(xlabel=\"Shape mode 2\"+\"\\n\"+\"Standard deviations\")\n", 755 | "ax[1][1].set_title(\"R = \"+\"{:.2f}\".format(R_1vsP[0])+\" p = \"+\"{:.0e}\".format(R_1vsV[1]), fontsize=6, pad=0.2, y=1.02)\n", 756 | "ax[1][1].set_xlim(left=-2, right=2)\n", 757 | "\n", 758 | "ax[1][2].scatter(X_test[:, 2]*8, velocity_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 759 | "ax[1][2].set(xlabel=\"Shape mode 3\"+\"\\n\"+\"Standard deviations\")\n", 760 | "ax[1][2].set_title(\"R = \"+\"{:.2f}\".format(R_2vsV[0])+\" p = \"+\"{:.0e}\".format(R_2vsV[1]), fontsize=6, pad=0.2, y=1.02)\n", 761 | "ax[1][2].set_xlim(left=-2, right=2)\n", 762 | "\n", 763 | "fig.tight_layout()\n", 764 | "plt.show()" 765 | ] 766 | }, 767 | { 768 | "cell_type": "markdown", 769 | "id": "43bf9afd", 770 | "metadata": {}, 771 | "source": [ 772 | "## Saving Predictions " 773 | ] 774 | }, 775 | { 776 | "cell_type": "markdown", 777 | "id": "419fcd3e", 778 | "metadata": {}, 779 | "source": [ 780 | "**Save csv file of metrics**" 781 | ] 782 | }, 783 | { 784 | "cell_type": "code", 785 | "execution_count": null, 786 | "id": "3a111803", 787 | "metadata": {}, 788 | "outputs": [], 789 | "source": [ 790 | "pressure_pred_evaluation.to_csv(data_dir+\"evaluation_pressure.csv\", sep='\\t')\n", 791 | "velocity_pred_evaluation.to_csv(data_dir+\"evaluation_velocity.csv\", sep='\\t')" 792 | ] 793 | }, 794 | { 795 | "cell_type": "markdown", 796 | "id": "6ee98987", 797 | "metadata": {}, 798 | "source": [ 799 | "**Save predicted point clouds as csv**" 800 | ] 801 | }, 802 | { 803 | "cell_type": "code", 804 | "execution_count": null, 805 | "id": "e858af93", 806 | "metadata": {}, 807 | "outputs": [], 808 | "source": [ 809 | "for i in range(len(pred_csv)):\n", 810 | " pred_full_csv = pd.DataFrame(pred_csv[i])\n", 811 | " pred_full_csv.rename(columns={0: 'x', 1: 'y', 2: 'z', 3: 'Pressure_pred_(Pa)', 4: 'Velocity_pred_(m/s)', \n", 812 | " 5: 'Pressure_error_(Pa)', 6: 'Velocity_error_(m/s)'}, inplace=True)\n", 813 | " pred_full_csv.to_csv(data_dir + \"pred_\" + str(fnames[i+train_n]) + \".csv\", index=False)" 814 | ] 815 | }, 816 | { 817 | "cell_type": "markdown", 818 | "id": "d2710bef-0900-4e93-a04d-3ad6dec34651", 819 | "metadata": {}, 820 | "source": [ 821 | "**Average predictions and average errors, visualised on template**" 822 | ] 823 | }, 824 | { 825 | "cell_type": "code", 826 | "execution_count": null, 827 | "id": "7e991ec7-1005-4e7f-8884-8ba11dd17423", 828 | "metadata": {}, 829 | "outputs": [], 830 | "source": [ 831 | "vtu_template_path = \"template_vtu_points.csv\"" 832 | ] 833 | }, 834 | { 835 | "cell_type": "code", 836 | "execution_count": null, 837 | "id": "37a8800d-26d4-43b5-88ce-86820d0623cc", 838 | "metadata": {}, 839 | "outputs": [], 840 | "source": [ 841 | "vtu_template_csv = open(vtu_template_path, \"r\")\n", 842 | "df_template = pd.read_csv(vtu_template_csv, header=None, index_col=None)\n", 843 | "df_template = df_template.drop(df_template.columns[0], axis=1) \n", 844 | "df_template = df_template.drop([0], axis=0)\n", 845 | "template_np = np.array(df_template).astype(float)" 846 | ] 847 | }, 848 | { 849 | "cell_type": "code", 850 | "execution_count": null, 851 | "id": "9aacd9b2-98d0-45d3-9a64-ee7bb68c0c7e", 852 | "metadata": {}, 853 | "outputs": [], 854 | "source": [ 855 | "# save mean (check variable p_data_flatten_errors correspond to correct error)\n", 856 | "stacked = np.c_[template_np, p_data_flatten_errors]\n", 857 | "stacked = np.c_[stacked, v_data_flatten_errors]\n", 858 | "new_csv = pd.DataFrame(stacked)\n", 859 | "new_csv.rename(columns={0: 'x', 1: 'y', 2: 'z', 3: 'Node-averaged Pressure Errors (%)', 4: 'Node-averaged Velocity Errors (%)'}, inplace=True)\n", 860 | "\n", 861 | "new_csv.to_csv(data_dir + \"average_pred_errors.csv\", index=False)" 862 | ] 863 | } 864 | ], 865 | "metadata": { 866 | "kernelspec": { 867 | "display_name": "keras-env", 868 | "language": "python", 869 | "name": "keras-env" 870 | }, 871 | "language_info": { 872 | "codemirror_mode": { 873 | "name": "ipython", 874 | "version": 3 875 | }, 876 | "file_extension": ".py", 877 | "mimetype": "text/x-python", 878 | "name": "python", 879 | "nbconvert_exporter": "python", 880 | "pygments_lexer": "ipython3", 881 | "version": "3.9.2" 882 | } 883 | }, 884 | "nbformat": 4, 885 | "nbformat_minor": 5 886 | } 887 | -------------------------------------------------------------------------------- /Keras/cfd_dnn_testing.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "b2196f2e", 6 | "metadata": {}, 7 | "source": [ 8 | "# Testing ML models for predicting CFD\n" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "id": "22ad3281", 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import os, glob, re, time, random\n", 19 | "import copy as cp\n", 20 | "import numpy as np\n", 21 | "import statistics, scipy\n", 22 | "import statsmodels.api as sm\n", 23 | "import pandas as pd\n", 24 | "from sklearn.preprocessing import StandardScaler\n", 25 | "from sklearn.decomposition import PCA\n", 26 | "%matplotlib inline\n", 27 | "import matplotlib.pyplot as plt\n", 28 | "import matplotlib\n", 29 | "import matplotlib.patheffects as PathEffects\n", 30 | "matplotlib.rcParams['figure.dpi']= 200\n", 31 | "matplotlib.rcParams.update({'font.size': 5})" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "id": "fa2bbf07", 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "import tensorflow as tf\n", 42 | "from tensorflow import keras\n", 43 | "import keras.backend as K\n", 44 | "from sklearn.pipeline import Pipeline\n", 45 | "from sklearn.metrics import mean_absolute_error, median_absolute_error, mean_squared_error\n", 46 | "import joblib" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "id": "0b060521", 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "from __future__ import print_function" 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "id": "9c27607e", 62 | "metadata": {}, 63 | "source": [ 64 | "## Import Shape Modelling PCA Data " 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "id": "3096523d", 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "# path to .csv with shape mode csvs\n", 75 | "ssm_pca_path = \"\"" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "id": "98c10be9", 82 | "metadata": { 83 | "scrolled": true 84 | }, 85 | "outputs": [], 86 | "source": [ 87 | "ssm_file = open(ssm_pca_path, \"r\")\n", 88 | "ssm_df = pd.read_csv(ssm_file, header=None, index_col=False)\n", 89 | "ssm_pca_u = ssm_df.to_numpy()\n", 90 | "print(np.shape(ssm_pca_u))" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "id": "3f67092a", 96 | "metadata": {}, 97 | "source": [ 98 | "**keep only first X modes (99% cumvar)**" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "d163604c", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "ssm_pca_u = ssm_pca_u[:, :35]\n", 109 | "print(np.shape(ssm_pca_u))" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "id": "4096f1ae", 115 | "metadata": {}, 116 | "source": [ 117 | "## Import CFD Data " 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "id": "7a8fc7ff", 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "# human sorting function\n", 128 | "\n", 129 | "def tryint(s):\n", 130 | " try:\n", 131 | " return int(s)\n", 132 | " except:\n", 133 | " return s\n", 134 | "\n", 135 | "def alphanum_key(s):\n", 136 | " return [ tryint(c) for c in re.split('([0-9]+)', s) ]\n", 137 | "\n", 138 | "def sort_nicely(l):\n", 139 | " l.sort(key=alphanum_key)\n", 140 | " return l" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "id": "30ca91b6", 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "# path to folder with cfd point cloud csvs in point correspondence\n", 151 | "cfd_path = \"\"" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "id": "d9b75172", 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "fnames = sort_nicely(os.listdir(cfd_path))" 162 | ] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "id": "4d94ff5d", 167 | "metadata": {}, 168 | "source": [ 169 | "**import all csv flow fields (keep columns 1: pressure, 3: velocity)**" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "id": "ff4f896a", 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "# build array of csv files\n", 180 | "cfd_files = sort_nicely(os.listdir(cfd_path))\n", 181 | "cfd_data = []\n", 182 | "cfd_empty = [] # only x,y,z\n", 183 | "\n", 184 | "for fn in cfd_files:\n", 185 | " file = open(cfd_path + fn, \"r\")\n", 186 | " df = pd.read_csv(file, index_col=False)\n", 187 | " df.columns = df.columns.str.replace(' ', '')\n", 188 | " # build list of cfd or empty dataframes\n", 189 | " df_cfd = df.drop(df.columns[[2, 3, 4]], axis=1)\n", 190 | " df_empty = df.drop(df.columns[[0, 1]], axis=1)\n", 191 | " cfd_data.append(df_cfd.values)\n", 192 | " cfd_empty.append(df_empty.values)" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "id": "f7a2a980", 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [ 202 | "# cfd_data[subject][node][pressure/velocity]\n", 203 | "cfd_data = np.array(cfd_data)\n", 204 | "\n", 205 | "# p_data[subject][node_pressure]\n", 206 | "p_data = np.squeeze(cfd_data[:, :, :1])\n", 207 | "v_data = np.squeeze(cfd_data[:, :, 1:])" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "id": "64f25544", 214 | "metadata": {}, 215 | "outputs": [], 216 | "source": [ 217 | "# no. of subjects, no. of pressure nodes (features)\n", 218 | "np.shape(p_data)" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "id": "2c45b94c", 224 | "metadata": {}, 225 | "source": [ 226 | "### SPLIT DATASET " 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": null, 232 | "id": "73c1f8a5", 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "train_n = 2800\n", 237 | "test_n = 200" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "id": "89cf1fc2", 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "p_data_test = p_data[train_n:]\n", 248 | "v_data_test = v_data[train_n:]" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": null, 254 | "id": "9dcef537", 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "X_train = ssm_pca_u[:train_n]\n", 259 | "X_test = ssm_pca_u[train_n:]\n", 260 | "X_test.shape" 261 | ] 262 | }, 263 | { 264 | "cell_type": "markdown", 265 | "id": "03038cfb", 266 | "metadata": {}, 267 | "source": [ 268 | "# DNN PREDICTION " 269 | ] 270 | }, 271 | { 272 | "cell_type": "markdown", 273 | "id": "6cc8768c", 274 | "metadata": {}, 275 | "source": [ 276 | "**Import models**" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "id": "a4f74620", 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "run_attempt = 1" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "id": "84e370f4", 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "model_dir = os.getcwd() + \"/Run_\" + str(run_attempt) + \"/model/\"\n", 297 | "\n", 298 | "# load S and Vt matrices (needed for estimators)\n", 299 | "S_p_tensor = tf.convert_to_tensor(np.load(model_dir + 'S_p.npy'))\n", 300 | "S_v_tensor = tf.convert_to_tensor(np.load(model_dir + 'S_v.npy'))\n", 301 | "Vt_p_tensor = tf.convert_to_tensor(np.load(model_dir + 'Vt_p.npy'))\n", 302 | "Vt_v_tensor = tf.convert_to_tensor(np.load(model_dir + 'Vt_v.npy'))\n", 303 | "\n", 304 | "# load pipeline\n", 305 | "pipeline_loaded = joblib.load(model_dir + 'pipeline.pkl')\n", 306 | "scaler_p = pipeline_loaded[0]\n", 307 | "scaler_v = pipeline_loaded[1]\n", 308 | "\n", 309 | "# load estimators\n", 310 | "dnn_p = keras.models.load_model(model_dir + \"dnn_p.h5\")\n", 311 | "dnn_v = keras.models.load_model(model_dir + \"dnn_v.h5\")" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": null, 317 | "id": "76f7b1fb-4500-443d-a0e1-a1ea81bf652d", 318 | "metadata": {}, 319 | "outputs": [], 320 | "source": [ 321 | "# output save directory\n", 322 | "\n", 323 | "data_dir = model_dir.replace(\"model/\", \"predictions/\")\n", 324 | "if not os.path.exists(data_dir):\n", 325 | " os.makedirs(data_dir)\n", 326 | "\n", 327 | "print(data_dir)" 328 | ] 329 | }, 330 | { 331 | "cell_type": "markdown", 332 | "id": "4af8c13b", 333 | "metadata": {}, 334 | "source": [ 335 | "**Pressure** " 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "id": "3a74f97d", 342 | "metadata": {}, 343 | "outputs": [], 344 | "source": [ 345 | "# predict standardised data\n", 346 | "P_pred = dnn_p.predict(X_test)\n", 347 | "\n", 348 | "# reverse standardisation\n", 349 | "P_pred_inv_scaling = scaler_p.inverse_transform(P_pred)" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "id": "de3ca26a", 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "np.shape(P_pred)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "markdown", 364 | "id": "b8e02599", 365 | "metadata": {}, 366 | "source": [ 367 | "**Velocity**" 368 | ] 369 | }, 370 | { 371 | "cell_type": "code", 372 | "execution_count": null, 373 | "id": "1e00770c", 374 | "metadata": {}, 375 | "outputs": [], 376 | "source": [ 377 | "# predict standardised data\n", 378 | "V_pred = dnn_v.predict(X_test)\n", 379 | "\n", 380 | "# inverse standardisation \n", 381 | "V_pred_inv_scaling = scaler_v.inverse_transform(V_pred)\n", 382 | "# make all negatives = 0\n", 383 | "V_pred_inv_scaling_no_negatives = np.clip(V_pred_inv_scaling, a_min=0, a_max=None)" 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": null, 389 | "id": "c7affe2b", 390 | "metadata": {}, 391 | "outputs": [], 392 | "source": [ 393 | "np.shape(V_pred_inv_scaling)" 394 | ] 395 | }, 396 | { 397 | "cell_type": "markdown", 398 | "id": "f91844d7", 399 | "metadata": {}, 400 | "source": [ 401 | "**Stack together prediction results**" 402 | ] 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": null, 407 | "id": "5024aa0a", 408 | "metadata": {}, 409 | "outputs": [], 410 | "source": [ 411 | "pred_empty_csv = cfd_empty[train_n:]" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": null, 417 | "id": "09a40c8c", 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [ 421 | "# add predictions to csv\n", 422 | "pred_csv = np.dstack((pred_empty_csv, P_pred_inv_scaling))\n", 423 | "pred_csv = np.dstack((pred_csv, V_pred_inv_scaling_no_negatives))\n", 424 | "\n", 425 | "# calculate P and V errors and add them to csv\n", 426 | "errors_p, errors_v = [], []\n", 427 | "for i in range(len(pred_csv)):\n", 428 | " err_p = abs(np.subtract(pred_csv[i, :, 3], p_data[i+train_n, :]))\n", 429 | " err_v = abs(np.subtract(pred_csv[i, :, 4], v_data[i+train_n, :]))\n", 430 | " errors_p.append(err_p)\n", 431 | " errors_v.append(err_v)\n", 432 | " \n", 433 | "pred_csv = np.dstack((pred_csv, errors_p))\n", 434 | "pred_csv = np.dstack((pred_csv, errors_v))" 435 | ] 436 | }, 437 | { 438 | "cell_type": "code", 439 | "execution_count": null, 440 | "id": "cf32d070", 441 | "metadata": {}, 442 | "outputs": [], 443 | "source": [ 444 | "np.shape(pred_csv)" 445 | ] 446 | }, 447 | { 448 | "cell_type": "markdown", 449 | "id": "4aef50b2", 450 | "metadata": {}, 451 | "source": [ 452 | "## Inspecting Errors " 453 | ] 454 | }, 455 | { 456 | "cell_type": "code", 457 | "execution_count": null, 458 | "id": "defa0481", 459 | "metadata": {}, 460 | "outputs": [], 461 | "source": [ 462 | "test_filenames = fnames[train_n:]\n", 463 | "test_filenames = [s.replace(\"_ext.csv\", \"\") for s in test_filenames]" 464 | ] 465 | }, 466 | { 467 | "cell_type": "markdown", 468 | "id": "13506c69-1021-4c56-ae67-0af43092b049", 469 | "metadata": {}, 470 | "source": [ 471 | "**get matrix of subject errors (rows=subjects)**" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": null, 477 | "id": "8f3ffda8", 478 | "metadata": { 479 | "scrolled": true 480 | }, 481 | "outputs": [], 482 | "source": [ 483 | "pressure_pred_evaluation = pd.DataFrame(columns=['filename', 'range_true (Pa)', 'MAE (Pa)', 'NMAE (%)'])\n", 484 | "for i in range(p_data_test.shape[0]):\n", 485 | " MAE = mean_absolute_error(p_data_test[i], P_pred_inv_scaling[i])\n", 486 | " p_range = max(p_data_test[i]) - min(p_data_test[i])\n", 487 | " pressure_pred_evaluation.loc[i] = [test_filenames[i], p_range, MAE, MAE*100/p_range]\n", 488 | " \n", 489 | "velocity_pred_evaluation = pd.DataFrame(columns=['filename', 'range_true (m/s)', 'MAE (m/s)', 'NMAE (%)'])\n", 490 | "for i in range(v_data_test.shape[0]):\n", 491 | " MAE = mean_absolute_error(v_data_test[i], V_pred_inv_scaling_no_negatives[i])\n", 492 | " v_range = max(v_data_test[i]) - min(v_data_test[i])\n", 493 | " velocity_pred_evaluation.loc[i] = [test_filenames[i], v_range, MAE, MAE*100/v_range]" 494 | ] 495 | }, 496 | { 497 | "cell_type": "markdown", 498 | "id": "da793fe4", 499 | "metadata": {}, 500 | "source": [ 501 | "**MAE**" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": null, 507 | "id": "4901e2eb", 508 | "metadata": {}, 509 | "outputs": [], 510 | "source": [ 511 | "print(\"average MAE = \" + \"{:.2f}\".format(np.mean(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 512 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 513 | "print(\"\")\n", 514 | "print(\"average MAE = \" + \"{:.2f}\".format(np.mean(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")\n", 515 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")" 516 | ] 517 | }, 518 | { 519 | "cell_type": "code", 520 | "execution_count": null, 521 | "id": "c011bae8", 522 | "metadata": {}, 523 | "outputs": [], 524 | "source": [ 525 | "print(\"value of max MAE = \" + \"{:.2f}\".format(max(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 526 | "print(\"index of max MAE = \" + str(np.argmax(pressure_pred_evaluation['MAE (Pa)'])))\n", 527 | "print(\"value of min MAE = \" + \"{:.2f}\".format(min(pressure_pred_evaluation['MAE (Pa)'])) + \" Pa\")\n", 528 | "print(\"index of min MAE = \" + str(np.argmin(pressure_pred_evaluation['MAE (Pa)'])))\n", 529 | "print(\"\")\n", 530 | "print(\"value of max MAE = \" + \"{:.2f}\".format(max(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")\n", 531 | "print(\"index of max MAE = \" + str(np.argmax(velocity_pred_evaluation['MAE (m/s)'])))\n", 532 | "print(\"value of min MAE = \" + \"{:.2f}\".format(min(velocity_pred_evaluation['MAE (m/s)'])) + \" m/s\")\n", 533 | "print(\"index of min MAE = \" + str(np.argmin(velocity_pred_evaluation['MAE (m/s)'])))" 534 | ] 535 | }, 536 | { 537 | "cell_type": "markdown", 538 | "id": "1098bbd4", 539 | "metadata": {}, 540 | "source": [ 541 | "**NMAE**" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": null, 547 | "id": "0c985545", 548 | "metadata": {}, 549 | "outputs": [], 550 | "source": [ 551 | "print(\"average NMAE = \" + \"{:.2f}\".format(np.mean(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 552 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 553 | "print(\"\")\n", 554 | "print(\"average NMAE = \" + \"{:.2f}\".format(np.mean(velocity_pred_evaluation['NMAE (%)'])) + \" %\")\n", 555 | "print(\"StDev = \" + \"{:.2f}\".format(statistics.stdev(velocity_pred_evaluation['NMAE (%)'])) + \" %\")" 556 | ] 557 | }, 558 | { 559 | "cell_type": "code", 560 | "execution_count": null, 561 | "id": "fd5ff201", 562 | "metadata": {}, 563 | "outputs": [], 564 | "source": [ 565 | "print(\"value of max NMAE = \" + \"{:.2f}\".format(max(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 566 | "print(\"index of max NMAE = \" + str(np.argmax(pressure_pred_evaluation['NMAE (%)'])))\n", 567 | "print(\"value of min NMAE = \" + \"{:.2f}\".format(min(pressure_pred_evaluation['NMAE (%)'])) + \" %\")\n", 568 | "print(\"index of min NMAE = \" + str(np.argmin(pressure_pred_evaluation['NMAE (%)'])))\n", 569 | "print(\"\")\n", 570 | "print(\"value of max NMAE = \" + \"{:.2f}\".format(max(velocity_pred_evaluation['NMAE (%)'])) + \" %\")\n", 571 | "print(\"index of max NMAE = \" + str(np.argmax(velocity_pred_evaluation['NMAE (%)'])))\n", 572 | "print(\"value of min NMAE = \" + \"{:.2f}\".format(min(velocity_pred_evaluation['NMAE (%)'])) + \" %\")\n", 573 | "print(\"index of min NMAE = \" + str(np.argmin(velocity_pred_evaluation['NMAE (%)'])))" 574 | ] 575 | }, 576 | { 577 | "cell_type": "markdown", 578 | "id": "38ff1291-a4bf-4808-8aa6-7fece287d0d1", 579 | "metadata": {}, 580 | "source": [ 581 | "## Box Plots " 582 | ] 583 | }, 584 | { 585 | "cell_type": "markdown", 586 | "id": "a553c3ed-6ae5-47dc-beea-737fecbfefbe", 587 | "metadata": {}, 588 | "source": [ 589 | "Subject-wise errors (SE)" 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "id": "c7640b80", 596 | "metadata": {}, 597 | "outputs": [], 598 | "source": [ 599 | "fig, ax = plt.subplots(1, 1, figsize=(3, 2))\n", 600 | "\n", 601 | "ax.boxplot([pressure_pred_evaluation['NMAE (%)'], \n", 602 | " velocity_pred_evaluation['NMAE (%)']], \n", 603 | " labels=[\"Pressure\", \"Velocity Magnitude\"],\n", 604 | " flierprops=dict(marker='.'),\n", 605 | " medianprops=dict(color='r'),\n", 606 | " showfliers=False)\n", 607 | "ax.set(title=\"Pressure and Velocity DNN errors (NMAE)\", ylabel = \"NMAE (%)\")\n", 608 | "\n", 609 | "fig.tight_layout()\n", 610 | "plt.show()" 611 | ] 612 | }, 613 | { 614 | "cell_type": "markdown", 615 | "id": "5e9111da-8094-4104-8314-4368b2156402", 616 | "metadata": {}, 617 | "source": [ 618 | "Node-wise errors (NE)" 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "execution_count": null, 624 | "id": "368108ae-4df1-4184-98cc-638bbc9504f8", 625 | "metadata": {}, 626 | "outputs": [], 627 | "source": [ 628 | "fig, ax = plt.subplots(1, 1, figsize=(2, 3))\n", 629 | "\n", 630 | "# compute range of pressure/velocity values per subject\n", 631 | "# use OVERALL ao range for each node\n", 632 | "ranges_p = np.ptp(p_data_test, axis=1)\n", 633 | "ranges_v = np.ptp(v_data_test, axis=1)\n", 634 | "\n", 635 | "p_data_flatten_errors = abs(p_data_test.flatten() - P_pred_inv_scaling.flatten())\n", 636 | "v_data_flatten_errors = abs(v_data_test.flatten() - V_pred_inv_scaling.flatten())\n", 637 | "\n", 638 | "p_data_flatten_errors = p_data_flatten_errors * 100 / np.repeat(ranges_p, p_data_test[0].shape[0])\n", 639 | "v_data_flatten_errors = v_data_flatten_errors * 100 / np.repeat(ranges_v, v_data_test[0].shape[0])\n", 640 | "\n", 641 | "p_data_flatten_errors = p_data_flatten_errors.reshape((p_data_test.shape[0], p_data_test.shape[1]))\n", 642 | "v_data_flatten_errors = v_data_flatten_errors.reshape((v_data_test.shape[0], v_data_test.shape[1]))\n", 643 | "\n", 644 | "p_data_flatten_errors = np.mean(p_data_flatten_errors, axis=0)\n", 645 | "v_data_flatten_errors = np.mean(v_data_flatten_errors, axis=0)\n", 646 | "\n", 647 | "ax.boxplot([p_data_flatten_errors, \n", 648 | " v_data_flatten_errors], \n", 649 | " labels=[\"Pressure\", \"Velocity Magnitude\"],\n", 650 | " showfliers=False,\n", 651 | " widths=0.3,\n", 652 | " flierprops=dict(marker='.'),\n", 653 | " medianprops=dict(color='r'))\n", 654 | "ax.set(title=\"Pressure and Velocity DNN errors (NMAE)\", ylabel = \"NMAE (%)\")\n", 655 | "\n", 656 | "print(np.median(p_data_flatten_errors))\n", 657 | "print(np.median(v_data_flatten_errors))\n", 658 | "print(np.percentile(p_data_flatten_errors, [25, 75])[1] - np.percentile(p_data_flatten_errors, [25, 75])[0])\n", 659 | "print(np.percentile(v_data_flatten_errors, [25, 75])[1] - np.percentile(v_data_flatten_errors, [25, 75])[0])\n", 660 | "\n", 661 | "fig.tight_layout()\n", 662 | "plt.show()" 663 | ] 664 | }, 665 | { 666 | "cell_type": "markdown", 667 | "id": "ac7d5923-c9a6-4d20-898f-565cee98bf97", 668 | "metadata": {}, 669 | "source": [ 670 | "Node-wise errors (NE) with no averaging" 671 | ] 672 | }, 673 | { 674 | "cell_type": "code", 675 | "execution_count": null, 676 | "id": "9971d88b-5fe8-458c-b370-22a87bbb3b2c", 677 | "metadata": {}, 678 | "outputs": [], 679 | "source": [ 680 | "# NO averaging, concat all subjects then do pred vs true errors and plot\n", 681 | "\n", 682 | "fig, ax = plt.subplots(1, 1, figsize=(3, 2))\n", 683 | "\n", 684 | "p_data_flatten_errors = abs(p_data_test.flatten() - P_pred_inv_scaling.flatten())\n", 685 | "v_data_flatten_errors = abs(v_data_test.flatten() - V_pred_inv_scaling.flatten())\n", 686 | "\n", 687 | "p_data_flatten_errors = p_data_flatten_errors * 100 / np.repeat(ranges_p, p_data_test[0].shape[0])\n", 688 | "v_data_flatten_errors = v_data_flatten_errors * 100 / np.repeat(ranges_v, v_data_test[0].shape[0])\n", 689 | "\n", 690 | "ax.boxplot([p_data_flatten_errors, \n", 691 | " v_data_flatten_errors], \n", 692 | " labels=[\"Pressure\", \"Velocity Magnitude\"],\n", 693 | " showfliers=False,\n", 694 | " flierprops=dict(marker='.'),\n", 695 | " medianprops=dict(color='r'))\n", 696 | "ax.set(title=\"Pressure and Velocity DNN errors (NMAE)\", ylabel = \"NMAE (%)\")\n", 697 | "\n", 698 | "fig.tight_layout()\n", 699 | "plt.show()" 700 | ] 701 | }, 702 | { 703 | "cell_type": "markdown", 704 | "id": "abc1e8bf", 705 | "metadata": {}, 706 | "source": [ 707 | "## Shape mode vs Subject Error " 708 | ] 709 | }, 710 | { 711 | "cell_type": "code", 712 | "execution_count": null, 713 | "id": "3d950b0c", 714 | "metadata": {}, 715 | "outputs": [], 716 | "source": [ 717 | "R_0vsP = scipy.stats.pearsonr(X_test[:, 0], pressure_pred_evaluation['NMAE (%)'])\n", 718 | "R_1vsP = scipy.stats.pearsonr(X_test[:, 1], pressure_pred_evaluation['NMAE (%)'])\n", 719 | "R_2vsP = scipy.stats.pearsonr(X_test[:, 2], pressure_pred_evaluation['NMAE (%)'])\n", 720 | "R_0vsV = scipy.stats.pearsonr(X_test[:, 0], velocity_pred_evaluation['NMAE (%)'])\n", 721 | "R_1vsV = scipy.stats.pearsonr(X_test[:, 1], velocity_pred_evaluation['NMAE (%)'])\n", 722 | "R_2vsV = scipy.stats.pearsonr(X_test[:, 2], velocity_pred_evaluation['NMAE (%)'])" 723 | ] 724 | }, 725 | { 726 | "cell_type": "code", 727 | "execution_count": null, 728 | "id": "0d0a16d2", 729 | "metadata": {}, 730 | "outputs": [], 731 | "source": [ 732 | "fig, ax = plt.subplots(2, 3, figsize=(4.5, 3))\n", 733 | "\n", 734 | "ax[0][0].scatter(X_test[:, 0]*8, pressure_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\", marker=\"o\")\n", 735 | "ax[0][0].set_ylabel(\"Pressure SE (%)\")\n", 736 | "ax[0][0].set_title(\"R = \"+\"{:.2f}\".format(R_0vsP[0])+\" p = \"+\"{:.2f}\".format(R_0vsP[1]), fontsize=6, pad=0.2, y=1.02)\n", 737 | "ax[0][0].set_xlim(left=-2, right=2)\n", 738 | "\n", 739 | "ax[0][1].scatter(X_test[:, 1]*8, pressure_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 740 | "ax[0][1].set_title(\"R = \"+\"{:.2f}\".format(R_1vsP[0])+\" p = \"+\"{:.2f}\".format(R_1vsP[1]), fontsize=6, pad=0.2, y=1.02)\n", 741 | "ax[0][1].set_xlim(left=-2, right=2)\n", 742 | "\n", 743 | "ax[0][2].scatter(X_test[:, 2]*8, pressure_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 744 | "ax[0][2].set_title(\"R = \"+\"{:.2f}\".format(R_2vsP[0])+\" p = \"+\"{:.2f}\".format(R_2vsP[1]), fontsize=6, pad=0.2, y=1.02)\n", 745 | "ax[0][2].set_xlim(left=-2, right=2)\n", 746 | "\n", 747 | "ax[1][0].scatter(X_test[:, 0]*8, velocity_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 748 | "ax[1][0].set(xlabel=\"Shape mode 1\"+\"\\n\"+\"Standard deviations\")\n", 749 | "ax[1][0].set_ylabel(\"Velocity SE (%)\")\n", 750 | "ax[1][0].set_title(\"R = \"+\"{:.2f}\".format(R_0vsV[0])+\" p = \"+\"{:.0e}\".format(R_0vsV[1]), fontsize=6, pad=0.2, y=1.02)\n", 751 | "ax[1][0].set_xlim(left=-2, right=2)\n", 752 | "\n", 753 | "ax[1][1].scatter(X_test[:, 1]*8, velocity_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 754 | "ax[1][1].set(xlabel=\"Shape mode 2\"+\"\\n\"+\"Standard deviations\")\n", 755 | "ax[1][1].set_title(\"R = \"+\"{:.2f}\".format(R_1vsP[0])+\" p = \"+\"{:.0e}\".format(R_1vsV[1]), fontsize=6, pad=0.2, y=1.02)\n", 756 | "ax[1][1].set_xlim(left=-2, right=2)\n", 757 | "\n", 758 | "ax[1][2].scatter(X_test[:, 2]*8, velocity_pred_evaluation['NMAE (%)'], s=0.1, c=\"k\")\n", 759 | "ax[1][2].set(xlabel=\"Shape mode 3\"+\"\\n\"+\"Standard deviations\")\n", 760 | "ax[1][2].set_title(\"R = \"+\"{:.2f}\".format(R_2vsV[0])+\" p = \"+\"{:.0e}\".format(R_2vsV[1]), fontsize=6, pad=0.2, y=1.02)\n", 761 | "ax[1][2].set_xlim(left=-2, right=2)\n", 762 | "\n", 763 | "fig.tight_layout()\n", 764 | "plt.show()" 765 | ] 766 | }, 767 | { 768 | "cell_type": "markdown", 769 | "id": "43bf9afd", 770 | "metadata": {}, 771 | "source": [ 772 | "## Saving Predictions " 773 | ] 774 | }, 775 | { 776 | "cell_type": "markdown", 777 | "id": "419fcd3e", 778 | "metadata": {}, 779 | "source": [ 780 | "**Save csv file of metrics**" 781 | ] 782 | }, 783 | { 784 | "cell_type": "code", 785 | "execution_count": null, 786 | "id": "3a111803", 787 | "metadata": {}, 788 | "outputs": [], 789 | "source": [ 790 | "pressure_pred_evaluation.to_csv(data_dir+\"evaluation_pressure.csv\", sep='\\t')\n", 791 | "velocity_pred_evaluation.to_csv(data_dir+\"evaluation_velocity.csv\", sep='\\t')" 792 | ] 793 | }, 794 | { 795 | "cell_type": "markdown", 796 | "id": "6ee98987", 797 | "metadata": {}, 798 | "source": [ 799 | "**Save predicted point clouds as csv**" 800 | ] 801 | }, 802 | { 803 | "cell_type": "code", 804 | "execution_count": null, 805 | "id": "e858af93", 806 | "metadata": {}, 807 | "outputs": [], 808 | "source": [ 809 | "for i in range(len(pred_csv)):\n", 810 | " pred_full_csv = pd.DataFrame(pred_csv[i])\n", 811 | " pred_full_csv.rename(columns={0: 'x', 1: 'y', 2: 'z', 3: 'Pressure_pred_(Pa)', 4: 'Velocity_pred_(m/s)', \n", 812 | " 5: 'Pressure_error_(Pa)', 6: 'Velocity_error_(m/s)'}, inplace=True)\n", 813 | " pred_full_csv.to_csv(data_dir + \"pred_\" + str(fnames[i+train_n]) + \".csv\", index=False)" 814 | ] 815 | }, 816 | { 817 | "cell_type": "markdown", 818 | "id": "d2710bef-0900-4e93-a04d-3ad6dec34651", 819 | "metadata": {}, 820 | "source": [ 821 | "**Average predictions and average errors, visualised on template**" 822 | ] 823 | }, 824 | { 825 | "cell_type": "code", 826 | "execution_count": null, 827 | "id": "7e991ec7-1005-4e7f-8884-8ba11dd17423", 828 | "metadata": {}, 829 | "outputs": [], 830 | "source": [ 831 | "vtu_template_path = \"template_vtu_points.csv\"" 832 | ] 833 | }, 834 | { 835 | "cell_type": "code", 836 | "execution_count": null, 837 | "id": "37a8800d-26d4-43b5-88ce-86820d0623cc", 838 | "metadata": {}, 839 | "outputs": [], 840 | "source": [ 841 | "vtu_template_csv = open(vtu_template_path, \"r\")\n", 842 | "df_template = pd.read_csv(vtu_template_csv, header=None, index_col=None)\n", 843 | "df_template = df_template.drop(df_template.columns[0], axis=1) \n", 844 | "df_template = df_template.drop([0], axis=0)\n", 845 | "template_np = np.array(df_template).astype(float)" 846 | ] 847 | }, 848 | { 849 | "cell_type": "code", 850 | "execution_count": null, 851 | "id": "9aacd9b2-98d0-45d3-9a64-ee7bb68c0c7e", 852 | "metadata": {}, 853 | "outputs": [], 854 | "source": [ 855 | "# save mean (check variable p_data_flatten_errors correspond to correct error)\n", 856 | "stacked = np.c_[template_np, p_data_flatten_errors]\n", 857 | "stacked = np.c_[stacked, v_data_flatten_errors]\n", 858 | "new_csv = pd.DataFrame(stacked)\n", 859 | "new_csv.rename(columns={0: 'x', 1: 'y', 2: 'z', 3: 'Node-averaged Pressure Errors (%)', 4: 'Node-averaged Velocity Errors (%)'}, inplace=True)\n", 860 | "\n", 861 | "new_csv.to_csv(data_dir + \"average_pred_errors.csv\", index=False)" 862 | ] 863 | } 864 | ], 865 | "metadata": { 866 | "kernelspec": { 867 | "display_name": "keras-env", 868 | "language": "python", 869 | "name": "keras-env" 870 | }, 871 | "language_info": { 872 | "codemirror_mode": { 873 | "name": "ipython", 874 | "version": 3 875 | }, 876 | "file_extension": ".py", 877 | "mimetype": "text/x-python", 878 | "name": "python", 879 | "nbconvert_exporter": "python", 880 | "pygments_lexer": "ipython3", 881 | "version": "3.9.2" 882 | } 883 | }, 884 | "nbformat": 4, 885 | "nbformat_minor": 5 886 | } 887 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Paraview/pview_resample_cfd2vtu.py: -------------------------------------------------------------------------------- 1 | from genericpath import isdir 2 | from paraview.simple import * 3 | # note install pv 5.8+ .tar.gz for import vtk to work: 4 | from paraview import numpy_support as ns 5 | from paraview import servermanager as sm 6 | import os, sys, vtk 7 | import numpy as np 8 | import re 9 | 10 | ''' 11 | sorting function 12 | ''' 13 | def tryint(s): 14 | try: 15 | return int(s) 16 | except: 17 | return s 18 | 19 | def alphanum_key(s): 20 | """ Turn a string into a list of string and number chunks. 21 | "z23a" -> ["z", 23, "a"] 22 | """ 23 | return [ tryint(c) for c in re.split('([0-9]+)', s) ] 24 | 25 | def sort_nicely(l): 26 | """ Sort the given list in the way that humans expect. 27 | """ 28 | l.sort(key=alphanum_key) 29 | return l 30 | 31 | def resample_cfd2vtu(idir, vdir, odir): 32 | ''' 33 | - For each case in directory: 34 | - load cfd .csv and deformed .vtu 35 | - resample dataset (source is .csv), target is vtu 36 | - save out file as csv (ideally) 37 | ''' 38 | if not os.path.exists(odir): 39 | os.makedirs(odir) 40 | 41 | idir_sort = sort_nicely(os.listdir(idir)) 42 | vdir_sort = sort_nicely(os.listdir(vdir)) 43 | 44 | for fname, vname in zip(idir_sort, vdir_sort): 45 | name = os.path.splitext(fname)[0] 46 | 47 | 48 | # read .csv 49 | print("Loading " + fname) 50 | cfd_csv = CSVReader(registrationName='cfd_csv', FileName = idir + '/' + fname) 51 | UpdatePipeline(time=0.0, proxy=cfd_csv) 52 | 53 | # read target mesh .vtu 54 | print("Loading " + vname) 55 | vtu = XMLUnstructuredGridReader(registrationName='vtu', FileName = [vdir + '/' + vname]) 56 | UpdatePipeline(time=0.0, proxy=vtu) 57 | 58 | # csv to point cloud 59 | tableToPoints = TableToPoints(registrationName='tableToPoints', Input=cfd_csv) 60 | tableToPoints.XColumn = ' x-coordinate' 61 | tableToPoints.YColumn = ' y-coordinate' 62 | tableToPoints.ZColumn = ' z-coordinate' 63 | UpdatePipeline(time=0.0, proxy=tableToPoints) 64 | 65 | pointVolumeInterpolator = PointVolumeInterpolator(registrationName='PointVolumeInterpolator', Input=tableToPoints, Source='Bounded Volume') 66 | pointVolumeInterpolator.Kernel = 'VoronoiKernel' 67 | pointVolumeInterpolator.Locator = 'Static Point Locator' 68 | pointVolumeInterpolator.Source.Padding = 5 69 | UpdatePipeline(time=0.0, proxy=pointVolumeInterpolator) 70 | 71 | # resample filter 72 | resampleWithDataset = ResampleWithDataset(registrationName='resampleWithDataset', 73 | SourceDataArrays=pointVolumeInterpolator, 74 | DestinationMesh=vtu) 75 | UpdatePipeline(time=0.0, proxy=resampleWithDataset) 76 | 77 | # clear and save 78 | print("writing interpolated cfd data: " + name) 79 | print("") 80 | SaveData(odir + '/' + name + ".csv", proxy=resampleWithDataset, PointDataArrays=[' pressure', 'velocity-magnitude'], Precision=8) 81 | 82 | 83 | Delete(resampleWithDataset) 84 | Delete(pointVolumeInterpolator) 85 | Delete(tableToPoints) 86 | Delete(cfd_csv) 87 | Delete(vtu) 88 | del(resampleWithDataset) 89 | del(pointVolumeInterpolator) 90 | del(tableToPoints) 91 | del(cfd_csv) 92 | del(vtu) 93 | 94 | ''' 95 | idir = "/home/endrit/Documents/Modelling/COA/67_subjects/Results_CFD/Results_csv/Synthetic/" 96 | vdir = "/home/endrit/Documents/Modelling/COA/SSM_67_subj/SSM/new_shapes_deformed_vtus/edge_0.27/" 97 | odir = "/home/endrit/Documents/Modelling/COA/67_subjects/Results_CFD/Results_Interpolated/" 98 | ''' 99 | 100 | idir = "/home/endrit/Documents/Modelling/Post_Repair_COA/Pipeline/Results_CFD_2/Point_Cloud/" 101 | vdir = "/home/endrit/Documents/Modelling/Post_Repair_COA/Pipeline/Vtu_SSM/" 102 | odir = "/home/endrit/Documents/Modelling/Post_Repair_COA/Pipeline/Results_CFD_2/Point_Cloud_Interpolated/" 103 | 104 | resample_cfd2vtu(idir, vdir, odir) -------------------------------------------------------------------------------- /Postprocessing/README.md: -------------------------------------------------------------------------------- 1 | # Misc files for post-processing data 2 | 3 | vmtk_cfdpointcloud2vtu.py allows point clouds to be saved back onto meshes (better visualisation than point clouds). 4 | 5 | pview_sampling_planes.py scripts slice along centerlines to create an array of planes which can be visualised or saved out as .csv. 6 | 7 | vtk_distance.py is used to compare distances between 2 surfaces and outputs a contour map. 8 | -------------------------------------------------------------------------------- /Postprocessing/pview_sampling_planes.py: -------------------------------------------------------------------------------- 1 | from paraview.simple import * 2 | # note install pv 5.8+ .tar.gz for import vtk to work: 3 | from paraview import numpy_support as ns 4 | from paraview import servermanager as sm 5 | import os, sys, vtk 6 | import numpy as np 7 | 8 | def slice_cfd_data(idir, cdir, odir, param): 9 | ''' 10 | - For each case in directory: 11 | - load cfd .cas (.dat needed) and centerline (care with naming) 12 | - for each point in centerline (0->len-1) 13 | - place slice: origin = point, normal = vector (point->point+1) 14 | - clip slice with sphere: origin = point, radius = centerlineMaxInscribedSphere 15 | - integrate variables: on clip to get avg pressure 16 | - concat and export .csv array of avg pressures 17 | ''' 18 | if not os.path.exists(odir): 19 | os.makedirs(odir) 20 | 21 | for fname in sorted(os.listdir(idir)): 22 | name = os.path.splitext(fname)[0] 23 | 24 | #pv_file = odir + '/' + name + '_pv.csv' 25 | #if os.path.exists(pv_file) == False: 26 | 27 | if fname.__contains__(".encas"): 28 | cname = fname.replace(".encas", "_centerline.vtk") # depends on naming convention 29 | 30 | # read .cas 31 | print("Loading " + fname) 32 | # deleted: renderView = GetActiveViewOrCreate('RenderView') 33 | cfd_cas = EnSightReader(registrationName='cfd_cas', CaseFileName = idir + '/' +fname) 34 | UpdatePipeline(time=0.0, proxy=cfd_cas) 35 | 36 | # read centerline .vtk 37 | print("Loading " + cname) 38 | reader = vtk.vtkPolyDataReader() 39 | reader.SetFileName(cdir + '/' + cname) 40 | reader.Update() 41 | points = ns.vtk_to_numpy(reader.GetOutput().GetPoints().GetData()) 42 | radii = ns.vtk_to_numpy(reader.GetOutput().GetPointData().GetArray("MaximumInscribedSphereRadius")) 43 | 44 | # initialise vtk filters 45 | slice_ = Slice(Input=cfd_cas) 46 | slice_.SliceType = 'Plane' 47 | clip_ = Clip(Input=slice_) 48 | clip_.ClipType = 'Sphere' 49 | clip_.Invert = 1 50 | integrateVariables_ = IntegrateVariables(registrationName='IntegrateVariables', Input=clip_) 51 | 52 | pressures = [] 53 | # compute 99 slices 54 | for i in range(0, len(radii)-1): 55 | point_1 = points[i] 56 | point_2 = points[i+1] 57 | normal = np.subtract(point_2, point_1) 58 | 59 | # slice 60 | slice_.SliceType.Origin = point_2 61 | slice_.SliceType.Normal = normal 62 | UpdatePipeline(time=0.0, proxy=slice_) 63 | 64 | # clip 65 | ''' 66 | CARE: centerlines must have been computed after surface scaling (m->mm). 67 | scaling centerline leaves stored radii values unscaled! 68 | ''' 69 | clip_.ClipType.Center = point_2 70 | clip_.ClipType.Radius = radii[i+1] * 1.3 71 | UpdatePipeline(time=0.0, proxy=clip_) 72 | 73 | # total pressure on slice 74 | UpdatePipeline(time=0.0, proxy=integrateVariables_) 75 | 76 | # avg_P = total_P / slice area 77 | integrate_data = sm.Fetch(integrateVariables_) 78 | param_arr = ns.vtk_to_numpy(integrate_data.GetPointData().GetArray(param)) 79 | area_arr = ns.vtk_to_numpy(integrate_data.GetCellData().GetArray('Area')) 80 | avg_param = param_arr[0] / area_arr[0] 81 | # to save x-sectional area 82 | if odir.__contains__("Area/"): 83 | avg_param = area_arr[0] 84 | 85 | ''' 86 | for max values instead of average 87 | ''' 88 | # clip_data = sm.Fetch(clip_) 89 | # max_P = max(ns.vtk_to_numpy(clip_data.GetBlock(0).GetPointData().GetArray('pressure'))) 90 | pressures.append(avg_param) 91 | 92 | # clear and save 93 | Delete(integrateVariables_) 94 | Delete(clip_) 95 | Delete(slice_) 96 | Delete(cfd_cas) 97 | del(integrateVariables_) 98 | del(clip_) 99 | del(slice_) 100 | del(cfd_cas) 101 | print("writing in " + odir) 102 | print("") 103 | np.savetxt(odir + '/' + name + '_' + param + ".csv", pressures, delimiter=",") 104 | 105 | 106 | idir = "/home/endrit/Documents/Modelling/Javier/New_Sims/PA_Vivek/Results_CFD/Ensight/" 107 | cdir = "/home/endrit/Documents/Modelling/Javier/New_Sims/PA_Vivek/Centerline_Branches/LPA/" 108 | odir = "/home/endrit/Documents/Modelling/Javier/New_Sims/PA_Vivek/Results_Pv/LPA/" 109 | 110 | slice_cfd_data(idir, cdir, odir + "/Avg_Pressure/", "pressure") 111 | slice_cfd_data(idir, cdir, odir + "/Avg_Velocity/", "velocity_magnitude") 112 | slice_cfd_data(idir, cdir, odir + "/Area/", "velocity_magnitude") 113 | 114 | idir = "/home/endrit/Documents/Modelling/Javier/New_Sims/PA_Vivek/Results_CFD/Ensight/" 115 | cdir = "/home/endrit/Documents/Modelling/Javier/New_Sims/PA_Vivek/Centerline_Branches/RPA/" 116 | odir = "/home/endrit/Documents/Modelling/Javier/New_Sims/PA_Vivek/Results_Pv/RPA/" 117 | 118 | slice_cfd_data(idir, cdir, odir + "/Avg_Pressure/", "pressure") 119 | slice_cfd_data(idir, cdir, odir + "/Avg_Velocity/", "velocity_magnitude") 120 | slice_cfd_data(idir, cdir, odir + "/Area/", "velocity_magnitude") -------------------------------------------------------------------------------- /Postprocessing/vmtk_cfdpointcloud2vtu.py: -------------------------------------------------------------------------------- 1 | import os, sys, copy, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | import numpy as np 5 | import pandas as pd 6 | import vtk 7 | from vtk.vtkCommonCore import vtkObject 8 | from vtk.util import numpy_support as ns 9 | 10 | def csv2vtu_multiple(idir, vdir, odir): 11 | ''' 12 | - take cfd point cloud arrays and add them to vtu arrays 13 | - save out as a vtu 14 | ''' 15 | if not os.path.exists(odir): 16 | os.makedirs(odir) 17 | idir_sort = sorted(os.listdir(idir)) 18 | vdir_sort = sorted(os.listdir(vdir)) 19 | 20 | for fname, vname in zip(idir_sort, vdir_sort): 21 | name = os.path.splitext(fname)[0] 22 | # read cfd csv 23 | cfd_csv = pd.read_csv(ifile, header=None) 24 | # get cfd data 25 | cfd_np = cfd_csv.values 26 | pressure_np = cfd_np[1:, 1].astype(np.float) 27 | velocity_np = cfd_np[1:, 3].astype(np.float) 28 | # cfd dict to go in mesh arr 29 | cfd_dict = {'PointData' : {'Pressure' : pressure_np, 'Velocity_Magnitude' : velocity_np}} 30 | # read vtu 31 | mesh_reader = vmtk.vmtkmeshreader.vmtkMeshReader() 32 | mesh_reader.InputFileName = vdir + '/' + vname 33 | mesh_reader.Execute() 34 | # convert vtu to np array 35 | mesh2np = vmtk.vmtkmeshtonumpy.vmtkMeshToNumpy() 36 | mesh2np.Mesh = mesh_reader.Mesh 37 | mesh2np.Execute() 38 | mesh_arr = mesh2np.ArrayDict 39 | # add CFD dict 40 | mesh_arr.update(cfd_dict) 41 | # convert new np array to mesh 42 | np2mesh = vmtk.vmtknumpytomesh.vmtkNumpyToMesh() 43 | np2mesh.ArrayDict = mesh_arr 44 | np2mesh.Execute() 45 | # write mesh as vtu file 46 | writer = vmtk.vmtkmeshwriter.vmtkMeshWriter() 47 | writer.Mesh = np2mesh.Mesh 48 | writer.OutputFileName = odir + '/' + name + '_cfd.vtu' 49 | writer.Execute() 50 | 51 | 52 | def csv2vtu_single(ifile, vfile, ofile): 53 | # read cfd csv 54 | cfd_csv = pd.read_csv(ifile, header=None) 55 | # get cfd data 56 | cfd_np = cfd_csv.values 57 | pressure_np = cfd_np[1:, 1].astype(np.float) 58 | velocity_np = cfd_np[1:, 3].astype(np.float) 59 | # cfd dict to go in mesh arr 60 | cfd_dict = {'PointData' : {'Pressure' : pressure_np, 'Velocity_Magnitude' : velocity_np}} 61 | # read vtu 62 | mesh_reader = vmtk.vmtkmeshreader.vmtkMeshReader() 63 | mesh_reader.InputFileName = vfile 64 | mesh_reader.Execute() 65 | # convert vtu to np array 66 | mesh2np = vmtk.vmtkmeshtonumpy.vmtkMeshToNumpy() 67 | mesh2np.Mesh = mesh_reader.Mesh 68 | mesh2np.Execute() 69 | mesh_arr = mesh2np.ArrayDict 70 | # add CFD dict 71 | mesh_arr.update(cfd_dict) 72 | # convert new np array to mesh 73 | np2mesh = vmtk.vmtknumpytomesh.vmtkNumpyToMesh() 74 | np2mesh.ArrayDict = mesh_arr 75 | np2mesh.Execute() 76 | # write mesh as vtu file 77 | writer = vmtk.vmtkmeshwriter.vmtkMeshWriter() 78 | writer.Mesh = np2mesh.Mesh 79 | writer.OutputFileName = ofile 80 | writer.Execute() 81 | 82 | 83 | if __name__=="__main__": 84 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 85 | readline.set_completer_delims(" \t\n=") 86 | readline.parse_and_bind("tab: complete") 87 | 88 | if mode==1: 89 | ifile = input("Enter path to cfd point cloud: ") 90 | vfile = input("Enter path to matching vtu mesh: ") 91 | ofile = input("Enter the desired output file path: ") 92 | csv2vtu_single(ifile, ofile) 93 | 94 | if mode==2: 95 | idir = input("Enter directory of cfd point clouds: ") 96 | vdir = input("Enter directory of matching vtu meshes: ") 97 | odir = input("Enter output directory: ") 98 | csv2vtu_multiple(idir, odir) -------------------------------------------------------------------------------- /Postprocessing/vtk_distance.py: -------------------------------------------------------------------------------- 1 | import os, sys, vtk, readline, statistics 2 | import numpy as np 3 | from vtk.util import numpy_support as ns 4 | 5 | def compute_distance_multiple(idir, rdir, odir): 6 | ''' 7 | - compute the distances between two surfaces 8 | - ifile is the source, rfile is used as the reference 9 | - outputs ifile surface with distribution of distances 10 | ''' 11 | if not os.path.exists(odir): 12 | os.makedirs(odir) 13 | 14 | surf_main = sorted(os.listdir(idir)) 15 | surf_ref = sorted(os.listdir(rdir)) 16 | 17 | for fname, rname in zip(surf_main, surf_ref): 18 | name = os.path.splitext(fname)[0] 19 | # load files 20 | ifile_reader = vtk.vtkPolyDataReader() 21 | ifile_reader.SetFileName(idir + '/' + fname) 22 | ifile_reader.Update() 23 | rfile_reader = vtk.vtkPolyDataReader() 24 | rfile_reader.SetFileName(rdir + '/' + rname) 25 | rfile_reader.Update() 26 | # compute distances 27 | dist_filter = vtk.vtkDistancePolyDataFilter() 28 | dist_filter.SetInputConnection(0, ifile_reader.GetOutputPort()) 29 | dist_filter.SetInputConnection(1, rfile_reader.GetOutputPort()) 30 | dist_filter.Update() 31 | distances = dist_filter.GetOutput() 32 | # write vtk 33 | writer = vtk.vtkPolyDataWriter() 34 | writer.SetInputData(distances) 35 | writer.SetFileName(odir + '/' + name + '_dist.vtk') 36 | writer.Write() 37 | 38 | 39 | def compute_distance_single(ifile, rfile, ofile): 40 | # load files 41 | ifile_reader = vtk.vtkPolyDataReader() 42 | ifile_reader.SetFileName(ifile) 43 | ifile_reader.Update() 44 | rfile_reader = vtk.vtkPolyDataReader() 45 | rfile_reader.SetFileName(rfile) 46 | rfile_reader.Update() 47 | # compute distances 48 | dist_filter = vtk.vtkDistancePolyDataFilter() 49 | dist_filter.SetInputConnection(0, ifile_reader.GetOutputPort()) 50 | dist_filter.SetInputConnection(1, rfile_reader.GetOutputPort()) 51 | dist_filter.Update() 52 | distances = dist_filter.GetOutput() 53 | # write vtk 54 | writer = vtk.vtkPolyDataWriter() 55 | writer.SetInputData(distances) 56 | writer.SetFileName(ofile) 57 | writer.Write() 58 | 59 | 60 | def compute_distance_custom(idir, odir): 61 | ''' 62 | - save csv of average distances 63 | ''' 64 | if not os.path.exists(odir): 65 | os.makedirs(odir) 66 | 67 | # ground truth + distance map outputted 68 | surf_main = sorted(os.listdir(idir))[10:] 69 | surf_ref = sorted(os.listdir(idir))[:10] 70 | 71 | average_dist = [] 72 | for fname, rname in zip(surf_main, surf_ref): 73 | print(fname) 74 | print(rname) 75 | name = os.path.splitext(fname)[0] 76 | # load files 77 | ifile_reader = vtk.vtkPolyDataReader() 78 | ifile_reader.SetFileName(idir + '/' + fname) 79 | ifile_reader.Update() 80 | rfile_reader = vtk.vtkPolyDataReader() 81 | rfile_reader.SetFileName(idir + '/' + rname) 82 | rfile_reader.Update() 83 | # compute distances 84 | dist_filter = vtk.vtkDistancePolyDataFilter() 85 | dist_filter.SetInputConnection(0, ifile_reader.GetOutputPort()) 86 | dist_filter.SetInputConnection(1, rfile_reader.GetOutputPort()) 87 | dist_filter.Update() 88 | distances = dist_filter.GetOutput() 89 | # write vtk 90 | writer = vtk.vtkImageWriter() 91 | writer.SetInputData(distances) 92 | writer.SetFileName(odir + '/' + name + '_dist.vtk') 93 | writer.Write() 94 | # get array of data 95 | dist_cell_data = distances.GetCellData().GetArray("Distance") 96 | dist_np = ns.vtk_to_numpy(dist_cell_data) 97 | dist_avg = statistics.mean(abs(dist_np)) 98 | print(dist_avg) 99 | average_dist.append(dist_avg) 100 | 101 | np.savetxt(odir + '/' + "avg_distances.csv", average_dist, delimiter=",") 102 | 103 | 104 | if __name__=="__main__": 105 | #mode = int(input("1 = single file, 2 = multiple files in directory: ")) 106 | #readline.set_completer_delims(" \t\n=") 107 | #readline.parse_and_bind("tab: complete") 108 | 109 | idir = "/home/endrit/Documents/Modelling/Javier/Ao_Pa/Ao_VMTK_based/Meshes_2_Clipped/" 110 | odir = "/home/endrit/Documents/Modelling/Javier/Ao_Pa/Ao_VMTK_based/Distances/Meshes_2/" 111 | compute_distance_custom(idir, odir) 112 | 113 | ''' 114 | if mode == 1: 115 | ifile = input("Enter path to main surface file: ") 116 | rfile = input("Enter path to reference surface (to compute distances to): ") 117 | ofile = input("Enter full save location: ") 118 | compute_distance_single(ifile, rfile, ofile) 119 | 120 | if mode == 2: 121 | idir = input("Enter directory of main surfaces: ") 122 | rdir = input("Enter directory of reference surfaces (to compute distances to): ") 123 | odir = input("Enter directory to save files with computed distances: ") 124 | compute_distance_multiple(idir, rdir, odir) 125 | ''' -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![alt text](https://github.com/EndritPJ/CFD_Machine_Learning/blob/main/coverpic.jpg?raw=true) 2 | 3 | # Deep Neural Networks for Fast Aortic CFD 4 | Pipeline and code for building deep neural networks (DNNs) to predict computational fluid dynamics (CFD) pressure and velocity point clouds in aortas. Uses VMTK, Deformetrica (v4.3), Ansys Fluent (v19.0), Paraview and Keras. The code in this repo enables users to build DNNs with a collection of their own aortic surfaces (or other single inlet/outlet vessels). 5 | 6 | ### Setup 7 | 8 | Clone the github repo: 9 | 10 | $ git clone https://github.com/EndritPJ/CFD_Machine_Learning 11 | 12 | Enter the Envs/ directory. You will need to build 3 separate environments (VMTK, DFCA, Keras). 13 | 14 | $ conda env create -f env_DFCA.yml 15 | 16 | ### Overview 17 | The process is split up into different stages: 18 | 1) Statistical shape modelling (SSM) which is used for expressing aortas using lower-dimensional latent vectors. This also allows for the generation of synthetic aortas through random sampling. Built using Deformetrica 4.3 and original code written by Raphael Sivera (https://github.com/ClinicalCardiovascEngGroup/SSM/tree/master/python) 19 | 2) Meshing of surfaces to create volume meshes for CFD. The package used primarily for mesh editing is VMTK. 20 | 3) Computational Fluid Dynamics is performed on a large train/test dataset of synthetic aortic meshes. In this case the commercial platform Ansys Fluent was used. Post-processing of data with the platform Paraview is necessary. 21 | 4) Finally, DNN model training and testing can commence. This is conducted using the package Keras and Tensorflow 2.0. It is recommended to have a high performance GPU (GTX1080 or higher) to speed up training. 22 | 23 | ### Initial Aortic Surface Preprocessing 24 | 1) Create an empty project directory (e.g. CFD_ML_Aortas/). 25 | 2) Create a subfolder containing your aortic surface meshes (in .vtk format). **If custom scaling has been applied to your aortic images/surface meshes please revert it**. Additionally, surface aortas should **be in millimetres**. 26 | 3) Enter the VMTK conda env. 27 | 4) Remesh and smooth your surfaces: `$ python vmtk_remesher.py` 28 | 5) Clip inlets and outlets manually: `$ python vmtk_clipper.py` . Ensure that clipping is consistent between subjects (e.g. STJ and diaphragm). Try to preserve curvature of aorta (no awkward angles in cuts). 29 | 6) Register all meshes using `$ python vmtk_registration.py` (some initial manual repositioning may be necessary) 30 | 31 | ### Statistical Shape Modelling 32 | 1. Create a new folder SSM/ 33 | 2. Grab the necessary code that manages the SSM estimation and more: 34 | `$ git clone ClinicalCardiovascEngGroup/SSM/tree/master/python` 35 | 3. You will need an initial "template" subject. This is an initial guess which is used as a reference for building the shape model. Ideally an aorta from another dataset or a simplified aortic shape. 36 | 4. Enter the deformetrica conda environment. 37 | 5. Run: `$ ssm_estimation.ipynb` (update the directory variables). By the end you should have a SSM/r2/output/ directory containing your final template, momenta and surface reconstructions. 38 | 6. Run: `$ ssm_new_shape_generation.ipynb` (update the directory variables). By the end, you should have generated synthetic surface/volume meshes and a pca_u_new_shapes_concat.csv file which has the shape scores for each synthetic subject. 39 | 40 | ### Meshing and CFD 41 | 1. Enter the VMTK conda environment. 42 | 2. Compute centerlines for each synthetic aortic surface: `$ python vmtk_centerlines_open_profiles.py` 43 | 3. Add flow extensions to the inlets of each surface: `$ python vmtk_extension.py` 44 | 4. Compute the meshes (.vtu) of each extended aorta: `$ python vmtk_cfdmesher.py` 45 | 5. Assign .vtu mesh boundary ids using previously computed centerlines: `$ python vmtk_idfix_inlet.py` 46 | 6. Convert new .vtu files to Fluent meshes (.msh): `$ python vmtk_vtu2msh.py` 47 | 7. Enter the Fluent/ directory and run: `$ python cfd_prepare.py`. This will output a Fluent journal file which will manage the CFD loop. Enter this file and edit it to select/change boundary conditions. 48 | 8. Run the Fluent CFD simulations in batch mode in the terminal. 49 | 9. After all simulations are completed, you should have a Point_Cloud directory in the results folder. The next step is to interpolate all the CFD results back on the volume meshes (computed by SSM) which have point-point correspondence. To do this run: `$ pvbatch pview_resample_cfd2vtu` (make sure you edit the directories in the code first). 50 | 51 | ### Neural Network Building 52 | 1. Enter the Keras conda environment. 53 | 2. The training/testing data consists of the aortic shape scores computed from SSM when creating the new surfaces (pca_u_new_shapes_concat.csv) and the synthetic simulations in point correspondence (interpolated point clouds). 54 | 3. Run: `$ cfd_dnn_training.ipynb` (update directories). 55 | 4. Run: `$ cfd_dnn_testing.ipynb` (update directories). 56 | 57 | To get in contact, email: endrit.pajaziti.13@ucl.ac.uk 58 | 59 | 60 | ![alt text](https://github.com/EndritPJ/CFD_Machine_Learning/blob/main/widget.gif) 61 | -------------------------------------------------------------------------------- /VMTK/__pycache__/custom_vmtkflowextensions.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndritPJ/CFD_Machine_Learning/566caec994e437fe8d79af447aca93229efd2294/VMTK/__pycache__/custom_vmtkflowextensions.cpython-36.pyc -------------------------------------------------------------------------------- /VMTK/custom_vmtkflowextensions.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import #NEEDS TO STAY AS TOP LEVEL MODULE FOR Py2-3 COMPATIBILITY 2 | import vtk 3 | import sys 4 | 5 | from vmtk import vtkvmtk 6 | from vmtk import pypes 7 | from vmtk import vmtkrenderer 8 | 9 | 10 | class vmtkFlowExtensions(pypes.pypeScript): 11 | 12 | def __init__(self): 13 | 14 | pypes.pypeScript.__init__(self) 15 | 16 | self.Surface = None 17 | self.Centerlines = None 18 | 19 | self.AdaptiveExtensionLength = 0 20 | self.AdaptiveExtensionRadius = 1 21 | self.AdaptiveNumberOfBoundaryPoints = 0 22 | self.ExtensionLength = 1.0 23 | self.ExtensionRatio = 10.0 24 | self.ExtensionRadius = 1.0 25 | self.TransitionRatio = 0.25 26 | self.TargetNumberOfBoundaryPoints = 50 27 | self.CenterlineNormalEstimationDistanceRatio = 1.0 28 | self.ExtensionMode = "centerlinedirection" 29 | self.InterpolationMode = "thinplatespline" 30 | self.Interactive = 1 31 | self.Exclude = 0 32 | self.Sigma = 1.0 33 | 34 | self.vmtkRenderer = None 35 | self.OwnRenderer = 0 36 | 37 | self.SetScriptName('vmtkflowextensions') 38 | self.SetScriptDoc('interactivly add flow extensions to a surface for CFD processing') 39 | self.SetInputMembers([ 40 | ['Surface','i','vtkPolyData',1,'','','vmtksurfacereader'], 41 | ['Centerlines','centerlines','vtkPolyData',1,'','','vmtksurfacereader'], 42 | ['ExtensionMode','extensionmode','str',1,'["centerlinedirection","boundarynormal"]','method for computing the normal for extension'], 43 | ['InterpolationMode','interpolationmode','str',1,'["linear","thinplatespline"]','method for computing interpolation from the model section to a circular section'], 44 | ['Sigma','sigma','float',1,'(0.0,)','thin plate spline stiffness'], 45 | ['AdaptiveExtensionLength','adaptivelength','bool',1], 46 | ['AdaptiveExtensionRadius','adaptiveradius','bool',1], 47 | ['AdaptiveNumberOfBoundaryPoints','adaptivepoints','bool',1], 48 | ['ExtensionLength','extensionlength','float',1,'(0.0,)'], 49 | ['ExtensionRatio','extensionratio','float',1,'(0.0,)'], 50 | ['ExtensionRadius','extensionradius','float',1,'(0.0,)'], 51 | ['TransitionRatio','transitionratio','float',1,'(0.0,)'], 52 | ['TargetNumberOfBoundaryPoints','boundarypoints','int',1,'(0,)'], 53 | ['Interactive','interactive','bool',1], 54 | ['Exclude','exclude','bool',1,'', 'create extensions for all boundaries except those selected'], 55 | ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer'], 56 | ['CenterlineNormalEstimationDistanceRatio','normalestimationratio','float',1,'(0.0,)'] 57 | ]) 58 | self.SetOutputMembers([ 59 | ['Surface','o','vtkPolyData',1,'','','vmtksurfacewriter'], 60 | ['Centerlines','centerlines','vtkPolyData',1] 61 | ]) 62 | 63 | def LabelValidator(self,text): 64 | import string 65 | if not text: 66 | return 0 67 | if not text.split(): 68 | return 0 69 | for char in text: 70 | if char not in string.digits + " ": 71 | return 0 72 | return 1 73 | 74 | def Execute(self): 75 | 76 | if self.Surface == None: 77 | self.PrintError('Error: No input surface.') 78 | 79 | if self.ExtensionMode == "centerlinedirection" and self.Centerlines == None: 80 | self.PrintError('Error: No input centerlines.') 81 | 82 | boundaryIds = vtk.vtkIdList() 83 | 84 | if self.Interactive: 85 | if not self.vmtkRenderer: 86 | self.vmtkRenderer = vmtkrenderer.vmtkRenderer() 87 | self.vmtkRenderer.Initialize() 88 | self.OwnRenderer = 1 89 | 90 | self.vmtkRenderer.RegisterScript(self) 91 | 92 | boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor() 93 | boundaryExtractor.SetInputData(self.Surface) 94 | boundaryExtractor.Update() 95 | boundaries = boundaryExtractor.GetOutput() 96 | numberOfBoundaries = boundaries.GetNumberOfCells() 97 | seedPoints = vtk.vtkPoints() 98 | for i in range(numberOfBoundaries): 99 | barycenter = [0.0, 0.0, 0.0] 100 | vtkvmtk.vtkvmtkBoundaryReferenceSystems.ComputeBoundaryBarycenter(boundaries.GetCell(i).GetPoints(),barycenter) 101 | seedPoints.InsertNextPoint(barycenter) 102 | seedPolyData = vtk.vtkPolyData() 103 | seedPolyData.SetPoints(seedPoints) 104 | labelsMapper = vtk.vtkLabeledDataMapper(); 105 | labelsMapper.SetInputData(seedPolyData) 106 | labelsMapper.SetLabelModeToLabelIds() 107 | labelsActor = vtk.vtkActor2D() 108 | labelsActor.SetMapper(labelsMapper) 109 | 110 | self.vmtkRenderer.Renderer.AddActor(labelsActor) 111 | 112 | surfaceMapper = vtk.vtkPolyDataMapper() 113 | surfaceMapper.SetInputData(self.Surface) 114 | surfaceMapper.ScalarVisibilityOff() 115 | surfaceActor = vtk.vtkActor() 116 | surfaceActor.SetMapper(surfaceMapper) 117 | surfaceActor.GetProperty().SetOpacity(0.25) 118 | 119 | self.vmtkRenderer.Renderer.AddActor(surfaceActor) 120 | 121 | #self.vmtkRenderer.Render() 122 | 123 | #self.vmtkRenderer.Renderer.RemoveActor(labelsActor) 124 | #self.vmtkRenderer.Renderer.RemoveActor(surfaceActor) 125 | 126 | ok = False 127 | while not ok: 128 | if(self.Exclude): 129 | labelString = self.InputText("Please input boundary ids to exclude: ",self.LabelValidator) 130 | else: 131 | labelString = self.InputText("Please input boundary ids: ",self.LabelValidator) 132 | labels = [int(label) for label in labelString.split()] 133 | ok = True 134 | for label in labels: 135 | if label not in list(range(numberOfBoundaries)): 136 | ok = False 137 | 138 | if(self.Exclude): 139 | for label in list(range(numberOfBoundaries)): 140 | if label not in labels: 141 | boundaryIds.InsertNextId(label) 142 | else: 143 | for label in labels: 144 | boundaryIds.InsertNextId(label) 145 | 146 | flowExtensionsFilter = vtkvmtk.vtkvmtkPolyDataFlowExtensionsFilter() 147 | flowExtensionsFilter.SetInputData(self.Surface) 148 | flowExtensionsFilter.SetCenterlines(self.Centerlines) 149 | flowExtensionsFilter.SetSigma(self.Sigma) 150 | flowExtensionsFilter.SetAdaptiveExtensionLength(self.AdaptiveExtensionLength) 151 | flowExtensionsFilter.SetAdaptiveExtensionRadius(self.AdaptiveExtensionRadius) 152 | flowExtensionsFilter.SetAdaptiveNumberOfBoundaryPoints(self.AdaptiveNumberOfBoundaryPoints) 153 | flowExtensionsFilter.SetExtensionLength(self.ExtensionLength) 154 | flowExtensionsFilter.SetExtensionRatio(self.ExtensionRatio) 155 | flowExtensionsFilter.SetExtensionRadius(self.ExtensionRadius) 156 | flowExtensionsFilter.SetTransitionRatio(self.TransitionRatio) 157 | flowExtensionsFilter.SetCenterlineNormalEstimationDistanceRatio(self.CenterlineNormalEstimationDistanceRatio) 158 | flowExtensionsFilter.SetNumberOfBoundaryPoints(self.TargetNumberOfBoundaryPoints) 159 | if self.ExtensionMode == "centerlinedirection": 160 | flowExtensionsFilter.SetExtensionModeToUseCenterlineDirection() 161 | elif self.ExtensionMode == "boundarynormal": 162 | flowExtensionsFilter.SetExtensionModeToUseNormalToBoundary() 163 | if self.InterpolationMode == "linear": 164 | flowExtensionsFilter.SetInterpolationModeToLinear() 165 | elif self.InterpolationMode == "thinplatespline": 166 | flowExtensionsFilter.SetInterpolationModeToThinPlateSpline() 167 | # ************************************************************************************************************ 168 | #if self.Interactive: 169 | boundaryIds.InsertNextId(0) 170 | flowExtensionsFilter.SetBoundaryIds(boundaryIds) 171 | flowExtensionsFilter.Update() 172 | 173 | self.Surface = flowExtensionsFilter.GetOutput() 174 | 175 | 176 | if __name__=='__main__': 177 | 178 | main = pypes.pypeMain() 179 | main.Arguments = sys.argv 180 | main.Execute() -------------------------------------------------------------------------------- /VMTK/vmtk_centerlines_open_profiles.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | 5 | def centerlines_multiple(idir, odir): 6 | ''' 7 | - calculate new centerlines (openprofiles) 8 | - profileidlist is automatic without renderer 9 | - subdivide into 99 segments (100 nodes) 10 | - divide by 99.1 (not 99) to ensure 100 nodes 11 | ''' 12 | if not os.path.exists(odir): 13 | os.makedirs(odir) 14 | 15 | for fname in sorted(os.listdir(idir)): 16 | 17 | name = os.path.splitext(fname)[0] 18 | print(name) 19 | output_name = odir + '/' + name + '_centerline.vtk' 20 | if os.path.isfile(output_name): 21 | continue 22 | # read surface 23 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 24 | reader.InputFileName = idir + '/' + fname 25 | reader.Execute() 26 | # compute centerline 27 | centerline = vmtk.vmtkcenterlines.vmtkCenterlines() 28 | centerline.SeedSelectorName = "profileidlist" 29 | centerline.SourceIds = [0] 30 | centerline.TargetIds = [1] 31 | #centerline.SeedSelectorName = "openprofiles" 32 | centerline.Surface = reader.Surface 33 | centerline.AppendEndPoints = 1 34 | centerline.Execute() 35 | # resample centerline to 100 points 36 | cent_geom = vmtk.vmtkcenterlinegeometry.vmtkCenterlineGeometry() 37 | cent_geom.Centerlines = centerline.Centerlines 38 | cent_geom.Execute() 39 | cent2np = vmtk.vmtkcenterlinestonumpy.vmtkCenterlinesToNumpy() 40 | cent2np.Centerlines = cent_geom.Centerlines 41 | cent2np.Execute() 42 | cent_length = cent2np.ArrayDict['CellData']['Length'] 43 | resampler = vmtk.vmtkcenterlineresampling.vmtkCenterlineResampling() 44 | resampler.Centerlines = centerline.Centerlines 45 | resampler.Length = cent_length / 99.1 46 | resampler.Execute() 47 | # write centerline 48 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 49 | writer.Input = resampler.Centerlines 50 | writer.OutputFileName = odir + '/' + name + '_centerline.vtk' 51 | writer.Execute() 52 | 53 | 54 | def centerlines_single(ifile, ofile): 55 | # read surface 56 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 57 | reader.InputFileName = ifile 58 | reader.Execute() 59 | # compute centerline 60 | centerline = vmtk.vmtkcenterlines.vmtkCenterlines() 61 | #centreline.SeedSelectorName = "profileidlist" 62 | #centreline.SourceIds = [0] 63 | #centreline.TargetIds = [1] 64 | centerline.SeedSelectorName = "openprofiles" 65 | centerline.Surface = reader.Surface 66 | centerline.AppendEndPoints = 1 67 | centerline.Execute() 68 | # resample centerline to 100 points 69 | cent_geom = vmtk.vmtkcenterlinegeometry.vmtkCenterlineGeometry() 70 | cent_geom.Centerlines = centerline.Centerlines 71 | cent_geom.Execute() 72 | cent2np = vmtk.vmtkcenterlinestonumpy.vmtkCenterlinesToNumpy() 73 | cent2np.Centerlines = cent_geom.Centerlines 74 | cent2np.Execute() 75 | cent_length = cent2np.ArrayDict['CellData']['Length'] 76 | resampler = vmtk.vmtkcenterlineresampling.vmtkCenterlineResampling() 77 | resampler.Centerlines = centerline.Centerlines 78 | resampler.Length = cent_length / 99.1 79 | resampler.Execute() 80 | # write centerline 81 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 82 | writer.Input = resampler.Centerlines 83 | writer.OutputFileName = ofile 84 | writer.Execute() 85 | 86 | 87 | if __name__=="__main__": 88 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 89 | readline.set_completer_delims(" \t\n=") 90 | readline.parse_and_bind("tab: complete") 91 | 92 | if mode==1: 93 | ifile = input("Enter path to file: ") 94 | ofile = input("Enter the full output path: ") 95 | centerlines_single(ifile, ofile) 96 | 97 | if mode==2: 98 | idir = input("Enter input directory: ") 99 | odir = input("Enter output directory: ") 100 | centerlines_multiple(idir, odir) -------------------------------------------------------------------------------- /VMTK/vmtk_cfdmesher.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | 3 | 4 | def cfdmesher_multiple(idir, odir, edge, bl): 5 | ''' 6 | - vascular volume meshing 7 | - uses vmtk in shell, script fails with python classes 8 | - option for boundary layer (bl) 9 | ''' 10 | if not os.path.exists(odir): 11 | os.makedirs(odir) 12 | 13 | for fname in sorted(os.listdir(idir)): 14 | name = os.path.splitext(fname)[0] 15 | if os.path.exists(odir+'/'+name+".vtu"): 16 | continue 17 | # meshing with inflation layers 18 | if(bl=="y"): 19 | arg = ( 20 | f" vmtksurfacereader -ifile {idir+'/'+fname} " 21 | f" --pipe vmtkcenterlines -seedselector profileidlist -sourceids 0 -targetids 1 -endpoints 1 " 22 | f" --pipe vmtkdistancetocenterlines -useradius 1 " 23 | f" --pipe vmtkmeshgenerator -elementsizemode edgelengtharray -edgelengtharray DistanceToCenterlines " 24 | f" -edgelengthfactor {edge} -boundarylayer 1 -thicknessfactor 0.5 -sublayers 3 -sublayerratio 0.5 " 25 | f" -boundarylayeroncaps 0 -tetrahedralize 1 -ofile {odir+'/'+name}.vtu" 26 | ) 27 | os.system(arg) 28 | else: 29 | arg = ( 30 | f" vmtkmeshgenerator -ifile {idir+'/'+fname} -edgelength {edge} " 31 | f" -ofile {odir+'/'+name}.vtu" 32 | ) 33 | os.system(arg) 34 | 35 | 36 | def cfdmesher_single(ifile, ofile, edge, bl): 37 | # meshing with inflation layers 38 | if(bl=="y"): 39 | arg = ( 40 | f" vmtksurfacereader -ifile {ifile} " 41 | f" --pipe vmtkcenterlines -endpoints 1 -seedselector profileidlist -sourceids 0 -targetids 1 " 42 | f" --pipe vmtkdistancetocenterlines -useradius 1 " 43 | f" --pipe vmtkmeshgenerator -elementsizemode edgelengtharray -edgelengtharray DistanceToCenterlines " 44 | f" -edgelengthfactor {edge} -boundarylayer 1 -thicknessfactor 0.5 -sublayers 3 -sublayerratio 0.8 " 45 | f" -boundarylayeroncaps 0 -tetrahedralize 1 -ofile {ofile}" 46 | ) 47 | os.system(arg) 48 | else: 49 | arg = ( 50 | f" vmtkmeshgenerator -ifile {ifile} -edgelength {edge} -ofile {ofile}" 51 | ) 52 | os.system(arg) 53 | 54 | 55 | if __name__=="__main__": 56 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 57 | readline.set_completer_delims(" \t\n=") 58 | readline.parse_and_bind("tab: complete") 59 | 60 | if mode==1: 61 | ifile = input("Enter path to file: ") 62 | ofile = input("Enter the full output path: ") 63 | edge = input("Element edge length factor (default=0.2): ") or "0.2" 64 | bl = input("Inflation layers (y or n): ") or "y" 65 | cfdmesher_single(ifile, ofile, edge, bl) 66 | 67 | if mode==2: 68 | idir = input("Enter input directory: ") 69 | odir = input("Enter output directory: ") 70 | edge = input("Element edge length factor (default=0.2): ") or "0.2" 71 | bl = input("Inflation layers (y or n): ") or "y" 72 | cfdmesher_multiple(idir, odir, edge, bl) -------------------------------------------------------------------------------- /VMTK/vmtk_clipper.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | 5 | def clipper_multiple(idir, cdir, odir): 6 | ''' 7 | - use existing centerlines to clip ends of aortas 8 | ''' 9 | if not os.path.exists(odir): 10 | os.makedirs(odir) 11 | idir_sort = sorted(os.listdir(idir)) 12 | cdir_sort = sorted(os.listdir(cdir)) 13 | 14 | for fname, cname in zip(idir_sort, cdir_sort): 15 | name = os.path.splitext(fname)[0] 16 | # read centerline 17 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 18 | reader.InputFileName = cdir + '/' + cname 19 | reader.Execute() 20 | # get end points of centerline 21 | endpoints = vmtk.vmtkendpointextractor.vmtkEndpointExtractor() 22 | endpoints.NumberOfEndpointSpheres = 1 23 | endpoints.Centerlines = reader.Surface 24 | endpoints.Execute() 25 | # read surface 26 | reader.InputFileName = idir + '/' + fname 27 | reader.Execute() 28 | # clip mesh ends 29 | branchclipper = vmtk.vmtkbranchclipper.vmtkBranchClipper() 30 | branchclipper.Surface = reader.Surface 31 | branchclipper.Centerlines = endpoints.Centerlines 32 | branchclipper.Execute() 33 | # re-triangulate 34 | connect = vmtk.vmtksurfaceconnectivity.vmtkSurfaceConnectivity() 35 | connect.Surface = branchclipper.Surface 36 | connect.CleanOutput = 1 37 | connect.Execute() 38 | # write surface 39 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 40 | writer.Surface = connect.Surface 41 | writer.OutputFileName = odir + '/' + name + '_clip.vtk' 42 | writer.Execute() 43 | 44 | 45 | def clipper_single(ifile, ofile): 46 | # read surface 47 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 48 | reader.InputFileName = ifile 49 | reader.Execute() 50 | # calculate centerlines 51 | centerline = vmtk.vmtkcenterlines.vmtkCenterlines() 52 | centerline.Surface = reader.Surface 53 | centerline.Execute() 54 | # get end points of centerline 55 | endpoints = vmtk.vmtkendpointextractor.vmtkEndpointExtractor() 56 | endpoints.NumberOfEndpointSpheres = 1 57 | endpoints.Centerlines = centerline.Centerlines 58 | endpoints.Execute() 59 | # clip mesh ends 60 | branchclipper = vmtk.vmtkbranchclipper.vmtkBranchClipper() 61 | branchclipper.Surface = reader.Surface 62 | branchclipper.Centerlines = endpoints.Centerlines 63 | branchclipper.Execute() 64 | # re-triangulate 65 | connect = vmtk.vmtksurfaceconnectivity.vmtkSurfaceConnectivity() 66 | connect.Surface = branchclipper.Surface 67 | connect.CleanOutput = 1 68 | connect.Execute() 69 | # write surface 70 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 71 | writer.Surface = connect.Surface 72 | writer.OutputFileName = ofile 73 | writer.Execute() 74 | 75 | 76 | if __name__=="__main__": 77 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 78 | readline.set_completer_delims(" \t\n=") 79 | readline.parse_and_bind("tab: complete") 80 | 81 | if mode==1: 82 | ifile = input("Enter path to file: ") 83 | ofile = input("Enter the full output path: ") 84 | clipper_single(ifile, ofile) 85 | 86 | if mode==2: 87 | idir = input("Enter input directory: ") 88 | cdir = input("Enter centerline directory: ") 89 | odir = input("Enter output directory: ") 90 | clipper_multiple(idir, cdir, odir) 91 | -------------------------------------------------------------------------------- /VMTK/vmtk_extension.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | import custom_vmtkflowextensions 5 | 6 | def extension_boundary_multi(idir, odir): 7 | ''' 8 | - add flow extensions for all meshes in directory 9 | - uses boundary normals as extension direction 10 | - surface normals recomputed after extension 11 | ''' 12 | if not os.path.exists(odir): 13 | os.makedirs(odir) 14 | 15 | for fname in sorted(os.listdir(idir)): 16 | name = os.path.splitext(fname)[0] 17 | print(name) 18 | # read surface 19 | surf_reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 20 | surf_reader.InputFileName = idir + '/' + fname 21 | surf_reader.Execute() 22 | # extensions 23 | extender = custom_vmtkflowextensions.vmtkFlowExtensions() 24 | extender.Surface = surf_reader.Surface 25 | extender.ExtensionMode = "boundarynormal" 26 | extender.Interactive = 0 27 | # 30mm 28 | extender.ExtensionLength = 40 29 | extender.Execute() 30 | # recompute normals 31 | normals = vmtk.vmtksurfacenormals.vmtkSurfaceNormals() 32 | normals.Surface = extender.Surface 33 | normals.Execute() 34 | # write surface 35 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 36 | writer.Surface = normals.Surface 37 | writer.OutputFileName = odir + '/' + name + '_ext.vtk' 38 | writer.Execute() 39 | 40 | 41 | def extension_boundary_single(ifile, ofile): 42 | # read surface 43 | surf_reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 44 | surf_reader.InputFileName = ifile 45 | surf_reader.Execute() 46 | # extensions 47 | extender = vmtk.vmtkflowextensions.vmtkFlowExtensions() 48 | extender.Surface = surf_reader.Surface 49 | extender.ExtensionMode = "boundarynormal" 50 | extender.Interactive = 0 51 | extender.ExtensionLength = 30 52 | extender.Execute() 53 | # recompute normals 54 | normals = vmtk.vmtksurfacenormals.vmtkSurfaceNormals() 55 | normals.Surface = extender.Surface 56 | normals.Execute() 57 | # write surface 58 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 59 | writer.Surface = normals.Surface 60 | writer.OutputFileName = ofile 61 | writer.Execute() 62 | 63 | 64 | if __name__=="__main__": 65 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 66 | readline.set_completer_delims(" \t\n=") 67 | readline.parse_and_bind("tab: complete") 68 | 69 | if mode==1: 70 | ifile = input("Enter path to file: ") 71 | ofile = input("Enter the full output path: ") 72 | extension_boundary_single(ifile, ofile) 73 | 74 | if mode==2: 75 | idir = input("Enter input directory: ") 76 | odir = input("Enter output directory: ") 77 | extension_boundary_multi(idir, odir) -------------------------------------------------------------------------------- /VMTK/vmtk_idfix_inlet.py: -------------------------------------------------------------------------------- 1 | import os, sys, copy, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | import numpy as np 5 | import vtk 6 | from vtk.vtkCommonCore import vtkObject 7 | from vtk.util import numpy_support as ns 8 | 9 | def id_fix_multiple(idir, cdir, odir): 10 | ''' 11 | - get inlet point from centerline 12 | - get ids of boundaries (in/out) from .vtu 13 | - get dist of outlet-id3 and outlet-id2 14 | - outlet-id2 should be smaller since no outlet extension 15 | ''' 16 | if not os.path.exists(odir): 17 | os.makedirs(odir) 18 | idir_sort = sorted(os.listdir(idir)) 19 | cdir_sort = sorted(os.listdir(cdir)) 20 | 21 | for fname, cname in zip(idir_sort, cdir_sort): 22 | name = os.path.splitext(fname)[0] 23 | # read centerlines 24 | cent_reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 25 | cent_reader.InputFileName = cdir + '/' + cname 26 | cent_reader.Execute() 27 | # convert centerlines to np array 28 | cent2np = vmtk.vmtkcenterlinestonumpy.vmtkCenterlinesToNumpy() 29 | cent2np.Centerlines = cent_reader.Surface 30 | cent2np.Execute() 31 | cent_arr = cent2np.ArrayDict 32 | # outlet centerline point 33 | ao_outlet = cent_arr['Points'][-1] 34 | # read vtu 35 | mesh_reader = vmtk.vmtkmeshreader.vmtkMeshReader() 36 | mesh_reader.InputFileName = idir + '/' + fname 37 | mesh_reader.Execute() 38 | # convert vtu to np array 39 | mesh2np = vmtk.vmtkmeshtonumpy.vmtkMeshToNumpy() 40 | mesh2np.Mesh = mesh_reader.Mesh 41 | mesh2np.Execute() 42 | mesh_arr = mesh2np.ArrayDict 43 | # read vtu with vtk 44 | vtk_reader = vtk.vtkXMLUnstructuredGridReader() 45 | vtk_reader.SetFileName(idir + '/' + fname) 46 | vtk_reader.Update() 47 | ugrid = vtk_reader.GetOutput() 48 | # get indices of two triangles (id=2, id=3) 49 | cell_id2 = np.where(mesh_arr['CellData']['CellEntityIds']==2)[0][0] 50 | cell_id3 = np.where(mesh_arr['CellData']['CellEntityIds']==3)[0][0] 51 | # get triangle verts 52 | points_id2 = copy.deepcopy(ns.vtk_to_numpy(ugrid.GetCell(cell_id2).GetPoints().GetData())) 53 | points_id3 = copy.deepcopy(ns.vtk_to_numpy(ugrid.GetCell(cell_id3).GetPoints().GetData())) 54 | # euclidean distances for centerline_inlet - boundaries 55 | dist_outlet_id2 = np.linalg.norm(ao_outlet - points_id2[0]) 56 | dist_outlet_id3 = np.linalg.norm(ao_outlet - points_id3[0]) 57 | ''' 58 | if outlet->id2 is smaller, then outlet is id2 (incorrect). Therefore switch: 59 | ''' 60 | if dist_outlet_id2 < dist_outlet_id3: 61 | print("switching CellEntityIds for " + fname + "...") 62 | for i, cell_id in enumerate(mesh_arr['CellData']['CellEntityIds']): 63 | if cell_id == 2: 64 | mesh_arr['CellData']['CellEntityIds'][i] = 3 65 | elif cell_id == 3: 66 | mesh_arr['CellData']['CellEntityIds'][i] = 2 67 | 68 | # convert new np array to mesh 69 | np2mesh = vmtk.vmtknumpytomesh.vmtkNumpyToMesh() 70 | np2mesh.ArrayDict = mesh_arr 71 | np2mesh.Execute() 72 | # write mesh as vtu file 73 | writer = vmtk.vmtkmeshwriter.vmtkMeshWriter() 74 | writer.Mesh = np2mesh.Mesh 75 | writer.OutputFileName = odir + '/' + name + '.vtu' 76 | writer.Execute() 77 | 78 | if __name__=="__main__": 79 | readline.set_completer_delims(" \t\n=") 80 | readline.parse_and_bind("tab: complete") 81 | 82 | idir = input("Enter vtu directory: ") 83 | cdir = input("Enter centerlines directory: ") 84 | odir = input("Enter output directory: ") 85 | id_fix_multiple(idir, cdir, odir) -------------------------------------------------------------------------------- /VMTK/vmtk_registration.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | 5 | def registration_multiple(idir, rfile, odir): 6 | if not os.path.exists(odir): 7 | os.makedirs(odir) 8 | 9 | # read reference surface 10 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 11 | reader.InputFileName = rfile 12 | reader.Execute() 13 | # set as registration target 14 | register = vmtk.vmtkicpregistration.vmtkICPRegistration() 15 | register.ReferenceSurface = reader.Surface 16 | 17 | for fname in sorted(os.listdir(idir)): 18 | name = os.path.splitext(fname)[0] 19 | # read surface + register 20 | reader.InputFileName = idir + '/' + fname 21 | reader.Execute() 22 | register.Surface = reader.Surface 23 | register.Execute() 24 | # write registered surface 25 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 26 | writer.Surface = register.Surface 27 | writer.OutputFileName = odir + '/' + name + '_reg.vtk' 28 | writer.Execute() 29 | 30 | def registration_single(ifile, rfile, ofile): 31 | # read reference surface 32 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 33 | reader.InputFileName = rfile 34 | reader.Execute() 35 | # read input surface 36 | surf_reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 37 | surf_reader.InputFileName = ifile 38 | surf_reader.Execute() 39 | # registration 40 | register = vmtk.vmtkicpregistration.vmtkICPRegistration() 41 | register.ReferenceSurface = reader.Surface 42 | register.Surface = surf_reader.Surface 43 | register.Execute() 44 | # write registered surface 45 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 46 | writer.Surface = register.Surface 47 | writer.OutputFileName = ofile 48 | writer.Execute() 49 | 50 | if __name__=="__main__": 51 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 52 | readline.set_completer_delims(" \t\n=") 53 | readline.parse_and_bind("tab: complete") 54 | 55 | if mode==1: 56 | ifile = input("Enter path to file: ") 57 | rfile = input("Enter path to registration target: ") 58 | ofile = input("Enter the full output path: ") 59 | registration_single(ifile, rfile, ofile) 60 | 61 | if mode==2: 62 | idir = input("Enter input directory: ") 63 | rfile = input("Enter path to registration target: ") 64 | odir = input("Enter output directory: ") 65 | registration_multiple(idir, rfile, odir) -------------------------------------------------------------------------------- /VMTK/vmtk_remesher.py: -------------------------------------------------------------------------------- 1 | import os, sys, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | 5 | def remesh_multiple(idir, odir, edge, scaling, smoothing): 6 | ''' 7 | - remesh, smooth, scale (m->mm) batch meshes 8 | - edge length 9 | ''' 10 | if not os.path.exists(odir): 11 | os.makedirs(odir) 12 | 13 | for fname in sorted(os.listdir(idir)): 14 | name = os.path.splitext(fname)[0] 15 | # read surface 16 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 17 | reader.InputFileName = idir + '/' + fname 18 | reader.Execute() 19 | # remesh 20 | remesher = vmtk.vmtksurfaceremeshing.vmtkSurfaceRemeshing() 21 | remesher.ElementSizeMode = 'edgelength' 22 | remesher.TargetEdgeLength = edge 23 | remesher.Surface = reader.Surface 24 | remesher.NumberOfIterations = 5 25 | remesher.Execute() 26 | # smooth 27 | smoother = vmtk.vmtksurfacesmoothing.vmtkSurfaceSmoothing() 28 | smoother.Surface = remesher.Surface 29 | smoother.PassBand = 0.1 30 | smoother.NumberOfIterations = 10 31 | if(smoothing=="y"): 32 | smoother.Execute() 33 | # scale from m -> mm 34 | scaler = vmtk.vmtksurfacescaling.vmtkSurfaceScaling() 35 | scaler.ScaleFactor = scaling 36 | scaler.Surface = smoother.Surface 37 | if(scaling is not 1.): 38 | scaler.Execute() 39 | # write surface as vtk 40 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 41 | writer.Surface = scaler.Surface 42 | writer.OutputFileName = odir + '/' + name + '_remsh.vtk' 43 | writer.Execute() 44 | 45 | 46 | def remesh_single(ifile, ofile, edge, scaling, smoothing): 47 | # read surface 48 | reader = vmtk.vmtksurfacereader.vmtkSurfaceReader() 49 | reader.InputFileName = ifile 50 | reader.Execute() 51 | # remesh 52 | remesher = vmtk.vmtksurfaceremeshing.vmtkSurfaceRemeshing() 53 | remesher.ElementSizeMode = 'edgelength' 54 | remesher.TargetEdgeLength = edge 55 | remesher.Surface = reader.Surface 56 | remesher.NumberOfIterations = 5 57 | remesher.Execute() 58 | # smooth 59 | smoother = vmtk.vmtksurfacesmoothing.vmtkSurfaceSmoothing() 60 | smoother.Surface = remesher.Surface 61 | smoother.PassBand = 0.1 62 | smoother.NumberOfIterations = 10 63 | if(smoothing=="y"): 64 | smoother.Execute() 65 | # scale from m -> mm 66 | scaler = vmtk.vmtksurfacescaling.vmtkSurfaceScaling() 67 | scaler.ScaleFactor = scaling 68 | scaler.Surface = smoother.Surface 69 | if(scaling is not 1.): 70 | scaler.Execute() 71 | # write surface as vtk 72 | writer = vmtk.vmtksurfacewriter.vmtkSurfaceWriter() 73 | writer.Surface = scaler.Surface 74 | writer.OutputFileName = ofile 75 | writer.Execute() 76 | 77 | if __name__=="__main__": 78 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 79 | readline.set_completer_delims(" \t\n=") 80 | readline.parse_and_bind("tab: complete") 81 | 82 | if mode==1: 83 | ifile = input("Enter path to file: ") 84 | ofile = input("Enter the full output path: ") 85 | edge = float(input("Global nominal target edge length (default=2mm):") or 2) 86 | scale = float(input("Scale factor (enter 1 for no scaling): ") or 1) 87 | smooth = input("smooth mesh (y or n): ") or "y" 88 | remesh_single(ifile, ofile, edge, scale, smooth) 89 | 90 | if mode==2: 91 | idir = input("Enter input directory: ") 92 | odir = input("Enter output directory: ") 93 | edge = float(input("Global nominal target edge length (default=2mm):") or 2) 94 | scale = float(input("Scale factor (enter 1 for no scaling): ") or 1) 95 | smooth = input("smooth mesh (y or n): ") or "y" 96 | remesh_multiple(idir, odir, edge, scale, smooth) -------------------------------------------------------------------------------- /VMTK/vmtk_vtu2msh.py: -------------------------------------------------------------------------------- 1 | import os, readline 2 | import vmtk 3 | from vmtk import vmtkscripts 4 | 5 | 6 | def write_msh_multi(idir, odir): 7 | 8 | if not os.path.exists(odir): 9 | os.makedirs(odir) 10 | 11 | for fname in sorted(os.listdir(idir)): 12 | name = os.path.splitext(fname)[0] 13 | # read vtu 14 | mesh_reader = vmtk.vmtkmeshreader.vmtkMeshReader() 15 | mesh_reader.InputFileName = idir + '/' + fname 16 | mesh_reader.Execute() 17 | # write mesh as fluent file 18 | writer = vmtk.vmtkmeshwriter.vmtkMeshWriter() 19 | writer.Mesh = mesh_reader.Mesh 20 | writer.OutputFileName = odir + '/' + name + '.msh' 21 | writer.Execute() 22 | 23 | 24 | def write_msh_single(ifile, ofile): 25 | # read vtu 26 | mesh_reader = vmtk.vmtkmeshreader.vmtkMeshReader() 27 | mesh_reader.InputFileName = ifile 28 | mesh_reader.Execute() 29 | # write mesh as fluent file 30 | writer = vmtk.vmtkmeshwriter.vmtkMeshWriter() 31 | writer.Mesh = mesh_reader.Mesh 32 | writer.OutputFileName = ofile 33 | writer.Execute() 34 | 35 | 36 | if __name__=="__main__": 37 | mode = int(input("1 = single file, 2 = multiple files in directory: ")) 38 | readline.set_completer_delims(" \t\n=") 39 | readline.parse_and_bind("tab: complete") 40 | 41 | if mode==1: 42 | ifile = input("Enter path to file: ") 43 | ofile = input("Enter the desired output file path: ") 44 | write_msh_single(ifile, ofile) 45 | 46 | if mode==2: 47 | idir = input("Enter input directory: ") 48 | odir = input("Enter output directory: ") 49 | write_msh_multi(idir, odir) -------------------------------------------------------------------------------- /coverpic.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndritPJ/CFD_Machine_Learning/566caec994e437fe8d79af447aca93229efd2294/coverpic.jpg -------------------------------------------------------------------------------- /widget.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndritPJ/CFD_Machine_Learning/566caec994e437fe8d79af447aca93229efd2294/widget.gif --------------------------------------------------------------------------------