workflow_sketch.sh 23.5 KB
Newer Older
1 2 3 4 5 6 7
#!/bin/bash

##############################
# Configurations             #
##############################
# Directory where runAnalysis.C is placed
export ALIROOT_SCRIPT_DIR=$(pwd)/aliRoot/
8
# Directory where Blender scripts are
9 10
export BLENDER_SCRIPT_DIR=$(pwd)/animate/
# alienv working directory
11
export ALIENV_WORK_DIR=$(pwd)/../sw
12
export ALIENV_OS_SPEC=ubuntu1804_x86-64
13
export ALIENV_ID=AliPhysics/latest-aliroot5-user
14
# Put Blender 2.79b in the PATH env var
15
export PATH="$(pwd)/../blender-2.79-linux-glibc219-x86_64/:$PATH"
16

17 18 19
# Progress log file
export PROGRESS_LOG=$(pwd)/progress.log

20 21 22 23 24 25 26 27
if [[ -f $PROGRESS_LOG ]]; then
  if grep -q "JOB FINISHED" $PROGRESS_LOG; then
    rm $PROGRESS_LOG
  fi
fi

# Define a timestamp function
timestamp() {
28
  date +"%y-%m-%d, %T, $1"
29 30
}

31
##############################
32
# Command-line options       #
33
##############################
34 35 36 37 38 39 40 41 42 43 44 45 46 47
# See the following link to understand the code below
# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash

# saner programming env: these switches turn some bugs into errors
set -o errexit -o pipefail -o noclobber -o nounset

# -allow a command to fail with !’s side effect on errexit
# -use return value from ${PIPESTATUS[0]}, because ! hosed $?
! getopt --test > /dev/null
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
    echo 'I’m sorry, `getopt --test` failed in this environment.'
    exit 1
fi

48
OPTIONS=c:hdau:m:n:t:r:
49
LONGOPTS=cameras:,mosaic,resolution:,fps:,transparency:,duration:,radius:,maxparticles:,\
50
minparticles:,numberofevents:,minavgpz:,minavgpt:,help,download,sample,url:,its,\
51
tpc,detailedtpc,trd,emcal,blendersave,picpct:,bgshade:
52 53 54 55 56 57 58 59 60 61 62 63 64 65

# -regarding ! and PIPESTATUS see above
# -temporarily store output to be able to check for errors
# -activate quoting/enhanced mode (e.g. by writing out “--options”)
# -pass arguments only via   -- "$@"   to separate them correctly
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
    # e.g. return value is 1
    #  then getopt has complained about wrong arguments to stdout
    exit 2
fi
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"

66 67 68
##############################
# Parse Parameters           #
##############################
69
CAMERAS=Overview
70
MOSAIC=false
71
DURATION=5
72
RADIUS=1
73
RESOLUTION=100
74
FPS=24
75
TRANSPARENCY=1
76 77 78
MAX_PARTICLES=1000
MIN_PARTICLES=0
N_OF_EVENTS=10
79
MIN_AVG_PZ=0
80
MIN_AVG_PT=0
81 82
HELP=false
DOWNLOAD=false
83
SAMPLE=false
84
URL=
85 86
ITS=1 # 1 means "build this detector", while 0 means "don't"
TPC=1
87
DETAILED_TPC=0
88 89
TRD=1
EMCAL=1
90
BLENDERSAVE=0
91
PICPCT=80
92
BGSHADE=0
93 94 95
# now enjoy the options in order and nicely split until we see --
while true; do
    case "$1" in
96 97 98 99 100
      -h|--help)
          HELP=true
          shift
          break
          ;;
101
      -d|--download)
102 103 104
          DOWNLOAD=true
          shift
          ;;
105
      -a|--sample)
106 107 108
          SAMPLE=true
          shift
          ;;
109 110
      -u|--url)
          URL="$2"
111 112
            shift 2
            ;;
113 114 115 116
      -m|--maxparticles)
          MAX_PARTICLES="$2"
          shift 2
          ;;
117 118 119 120 121 122 123 124
      --minparticles)
          MIN_PARTICLES="$2"
          shift 2
          ;;
      -n|--numberofevents)
          N_OF_EVENTS="$2"
          shift 2
          ;;
125 126 127 128
      --minavgpz)
          MIN_AVG_PZ="$2"
          shift 2
          ;;
129 130 131 132
      --minavgpt)
          MIN_AVG_PT="$2"
          shift 2
          ;;
133 134 135 136
      -t|--duration)
          DURATION="$2"
          shift 2
          ;;
137 138 139 140 141
      -r|--radius)
          RADIUS="$2"
          shift 2
          ;;
      --resolution)
142 143 144
          RESOLUTION="$2"
          shift 2
          ;;
145 146 147 148
      --fps)
          FPS="$2"
          shift 2
          ;;
149 150
      --transparency)
          TRANSPARENCY="$2"
151 152
          shift 2
          ;;
153 154
      -c|--cameras)
      	  CAMERAS="$2"
155 156
      	  shift 2
      	  ;;
157 158 159 160
      --mosaic)
          MOSAIC=true
          shift
          ;;
161 162 163 164
      --picpct)
      	  PICPCT="$2"
      	  shift 2
      	  ;;
165 166 167 168
      --bgshade)
      	  BGSHADE="$2"
      	  shift 2
      	  ;;
169
      --its)
170 171 172
          ITS=0
          shift
          ;;
173
      --tpc)
174 175 176
          TPC=0
          shift
          ;;
177 178 179 180
      --detailedtpc)
          DETAILED_TPC=1
          shift
          ;;
181
      --trd)
182 183 184
          TRD=0
          shift
          ;;
185
      --emcal)
186 187 188
          EMCAL=0
          shift
          ;;
189 190 191 192
      --blendersave)
          BLENDERSAVE=1
          shift
          ;;
193 194 195 196 197
        --)
            shift
            break
            ;;
        *)
198
            echo "Programming error $*"
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
            exit 3
            ;;
    esac
done

##############################
# Usage                      #
##############################
function usage()
{
    # Using a here doc with standard out.
    cat <<-END
Usage:
------
   -h | --help
     Display this help
   -d | --download
     Download the AliESDs.root file using the provided URL
   -u | --url URL
     Provide the URL to uniquely identify a AliESDs.root dataset.
     This should be in the format provided by http://opendata.cern.ch.
     See example below.
221
   -m | --maxparticles VALUE
222 223
     Get only events for which its number of particles does not
     exceed VALUE.
224
   --minparticles VALUE
225 226
     Get only events for which its number of particles is greater than
     or equal to VALUE.
227
   -n | --numberofevents VALUE
228
     Set number of events to be animated inside chosen ESD file (defaults to 10)
229 230
   --minavgpz VALUE
     Get only events for which its absolute value of average momentum in
231 232
     the z direction is greater than or equal to VALUE, in GeV/c. Useful
     for animating events with 'boosts' of particles to the same side.
233 234
   --minavgpt VALUE
     Get only events for which its average transversal momentum is
235 236
     greater than or equal to VALUE, in GeV/c. Useful for animating
     events with 'boosts' of particles on the xy plane.
237 238
   -t | --duration VALUE
     Set the animation duration in seconds.
239 240 241 242
   -r | --radius VALUE
     Scale default particle radius to a given VALUE, greater than zero.
     For example, VALUE=2 scales particle to twice its default size.
   --resolution VALUE
243 244
     Set the animation resolution percentage, where
     VALUE must be an integer from 1 to 100.
245 246
   --fps VALUE
     Set number of frames per second in animation.
247 248 249
   --transparency VALUE
     Set detector transparency as a number greater than zero,
     where zero is full transparency and 1 is standard transparency
250 251
   -c | --cameras VALUE
     Which cameras to use for the animation, where VALUE
252
     is a comma-separated list (without spaces)
253
     Options: Barrel,Side,Forward,Overview,Moving1,Moving2,Moving3,Moving4 (defaults to Overview)
254
   --mosaic
255 256 257
     Make animations in all four available steady cameras and combine them into
     a single 2x2 clip containing all perspectives, totalizing at least five
     generated .mp4 videos.
258
   --picpct VALUE
259 260
     Percentage of animation to take HD picture, saved along with the clip,
     where VALUE must be an integer
261 262 263
   --bgshade VALUE
     Set background shade of black to VALUE, where 0 is totally black
     and 1 is totally white
264
   -a | --sample
265
     Creates a sample Blender animation of Event 2 from URL
266 267
     http://opendata.cern.ch/record/1102/files/assets/alice/2010/LHC10h/000139\
038/ESD/0001/AliESDs.root
268
   --its
269
     Removes ITS detector from animation
270 271
   --detailedtpc
     Includes more detailed version of TPC in animation
272
   --tpc
273
     Removes TPC detector from animation
274
   --trd
275
     Removes TRD detector from animation
276
   --emcal
277
     Removes EMCal detector from animation
278 279
   --blendersave
     Saves Blender file along with animation clip
280 281 282

Example:
--------
283 284
$0 --url http://opendata.cern.ch/record/1103/files/assets/alice/2010/LHC10h/000\
139173/ESD/0004/AliESDs.root --download
285 286 287

END
}
288

289
# Fix CAMERA to be accepted by the for loop
290 291
if [[ $CAMERAS != "" ]]; then
    CAMERAS=$(echo $CAMERAS | sed -e 's#,#Camera #g' -e 's#$#Camera#')
292 293
fi

294
# Set cameras properly if MOSAIC is called
295
if [[ $MOSAIC = "true" ]]; then
296

297 298 299 300 301 302 303 304 305
    CAMS=
    for type in $CAMERAS; do # Add 'non-mosaic' selected cameras to variable CAMS
      if [[ "${type}" != "OverviewCamera" && "${type}" != "BarrelCamera" \
      && "${type}" != "Moving1Camera" && "${type}" != "ForwardCamera" ]]; then
        CAMS+="${type} "
      fi
    done
    # Set variable CAMERAS to contain all selected cameras + mosaic cameras
    CAMERAS="${CAMS}OverviewCamera BarrelCamera Moving1Camera ForwardCamera"
306

307 308
fi

309 310 311 312 313 314 315
if [[ $HELP = "true" ]]; then
    usage
    exit
else
    echo "-------- Parsed parameters --------"
    echo "URL: $URL"
    echo "Download: $DOWNLOAD"
316
    echo "Sample: $SAMPLE"
317
    echo "Transparency Parameter: $TRANSPARENCY"
318
    echo "Duration: $DURATION"
319
    echo "Particle Radius Scale: $RADIUS"
320
    echo "Resolution: $RESOLUTION"
321
    echo "FPS: $FPS"
322
    echo "Max particles: ${MAX_PARTICLES}"
323 324
    echo "Min particles: ${MIN_PARTICLES}"
    echo "Number of events: ${N_OF_EVENTS}"
325
    echo "Min Average Z Momentum: ${MIN_AVG_PZ}"
326
    echo "Min Average Transversal Momentum: ${MIN_AVG_PT}"
327
    echo "Cameras: $CAMERAS"
328
    echo "Mosaic: $MOSAIC"
329
    echo "Picture Percentage: ${PICPCT}%"
330
    echo "Background Shade: ${BGSHADE}"
331
    echo "-----------------------------------"
332 333 334 335
    echo "------------ Detectors ------------"
    if [[ $ITS = 1 ]]; then
      echo "Building ITS"
    fi
336 337 338 339 340 341
    if [[ $DETAILED_TPC = 1 ]]; then
      echo "Building detailed TPC"
    else
      if [[ $TPC = 1 ]]; then
        echo "Building TPC"
      fi
342 343 344 345 346 347 348 349 350 351 352
    fi
    if [[ $TRD = 1 ]]; then
      echo "Building TRD"
    fi
    if [[ $EMCAL = 1 ]]; then
      echo "Building EMCAL"
    fi
    if [[ $TPC = 0 && $TPC = 0 && $TRD = 0 && $EMCAL = 0 ]]; then
      echo "Not building any detectors"
    fi
    echo "-----------------------------------"
353 354
fi

355 356 357 358 359
# Get number of frames
FPS_DUR="$FPS $DURATION"
FPS_DUR=$(echo $FPS_DUR | awk '{print $1*$2}')


360 361 362 363 364 365 366
# handle non-option arguments
if [[ $# -ne 0 ]]; then
    echo "$0: non-option arguments ($#, $*) are ignored."
    echo "Remove them manually as indicated between parenthesis."
    exit
fi

367

368 369 370 371
##############################
# Download Dataset           #
##############################
if [ "$DOWNLOAD" = "true" ]; then
372
    if [ -z $URL ]; then
373
        echo "Error. Must pass the dataset URL in order to download ESD file."
374 375 376
        usage
        exit
    fi
377

378
    if ! grep -q "ESD DOWNLOAD DONE" $PROGRESS_LOG; then
379 380
      echo "Downloading data."
      wget $URL
381
      timestamp "ESD DOWNLOAD DONE" >> $PROGRESS_LOG
382
    fi
383

384 385 386 387 388 389 390 391 392 393 394 395
    ######################################
    # Established Unique ID based on URL #
    ######################################
    UNIQUEID=$(echo $URL | sed \
                         -e "s#http://opendata.cern.ch/##" \
                         -e "s#/AliESDs.root##" \
                         -e "s#files/assets/##" \
                         -e "s#/#_#g")

    echo "The unique ID is $UNIQUEID."

fi
396

397
##############################
398
# Sample synthetic animation#
399
##############################
400
if [ "$SAMPLE" = "true" ]; then
401
    ##############################
402
    # Phase 1: Blender animate   #
403
    ##############################
404 405 406
    BLENDER_OUTPUT=$(pwd)/sample
    mkdir --verbose -p ${BLENDER_OUTPUT}

407
    pushd ${BLENDER_SCRIPT_DIR}
408 409
    echo "Preparing sample animation in Blender"

410
    blender -noaudio --background -P animate_particles.py -- -radius=${RADIUS} \
411
    -duration=${DURATION} -cameras="${CAMERAS}" -datafile="d-esd-detail.dat" -simulated_t=0.03\
412 413
    -fps=${FPS} -resolution=${RESOLUTION} -transparency=${TRANSPARENCY} \
    -stamp_note="opendata.cern.ch_record_1102_alice_2010_LHC10h_000139038_ESD_0001_2" -its=${ITS}\
414
    -tpc=${TPC} -trd=${TRD} -emcal=${EMCAL} -detailed_tpc=${DETAILED_TPC} \
415
    -blendersave=1 -bgshade=${BGSHADE} -tpc_blender_path=${BLENDER_SCRIPT_DIR} \
416
    -output_path="${BLENDER_OUTPUT}"
417

418 419 420
    popd
    echo "Done."

421 422 423
##############################
# Animation from file        #
##############################
424
elif [ "$SAMPLE" = "false" ]; then
425

426
  if ! grep -q "DATA_ANALYSIS, FINISHED" $PROGRESS_LOG; then
427 428 429 430 431 432 433 434 435 436 437 438

    # Verify if AliESDs.root is here
    ALIESD_ROOT_FILE=$(pwd)/AliESDs.root
    if ! [[ -f "$ALIESD_ROOT_FILE" ]]
    then
        echo "AliESDs.root not found."
        exit
    fi

    ############################
    # Phase 1: aliroot extract #
    ############################
439
    timestamp "STARTING DATA ANALYSIS" >> $PROGRESS_LOG
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    eval $(alienv -w ${ALIENV_WORK_DIR} -a ${ALIENV_OS_SPEC} load ${ALIENV_ID})
    pushd ${ALIROOT_SCRIPT_DIR}
    # Remove existing symbolic link
    rm -f --verbose AliESDs.root
    # Create a symbolic link to the actual AliESDs.root
    ln --verbose -s ${ALIESD_ROOT_FILE} AliESDs.root
    # Run the extraction tool
    aliroot runAnalysis.C

    if [ "$DOWNLOAD" = "false" ]; then

      UNIQUEID=$(more uniqueid.txt)
      echo "The unique ID is $UNIQUEID."

    fi

    popd
457
    timestamp "${UNIQUEID}, DATA_ANALYSIS, FINISHED" >> $PROGRESS_LOG
458 459 460 461 462 463 464 465 466 467

  else
    if [ "$DOWNLOAD" = "false" ]; then

      pushd ${ALIROOT_SCRIPT_DIR}
      UNIQUEID=$(more uniqueid.txt)
      echo "The unique ID is $UNIQUEID."
      popd

    fi
468 469
  fi

470
  if ! grep -q "${UNIQUEID}, ANIMATION DIRECTORY CREATED" $PROGRESS_LOG ; then
471 472 473 474

    # Create directory where animations will be saved
    BLENDER_OUTPUT=$(pwd)/$UNIQUEID
    mkdir --verbose -p ${BLENDER_OUTPUT}
475

476
    timestamp "${UNIQUEID}, ANIMATION DIRECTORY CREATED" >> $PROGRESS_LOG
477 478
  else
    BLENDER_OUTPUT=$(pwd)/$UNIQUEID
479 480 481 482
  fi

  pushd ${ALIROOT_SCRIPT_DIR} # push back to aliroot directory

483
  if ! grep -q "${UNIQUEID}, DATA ANALYSIS FILES MOVED to animation directory" $PROGRESS_LOG; then
484 485 486
    #################################################
    # Phase 1: iteration for every event identifier #
    #################################################
487

488 489
    # Get all extracted files
    EXTRACTED_FILES=$(ls -1 esd_detail-event_*.dat | sort --version-sort)
490

491
    for FILE_WITH_DATA in $EXTRACTED_FILES; do
492

493 494
        if ! [[ -s $FILE_WITH_DATA ]]; then
            echo "File $FILE_WITH_DATA has zero size. Ignore and continue."
495
  	        rm -f $FILE_WITH_DATA
496 497
            continue
        fi
498

499 500
        mv ${ALIROOT_SCRIPT_DIR}/$FILE_WITH_DATA \
         ${BLENDER_SCRIPT_DIR}
501

502
    done
503

504
    timestamp "${UNIQUEID}, DATA ANALYSIS FILES MOVED to animation directory" >> $PROGRESS_LOG
505

506
  fi
507

508 509
  popd
  pushd ${BLENDER_SCRIPT_DIR}
510

511
  if ! grep -q "${UNIQUEID}, CREATED EVENT COUNTER FILE" $PROGRESS_LOG; then
512

513
    # Event counter for animating no more events than the informed amount
514
    rm -f event_counter.txt
515 516
    EVENT_COUNTER=0
    echo "$EVENT_COUNTER" > event_counter.txt
517
    timestamp "${UNIQUEID}, CREATED EVENT COUNTER FILE" >> $PROGRESS_LOG
518 519 520

  fi

521
  if ! grep -q "${UNIQUEID}, DATA FILES RENAMED according to UNIQUEID" $PROGRESS_LOG; then
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

    EXTRACTED_FILES=$(ls -1 esd_detail-event_*.dat | sort --version-sort)

    for FILE_WITH_DATA in $EXTRACTED_FILES; do

        EVENT_ID=$(echo $FILE_WITH_DATA | \
                   sed -e "s#esd_detail-event_##" \
                     -e "s#\.dat##")
        EVENT_UNIQUE_ID=${UNIQUEID}_${EVENT_ID}

        LOCAL_FILE_WITH_DATA=${EVENT_UNIQUE_ID}.dat

        mv $FILE_WITH_DATA $LOCAL_FILE_WITH_DATA

    done
537

538
    timestamp "${UNIQUEID}, DATA FILES RENAMED according to UNIQUEID" >> $PROGRESS_LOG
539

540 541 542 543
  fi

  EXTRACTED_FILES=$(ls -1 ${UNIQUEID}_*.dat | sort --version-sort)

544
  if ! grep -q "${UNIQUEID}, REMOVED UNUSED FILES" $PROGRESS_LOG; then
545

546
    for LOCAL_FILE_WITH_DATA in $EXTRACTED_FILES; do
547

548 549 550
      ##############################
      # Phase 2: Event selection   #
      ##############################
551

552 553
      NUMBER_OF_PARTICLES=$(wc -l $LOCAL_FILE_WITH_DATA | \
                        awk '{ print $1 }')
554

555
      AVERAGE_PZ=$(awk 'BEGIN {pzsum=0;n=0} {pzsum+=$8;n++} END {printf "%f", sqrt(pzsum*pzsum/n/n)}'\
556 557
      ${LOCAL_FILE_WITH_DATA})

558
      AVERAGE_PT=$(awk 'BEGIN {ptsum=0;n=0} {ptsum+=$9;n++} END {printf "%f", ptsum/n}' \
559 560 561 562 563
      ${LOCAL_FILE_WITH_DATA})

      echo "File $LOCAL_FILE_WITH_DATA:"
      echo "Number of particles: $NUMBER_OF_PARTICLES"
      echo "Average Z momentum: $AVERAGE_PZ"
564
      echo "Average transversal momentum: $AVERAGE_PT"
565 566 567 568 569 570 571 572 573 574 575 576 577 578

      EVENT_COUNTER=$(more event_counter.txt)

      ######################################################################
      # Remove text data of files for events that will not be animated:    #
      ######################################################################
      if (( $(echo "$AVERAGE_PT < $MIN_AVG_PT" |bc -l) )); then

        echo "Average Transversal Momentum too low (minimum accepted is $MIN_AVG_PT). Deleting data text file."

        # Remove non-processed files
        rm -f $LOCAL_FILE_WITH_DATA

      elif (( $(echo "$AVERAGE_PZ < $MIN_AVG_PZ" |bc -l) )); then
579

580
        echo "Average Z Momentum too low (minimum accepted is $MIN_AVG_PZ). Deleting data text file."
581

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
        # Remove non-processed files
        rm -f $LOCAL_FILE_WITH_DATA

      elif [[ $NUMBER_OF_PARTICLES -lt $MIN_PARTICLES ]]; then

        echo "Too little particles (minimum accepted is $MIN_PARTICLES). Deleting data text file."

        # Remove non-processed files
        rm -f $LOCAL_FILE_WITH_DATA

      elif [[ $NUMBER_OF_PARTICLES -gt $MAX_PARTICLES ]]; then

        echo "Too many particles (maximum accepted is $MAX_PARTICLES). Deleting data text file."

        # Remove non-processed files
        rm -f $LOCAL_FILE_WITH_DATA

      elif [[ $EVENT_COUNTER -ge $N_OF_EVENTS ]]; then

        echo "Numbers of events set to be animated has already been reached. Deleting data text file."

        # Remove non-processed files
        rm -f $LOCAL_FILE_WITH_DATA
      else
606

607 608 609 610
        # Increment event counter
        EVENT_COUNTER=$EVENT_COUNTER+1
        rm -f event_counter.txt
        echo "$EVENT_COUNTER" > event_counter.txt
611

612
        echo "This event will be animated. Continue."
613

614
      fi
615

616
      echo " " # Skip line to make it neat
617

618
    done
619

620
    timestamp "${UNIQUEID}, REMOVED UNUSED FILES" >> $PROGRESS_LOG
621

622
  fi
623

624 625
  # Remove event counter file
  rm -f event_counter.txt
626

627
  if ! $(ls | grep -q "${UNIQUEID}"); then
628 629 630 631 632 633
    timestamp "${UNIQUEID}, JOB FINISHED" >> $PROGRESS_LOG
    exit
  else
    # Now the list of extracted files shall only include events we want to animate
    EXTRACTED_FILES=$(ls -1 ${UNIQUEID}_*.dat | sort --version-sort)
  fi
634

635 636 637 638
  ################################################
  #   Create script so we can use GNU parallel   #
  #     to create multiple Blender scenes        #
  ################################################
639
  if ! grep -q "${UNIQUEID}, PARALLEL, SCENES, STARTING" $PROGRESS_LOG; then
640 641

    rm -f scene-making
642 643
    rm -f make-event-*
    rm -f blender-scenes
644 645 646 647 648 649 650

    for LOCAL_FILE_WITH_DATA in $EXTRACTED_FILES; do

      EVENT_ID=$(echo $LOCAL_FILE_WITH_DATA | \
                 sed -e "s#${UNIQUEID}_##" \
                   -e "s#\.dat##")
      EVENT_UNIQUE_ID=${UNIQUEID}_${EVENT_ID}
651 652
      NUMBER_OF_PARTICLES=$(wc -l $LOCAL_FILE_WITH_DATA | \
                        awk '{ print $1 }')
653

654 655 656 657 658 659
      # Write commands for making scene and tracking their progress to separate files "make-event-N"
      echo "# Define a timestamp function" >> make-event-${EVENT_ID}
      echo "timestamp() {" >> make-event-${EVENT_ID}
      echo "  date +\"%y-%m-%d, %T, \$1\"" >> make-event-${EVENT_ID}
      echo "}" >> make-event-${EVENT_ID}
      echo timestamp \"${UNIQUEID}, ${EVENT_ID}, BLENDER SCENE, STARTING, ${NUMBER_OF_PARTICLES}\" \>\> $PROGRESS_LOG >> make-event-${EVENT_ID}
660
      echo blender -noaudio --background -P animate_particles.py -- -radius=${RADIUS} \
661 662 663 664
  -duration=${DURATION} -datafile=\'${LOCAL_FILE_WITH_DATA}\' \
  -n_event=${EVENT_ID} -simulated_t=0.03 -fps=${FPS} -resolution=${RESOLUTION} \
  -transparency=${TRANSPARENCY} -stamp_note=\'${EVENT_UNIQUE_ID}\' -its=${ITS} \
  -tpc=${TPC} -trd=${TRD} -emcal=${EMCAL} -detailed_tpc=${DETAILED_TPC} \
665
  -blendersave=1 -bgshade=${BGSHADE} -tpc_blender_path=${BLENDER_SCRIPT_DIR} \
666 667 668 669 670 671 672 673
  -output_path=\'${BLENDER_OUTPUT}\' >> make-event-${EVENT_ID}
      echo timestamp \"${UNIQUEID}, ${EVENT_ID}, BLENDER SCENE, FINISHED, ${NUMBER_OF_PARTICLES}\" \>\> $PROGRESS_LOG >> make-event-${EVENT_ID}

      # Write text inside "make-event-N" on common file for all events for registering sake
      more make-event-${EVENT_ID} >> blender-scenes

      # Write command to run code inside "make-event-N" on "scene-making" file
      echo ./make-event-${EVENT_ID} >> scene-making
674
    done
675

676 677
    mv blender-scenes ${BLENDER_OUTPUT}/blender-scenes

678
    timestamp "${UNIQUEID}, PARALLEL, SCENES, STARTING" >> $PROGRESS_LOG
679

680
  fi
681

682 683 684 685
  ###################################
  # Make Blender scenes in parallel #
  ###################################
  if ! grep -q "${UNIQUEID}, PARALLEL, SCENES, FINISHED" $PROGRESS_LOG; then
686

687
    chmod +x make-event-*
688
    parallel < scene-making
689

690
    timestamp "${UNIQUEID}, PARALLEL, SCENES, FINISHED" >> $PROGRESS_LOG
691

692
  fi
693

694
  rm -f scene-making
695
  rm -f make-event-*
696

697 698 699 700
  #####################################
  # Render scenes in selected cameras #
  #####################################
  for LOCAL_FILE_WITH_DATA in $EXTRACTED_FILES; do
701

702 703 704 705 706 707
    EVENT_ID=$(echo $LOCAL_FILE_WITH_DATA | \
               sed -e "s#${UNIQUEID}_##" \
                 -e "s#\.dat##")
    EVENT_UNIQUE_ID=${UNIQUEID}_${EVENT_ID}
    NUMBER_OF_PARTICLES=$(wc -l $LOCAL_FILE_WITH_DATA | \
                      awk '{ print $1 }')
708

709
    for type in $CAMERAS; do
710

711
      if ! grep -q "${UNIQUEID}, ${EVENT_ID}, ${type}, FINISHED" $PROGRESS_LOG; then
712

713 714 715
        timestamp "${UNIQUEID}, ${EVENT_ID}, ${type}, STARTING, $NUMBER_OF_PARTICLES" >> $PROGRESS_LOG
        blender -noaudio --background -P render.py -- -cam ${type} -datafile\
         "${LOCAL_FILE_WITH_DATA}" -n_event ${EVENT_ID} -pic_pct ${PICPCT} -output_path "${BLENDER_OUTPUT}"
716

717
        timestamp "${UNIQUEID}, ${EVENT_ID}, ${type}, FINISHED, $NUMBER_OF_PARTICLES" >> $PROGRESS_LOG
718

719
      fi
720

721
    done
722

723 724 725 726
    ########################
    # Make mosaic 2x2 clip #
    ########################
    if [ "$MOSAIC" = "true" ]; then
727

728 729
      if ! grep -q "${UNIQUEID}, ${EVENT_ID}, MOSAIC, FINISHED" $PROGRESS_LOG; then
        pushd ${BLENDER_OUTPUT}
730

731
        timestamp "${UNIQUEID}, ${EVENT_ID}, MOSAIC, STARTING, $NUMBER_OF_PARTICLES" >> $PROGRESS_LOG
732

733 734 735
        # Delete existing incomplete .mp4 file
        if [[ -f ${EVENT_UNIQUE_ID}_Mosaic.mp4 ]]; then
          rm ${EVENT_UNIQUE_ID}_Mosaic.mp4
736
        fi
737

738
        # Setting input names for clips in order to make mosaic clip
739 740 741 742
        INPUT_ONE=*${EVENT_UNIQUE_ID}.dat*BarrelCamera*${FPS_DUR}.mp4
        INPUT_TWO=*${EVENT_UNIQUE_ID}.dat*ForwardCamera*${FPS_DUR}.mp4
        INPUT_THREE=*${EVENT_UNIQUE_ID}.dat*Moving1Camera*${FPS_DUR}.mp4
        INPUT_FOUR=*${EVENT_UNIQUE_ID}.dat*OverviewCamera*${FPS_DUR}.mp4
743 744 745 746 747 748 749 750

        ffmpeg -i ${INPUT_FOUR} -i ${INPUT_TWO} -i ${INPUT_THREE} -i ${INPUT_ONE} -filter_complex\
         "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v]"\
         -map "[v]" ${EVENT_UNIQUE_ID}_Mosaic.mp4

        timestamp "${UNIQUEID}, ${EVENT_ID}, MOSAIC, FINISHED, $NUMBER_OF_PARTICLES" >> $PROGRESS_LOG

        popd
751
      fi
752 753 754

    fi

755 756 757 758
    #######################################################
    # Move text data files to where animations are stored #
    #######################################################
    if ! grep -q "${UNIQUEID}, ${EVENT_ID}, TEXT DATA MOVED to final location" $PROGRESS_LOG; then
759

760 761 762
      # Move processed file to final location
      mv $LOCAL_FILE_WITH_DATA ${BLENDER_OUTPUT}/$LOCAL_FILE_WITH_DATA
      timestamp "${UNIQUEID}, ${EVENT_ID}, TEXT DATA MOVED to final location" >> $PROGRESS_LOG
763

764 765 766 767 768
    fi

    echo "EVENT ${EVENT_UNIQUE_ID} DONE with FILE $LOCAL_FILE_WITH_DATA."

  done
769
  popd
770

771 772 773 774 775 776 777 778 779
  ########################
  # Remove blender files #
  ########################
  if [[ $BLENDERSAVE = 0 ]]; then
    pushd ${BLENDER_OUTPUT}
    rm -f *.blend
    popd
  fi

780
fi
781
timestamp "${UNIQUEID}, JOB FINISHED" >> $PROGRESS_LOG