<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/env python

'''
-------------------
Copyright (c) 2015 Computational Biomechanics (CoBi) Core, Department of
Biomedical Engineering, Cleveland Clinic

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------

WRITTEN BY:
-----------
Craig Bennetts, MS
Computational Biomodeling (CoBi) Core
Department of Biomedical Engineering
Lerner Research Institute
Cleveland Clinic
Cleveland, OH
bennect2@ccf.org


DESCRIPTION:
------------
Reads a batch of FEBio .log files and creates text files that rank the simulations
according to a set of desired FEBio simulation results.


LEGEND:
-------
&lt;...&gt; = variable argument

USAGE:
------
./FEBio_BATCH_analysis.py &lt;FEBio .log file(s)&gt;


ASSUMPTION:
-----------
- FEBio .log files are in simulation batch folders (generated by SLURM_FEBio_BATCH.py),
  with the following format:
  	sim_&lt;param#.1&gt;_..._&lt;param#.N&gt;
- script should be run in the parent folder of the batch simulation subfolders
  =&gt; input argument should include subfolders, e.g.:
     sim_*/*.log
- simulations will be identified by the subfolder name in output files


OUTPUT FILES:
------------

RANK_&lt;FEBio_parameter&gt;.txt

	DESCRIPTION:
	Modified FEBio model, with specified kinematic/kinetic DOF data curves applied
 
'''


import sys


def USAGE(argv):

	print
	print 'USAGE: ' + argv[0] + ' &lt;FEBio .log file(s)&gt;'
	print


def FEBio_BATCH_ranking(argv):

	# CHECK SCRIPT USAGE
	if len(argv)&lt;2:
		USAGE(argv)
		sys.exit(1)

	log_filenames = argv[1:]

	# number of lines from end of log file to look for 3 cases:
	# 1) successful convergence
	# 2) error in convergence
	# 3) terminated (timed-out) by SLURM scheduler (i.e. not enough time requested in SLURM_FEBio_submit.sh)
	NUM_LINES_FROM_END = 30  
	
	# Create lists to store index-matched values
	# lists for converged simulations
	conv_sim_ids = []
	num_time_steps = []
	total_eq_iters = []
	avg_eq_iters = []
	num_RH_evals = []
	num_stiff_refs = []
	solver_times = []
	elapsed_times = []
	
	# lists for nonconverged simulations
	nonconv_sim_ids = []
	nonconv_sim_times = []
	nonconv_elapsed_times = []

	# lists for SLURM terminated (timed-out) jobs
	timeout_sim_ids = []

	# LOG FILE PARSING LOOP
	for log_filename in log_filenames:

		# READ LOG FILE
		LogFile = open(log_filename,'r')
		LogFileLines = LogFile.readlines()
		LogFile.close()

		# Determine simulation id
		# use simulation folder name for simulation id if it is included
		if '/' in log_filename:
			sim_id = log_filename.split('/')[0]
		# use full log filename
		else:
			sim_id = log_filename

		converged = -1  # timed-out by SLURM scheduler

		# Determine if simulation converged or not
		for line in reversed(LogFileLines[-NUM_LINES_FROM_END:]):

			# WARNING: these will need to change if FEBio .log file format changes				
			if 'N O R M A L   T E R M I N A T I O N' in line:
				converged = 1  # True
				break
			elif 'E R R O R   T E R M I N A T I O N' in line:
				converged = 0  # False
				break

		# Parse desired values for each type
		if converged==True:
			
			conv_sim_ids.append( sim_id )
			
			for line in reversed(LogFileLines[-NUM_LINES_FROM_END:]):

				# WARNING: these will need to change if FEBio .log file format changes				
				if 'Elapsed time' in line:
					value = line.strip('\r\n').split(' : ')[-1]
					elapsed_times.append( value )
				elif 'Time in solver' in line:
					value = line.strip('\r\n').split(': ')[-1]
					solver_times.append( value )
				elif 'Total number of stiffness reformations' in line:
					value = int( line.strip('\r\n').split(':')[-1] )
					num_stiff_refs.append( value )
				elif 'Total number of right hand evaluations' in line:
					value = int( line.strip('\r\n').split(':')[-1] )
					num_RH_evals.append( value )
				elif 'Average number of equilibrium iterations' in line:
					value = float( line.strip('\r\n').split(':')[-1] )
					avg_eq_iters.append( value )
				elif 'Total number of equilibrium iterations' in line:
					value = int( line.strip('\r\n').split(':')[-1] )
					total_eq_iters.append( value )
				elif 'Number of time steps completed' in line:
					value = int( line.strip('\r\n').split(':')[-1] )
					num_time_steps.append( value )

		elif converged==False:

			nonconv_sim_ids.append( sim_id )
			
			for line in reversed(LogFileLines):
				
				# WARNING: these will need to change if FEBio .log file format changes				
				if 'Elapsed time' in line:
					value = line.strip('\r\n').split(' : ')[-1]
					nonconv_elapsed_times.append( value )
				elif 'converged at time' in line:
					value = float( line.strip('\r\n').split(':')[-1] )
					nonconv_sim_times.append( value )
					break
			
		else:

			timeout_sim_ids.append( sim_id )

	# END OF LOG FILE PARSING LOOP


	# RANK/OUTPUT SIMULATIONS BY SELECTED PARAMETERS

	# Rank/Output converged simulation parameters

	if len(conv_sim_ids)&gt;0:

		output_filename = 'RANK_CONVERGED.txt'
		RankFile = open(output_filename,'w')
		for sim_id in conv_sim_ids:
			RankFile.write( sim_id + '\n')
		RankFile.close()
	
		output_filename = 'RANK_num_time_steps.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(num_time_steps,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + str(value) + '\n')
		RankFile.close()
	
		output_filename = 'RANK_total_eq_iters.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(total_eq_iters,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + str(value) + '\n')
		RankFile.close()
	
		output_filename = 'RANK_avg_eq_iters.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(avg_eq_iters,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + str(value) + '\n')
		RankFile.close()
	
		output_filename = 'RANK_num_RH_evals.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(num_RH_evals,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + str(value) + '\n')
		RankFile.close()
	
		output_filename = 'RANK_num_stiff_refs.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(num_stiff_refs,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + str(value) + '\n')
		RankFile.close()
	
		output_filename = 'RANK_solver_times.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(solver_times,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + value + '\n')
		RankFile.close()
	
		output_filename = 'RANK_elapsed_times.txt'
		RankFile = open(output_filename,'w')
		for (value,sim_id) in sorted(zip(elapsed_times,conv_sim_ids)):
			RankFile.write( sim_id + ' ' + value + '\n')
		RankFile.close()

	
	# Rank/Output nonconverged simulation parameters
	
	if len(nonconv_sim_ids)&gt;0:

		output_filename = 'RANK_NONCONVERGED.txt'
		RankFile = open(output_filename,'w')
		for (sim_time,elapsed_time,sim_id) in sorted(zip(nonconv_sim_times,nonconv_elapsed_times,nonconv_sim_ids)):
			RankFile.write( sim_id + ' ' + str(sim_time) + ' ' + elapsed_time + '\n')
		RankFile.close()


	# Output SLURM terminated (timed-out) simulations
	
	if len(timeout_sim_ids)&gt;0:

		output_filename = 'RANK_TIMEOUT.txt'
		RankFile = open(output_filename,'w')
		for sim_id in timeout_sim_ids:
			RankFile.write( sim_id + '\n')
		RankFile.close()

# END OF FEBio_BATCH_ranking()


# Default calls SLURM_FEBio_BATCH() if this script is not called as a function
if __name__ == "__main__":
	FEBio_BATCH_ranking(sys.argv)</pre></body></html>