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

##############################
# Configurations             #
##############################
# Put aliBuild in the PATH env var
export PATH="/mnt/SSD/schnorr/python/bin:$PATH"
# Directory where runAnalysis.C is placed
export ALIROOT_SCRIPT_DIR=$(pwd)/aliRoot/
10
# Directory where Blender scripts are
11 12
export BLENDER_SCRIPT_DIR=$(pwd)/animate/
# alienv working directory
13 14
export ALIENV_WORK_DIR=/home/breno/alice/sw
export ALIENV_OS_SPEC=ubuntu1804_x86-64
15
export ALIENV_ID=AliPhysics/latest-aliroot5-user
16
# Put Blender 2.79b in the PATH env var
17 18 19
export PATH="/home/schnorr/install/blender-2.79-linux-glibc219-x86_64/:$PATH"

##############################
20
# Command-line options       #
21
##############################
22 23 24 25 26 27 28 29 30 31 32 33 34 35
# 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

36
OPTIONS=c:hdau:m:n:t:r:
37 38 39
LONGOPTS=camera:,mosaic,resolution:,fps:,transparency:,duration:,maxparticles:,\
minparticles:,numberofevents:,minavgpz:,minavgpt:,help,download,sample,url:,its,\
tpc,trd,emcal,blendersave,picpct:
40 41 42 43 44 45 46 47 48 49 50 51 52 53

# -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"

54 55 56
##############################
# Parse Parameters           #
##############################
57
CAMERA=Overview
58
MOSAIC=false
59 60
DURATION=10
RESOLUTION=100
61
FPS=24
62
TRANSPARENCY=1
63 64 65
MAX_PARTICLES=1000
MIN_PARTICLES=0
N_OF_EVENTS=10
66
MIN_AVG_PZ=0
67
MIN_AVG_PT=0
68 69
HELP=false
DOWNLOAD=false
70
SAMPLE=false
71
URL=
72 73 74 75
ITS=1 # 1 means "build this detector", while 0 means "don't"
TPC=1
TRD=1
EMCAL=1
76
BLENDERSAVE=0
77
PICPCT=80
78 79 80
# now enjoy the options in order and nicely split until we see --
while true; do
    case "$1" in
81 82 83 84 85
      -h|--help)
          HELP=true
          shift
          break
          ;;
86
      -d|--download)
87 88 89
          DOWNLOAD=true
          shift
          ;;
90
      -a|--sample)
91 92 93
          SAMPLE=true
          shift
          ;;
94 95
      -u|--url)
          URL="$2"
96 97
            shift 2
            ;;
98 99 100 101
      -m|--maxparticles)
          MAX_PARTICLES="$2"
          shift 2
          ;;
102 103 104 105 106 107 108 109
      --minparticles)
          MIN_PARTICLES="$2"
          shift 2
          ;;
      -n|--numberofevents)
          N_OF_EVENTS="$2"
          shift 2
          ;;
110 111 112 113
      --minavgpz)
          MIN_AVG_PZ="$2"
          shift 2
          ;;
114 115 116 117
      --minavgpt)
          MIN_AVG_PT="$2"
          shift 2
          ;;
118 119 120 121 122 123 124 125
      -t|--duration)
          DURATION="$2"
          shift 2
          ;;
      -r|--resolution)
          RESOLUTION="$2"
          shift 2
          ;;
126 127 128 129
      --fps)
          FPS="$2"
          shift 2
          ;;
130 131
      --transparency)
          TRANSPARENCY="$2"
132 133
          shift 2
          ;;
134
      -c|--camera)
135 136 137
      	  CAMERA="$2"
      	  shift 2
      	  ;;
138 139 140 141
      --mosaic)
          MOSAIC=true
          shift
          ;;
142 143 144 145
      --picpct)
      	  PICPCT="$2"
      	  shift 2
      	  ;;
146
      --its)
147 148 149
          ITS=0
          shift
          ;;
150
      --tpc)
151 152 153
          TPC=0
          shift
          ;;
154
      --trd)
155 156 157
          TRD=0
          shift
          ;;
158
      --emcal)
159 160 161
          EMCAL=0
          shift
          ;;
162 163 164 165
      --blendersave)
          BLENDERSAVE=1
          shift
          ;;
166 167 168 169 170
        --)
            shift
            break
            ;;
        *)
171
            echo "Programming error $*"
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            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.
194
   -m | --maxparticles VALUE
195 196
     Get only events for which its number of particles does not
     exceed VALUE.
197
   --minparticles VALUE
198 199
     Get only events for which its number of particles is greater than
     or equal to VALUE.
200
   -n | --numberofevents VALUE
201
     Set number of events to be animated inside chosen ESD file (defaults to 10)
202 203
   --minavgpz VALUE
     Get only events for which its absolute value of average momentum in
204 205
     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.
206 207
   --minavgpt VALUE
     Get only events for which its average transversal momentum is
208 209
     greater than or equal to VALUE, in GeV/c. Useful for animating
     events with 'boosts' of particles on the xy plane.
210 211 212
   -t | --duration VALUE
     Set the animation duration in seconds.
   -r | --resolution VALUE
213 214
     Set the animation resolution percentage, where
     VALUE must be an integer from 1 to 100.
215 216
   --fps VALUE
     Set number of frames per second in animation.
217 218 219
   --transparency VALUE
     Set detector transparency as a number greater than zero,
     where zero is full transparency and 1 is standard transparency
220 221 222
   -c | --camera VALUE
     Which camera to use for the animation, where VALUE
     is a comma-separated list (without spaces)
223
     Options: Barrel,Forward,Overview,AntiOverview (defaults to Overview)
224 225 226 227
   --mosaic
     Make animations in all four available cameras and combine them into
     a single 2x2 clip containing all perspectives, totalizing five generated
     .mp4 videos.
228
   --picpct VALUE
229 230
     Percentage of animation to take HD picture, saved along with the clip,
     where VALUE must be an integer
231
   -a | --sample
232
     Creates a sample Blender animation of Event 2 from URL
233 234
     http://opendata.cern.ch/record/1102/files/assets/alice/2010/LHC10h/000139\
038/ESD/0001/AliESDs.root
235
   --its
236
     Removes ITS detector from animation
237
   --tpc
238
     Removes TPC detector from animation
239
   --trd
240
     Removes TRD detector from animation
241
   --emcal
242
     Removes EMCal detector from animation
243 244
   --blendersave
     Saves Blender file along with animation clip
245 246 247

Example:
--------
248 249
$0 --url http://opendata.cern.ch/record/1103/files/assets/alice/2010/LHC10h/000\
139173/ESD/0004/AliESDs.root --download
250 251 252

END
}
253

254 255 256 257 258
# Fix CAMERA to be accepted by the for loop
if [[ $CAMERA != "" ]]; then
    CAMERA=$(echo $CAMERA | sed -e 's#,#Camera #g' -e 's#$#Camera#')
fi

259 260 261 262
if [[ $MOSAIC == "true" ]]; then
    CAMERA=$(echo "OverviewCamera BarrelCamera AntiOverviewCamera ForwardCamera")
fi

263 264 265 266 267 268 269
if [[ $HELP = "true" ]]; then
    usage
    exit
else
    echo "-------- Parsed parameters --------"
    echo "URL: $URL"
    echo "Download: $DOWNLOAD"
270
    echo "Sample: $SAMPLE"
271
    echo "Transparency Parameter: $TRANSPARENCY"
272 273
    echo "Duration: $DURATION"
    echo "Resolution: $RESOLUTION"
274
    echo "FPS: $FPS"
275
    echo "Max particles: ${MAX_PARTICLES}"
276 277
    echo "Min particles: ${MIN_PARTICLES}"
    echo "Number of events: ${N_OF_EVENTS}"
278
    echo "Min Average Z Momentum: ${MIN_AVG_PZ}"
279
    echo "Min Average Transversal Momentum: ${MIN_AVG_PT}"
280
    echo "Camera: $CAMERA"
281
    echo "Mosaic: $MOSAIC"
282
    echo "Picture Percentage: ${PICPCT}%"
283
    echo "-----------------------------------"
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    echo "------------ Detectors ------------"
    if [[ $ITS = 1 ]]; then
      echo "Building ITS"
    fi
    if [[ $TPC = 1 ]]; then
      echo "Building TPC"
    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 "-----------------------------------"

302 303
fi

304 305 306 307 308 309 310
# 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

311 312 313 314
##############################
# Download Dataset           #
##############################
if [ "$DOWNLOAD" = "true" ]; then
315
    if [ -z $URL ]; then
316
        echo "Error. Must pass the dataset URL in order to download ESD file."
317 318 319
        usage
        exit
    fi
320 321 322
    echo "Downloading data."
    wget $URL

323 324 325 326 327 328 329 330 331 332 333 334
    ######################################
    # 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
335

336
##############################
337
# Sample synthetic animation#
338
##############################
339
if [ "$SAMPLE" = "true" ]; then
340
    ##############################
341
    # Phase 1: Blender animate   #
342 343
    ##############################
    pushd ${BLENDER_SCRIPT_DIR}
344
    for type in $CAMERA; do
345
      echo "Preparing sample animation with $type in Blender"
346 347 348 349 350
      blender -noaudio --background -P animate_particles.py -- -radius=0.05 \
      -duration=${DURATION} -camera=${type} -datafile="d-esd-detail.dat" -simulated_t=0.03\
      -fps=${FPS} -resolution=${RESOLUTION} -transparency=${TRANSPARENCY} -stamp_note=\
      "opendata.cern.ch_record_1102_alice_2010_LHC10h_000139038_ESD_0001_2" -its=${ITS} \
      -tpc=${TPC} -trd=${TRD} -emcal=${EMCAL} -blendersave=${BLENDERSAVE} -picpct=5
351
    done
352
    popd
353
    BLENDER_OUTPUT=.
354
    mkdir --verbose -p ${BLENDER_OUTPUT}
355
    mv --verbose /tmp/alice_blender ${BLENDER_OUTPUT}
356 357
    echo "Done."

358 359 360
##############################
# Animation from file        #
##############################
361
elif [ "$SAMPLE" = "false" ]; then
362

363
  # Verify if AliESDs.root is here
364 365 366
  ALIESD_ROOT_FILE=$(pwd)/AliESDs.root
  if ! [[ -f "$ALIESD_ROOT_FILE" ]]
  then
Lucas Mello Schnorr's avatar
Lucas Mello Schnorr committed
367 368
      echo "AliESDs.root not found."
      exit
369 370
  fi

371 372 373
  ############################
  # Phase 1: aliroot extract #
  ############################
374
  eval $(alienv -w ${ALIENV_WORK_DIR} -a ${ALIENV_OS_SPEC} load ${ALIENV_ID})
375
  pushd ${ALIROOT_SCRIPT_DIR}
376
  # Remove existing symbolic link
377
  rm -f --verbose AliESDs.root
378 379 380
  # Create a symbolic link to the actual AliESDs.root
  ln --verbose -s ${ALIESD_ROOT_FILE} AliESDs.root
  # Run the extraction tool
381
  aliroot runAnalysis.C
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396
  if [ "$DOWNLOAD" = "false" ]; then

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

  fi

  # Create directory where animations will be saved
  popd
  BLENDER_OUTPUT=$(pwd)/$UNIQUEID
  mkdir --verbose -p ${BLENDER_OUTPUT}
  pushd ${ALIROOT_SCRIPT_DIR} # push back to aliroot directory

397 398 399
  #################################################
  # Phase 1: iteration for every event identifier #
  #################################################
400

401 402 403
  # Event counter for animating no more events than the informed amount
  EVENT_COUNTER=0

404 405 406 407
  # Get all extracted files
  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 | \
408 409
                 sed -e "s#esd_detail-event_##" \
                   -e "s#\.dat##")
410 411
      EVENT_UNIQUE_ID=${UNIQUEID}_${EVENT_ID}

412
      if ! [[ -s $FILE_WITH_DATA ]]; then
413
          echo "File $FILE_WITH_DATA has zero size. Ignore and continue."
414
	        rm $FILE_WITH_DATA
415
          continue
416
      fi
417

418 419 420
      ##############################
      # Phase 2: blender animate   #
      ##############################
421 422 423

      LOCAL_FILE_WITH_DATA=${EVENT_UNIQUE_ID}.dat
      cp ${ALIROOT_SCRIPT_DIR}/$FILE_WITH_DATA \
424 425
       ${BLENDER_SCRIPT_DIR}/${LOCAL_FILE_WITH_DATA}

426 427
      rm $FILE_WITH_DATA

428 429
      NUMBER_OF_PARTICLES=$(wc -l ${BLENDER_SCRIPT_DIR}/$LOCAL_FILE_WITH_DATA | \
                        awk '{ print $1 }')
430

431 432
      AVERAGE_PZ=$(awk 'BEGIN {pzsum=0;n=0} {pzsum+=$8;n++} END {print sqrt(pzsum*pzsum/n/n)}'\
      ${BLENDER_SCRIPT_DIR}/${LOCAL_FILE_WITH_DATA})
433

434 435
      AVERAGE_PT=$(awk 'BEGIN {ptsum=0;n=0} {ptsum+=$9;n++} END {print ptsum/n}' \
      ${BLENDER_SCRIPT_DIR}/${LOCAL_FILE_WITH_DATA})
436

437 438 439
      echo "File $LOCAL_FILE_WITH_DATA has $NUMBER_OF_PARTICLES particles."
      echo "Average Z momentum: $AVERAGE_PZ"
      echo "Average transversal momentum $AVERAGE_PT"
440

441 442
      if (( $(echo "$AVERAGE_PT >= $MIN_AVG_PT" |bc -l) )); then
        if (( $(echo "$AVERAGE_PZ >= $MIN_AVG_PZ" |bc -l) )); then
443 444
          if [[ $NUMBER_OF_PARTICLES -le $MAX_PARTICLES && $NUMBER_OF_PARTICLES \
-ge $MIN_PARTICLES && $EVENT_COUNTER -lt $N_OF_EVENTS ]]; then
445

446 447
            # Increment event counter
            EVENT_COUNTER=$EVENT_COUNTER+1
448

449
            echo "Processing ${EVENT_UNIQUE_ID} ($NUMBER_OF_PARTICLES tracks) in Blender"
450

451
            pushd ${BLENDER_SCRIPT_DIR}
452

453 454
            for type in $CAMERA; do
                  echo "Processing ${EVENT_UNIQUE_ID} with $type in Blender"
455

456 457 458 459 460
                  blender -noaudio --background -P animate_particles.py -- -radius=0.05 \
                  -duration=${DURATION} -camera=${type} -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} -blendersave=${BLENDERSAVE} -picpct=${PICPCT}
461 462
                  echo "${type} for event ${EVENT_UNIQUE_ID} done."
            done
463

464 465 466 467 468 469 470 471 472 473 474 475 476 477
            if [ "$MOSAIC" = "true" ]; then

              popd
              pushd /tmp/alice_blender

              # Move animation images to final location
              mv /tmp/alice_blender/*.png ${BLENDER_OUTPUT}

              # Setting input names for clips in order to make mosaic clip
              INPUT_ONE=$(ls | awk 'NR==1')
              INPUT_TWO=$(ls | awk 'NR==2')
              INPUT_THREE=$(ls | awk 'NR==3')
              INPUT_FOUR=$(ls | awk 'NR==4')

478 479 480
              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
481 482 483 484 485 486 487 488 489

              popd
              pushd ${BLENDER_SCRIPT_DIR}

            fi

            # Move generated clips to final location
            mv /tmp/alice_blender/* ${BLENDER_OUTPUT}

490 491
            # Move processed file to final location
            mv $LOCAL_FILE_WITH_DATA ${BLENDER_OUTPUT}/$LOCAL_FILE_WITH_DATA
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
            popd
            echo "EVENT ${EVENT_UNIQUE_ID} DONE with FILE $LOCAL_FILE_WITH_DATA."
          else

            if [[ $NUMBER_OF_PARTICLES -lt $MIN_PARTICLES ]]; then
              echo "Too little particles (minimum accepted is $MIN_PARTICLES). Continue."
            elif [[ $NUMBER_OF_PARTICLES -gt $MAX_PARTICLES ]]; then
              echo "Too many particles (maximum accepted is $MAX_PARTICLES). Continue."
            elif [[ $EVENT_COUNTER -ge $N_OF_EVENTS ]]; then
              echo "Numbers of events set to be animated has already been reached. Continue."
            fi

            # Remove non-processed files
            pushd ${BLENDER_SCRIPT_DIR}
            rm $LOCAL_FILE_WITH_DATA
            popd

            continue
511
          fi
512 513
        else
          echo "Average Z Momentum too low (minimum accepted is $MIN_AVG_PZ). Continue."
514

515 516 517 518 519 520
          # Remove non-processed files
          pushd ${BLENDER_SCRIPT_DIR}
          rm $LOCAL_FILE_WITH_DATA
          popd
        fi
      else
521
        echo "Average Transversal Momentum too low (minimum accepted is $MIN_AVG_PT). Continue."
522 523 524 525 526

        # Remove non-processed files
        pushd ${BLENDER_SCRIPT_DIR}
        rm $LOCAL_FILE_WITH_DATA
        popd
527
      fi
Lucas Mello Schnorr's avatar
Lucas Mello Schnorr committed
528
  done
529
  popd
530

531
fi