
; Copyright 2015 ANSYS Inc. All rights reserved.


;;(display "\nScheme setup for FLUX.\n\n")

(set! *cx-overwrite-prompt?* #f)
(set! *cx-disclaimer* "")

(define (open-udf-libraries)
    (rpsetvar 'udf/init-fcns '())
    (rpsetvar 'udf/adjust-fcns '())
    (rpsetvar 'udf/execute-at-end-fcns '())
    (rpsetvar 'udf/read-case-fcns '())
    (rpsetvar 'udf/write-case-fcns '())
    (rpsetvar 'udf/read-data-fcns '())
    (rpsetvar 'udf/write-data-fcns '())
    )

(define (rename-thread old-name new-name)
  (send (get-thread old-name) set-var! 'name new-name)
  )

(define (update-thread-solver-vars thread)
  (send (get-thread thread) update-solver-vars!)
  )

(define (set-thread-type-and-update thread type)
  (let ((thread-id (thread-id thread)))
    (set-thread-type! thread type)
    (send (get-thread thread-id) update-solver-vars!)
    )
  )

(define (upload-graphics-manager)
  (send graphics-manager upload-objects)
  )


(set! inquire-material-names
    (lambda type
       (filter
           (lambda (x) (not (pair? x)))
             (apply inquire-material-names-all type)))
    )

; AFD specific create-si function
; can be removed once create-si supports zone ids as inputs as well
(define afd-create-si
  (lambda (name zone1 zone2 param-list)
    (let ((sis (rpgetvar 'sliding-interfaces)))
      (rpsetvar 'sliding-interfaces (cons (create-si name (map get-thread zone1) (map get-thread zone2) param-list) sis))
      )))

;; Whether all materials of all threads are defined
(define (all-thread-materials-defined?)
  (and (get-all-materials)
       (begin
         ;;  whether materials defined for a thread
         (define (materials-defined-for-thread? thread)
           (let ((mat (send thread get-var 'material)))
             (cond
               ((not mat) #f)
               ((not (pair? mat))
                (get-material mat))
               (else
                 (let loop ((remaining (if (pair? mat) mat (list mat))))
                   (if (null? remaining)
                     #t
                     (and (get-material (car remaining))
                          (loop (cdr remaining))))
                   )))))
         (let loop ((remaining (get-cell-threads)))
           (if (null? remaining)
             #t
             (and (materials-defined-for-thread? (car remaining))
                  (loop (cdr remaining))))
           )
         )
       ))

(define (get-zone-type id)
  (let ((thread (%get-thread-by-id id)))
    (if thread (send thread thread-type) #f)
    )
  )

(define (get-zone-name id)
  (let ((thread (%get-thread-by-id id)))
    (if thread (send thread thread-name) #f)
    )
  )

(define (get-zone-id name)
  (let ((thread (%get-thread-by-name name)))
    (if thread (send thread thread-id) #f)
    )
  )

(define (get-zone-thread-vars id)
  (send (%get-thread-by-id id) get-thread-vars)
  )

(define (get-all-zone-vars)
  (map (lambda (t)
         (cons (thread-id t) (list (send t get-thread-vars ))))
         (get-all-threads)))

(define (get-all-thread-ids)
  (map thread-id (get-all-threads))
  )

(define (get-zone-id-name-map)
  (map (lambda (t) (cons (thread-id t) (symbol->string (send t thread-name))))
     (get-all-threads))
     )

(define (get-zone-id-type-map)
  (map (lambda (t) (cons (thread-id t) (symbol->string (send t thread-type))))
     (get-all-threads))
     )

(define (get-cell-thread-ids)
  (map thread-id (get-cell-threads))
  )

(define (get-face-thread-ids)
  (map thread-id (get-face-threads))
  )

(define (get-boundary-thread-ids)
  (map thread-id (get-boundary-threads))
  )

(define (get-interior-thread-ids)
  (map thread-id (get-surface-interior-threads))
  )

(define (get-surface-interior-threads)
  (let loop ((tl (get-threads-of-type 'interior))
            (itl '()))
    (if (null? tl)
      itl
      (let* ((id (thread-id (car tl)))
             (adjacent-threads (inquire-adjacent-threads id))
             (id0 (car adjacent-threads))
             (id1 (cadr adjacent-threads)))
        (if (not(equal? id0 id1))
          (loop (cdr tl) (cons (car tl) itl))
          (loop (cdr tl) itl)
          )
        )
      )
    )
  )

(define (get-boundary-and-surface-interior-threads)
  (append (get-boundary-threads) (get-surface-interior-threads))
  )

(define (set-zone-thread-vars id zonevars update?)
  (let ((thread (%get-thread-by-id id)))
    (if thread (send thread set-thread-vars zonevars))
    (bcs-changed)
    (if thread (if update? (send thread update-solver-vars!)))
    )
  )

(define (set-zone-type! id type)
  (let ((thread (%get-thread-by-id id)))
    (if thread
      (let ((old-type (thread-type thread))
            (old-name (send thread thread-name)))

        (if (not (eq? type old-type))
          (if (eq? old-type 'periodic)
            (let ((new-t (slit-periodic id)))
              (list (cons "added" (list (list (thread-id new-t))))))
            (let ((was-interior (memq old-type '(interior radiator fan porous-jump)))
                  (shadow (and (send thread boundary-face-thread?) (caddr (inquire-adjacent-threads id)))))
              (send thread set-thread-type! type)
              (let ((thread (%get-thread-by-id id)))
                (send thread update-solver-vars!)
                ;;in case set-thread-type renames the thread:
                (send thread set-var! 'name old-name)
                (if (and was-interior (eq? type 'wall))
                  (list (cons "added"  (list (list (caddr (inquire-adjacent-threads id))))))
                  (if (and shadow (memq type '(interior radiator fan porous-jump)))
                    (list (cons "deleted"  (list (list shadow))))
                    (list)))
                )
              )
            )
          (list)
          )
        )
      (begin
        (format "Zone ~a does not exist!"  id)
        (list)
        )
      )
    )
  )

;; Call (models-changed) only if thread materials are defined, as otherwise
;; queries such as ideal-gas? will fail on the thread
(define models-changed
  (let ((old-models-changed models-changed))
    (lambda ()
      (if (all-thread-materials-defined?)
        (begin
          (set! reading-case-file and)
          (update-species-variable-lengths)
          (old-models-changed)
          )
        )
      )
    )
  )

(define (clear-settings-except-surface)
  (cx-save-case-state)
  (let ((state (cx-show-state))
        (surface-list (list->vector (vector->list (cxgetvar 'cx-surface-list))))
        )
    (clear-settings)
    (prf-update-all-rpvars)
    (copy-database-material 'air (get-database-material-copy 'air 'fluid))
    (copy-database-material 'aluminum (get-database-material-copy 'aluminum 'solid))
    (set-domain-material! 1 'air)
    (if (pair? state)
      (begin
        (cx-set-state state)
        (cxsetvar 'cx-surface-list surface-list)
        (cx-set-surface-lists)
        )
    )))

(define set/unset-pseudo-transient-settings and)

(define (copy-move-solid-from-fluid fluid-id)
  (let ((dual-id))
  (copy-move-cell-thread fluid-id #t (list 0.0 0.0 0.0) () 0.0)
  (set! dual-id (inquire-dual-zone-id fluid-id))
  (set-thread-type! (get-thread dual-id) 'solid)
  ))

(define client-fill-node-and-face-values
  (lambda (what)
    (client-fill-node-values what)
    (for-each
      (lambda (thread)
        (fill-face-thread-values (thread-id thread) what)
        )
      (get-boundary-and-surface-interior-threads))
    )
  )

;; AFD specific iterate function
(define (afd-iterate ncyc)
  (update-mixing-planes)
  (%update-dynamic-profiles)
  (%iterate ncyc)
  (%solver-statistics)
  (if (and (>= (%iterate 0) 1)
           (eq? (rpgetvar 'flow/solve?) #t)
           (not (eqv? (rpgetvar 'pressure/flow-init-type) 0))
           )
    (begin
      (rpsetvar 'pressure/flow-init-type 0)
      ))

  )

;; redefine function for core mode to handle Solution Steering detection
;; and relevant FMG initialization
(let ((old-iterate iterate))
  (set! iterate
    (lambda args
      (if (and (rp-amg?) (not (rp-unsteady?)) (rpgetvar 'cpld/sol-steering?))
        (begin
          (if (rpgetvar 'cpld/sol-steering/fmg-init-needed?)
            (fmg-initialize))))
      (let ((ret (apply old-iterate args)))
        ret)
      )
    )
  )

;; refactored get-residual-settings function from clres.scm
;; used for getting synced residual settings since rpvar residuals/settings
;; may not contain the latest value
(define (get-residual-settings)
  (if (%grid-valid?)
      (let ((settings (client-get-var 'residuals/settings)))
        (if settings
          ;; Add missing settings in same order as (solver-residuals)
          ;; ;; result.  This is required because many of the monitoring
          ;; ;; functions assume the same ordering for efficiency.
          (map
            (lambda (r)
              (let ((s (assq r settings)))
                (if s
                  (if (= 7 (length s))
                    s
                    (append s
                            (list
                              (list-ref (residual-default-setting r) 5)
                              (list-ref (residual-default-setting r) 6))))
                  (residual-default-setting r))))
            (map car (solver-residuals)))
          ;; List not set yet... build from scratch.
          (map residual-default-setting
               (map car (solver-residuals)))
          ))
      ())
  )

(rpsetvar 'reorder/thread/at-mesh-read? #t)
(set! *main-menu* main-menu)
(set! check-append-cfd-post-mesh-info and)

(let ((old-crc client-read-case))
  (set! client-read-case
    (lambda args
      (rpsetvar 'partition/auto/method "Metis")
      (rpsetvar 'parallel/separate-and-order 0)
      (use-default-auto-partition)
      (let ((ret (apply old-crc args)))
        ; work around a minor issue in FLUENT:
        (rpsetvar 'statistics/plot? #f)
        (species-var-length-compat)
        ret)
      )
    )
  )

;; handle compatibility for old format of species vars
(define species-var-length-compat
  (lambda ()
    (for-each
      (lambda (did)
        (for-each
          (lambda (var)
            (let* ((var-name (string->symbol (string-append "species/" var)))
                   (var-value (domaingetvar did var-name)))
              (if (and (not (pair? var-value)) (not (null? var-value)))
                (domainsetvar did  var-name (list var-value)))
              )
            )
            (list "solve?" "relax" "scheme" "cycle-type" "amg-alpha" "amg-beta"
                  "patch" "default" "amg-method" "amg-stabilization"
                  "max-iter" "iter-tolerance" "residual-tolerance"
                  "pseudo-specific?" "pseudo-implicit-relax" "pseudo-time-scale-factor"
                  "explicit-relax" "pseudo-relax")))
      (map domain-id (append (get-geom-domains) (get-phase-domains))))))

(define (update-before-mesh-read . args)
  (init-par-settings)
  (clear-settings)
  (init-case-settings)
  (%clear-grid (if (pair? args) (car args) #t))
  )

(define (update-after-mesh-read)
  ;; initial rpvars and configuration
  (rpsetvar 'parallel/separate-and-order 0)
  (prf-update-all-rpvars)

  (newline)
  (display "  Building...")
  (newline)
  (display "     mesh")
  ;; partition
  (auto-partition)
  ;; building of grid
  (%build-grid)

  (newline)
  (display "     materials,")
  (create-case-materials)

  (newline)
  (display "     domains,")
  (create-case-domains)

  (newline)
  (display "     zones,")
  (create-case-threads)

  (err-protect (slit-all-two-sided-walls))

  (cx-set-surface-type-all)
  (cx-suspend-all-surfaces)

  (newline)
  (display "     parallel,")
  (clear-flow-timer)
  (init-timer-history)
  (clear-data-timer)

  (err-protect (load-morpher))
  (cx-set-case-defaults)
  (dpm-parameters-changed)

  (%set-case-valid #t)
  )

(define (update-after-nc-metric-read)
  (newline)
  (display "  Done.")
  (newline)
  (%save-case-id)
  (save-cortex-case-id)
  (%save-casefile-grid-id)
  )

(define (resume-si-settings si-name zone1 zone2 item-list)
  (let ((new-si (make-si-settings si-name
                                  (map %get-thread-by-id zone1)
                                  (map %get-thread-by-id zone2)
                                  item-list)))
    (si-compat)
    (%mesh-interface-init-node-visit)
    (build-si-grids new-si #f)
    (%mesh-interface-free-node-visit)
    (create-si-threads new-si)
    (rpsetvar 'sliding-interfaces (append (rpgetvar 'sliding-interfaces) (list new-si)))
    new-si)
  )

(define (afd-convert-polyhedra)
  (if (and (rp-3d?)
           (%grid-valid?))
    (begin
      (setup-recommended-polyhedra-conversion #t)
      (if (and (all-polyhedra-possible?)
               (set-dual-conversion-feature-angle))
        (if (create-dual #t #f #f)
          (begin
            (newline)
            (display "Finished conversion to polyhedra.")
            (newline)
            #t)
          #f)
        (begin
          (newline)
          (display "Skipped conversion to polyhedra.")
          (newline)
          #t)))
    #t)
  )

;;;;;;;;;; Fluent message control ;;;;;;;;;;;;

(define set-scheme-message-status)
(define enable-scheme-output)
(define disable-scheme-output)

(let* ((flmsg? #f)
       (old-output-port *current-output-port*)
       (file (if (nt?) "Nul" "/dev/null"))
       (port (if (%is-writable? file) (open-file file "w+") #f))
       )

  (set! set-scheme-message-status
    (lambda (value)
      (set! flmsg? value))
    )

  (set! disable-scheme-output
    (lambda ()
      (if (and port (not flmsg?))
        (set! *current-output-port* port)
        ))
    )

  (set! enable-scheme-output
    (lambda()
      (set! *current-output-port* old-output-port))
    )
)
