Пример #1
0
def crawl_article(url):
  domain = html_helper.url_parse(url)
  html = html_helper.get_html_content(url)
  content = html_helper.extra_content(html)
  file.create_file(content['title'], content['content'])
  return {
      "slug": content['next_link'],
      "url": domain + content['next_link']
  }
def main():
    """
    1. random 產生 high dimension data
    2. create_dis_sigmas_prob
    3. create_p_q
    4. gradient descent(without momentum)
    """
    dir_name = "File"

    label = np.zeros(200)
    '''
    #  step 1 & step 2
    # '''
    raw_high_file_name = "high.json"
    file.create_file(raw_high_file_name, dir_name)
    rewrite = True
    if rewrite:
        raw_high_data = np.random.randint(100, size=(50, 5))
        file.write_json(file.numpy_array_to_list(raw_high_data),
                        raw_high_file_name, dir_name)
    high_data = file.list_to_numpy_array(
        file.read_json(raw_high_file_name, dir_name))
    print(high_data)
    tsne = TSNE(label, high_data, dir_name)

    tsne.create_dis_sigmas_prob()
    '''
    #  step 3
    '''
    # high_dim_vectors = file.list_to_numpy_array(file.read_json("high.json", dir_name))
    # dis = file.list_to_numpy_array(file.read_json("dis.json", dir_name))
    # sigmas = file.list_to_numpy_array(file.read_json("sigmas.json", dir_name))
    # prob = file.list_to_numpy_array(file.read_json("prob.json", dir_name))
    #
    # dis_df = pd.DataFrame(dis)
    # prob_df = pd.DataFrame(prob)
    # sigmas_df = pd.DataFrame(sigmas)
    #
    # tsne = TSNE(label, high_dim_vectors,dir_name)
    # tsne.fromfile(dis,prob,sigmas)
    # tsne.create_p()
    '''
    def create_dis_sigmas_prob(self):
        self.calculate_dis()
        self.find_sigmas()
        for i in range(self.n):
            self.calculate_row_prob(i)

        dis_df = pd.DataFrame(self.dis)
        prob_df = pd.DataFrame(self.prob)
        sigmas_df = pd.DataFrame(self.sigmas)

        prob_file_name = "prob.json"
        dir_name = self.dir_name
        file.create_file(prob_file_name, dir_name)
        file.write_json(file.numpy_array_to_list(self.prob), prob_file_name,
                        dir_name)

        dis_file_name = "dis.json"
        dir_name = self.dir_name
        file.create_file(dis_file_name, dir_name)
        file.write_json(file.numpy_array_to_list(self.dis), dis_file_name,
                        dir_name)

        sigmas_file_name = "sigmas.json"
        dir_name = self.dir_name
        file.create_file(sigmas_file_name, dir_name)
        file.write_json(file.numpy_array_to_list(self.sigmas),
                        sigmas_file_name, dir_name)
Пример #4
0
def handle_files():
    if request.method == 'POST':
        file = request.files['file']
        # validate assets type
        if file is None:
            return json.jumps({'code': -2, 'msg': 'Missing uploaded assets.'})
        try:
            file_id = create_file(file)
            print('ok')
            return json.dumps({'code': 0, 'data': file_id})
        except ValueError as e:
            print(str(e))
            return json.dumps({'code': -1, 'msg': str(e)})
    else:
        file_id = request.data.decode('utf-8')
        if file_id is None or file_id == '':
            return json.dumps({'code': -1, 'msg': 'Missing assets id.'})
        remove_file(file_id)
        return json.dumps({'code': 0, 'data': file_id})
def run_on_video(video_path, output_video_name, conf_thresh):
    cap = cv2.VideoCapture(video_path,cv2.CAP_DSHOW)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    fps = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    # writer = cv2.VideoWriter(output_video_name, fourcc, int(fps), (int(width), int(height)))
    total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    if not cap.isOpened():
        raise ValueError("Video open failed.")
    status = True
    idx = 0
    while status:
        start_stamp = time.time()
        status, img_raw = cap.read()
        img_raw = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
        read_frame_stamp = time.time()
        if (status):
            inference(img_raw,
                      conf_thresh,
                      iou_thresh=0.5,
                      target_shape=(260, 260),
                      draw_result=True,
                      show_result=False)
            cv2.imshow('image', img_raw[:, :, ::-1])
            k = cv2.waitKey(10)
            inference_stamp = time.time()
            # writer.write(img_raw)
            write_frame_stamp = time.time()
            idx += 1
            global i
            #print("%d of %d" % (idx, total_frames))
            if k ==ord('p'):
                
                create()#创建数据库
                
                time_now,the_path = create_file()
                cv2.imwrite(str(the_path)+'/'+'demo'+str(i) + '.jpg', img_raw[:, :, ::-1])
                print(time_now[11:])
                #os.renames('./time/'+time_now[0:10]+'/demo.jpg','./time/'+time_now[0:10]+'/'+time_now[11:]+'.jpg')
                #cv2.imwrite('D:/picture/' + time_now[11:-1] +'.jpg', img_raw[:, :, ::-1])
                #print(str(the_path)+'/'+str(time_now[11:21])+str(i)+'.jpg')
                i += 1
                print(i)
                print("successfully capture!")
                
                store(flag)
                
                f = open('record.txt', 'a')
                if flag ==1:
                    f.write( '时间:  ' + time_now + '   识别结果:未佩戴口罩 ' + '\n')
                    print("未佩戴口罩")
                if flag ==0:
                    f.write( '时间:  ' + time_now + '    识别结果:已佩戴口罩 ' + '\n')
                    print("已佩戴口罩")
                if flag == -1:
                    f.write( '时间:  ' + time_now + '    识别结果: 未识别到人像' + '\n')
                    print("未识别到人像")
                f.close
            if k ==ord('o'):
                print("over")
                cap.release()
                cv2.destroyAllWindows()
                return
def run_on_video(video_path, output_video_name, conf_thresh):
    cap = cv2.VideoCapture(video_path, cv2.CAP_DSHOW)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    fps = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    if not cap.isOpened():
        raise ValueError("Video open failed.")
    status = True
    idx = 0
    while status:
        start_stamp = time.time()
        status, img_raw = cap.read()
        img_raw = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
        read_frame_stamp = time.time()
        if (status):
            inference(img_raw,
                      conf_thresh,
                      iou_thresh=0.5,
                      target_shape=(260, 260),
                      draw_result=True,
                      show_result=False)
            cv2.imshow('image', img_raw[:, :, ::-1])

            k = cv2.waitKey(10)
            inference_stamp = time.time()
            write_frame_stamp = time.time()
            idx += 1
            global i
            if k == ord('p'):

                db.create()  #创建数据库

                time_now, the_path = create_file()
                cv2.imwrite(
                    str(the_path) + '/' + 'demo' + str(i) + '.jpg',
                    img_raw[:, :, ::-1])
                #print("现在时间:" + time_now[11:])
                print("成功捕获第{}张图像!".format(i + 1))
                isHelmet = hg.classifier(
                    str(the_path) + '/' + 'demo' + str(i) + '.jpg')
                flag = isHelmet
                db.store(flag, time_now)
                #mysql.store(flag,time_now)
                i += 1
                f = open('record.txt', 'a')
                if flag == 1:
                    f.write('时间:  ' + time_now + '   识别结果:未佩戴安全帽 ' + '\n')
                    print("未佩戴安全帽")
                if flag == 0:
                    f.write('时间:  ' + time_now + '    识别结果:已佩戴安全帽 ' + '\n')
                    print("已佩戴安全帽")
                if flag == -1:
                    f.write('时间:  ' + time_now + '    识别结果: 未识别到人像' + '\n')
                    print("未识别到人像")

                matching.matching(i, the_path)
                #匹配
            if k == ord('o'):
                print("over")
                cap.release()
                cv2.destroyAllWindows()
                return
Пример #7
0
def check(pluto_dir, get_arch):

    work_dir = os.getcwd()
    print ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
    print ("\n>> Inspecting system configuration << \n")

    # log_file     = pluto_dir+'/system.conf'
    log_file = work_dir + "/sysconf.out"
    config_dir = pluto_dir + "/Config/"
    python_dir = pluto_dir + "/Tools/Python"
    bintools_dir = pluto_dir + "/Tools/bin_tools"
    param_file = pluto_dir + "/Src/pluto.h"

    os.chdir(python_dir)
    log = []

    #  ---------------------
    #    get user name
    #  ---------------------

    try:
        user = os.getlogin()
    except OSError:
        user = "******"

    #  ---------------------
    #    get system spec.
    #  ---------------------

    PLATFORM = os.uname()

    #  ---------------------
    #   find current
    #   version of PLUTO
    #  ---------------------

    scrh = file.word_find(param_file, "PLUTO_VERSION")
    ipos = scrh[0]
    scrh = file.read_lines(param_file, ipos, ipos + 1)
    vers = string.split(scrh[0])
    vers = vers[2]

    # ------------------------------
    #  print a short system summary
    # ------------------------------

    print "User.......................", user
    print "System name................", PLATFORM[0]
    print "Node name..................", PLATFORM[1]
    print "Release....................", PLATFORM[2]
    print "Arch.......................", PLATFORM[4]
    print "Byteorder..................", sys.byteorder
    print "Version....................", PLATFORM[3]
    print "Working_dir................", work_dir
    print "PLUTO main dir.............", pluto_dir
    print "PLUTO version..............", vers

    # --------------------------------------
    #  Check for gcc or another c compiler
    # --------------------------------------

    compiler_list = ["gcc", "cc", "gcc2"]
    COMPILER_NAME = ""

    for x in compiler_list:
        if CHECK_FOR(x) == "YES":
            print "C Compiler................. " + x
            COMPILER_NAME = x
            break

    if COMPILER_NAME == "":
        print "! Can not find a C compiler       !"

    # -----------------
    #  check for mpi
    # -----------------

    mpi_compiler_list = ["mpicc", "mpiCC", "mpcc_r", "hcc", "mpcc"]
    MPI_COMPILER_NAME = ""

    for x in mpi_compiler_list:
        if CHECK_FOR(x) == "YES":
            print "MPI Compiler .............. " + x
            MPI_COMPILER_NAME = x
            break

    if MPI_COMPILER_NAME == "":
        print "MPI Compiler............... NOT FOUND"

    if get_arch:
        print "\n"
        print "Proposed makefile names: \n"
        print "> " + PLATFORM[0] + "." + PLATFORM[4] + "." + COMPILER_NAME + ".defs"
        print "> " + PLATFORM[0] + "." + PLATFORM[4] + "." + MPI_COMPILER_NAME + ".defs"
        return

    # ---------------------------------------------------
    #  Build log list, that will be compared to the
    #  sysconf.out file.
    # ---------------------------------------------------

    log.append("USER           = "******"\n")
    log.append("WORKING_DIR    = " + work_dir + "\n")
    log.append("SYSTEM_NAME    = " + PLATFORM[0] + "\n")
    log.append("NODE_NAME      = " + PLATFORM[1] + "\n")
    log.append("RELEASE        = " + PLATFORM[2] + "\n")
    log.append("ARCH           = " + PLATFORM[4] + "\n")
    log.append("BYTE_ORDER     = " + sys.byteorder + "\n")
    log.append("VERSION        = " + PLATFORM[3] + "\n")
    log.append("PLUTO_DIR      = " + pluto_dir + "\n")
    log.append("PLUTO_VERSION  = " + vers + "\n")
    log.append("C_COMPILER     = " + COMPILER_NAME + "\n")
    log.append("MPI_C_COMPILER = " + MPI_COMPILER_NAME + "\n")

    #  ----------------------------
    #    check for online updates
    #  ----------------------------

    print "\n> Checking for updates (canceled)...\n"
    # try:
    #   urllib.urlretrieve("http://plutocode.ph.unito.it/updates.txt","updates.txt")
    #   scrh = file.word_find ("updates.txt","release")
    #   ipos = scrh[0]
    #   scrh = file.read_lines ("updates.txt", ipos, ipos + 1)
    #   rels = string.split(scrh[0])
    #   if (rels[1] != vers):
    #     print "   ******************************************************* "
    #     print "    A new version of PLUTO ("+rels[1]+") is available at"
    #     print "    http://plutocode.oato.inaf.it"
    #     print "   *******************************************************\n"
    #     scrh = raw_input("> Press enter to continue.")
    #     os.chdir(work_dir)
    # except:
    #   print "! Connection not available\n"

    # ------------------------------------------------
    #  Compare the list 'log' with the file log_file;
    #
    #   - if they match, no update is necessary,
    #               ==> return to main menu
    #
    #   - if they do not match or if log_file does not
    #     exists, create a new one
    #
    # ------------------------------------------------

    if os.path.exists(log_file):
        scrh = file.read_lines(log_file, 0, 128)
        if scrh[0:] == log[0:]:
            print "\n>> ok"
            os.chdir(work_dir)
            return
        else:
            print "\n> System configuration file is not up to date. Updating..."
    else:
        print "\n> System configuration file not found, creating one..."

    file.create_file(log_file, log)

    # ------------
    #  Make Tools
    # ------------

    # print (" > Making binary tools in "+bintools_dir+"...")
    # os.chdir(bintools_dir)
    # os.system('make -s clean')
    # os.system('make -s dbl2flt')
    # os.system('make -s bin2ascii')
    # if (HAVE_LIBPNG == 'YES'):
    #   os.system('make -s bin2png')

    # ---------------------------
    #   Add important info here
    # ---------------------------

    # scrh = raw_input(" > Press enter to continue.")
    os.chdir(work_dir)
    return
Пример #8
0
def problem(work_dir, pluto_path, pluto_dir, additional_files,
            additional_flags, makefile_template, AUTO_UPDATE):

    #  before proceeding we scan pre-existing definitions.h
    #  for obsolete statements in order to and make  proper replacements.

    replace_obsoletes(work_dir)

    #  sys.exit(1)

    HD = 1
    RHD = 2
    MHD = 3
    SRMHD = 4
    RMHD = 5

    WITH_CHOMBO = 0  # enable/disable Chombo AMR
    FULL = 0
    WITH_FD = 0  # enable/disable finite difference schemes
    WITH_SB = 0  # enable/disable shearing box module
    WITH_FARGO = 0  # enable/disable FARGO module for orbital advection

    # *****************************************
    #      check command line arguments
    # *****************************************

    for x in sys.argv:
        if (x == "--with-chombo" or x == "--with-chombo:"):
            WITH_CHOMBO = 1
        if (x == "--full"):
            FULL = 1
        if (x == "--with-fd"):
            WITH_FD = 1
        if (x == "--with-sb"):
            WITH_SB = 1
        if (x == "--with-fargo"):
            WITH_FARGO = 1

# -- default makefile template --

    if (WITH_CHOMBO):
        makefile_template.append('/Src/Templates/makefile.chombo')
    else:
        makefile_template.append('/Src/Templates/makefile')

# Create user-editable menu

    entries = []
    options = []
    default = []
    scrh = []

    entries.append('PHYSICS')
    if (WITH_FD or WITH_FARGO):
        options.append(['HD', 'MHD'])
        default.append('HD')
    elif (WITH_SB):
        options.append(['MHD'])
        default.append('MHD')
    else:
        options.append(['HD', 'RHD', 'MHD', 'RMHD'])
        default.append('HD')

    entries.append('DIMENSIONS')
    if (WITH_SB or WITH_FARGO):
        options.append(['2', '3'])
        default.append('2')
    else:
        options.append(['1', '2', '3'])
        default.append('1')

    entries.append('COMPONENTS')
    if (WITH_SB):
        options.append(['2', '3'])
        default.append('2')
    else:
        options.append(['1', '2', '3'])
        default.append('1')

    entries.append('GEOMETRY')
    if (WITH_CHOMBO):
        #    options.append(['CARTESIAN','CYLINDRICAL','AXISYM'])
        options.append(['CARTESIAN', 'CYLINDRICAL'])
        default.append('CARTESIAN')
    elif (WITH_FD or WITH_SB):
        options.append(['CARTESIAN'])
        default.append('CARTESIAN')
    else:
        #    options.append(['CARTESIAN','CYLINDRICAL','AXISYM','POLAR','SPHERICAL'])
        options.append(['CARTESIAN', 'CYLINDRICAL', 'POLAR', 'SPHERICAL'])
        default.append('CARTESIAN')

#  entries.append('UNIFORM_GRID')
#  if (WITH_CHOMBO):
#    options.append('YES')
#    default.append('YES')
#  else:
#    options.append(['YES','NO'])
#    default.append('YES')

    entries.append('BODY_FORCE')
    if (WITH_SB):
        options.append(['VECTOR', 'POTENTIAL', '(VECTOR+POTENTIAL)'])
        default.append('VECTOR')
    else:
        options.append(['NO', 'VECTOR', 'POTENTIAL', '(VECTOR+POTENTIAL)'])
        default.append('NO')

    entries.append('COOLING')
    options.append(['NO', 'POWER_LAW', 'TABULATED', 'SNEq',
                    'MINEq'])  # ,'H2_COOL'])
    default.append('NO')

    #  entries.append('INCLUDE_PARTICLES')
    #  options.append(['NO','YES'])
    #  default.append('NO')

    # set interpolation options

    entries.append('INTERPOLATION')
    if (WITH_CHOMBO):
        options.append(['FLAT', 'LINEAR', 'WENO3', 'PARABOLIC'])
        default.append('LINEAR')
    elif (FULL):
        options.append(
            ['FLAT', 'LINEAR', 'LimO3', 'WENO3', 'PARABOLIC', 'MP5'])
        default.append('LINEAR')
    elif (WITH_FD):
        options.append(['WENO3_FD', 'WENOZ_FD', 'MP5_FD', 'LIMO3_FD'])
        default.append('WENOZ_FD')
    else:
        options.append(['FLAT', 'LINEAR', 'LimO3', 'WENO3',
                        'PARABOLIC'])  # Default
        default.append('LINEAR')

    entries.append('TIME_STEPPING')
    if (WITH_CHOMBO):
        #    options.append(['HANCOCK','CHARACTERISTIC_TRACING','RK_MIDPOINT','EULER','RK2'])
        options.append(['EULER', 'HANCOCK', 'CHARACTERISTIC_TRACING', 'RK2'])
        default.append('HANCOCK')
    elif (WITH_FD):
        options.append(['RK3'])
        default.append('RK3')
    else:
        #    options.append(['EULER','RK_MIDPOINT','RK2','RK3','HANCOCK','CHARACTERISTIC_TRACING'])
        options.append(
            ['EULER', 'RK2', 'RK3', 'HANCOCK', 'CHARACTERISTIC_TRACING'])
        default.append('RK2')

    entries.append('DIMENSIONAL_SPLITTING')
    if (WITH_CHOMBO or WITH_FARGO):
        options.append(['NO'])
        default.append('NO')
    else:
        options.append(['YES', 'NO'])
        default.append('YES')

    entries.append('NTRACER')
    for n in range(5):
        scrh.append(repr(n))
    options.append(scrh)
    default.append('0')

    scrh = []
    entries.append('USER_DEF_PARAMETERS')
    for n in range(32):
        scrh.append(repr(n + 1))
    options.append(scrh)
    default.append('1')

    # **************************************************
    #   If  definitions.h already exists try to read
    #   default values from it.
    # **************************************************

    if (os.path.exists(work_dir + '/definitions.h')):
        for x in entries:
            try:
                scrh = file.string_list(work_dir + '/definitions.h', x)
                tmp = string.split(scrh[0])
                i = entries.index(tmp[1])
                y = options[i]
                i2 = y.index(tmp[2])
                default[entries.index(x)] = tmp[2]

            except ValueError:
                continue

            except IndexError:
                continue

#  ****  ok, call menu  ****

    if AUTO_UPDATE == 0:
        selection = ''
        menu.SetTitle("Setup problem")
        selection = menu.Browse(entries, default, options)
#    selection = menu.select(entries,options,default,'Setup problem')

# **************************************************
#       define Physics module sub-menus
# **************************************************

    i = entries.index('DIMENSIONS')
    dimensions = int(default[i])
    i = entries.index('PHYSICS')
    physics_module = default[i]
    i = entries.index('GEOMETRY')
    geometry = default[i]
    i = entries.index('INTERPOLATION')
    interpolation = default[i]
    i = entries.index('TIME_STEPPING')
    time_stepping = default[i]
    i = entries.index('DIMENSIONAL_SPLITTING')
    dim_splitting = default[i]

    # HD

    if physics_module == 'HD':
        entries_HD = []
        options_HD = []
        default_HD = []

        entries_HD.append('EOS')
        options_HD.append(['IDEAL', 'ISOTHERMAL'])
        default_HD.append('IDEAL')

        entries_HD.append('ENTROPY_SWITCH')
        options_HD.append(['NO', 'YES'])
        default_HD.append('NO')

        entries_HD.append('THERMAL_CONDUCTION')
        if (WITH_CHOMBO == 1):
            options_HD.append(['NO', 'EXPLICIT'])
        else:
            #      options_HD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
            options_HD.append(['NO', 'EXPLICIT', 'SUPER_TIME_STEPPING'])

        default_HD.append('NO')

        entries_HD.append('VISCOSITY')
        if (WITH_CHOMBO == 1):
            options_HD.append(['NO', 'EXPLICIT'])
        else:
            #      options_HD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
            options_HD.append(['NO', 'EXPLICIT', 'SUPER_TIME_STEPPING'])

        default_HD.append('NO')

        entries_HD.append('ROTATING_FRAME')
        options_HD.append(['NO', 'YES'])
        default_HD.append('NO')

        #    if (physics_module == "HD" and dim_splitting == "YES"):
        #      if (geometry == "POLAR" or geometry == "SPHERICAL"):
        #        entries_HD.append('FARGO_SCHEME')
        #        options_HD.append(['NO','YES'])
        #        default_HD.append('NO')

        #  Read HD pre-existing HD submenu defaults, if they exists

        if (os.path.exists(work_dir + '/definitions.h')):
            for x in entries_HD:
                try:
                    scrh = file.string_list(work_dir + '/definitions.h', x)
                    tmp = string.split(scrh[0])
                    default_HD[entries_HD.index(x)] = tmp[2]
                except IndexError:
                    continue

        if AUTO_UPDATE == 0:
            selection = ''
            menu.SetTitle("HD Menu")
            selection = menu.Browse(entries_HD, default_HD, options_HD)
#      selection = menu.select(entries_HD,options_HD,default_HD,'HD MENU')

# RHD

    if physics_module == 'RHD':
        entries_RHD = []
        options_RHD = []
        default_RHD = []

        entries_RHD.append('EOS')
        options_RHD.append(['IDEAL', 'TAUB'])
        default_RHD.append('IDEAL')

        entries_RHD.append('USE_FOUR_VELOCITY')
        options_RHD.append(['NO', 'YES'])
        default_RHD.append('NO')

        entries_RHD.append('ENTROPY_SWITCH')
        options_RHD.append(['NO', 'YES'])
        default_RHD.append('NO')

        #  Read RHD pre-existing RHD submenu defaults, if they exists

        if (os.path.exists(work_dir + '/definitions.h')):
            for x in entries_RHD:
                try:
                    scrh = file.string_list(work_dir + '/definitions.h', x)
                    tmp = string.split(scrh[0])
                    default_RHD[entries_RHD.index(x)] = tmp[2]
                except IndexError:
                    continue

        if AUTO_UPDATE == 0:
            selection = ''
            menu.SetTitle("RHD Menu")
            selection = menu.Browse(entries_RHD, default_RHD, options_RHD)
#      selection = menu.select(entries_RHD,options_RHD,default_RHD,'RHD MENU')

# MHD

    if (physics_module == 'MHD'):
        entries_MHD = []
        options_MHD = []
        default_MHD = []

        entries_MHD.append('EOS')
        options_MHD.append(['IDEAL', 'BAROTROPIC', 'ISOTHERMAL'])
        default_MHD.append('IDEAL')

        entries_MHD.append('ENTROPY_SWITCH')
        options_MHD.append(['NO', 'YES'])
        default_MHD.append('NO')

        entries_MHD.append('MHD_FORMULATION')
        if (WITH_CHOMBO or WITH_FD):
            options_MHD.append(['NONE', 'EIGHT_WAVES', 'DIV_CLEANING'])
            default_MHD.append('EIGHT_WAVES')
        elif (WITH_SB or WITH_FARGO):
            options_MHD.append(['CONSTRAINED_TRANSPORT'])
            default_MHD.append('CONSTRAINED_TRANSPORT')
        else:
            options_MHD.append([
                'NONE', 'EIGHT_WAVES', 'DIV_CLEANING', 'CONSTRAINED_TRANSPORT'
            ])
            default_MHD.append('EIGHT_WAVES')

        entries_MHD.append('BACKGROUND_FIELD')
        options_MHD.append(['NO', 'YES'])
        default_MHD.append('NO')

        entries_MHD.append('RESISTIVE_MHD')
        if (WITH_CHOMBO == 1):
            options_MHD.append(['NO', 'EXPLICIT'])
        else:
            #      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
            options_MHD.append(['NO', 'EXPLICIT', 'SUPER_TIME_STEPPING'])

        default_MHD.append('NO')

        entries_MHD.append('HALL_MHD')
        options_MHD.append(['NO', 'RIEMANN', 'SOURCE'])
        default_MHD.append('NO')

        entries_MHD.append('AMBIPOLAR_DIFFUSION')
        options_MHD.append(['NO', 'EXPLICIT'])
        default_MHD.append('NO')

        entries_MHD.append('THERMAL_CONDUCTION')
        if (WITH_CHOMBO == 1):
            options_MHD.append(['NO', 'EXPLICIT'])
        else:
            #      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
            options_MHD.append(['NO', 'EXPLICIT', 'SUPER_TIME_STEPPING'])

        default_MHD.append('NO')

        entries_MHD.append('VISCOSITY')
        if (WITH_CHOMBO == 1):
            options_MHD.append(['NO', 'EXPLICIT'])
        else:
            #      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
            options_MHD.append(['NO', 'EXPLICIT', 'SUPER_TIME_STEPPING'])

        default_MHD.append('NO')

        entries_MHD.append('ROTATING_FRAME')
        options_MHD.append(['NO', 'YES'])
        default_MHD.append('NO')

        #  Read MHD pre-existing MHD submenu defaults, if they exists

        if (os.path.exists(work_dir + '/definitions.h')):
            for x in entries_MHD:
                ix = entries_MHD.index(x)
                try:
                    scrh = file.string_list(work_dir + '/definitions.h', x)
                    tmp = string.split(scrh[0])
                    try:  # if the choice is not in the permitted list of options,
                        # ValueError is raised and the default choice is kept.
                        i = options_MHD[ix].index(tmp[2])
                        default_MHD[ix] = tmp[2]
                    except ValueError:
                        continue
                except IndexError:
                    continue

        if AUTO_UPDATE == 0:
            selection = ''
            if (physics_module == 'MHD'):
                menu.SetTitle("MHD Menu")
                selection = menu.Browse(entries_MHD, default_MHD, options_MHD)
#        selection = menu.select(entries_MHD,options_MHD,default_MHD,'MHD MENU')

# RMHD

    if physics_module == 'RMHD':
        entries_RMHD = []
        options_RMHD = []
        default_RMHD = []

        entries_RMHD.append('EOS')
        options_RMHD.append(['IDEAL', 'TAUB'])
        default_RMHD.append('IDEAL')

        entries_RMHD.append('ENTROPY_SWITCH')
        options_RMHD.append(['NO', 'YES'])
        default_RMHD.append('NO')

        entries_RMHD.append('MHD_FORMULATION')
        if (WITH_CHOMBO == 1):
            options_RMHD.append(['NONE', 'EIGHT_WAVES', 'DIV_CLEANING'])
        else:
            options_RMHD.append([
                'NONE', 'EIGHT_WAVES', 'DIV_CLEANING', 'CONSTRAINED_TRANSPORT'
            ])

        default_RMHD.append('NONE')

        #  Read RMHD pre-existing RMHD submenu defaults, if they exists

        if (os.path.exists(work_dir + '/definitions.h')):
            for x in entries_RMHD:
                ix = entries_RMHD.index(x)
                try:
                    scrh = file.string_list(work_dir + '/definitions.h', x)
                    tmp = string.split(scrh[0])
                    try:  # if the choice is not in the permitted list of options,
                        # ValueError is raised and the default choice is kept.
                        i = options_RMHD[ix].index(tmp[2])
                        default_RMHD[ix] = tmp[2]
                    except ValueError:
                        continue
                except IndexError:
                    continue

        if AUTO_UPDATE == 0:
            selection = ''
            if (physics_module == 'RMHD'):
                menu.SetTitle("RMHD Menu")
                selection = menu.Browse(entries_RMHD, default_RMHD,
                                        options_RMHD)
#        selection = menu.select(entries_RMHD,options_RMHD,default_RMHD,'RMHD MENU')

# ********************************************************************
#    USER_DEF PARAMETERS:
#
#      Read them from definitions.h if the file exists;
#      assign  'SCRH' otherwise.
# ********************************************************************

    i = entries.index('USER_DEF_PARAMETERS')
    npar = int(default[i])
    u_def_par = []
    if (os.path.exists(work_dir + '/definitions.h')):
        scrh = file.word_find(work_dir + '/definitions.h', 'parameters')
        k0 = scrh[0] + 2
        scrh = file.read_lines(work_dir + '/definitions.h', k0, k0 + npar)
        for n in range(npar):
            try:
                x = string.split(scrh[n])
                if (x[0] == "#define"):
                    u_def_par.append(x[1])
                else:
                    u_def_par.append('SCRH')
            except IndexError:
                u_def_par.append('SCRH')
#        scrh[n + 1] = '#define SCRH  x'

    else:
        for n in range(npar):
            u_def_par.append('SCRH')

    if AUTO_UPDATE == 0:
        #    u_def_par = ['SCRH']
        menu.SetTitle("User-defined parameters")
        menu.Insert(int(default[i]), u_def_par)
#    menu.put(int(default[i]),u_def_par,'USER DEF SECTION')

# -----------------------------------------------------
#   Create the list 'tmp' that will be used to write
#   the new definitions.h header file
# -----------------------------------------------------

    tmp = []
    for x in entries:
        i = entries.index(x)
        y = default[i]
        tmp.append('#define  ' + x.ljust(21) + '   ' + y + '\n')

    tmp.append('\n/* -- physics dependent declarations -- */\n\n')

    if (physics_module == 'MHD'):
        for x in entries_MHD:
            i = entries_MHD.index(x)
            tmp.append('#define  ' + x.ljust(21) + '   ' + default_MHD[i] +
                       '\n')

    if physics_module == 'HD':
        for x in entries_HD:
            i = entries_HD.index(x)
            tmp.append('#define    ' + x.ljust(21) + '   ' + default_HD[i] +
                       '\n')

    if physics_module == 'RHD':
        for x in entries_RHD:
            i = entries_RHD.index(x)
            tmp.append('#define    ' + x.ljust(21) + '   ' + default_RHD[i] +
                       '\n')

    if physics_module == 'RMHD':
        for x in entries_RMHD:
            i = entries_RMHD.index(x)
            tmp.append('#define    ' + x.ljust(21) + '   ' + default_RMHD[i] +
                       '\n')

# *****************************************
#     add Chombo-AMR specific flags
# *****************************************

    if (WITH_CHOMBO and os.path.exists(work_dir + '/definitions.h')):
        scrh = file.string_list(work_dir + '/definitions.h', 'AMR_EN_SWITCH')
        tmp.append('\n/* -- Chombo-AMR flags -- */\n\n')
        if (len(scrh) != 0):
            strsplit = string.split(scrh[0])
            value = strsplit[2]
            tmp.append('#define  AMR_EN_SWITCH   ' + value + '\n')
        else:
            tmp.append('#define  AMR_EN_SWITCH   NO\n')

# *******************************************************
#     add pointer names to user defined parameters
# *******************************************************

    tmp.append('\n/* -- pointers to user-def parameters -- */\n\n')

    for x in u_def_par:
        i = u_def_par.index(x)
        tmp.append('#define  ' + x.ljust(16) + '   ' + repr(i) + '\n')

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #   In this section, also, udpate the pluto.ini
    #   initialization file by appending the correct
    #   sequence of user defined parameters
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

#  menu.RestoreScreen()
    plutoini = work_dir + "/pluto.ini"
    scrh = file.string_find(plutoini, 'Parameters')
    ipos = scrh[0] + 2  # start reading/writing pluto.ini at this point
    # to build a list of the userdef parameters
    scrh = file.read_lines(plutoini, ipos, 999)  # read until end of file

    pname = []
    pvalue = []

    for x in scrh:
        y = string.split(x)  # pname and pvalue contain the list of parameter
        if (len(y) == 0): continue  # skip blank lines
        pname.append(y[0])  # names and their respective values as present
        pvalue.append(y[1])  # in pluto.ini

    for x in u_def_par:  # loop on the actual list of parameters;
        par_exist = 0  # is the parameter already present in pluto.ini ?
        for y in pname:
            if (x == y):  # if yes, use the original value instead of '0'
                par_exist = 1
                i = pname.index(y)
                file.insert(plutoini, pname[i] + "    " + pvalue[i] + "\n",
                            ipos)
                break

        if (par_exist == 0):  # if not, set default value to 0
            file.insert(plutoini, x + '    0\n', ipos)

        ipos = ipos + 1

    # delete all other lines in pluto.ini

    file.delete_lines(plutoini, ipos, ipos + 256)

    # ***************************************************************
    #    check dependencies for conditional inclusion
    #    of additional object files; this is useful
    #    for makefile creation
    # ***************************************************************

    # additional files will be compiled
    # depending on the user's choice of
    # time integration scheme

    # the next line removes all elements from additional_files
    # and pluto_path so the list can be built from scratch

    #  for x in additional_files: additional_files.remove(x)
    #  for x in pluto_path      : pluto_path.remove(x)

    additional_files[:] = []
    additional_flags[:] = []
    pluto_path[:] = []

    divb = ' '

    # **********************************************
    #   physics module & parabolic term treatment
    # **********************************************

    sts_flag = 0  # if changed to 1, include the super-time-stepping driver
    rkc_flag = 0  # if changed to 1, include the runge-kutta-Chebyshev driver
    exp_flag = 0  # if changed to 1, include explicit parabolic time-stepping
    cur_flag = 0  # if changed to 1, include current calculation

    if (physics_module == 'HD'):
        pluto_path.append('HD/')
        entries_MOD = entries_HD
        default_MOD = default_HD

        n = entries_MOD.index('THERMAL_CONDUCTION')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('Thermal_Conduction/')
            if (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
            elif (default_MOD[n] == 'RK_CHEBYSHEV'): rkc_flag = 1
            elif (default_MOD[n] == 'EXPLICIT'): exp_flag = 1

        n = entries_MOD.index('VISCOSITY')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('Viscosity/')
            if (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
            elif (default_MOD[n] == 'RK_CHEBYSHEV'): rkc_flag = 1
            elif (default_MOD[n] == 'EXPLICIT'): exp_flag = 1

    elif (physics_module == 'RHD'):
        pluto_path.append('RHD/')
        entries_MOD = entries_RHD
        default_MOD = default_RHD

    elif (physics_module == 'MHD'):
        pluto_path.append('MHD/')
        entries_MOD = entries_MHD
        default_MOD = default_MHD
        n = entries_MOD.index('MHD_FORMULATION')
        divb = default_MOD[n]
        if (divb == 'CONSTRAINED_TRANSPORT'):
            pluto_path.append('MHD/CT/')
        elif (divb == 'DIV_CLEANING'):
            pluto_path.append('MHD/GLM/')

        n = entries_MOD.index('RESISTIVE_MHD')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('MHD/Resistive/')
            cur_flag = 1
            if (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
            elif (default_MOD[n] == 'RK_CHEBYSHEV'): rkc_flag = 1
            elif (default_MOD[n] == 'EXPLICIT'): exp_flag = 1

        n = entries_MOD.index('HALL_MHD')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('MHD/Hall/')
            if (default_MOD[n] == 'RIEMANN'): cur_flag = 1

        n = entries_MOD.index('AMBIPOLAR_DIFFUSION')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('MHD/Ambipolar/')
            cur_flag = 1

        n = entries_MOD.index('THERMAL_CONDUCTION')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('Thermal_Conduction/')
            if (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
            elif (default_MOD[n] == 'RK_CHEBYSHEV'): rkc_flag = 1
            elif (default_MOD[n] == 'EXPLICIT'): exp_flag = 1

        n = entries_MOD.index('VISCOSITY')
        if (default_MOD[n] != 'NO'):
            pluto_path.append('Viscosity/')
            if (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
            elif (default_MOD[n] == 'RK_CHEBYSHEV'): rkc_flag = 1
            elif (default_MOD[n] == 'EXPLICIT'): exp_flag = 1

        if (cur_flag == 1):
            pluto_path.append('MHD/Current/')
            additional_flags.append(' -DNEED_CURRENT')
        # ***************************
        #  need shearingbox module ?
        # ***************************

        if (WITH_SB == 1):
            pluto_path.append('MHD/ShearingBox/')
            additional_flags.append(' -DSHEARINGBOX')

    elif (physics_module == 'RMHD'):
        pluto_path.append('RMHD/')
        entries_MOD = entries_RMHD
        default_MOD = default_RMHD
        n = entries_MOD.index('MHD_FORMULATION')
        divb = default_MOD[n]
        if (divb == 'CONSTRAINED_TRANSPORT'):
            pluto_path.append('MHD/CT/')
        elif (divb == 'DIV_CLEANING'):
            pluto_path.append('MHD/GLM/')

    # *****************************
    #       Interpolation
    # *****************************

    if (interpolation == 'FLAT'):
        additional_files.append('states_flat.o')
    elif (interpolation == 'LINEAR'):
        additional_files.append('states_plm.o')
    elif (interpolation == 'PARABOLIC'):
        additional_files.append('states_ppm.o')
    elif (interpolation == 'LimO3'):
        additional_files.append('states_limo3.o')
    elif (interpolation == 'WENO3'):
        additional_files.append('states_weno3.o')

    elif (WITH_FD):  # Finite Difference

        additional_files.append('states_fd.o')
        additional_files.append('fd_reconstruct.o')
        additional_files.append('fd_flux.o')
        additional_flags.append(' -DFINITE_DIFFERENCE')

    # *****************************
    #       Time Stepping
    # *****************************

    if (WITH_CHOMBO):  # ** AMR file inclusion **

        if (dimensions == 1): additional_files.append('PatchCTU.1D.o')
        else:
            if (time_stepping == 'RK_MIDPOINT'):
                additional_files.append('PatchRK.3D.o')
            elif (time_stepping == 'EULER'):
                additional_files.append('PatchEuler.3D.o')
            elif (time_stepping == 'RK2'):
                additional_files.append('PatchEuler.3D.o')
            else:
                additional_files.append('PatchCTU.3D.o')

    else:
        if (time_stepping == 'CHARACTERISTIC_TRACING'):
            if (dim_splitting == 'YES'): additional_files.append('sweep.o')
            else: additional_files.append('unsplit_ctu.o')
        elif (time_stepping == 'HANCOCK'):
            if (dim_splitting == 'YES'): additional_files.append('sweep.o')
            else: additional_files.append('unsplit_ctu.o')
        elif (time_stepping == 'RK_MIDPOINT'):
            additional_files.append('rk_midpoint.o')
        else:
            if (dim_splitting == 'YES'): additional_files.append('sweep.o')
            else: additional_files.append('unsplit.o')

    if (time_stepping == 'CHARACTERISTIC_TRACING'):
        additional_files.append('char_tracing.o')
    elif (time_stepping == 'HANCOCK'):
        additional_files.append('hancock.o')

#  if (interpolation != 'LINEAR'):
#    if (time_stepping == 'CHARACTERISTIC_TRACING'):
#      additional_files.append('states_ppm_char.o')
#    else:
#      additional_files.append('rk_states.o')

# *****************************
#      FARGO Scheme
# *****************************

    if (WITH_FARGO):
        pluto_path.append('Fargo/')
        additional_flags.append(' -DFARGO')

    # *****************************
    #      Geometry
    # *****************************

#  additional_files.append('rhs.o')
#   additional_files.append('rhs.o')

#  if (geometry == "CARTESIAN"):
#    additional_files.append('rhs_cart.o')
#  if (geometry == "AXISYM"):
#    additional_files.append('cylsource.o')

# *****************************
#         Cooling
# *****************************

    n = entries.index('COOLING')

    if (default[n] == 'POWER_LAW'):
        pluto_path.append('Cooling/Power_Law/')
    elif (default[n] == 'TABULATED'):
        pluto_path.append('Cooling/Tab/')
        additional_files.append('cooling_source.o')
        additional_files.append('cooling_ode_solver.o')
    elif (default[n] == 'SNEq'):
        pluto_path.append('Cooling/SNEq/')
        additional_files.append('cooling_source.o')
        additional_files.append('cooling_ode_solver.o')
    elif (default[n] == 'MINEq'):
        pluto_path.append('Cooling/MINEq/')
        additional_files.append('cooling_source.o')
        additional_files.append('cooling_ode_solver.o')
    elif (default[n] == 'H2_COOL'):
        pluto_path.append('Cooling/H2_COOL/')
        additional_files.append('cooling_source.o')
        additional_files.append('cooling_ode_solver.o')

    # **********************************
    #   parabolic flux: file inclusion
    # **********************************

    if (sts_flag == 1):
        additional_files.append('sts.o')
        additional_files.append('parabolic_rhs.o')

    if (rkc_flag == 1):
        additional_files.append('rkc.o')
        additional_files.append('parabolic_rhs.o')

    if (exp_flag == 1):
        additional_files.append('parabolic_flux.o')

    # **********************************************
    #          Vector potential
    # **********************************************

    if (physics_module == 'MHD' or physics_module == 'RMHD'):
        additional_files.append('vec_pot_diff.o')
        if (WITH_CHOMBO == 0): additional_files.append('vec_pot_update.o')

    # *****************************
    #          Particles
    # *****************************

#  n = entries.index('INCLUDE_PARTICLES')
#  if (default[n] == 'YES'):
#    pluto_path.append('Particles/')

# ****************************************************************
#       DEFINE ALL NON-USER FRIENDLY CONSTANTS
# ****************************************************************

    tmp.append('\n/* -- supplementary constants (user editable) -- */ \n\n')

    no_us_fr = []

    no_us_fr.append('#define  INITIAL_SMOOTHING     NO\n')
    no_us_fr.append('#define  WARNING_MESSAGES      NO\n')
    no_us_fr.append('#define  PRINT_TO_FILE         NO\n')
    no_us_fr.append('#define  INTERNAL_BOUNDARY     NO\n')
    no_us_fr.append('#define  SHOCK_FLATTENING      NO\n')
    if (not WITH_FD):
        no_us_fr.append('#define  ARTIFICIAL_VISCOSITY  NO\n')
        no_us_fr.append('#define  CHAR_LIMITING         NO\n')
        no_us_fr.append('#define  LIMITER               DEFAULT\n')

# add geometry-dependent switches

    if (geometry == "AXISYM"):
        no_us_fr.append('#define  ADD_CYLSOURCE            1\n')

#  if (geometry == "POLAR" and physics_module == "HD"):
#    no_us_fr.append('#define  FARGO_SCHEME          NO\n')

# add flux ct switches for MHD or RMHD

    if (divb == "CONSTRAINED_TRANSPORT"):
        no_us_fr.append('#define  CT_EMF_AVERAGE           UCT_HLL\n')
        no_us_fr.append('#define  CT_EN_CORRECTION         NO\n')
        no_us_fr.append('#define  ASSIGN_VECTOR_POTENTIAL  YES\n')
    elif (physics_module == "MHD" or physics_module == "RMHD"):
        no_us_fr.append('#define  ASSIGN_VECTOR_POTENTIAL  NO\n')

    if (physics_module == "MHD" or physics_module == "RMHD"):
        if (not WITH_CHOMBO):
            no_us_fr.append('#define  UPDATE_VECTOR_POTENTIAL  NO\n')

    if (time_stepping == 'HANCOCK'):
        if (physics_module == 'RMHD'):
            no_us_fr.append('#define  PRIMITIVE_HANCOCK     NO\n')
        else:
            no_us_fr.append('#define  PRIMITIVE_HANCOCK     YES\n')

# add definition of STS_NU

    if (sts_flag == 1):
        no_us_fr.append('#define  STS_nu                0.01\n')

# ***************************************************************
#    Read pre-existing non-user-editable defaults;
#    Use the default value if they exist
# ***************************************************************

    if (os.path.exists(work_dir + '/definitions.h')):
        for x in no_us_fr:
            try:
                xl = string.split(x)
                scrh = file.string_list(work_dir + '/definitions.h', xl[1])
                no_us_fr[no_us_fr.index(x)] = scrh[0]
            except IndexError:
                continue

# add elements of no_us_fr to tmp

    for x in no_us_fr:
        tmp.append(x)

# -- create definitions.h --

    file.create_file(work_dir + '/definitions.h', tmp)

    return
def scatter_2d(point2d,
               class_indexes,
               n_iter,
               dir_name,
               ms=3,
               alpha=0.1,
               momentum=None,
               save=None):
    """

    :param save:
    :param momentum:
    :param dir_name:
    :param n_iter:
    :param point2d:
    :param class_indexes:
    :param ms: marker size
    :param alpha:
    :param savename:
    :return:
    """
    fig, ax = plt.subplots(figsize=(9, 6))
    classes = list(np.unique(class_indexes))
    markers = 'os' * len(classes)
    colors = plt.cm.rainbow(np.linspace(0, 1, len(classes)))

    for i, cls in enumerate(classes):
        mark = markers[i]
        ax.plot(point2d[class_indexes == cls, 0],
                point2d[class_indexes == cls, 1],
                marker=mark,
                linestyle='',
                ms=ms,
                label=str(cls),
                alpha=alpha,
                color=colors[i],
                markeredgecolor='black',
                markeredgewidth=0.4)
    ax.legend()
    # plt.show()

    if save:
        '''
        # save picture at every iteration
        '''
        pic_name = "iter"
        if momentum:
            pic_name = "momentum_" + pic_name
        file.create_dir(dir_name + "\\" + "pic")
        plt.savefig(dir_name + "\\" + "pic\\" + pic_name + str(n_iter))
        '''
        # save low dimension vectors at every iteration
        '''
        low_file_name = "low_" + str(n_iter) + ".json"
        if momentum:
            low_file_name = "momentum_" + low_file_name
        dir_name = dir_name
        file.create_file(low_file_name, dir_name)
        file.write_json(file.numpy_array_to_list(point2d), low_file_name,
                        dir_name)

    return ax
Пример #10
0
def check(pluto_dir, get_arch):

    work_dir = os.getcwd()
    print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
    print("\n>> Inspecting system configuration << \n")

    # log_file     = pluto_dir+'/system.conf'
    log_file = work_dir + '/sysconf.out'
    config_dir = pluto_dir + '/Config/'
    python_dir = pluto_dir + '/Tools/Python'
    bintools_dir = pluto_dir + '/Tools/bin_tools'
    param_file = pluto_dir + '/Src/pluto.h'

    os.chdir(python_dir)
    log = []

    #  ---------------------
    #    get user name
    #  ---------------------

    try:
        user = os.getlogin()
    except OSError:
        user = '******'

    #  ---------------------
    #    get system spec.
    #  ---------------------

    PLATFORM = os.uname()

    #  ---------------------
    #   find current
    #   version of PLUTO
    #  ---------------------

    scrh = file.word_find(param_file, "PLUTO_VERSION")
    ipos = scrh[0]
    scrh = file.read_lines(param_file, ipos, ipos + 1)
    vers = string.split(scrh[0])
    vers = vers[2]

    # ------------------------------
    #  print a short system summary
    # ------------------------------

    print "User.......................", user
    print "System name................", PLATFORM[0]
    print "Node name..................", PLATFORM[1]
    print "Release....................", PLATFORM[2]
    print "Arch.......................", PLATFORM[4]
    print "Byteorder..................", sys.byteorder
    print "Version....................", PLATFORM[3]
    print "Working_dir................", work_dir
    print "PLUTO main dir.............", pluto_dir
    print "PLUTO version..............", vers

    # --------------------------------------
    #  Check for gcc or another c compiler
    # --------------------------------------

    compiler_list = ['gcc', 'cc', 'gcc2']
    COMPILER_NAME = ''

    for x in compiler_list:
        if (CHECK_FOR(x) == 'YES'):
            print "C Compiler................. " + x
            COMPILER_NAME = x
            break

    if (COMPILER_NAME == ''):
        print "! Can not find a C compiler       !"

# -----------------
#  check for mpi
# -----------------

    mpi_compiler_list = ['mpicc', 'mpiCC', 'mpcc_r', 'hcc', 'mpcc']
    MPI_COMPILER_NAME = ''

    for x in mpi_compiler_list:
        if (CHECK_FOR(x) == 'YES'):
            print "MPI Compiler .............. " + x
            MPI_COMPILER_NAME = x
            break

    if (MPI_COMPILER_NAME == ''):
        print "MPI Compiler............... NOT FOUND"

    if (get_arch):
        print "\n"
        print "Proposed makefile names: \n"
        print "> " + PLATFORM[0] + "." + PLATFORM[
            4] + "." + COMPILER_NAME + ".defs"
        print "> " + PLATFORM[0] + "." + PLATFORM[
            4] + "." + MPI_COMPILER_NAME + ".defs"
        return

# ---------------------------------------------------
#  Build log list, that will be compared to the
#  sysconf.out file.
# ---------------------------------------------------

    log.append("USER           = "******"WORKING_DIR    = " + work_dir + "\n")
    log.append("SYSTEM_NAME    = " + PLATFORM[0] + "\n")
    log.append("NODE_NAME      = " + PLATFORM[1] + "\n")
    log.append("RELEASE        = " + PLATFORM[2] + "\n")
    log.append("ARCH           = " + PLATFORM[4] + "\n")
    log.append("BYTE_ORDER     = " + sys.byteorder + "\n")
    log.append("VERSION        = " + PLATFORM[3] + "\n")
    log.append("PLUTO_DIR      = " + pluto_dir + '\n')
    log.append("PLUTO_VERSION  = " + vers + '\n')
    log.append("C_COMPILER     = " + COMPILER_NAME + '\n')
    log.append("MPI_C_COMPILER = " + MPI_COMPILER_NAME + '\n')

    #  ----------------------------
    #    check for online updates
    #  ----------------------------

    print "\n> Checking for updates (canceled)...\n"
    # try:
    #   urllib.urlretrieve("http://plutocode.ph.unito.it/updates.txt","updates.txt")
    #   scrh = file.word_find ("updates.txt","release")
    #   ipos = scrh[0]
    #   scrh = file.read_lines ("updates.txt", ipos, ipos + 1)
    #   rels = string.split(scrh[0])
    #   if (rels[1] != vers):
    #     print "   ******************************************************* "
    #     print "    A new version of PLUTO ("+rels[1]+") is available at"
    #     print "    http://plutocode.oato.inaf.it"
    #     print "   *******************************************************\n"
    #     scrh = raw_input("> Press enter to continue.")
    #     os.chdir(work_dir)
    # except:
    #   print "! Connection not available\n"

    # ------------------------------------------------
    #  Compare the list 'log' with the file log_file;
    #
    #   - if they match, no update is necessary,
    #               ==> return to main menu
    #
    #   - if they do not match or if log_file does not
    #     exists, create a new one
    #
    # ------------------------------------------------

    if (os.path.exists(log_file)):
        scrh = file.read_lines(log_file, 0, 128)
        if (scrh[0:] == log[0:]):
            print "\n>> ok"
            os.chdir(work_dir)
            return
        else:
            print "\n> System configuration file is not up to date. Updating..."
    else:
        print "\n> System configuration file not found, creating one..."

    file.create_file(log_file, log)

    # ------------
    #  Make Tools
    # ------------

    # print (" > Making binary tools in "+bintools_dir+"...")
    # os.chdir(bintools_dir)
    # os.system('make -s clean')
    # os.system('make -s dbl2flt')
    # os.system('make -s bin2ascii')
    # if (HAVE_LIBPNG == 'YES'):
    #   os.system('make -s bin2png')

    # ---------------------------
    #   Add important info here
    # ---------------------------

    # scrh = raw_input(" > Press enter to continue.")
    os.chdir(work_dir)
    return
Пример #11
0
def problem(work_dir, pluto_path, pluto_dir, additional_files, 
            additional_flags, makefile_template, AUTO_UPDATE):

#  before proceeding we scan pre-existing definitions.h 
#  for obsolete statements in order to and make  proper replacements.

  replace_obsoletes(work_dir)
 
#  sys.exit(1)

  HD     = 1
  RHD    = 2
  MHD    = 3
  SRMHD  = 4
  RMHD   = 5
  
  WITH_CHOMBO = 0  # enable/disable Chombo AMR
  FULL        = 0
  WITH_FD     = 0  # enable/disable finite difference schemes 
  WITH_SB     = 0  # enable/disable shearing box module
  WITH_FARGO  = 0  # enable/disable FARGO module for orbital advection

# *****************************************
#      check command line arguments   
# *****************************************

  for x in sys.argv:
    if (x == "--with-chombo" or x == "--with-chombo:"):
      WITH_CHOMBO = 1
    if (x == "--full"):
      FULL = 1
    if (x == "--with-fd"):
      WITH_FD = 1
    if (x == "--with-sb"):
      WITH_SB = 1
    if (x == "--with-fargo"):
      WITH_FARGO = 1
        
# -- default makefile template -- 

  if (WITH_CHOMBO):
    makefile_template.append('/Src/Templates/makefile.chombo')
  else:
    makefile_template.append('/Src/Templates/makefile')
  
# Create user-editable menu

  entries = []
  options = []
  default = []
  scrh    = []

  entries.append('PHYSICS')
  if (WITH_FD or WITH_FARGO):
    options.append(['HD','MHD'])
    default.append('HD')
  elif (WITH_SB):
    options.append(['MHD'])
    default.append('MHD')
  else:
    options.append(['HD','RHD','MHD','RMHD'])
    default.append('HD')

  entries.append('DIMENSIONS')
  if(WITH_SB or WITH_FARGO):
    options.append(['2','3'])
    default.append('2')
  else:
    options.append(['1','2','3'])
    default.append('1')


  entries.append('COMPONENTS')
  if (WITH_SB):
    options.append(['2','3'])
    default.append('2')
  else:
    options.append(['1','2','3'])
    default.append('1')

  entries.append('GEOMETRY')
  if (WITH_CHOMBO):
#    options.append(['CARTESIAN','CYLINDRICAL','AXISYM'])
    options.append(['CARTESIAN','CYLINDRICAL'])
    default.append('CARTESIAN')
  elif (WITH_FD or WITH_SB):
    options.append(['CARTESIAN'])
    default.append('CARTESIAN')
  else:
#    options.append(['CARTESIAN','CYLINDRICAL','AXISYM','POLAR','SPHERICAL'])
    options.append(['CARTESIAN','CYLINDRICAL','POLAR','SPHERICAL'])
    default.append('CARTESIAN')

#  entries.append('UNIFORM_GRID')
#  if (WITH_CHOMBO):
#    options.append('YES')
#    default.append('YES')
#  else:
#    options.append(['YES','NO'])
#    default.append('YES')

    
  entries.append('BODY_FORCE')
  if (WITH_SB): 
    options.append(['VECTOR', 'POTENTIAL', '(VECTOR+POTENTIAL)'])
    default.append('VECTOR')
  else:
    options.append(['NO','VECTOR', 'POTENTIAL', '(VECTOR+POTENTIAL)'])
    default.append('NO')

  entries.append('COOLING')
  options.append(['NO','POWER_LAW','TABULATED','SNEq','MINEq']) # ,'H2_COOL'])
  default.append('NO')

#  entries.append('INCLUDE_PARTICLES')
#  options.append(['NO','YES'])
#  default.append('NO')

# set interpolation options

  entries.append('INTERPOLATION')
  if (WITH_CHOMBO):
    options.append(['FLAT','LINEAR','WENO3','PARABOLIC'])
    default.append('LINEAR')
  elif (FULL):
    options.append(['FLAT','LINEAR','LimO3',
                    'WENO3','PARABOLIC', 'MP5'])
    default.append('LINEAR')
  elif (WITH_FD):
    options.append(['WENO3_FD', 'WENOZ_FD', 
                    'MP5_FD','LIMO3_FD'])
    default.append('WENOZ_FD')
  else: 
    options.append(['FLAT','LINEAR','LimO3','WENO3','PARABOLIC'])  # Default
    default.append('LINEAR')


  entries.append('TIME_STEPPING')
  if (WITH_CHOMBO):
#    options.append(['HANCOCK','CHARACTERISTIC_TRACING','RK_MIDPOINT','EULER','RK2'])
    options.append(['EULER','HANCOCK','CHARACTERISTIC_TRACING','RK2'])
    default.append('HANCOCK')
  elif (WITH_FD):
    options.append(['RK3'])
    default.append('RK3')
  else:    
#    options.append(['EULER','RK_MIDPOINT','RK2','RK3','HANCOCK','CHARACTERISTIC_TRACING'])
    options.append(['EULER','RK2','RK3','HANCOCK','CHARACTERISTIC_TRACING'])
    default.append('RK2')

  entries.append('DIMENSIONAL_SPLITTING')
  if (WITH_CHOMBO or WITH_FARGO):
    options.append(['NO'])
    default.append('NO')
  else:  
    options.append(['YES','NO'])
    default.append('YES')

  entries.append('NTRACER')
  for n in range(5): scrh.append(repr(n))
  options.append(scrh)
  default.append('0')

  scrh =[]
  entries.append('USER_DEF_PARAMETERS')
  for n in range(32): scrh.append(repr(n+1))
  options.append(scrh)
  default.append('1')

# **************************************************
#   If  definitions.h already exists try to read 
#   default values from it. 
# **************************************************

  if (os.path.exists(work_dir+'/definitions.h')):
    for x in entries:
      try:
        scrh = file.string_list(work_dir+'/definitions.h',x)
        tmp  = string.split(scrh[0])
        i  = entries.index(tmp[1])
        y  = options[i]
        i2 = y.index(tmp[2]) 
        default[entries.index(x)] = tmp[2]
  
      except ValueError:
        continue

      except IndexError:
        continue

#  ****  ok, call menu  ****

  if AUTO_UPDATE == 0:
    selection = '' 
    menu.SetTitle("Setup problem")
    selection = menu.Browse(entries,default,options)
#    selection = menu.select(entries,options,default,'Setup problem')

# **************************************************
#       define Physics module sub-menus
# **************************************************

  i              = entries.index('DIMENSIONS')
  dimensions     = int(default[i])
  i              = entries.index('PHYSICS')
  physics_module = default[i]
  i              = entries.index('GEOMETRY')
  geometry       = default[i]
  i              = entries.index('INTERPOLATION')
  interpolation  = default[i]
  i              = entries.index('TIME_STEPPING')
  time_stepping  = default[i]
  i              = entries.index('DIMENSIONAL_SPLITTING')
  dim_splitting  = default[i]

# HD

  if physics_module == 'HD':
    entries_HD = []
    options_HD = []
    default_HD = []

    entries_HD.append('EOS')
    options_HD.append(['IDEAL','ISOTHERMAL'])
    default_HD.append('IDEAL')

    entries_HD.append('ENTROPY_SWITCH')
    options_HD.append(['NO','YES'])
    default_HD.append('NO')

    entries_HD.append('THERMAL_CONDUCTION')
    if (WITH_CHOMBO == 1):
      options_HD.append(['NO','EXPLICIT'])
    else:
#      options_HD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
      options_HD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING'])
      
    default_HD.append('NO')

    entries_HD.append('VISCOSITY')
    if (WITH_CHOMBO == 1):
      options_HD.append(['NO','EXPLICIT'])
    else:
#      options_HD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
      options_HD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING'])
      
    default_HD.append('NO')

    entries_HD.append('ROTATING_FRAME')
    options_HD.append(['NO','YES'])
    default_HD.append('NO')


#    if (physics_module == "HD" and dim_splitting == "YES"):
#      if (geometry == "POLAR" or geometry == "SPHERICAL"):
#        entries_HD.append('FARGO_SCHEME')
#        options_HD.append(['NO','YES'])
#        default_HD.append('NO')

#  Read HD pre-existing HD submenu defaults, if they exists

    if (os.path.exists(work_dir+'/definitions.h')):
      for x in entries_HD:
        try:
          scrh = file.string_list(work_dir+'/definitions.h',x)
          tmp  = string.split(scrh[0])
          default_HD[entries_HD.index(x)] = tmp[2]
        except IndexError:
          continue


    if AUTO_UPDATE == 0:
      selection = ''
      menu.SetTitle("HD Menu")
      selection = menu.Browse(entries_HD, default_HD, options_HD)
#      selection = menu.select(entries_HD,options_HD,default_HD,'HD MENU')

# RHD

  if physics_module == 'RHD':
    entries_RHD = []
    options_RHD = []
    default_RHD = []

    entries_RHD.append('EOS')
    options_RHD.append(['IDEAL','TAUB'])
    default_RHD.append('IDEAL')

    entries_RHD.append('USE_FOUR_VELOCITY')
    options_RHD.append(['NO','YES'])
    default_RHD.append('NO')

    entries_RHD.append('ENTROPY_SWITCH')
    options_RHD.append(['NO','YES'])
    default_RHD.append('NO')

#  Read RHD pre-existing RHD submenu defaults, if they exists

    if (os.path.exists(work_dir+'/definitions.h')):
      for x in entries_RHD:
        try:
          scrh = file.string_list(work_dir+'/definitions.h',x)
          tmp  = string.split(scrh[0])
          default_RHD[entries_RHD.index(x)] = tmp[2]
        except IndexError:
          continue


    if AUTO_UPDATE == 0:
      selection = ''
      menu.SetTitle("RHD Menu")
      selection = menu.Browse(entries_RHD, default_RHD, options_RHD)
#      selection = menu.select(entries_RHD,options_RHD,default_RHD,'RHD MENU')

# MHD

  if (physics_module == 'MHD'):
    entries_MHD = []
    options_MHD = []
    default_MHD = []

    entries_MHD.append('EOS')
    options_MHD.append(['IDEAL','BAROTROPIC','ISOTHERMAL'])
    default_MHD.append('IDEAL')

    entries_MHD.append('ENTROPY_SWITCH')
    options_MHD.append(['NO','YES'])
    default_MHD.append('NO')

    entries_MHD.append('MHD_FORMULATION')
    if (WITH_CHOMBO or WITH_FD):
      options_MHD.append(['NONE','EIGHT_WAVES','DIV_CLEANING'])
      default_MHD.append('EIGHT_WAVES')
    elif (WITH_SB or WITH_FARGO):
      options_MHD.append(['CONSTRAINED_TRANSPORT'])
      default_MHD.append('CONSTRAINED_TRANSPORT')
    else:
      options_MHD.append(['NONE','EIGHT_WAVES','DIV_CLEANING', 'CONSTRAINED_TRANSPORT'])
      default_MHD.append('EIGHT_WAVES')


    entries_MHD.append('BACKGROUND_FIELD')
    options_MHD.append(['NO','YES'])
    default_MHD.append('NO')

    entries_MHD.append('RESISTIVE_MHD')
    if (WITH_CHOMBO == 1):
      options_MHD.append(['NO','EXPLICIT'])
    else:
#      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING'])

    default_MHD.append('NO')
    
    entries_MHD.append('HALL_MHD')
    options_MHD.append(['NO','RIEMANN','SOURCE'])
    default_MHD.append('NO')
    
    entries_MHD.append('AMBIPOLAR_DIFFUSION')
    options_MHD.append(['NO','EXPLICIT'])
    default_MHD.append('NO')

    entries_MHD.append('THERMAL_CONDUCTION')
    if (WITH_CHOMBO == 1):
      options_MHD.append(['NO','EXPLICIT'])
    else:
#      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING'])

    default_MHD.append('NO')

    entries_MHD.append('VISCOSITY')
    if (WITH_CHOMBO == 1):
      options_MHD.append(['NO','EXPLICIT']) 
    else:   
#      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING','RK_CHEBYSHEV'])
      options_MHD.append(['NO','EXPLICIT','SUPER_TIME_STEPPING'])
    
    default_MHD.append('NO')

    entries_MHD.append('ROTATING_FRAME')
    options_MHD.append(['NO','YES'])
    default_MHD.append('NO')

#  Read MHD pre-existing MHD submenu defaults, if they exists
 
    if (os.path.exists(work_dir+'/definitions.h')):
      for x in entries_MHD:
        ix = entries_MHD.index(x)
        try:
          scrh = file.string_list(work_dir+'/definitions.h',x)
          tmp  = string.split(scrh[0])
          try:   # if the choice is not in the permitted list of options,
                 # ValueError is raised and the default choice is kept.
            i = options_MHD[ix].index(tmp[2])
            default_MHD[ix] = tmp[2]
          except ValueError:
            continue
        except IndexError:
          continue

    if AUTO_UPDATE == 0:
      selection = ''
      if (physics_module == 'MHD'):
        menu.SetTitle("MHD Menu")
        selection = menu.Browse(entries_MHD, default_MHD, options_MHD)
#        selection = menu.select(entries_MHD,options_MHD,default_MHD,'MHD MENU')


# RMHD

  if physics_module == 'RMHD':
    entries_RMHD = []
    options_RMHD = []
    default_RMHD = []

    entries_RMHD.append('EOS')
    options_RMHD.append(['IDEAL','TAUB'])
    default_RMHD.append('IDEAL')

    entries_RMHD.append('ENTROPY_SWITCH')
    options_RMHD.append(['NO','YES'])
    default_RMHD.append('NO')

    entries_RMHD.append('MHD_FORMULATION')
    if (WITH_CHOMBO == 1):
      options_RMHD.append(['NONE','EIGHT_WAVES','DIV_CLEANING'])
    else:
      options_RMHD.append(['NONE','EIGHT_WAVES','DIV_CLEANING','CONSTRAINED_TRANSPORT'])
 
    default_RMHD.append('NONE')

#  Read RMHD pre-existing RMHD submenu defaults, if they exists

    if (os.path.exists(work_dir+'/definitions.h')):
      for x in entries_RMHD:
        ix = entries_RMHD.index(x)
        try:
          scrh = file.string_list(work_dir+'/definitions.h',x)
          tmp  = string.split(scrh[0])
          try:   # if the choice is not in the permitted list of options,
                 # ValueError is raised and the default choice is kept.
            i = options_RMHD[ix].index(tmp[2])
            default_RMHD[ix] = tmp[2]
          except ValueError:
            continue
        except IndexError:
          continue

    if AUTO_UPDATE == 0:
      selection = ''
      if (physics_module == 'RMHD'):
        menu.SetTitle("RMHD Menu")
        selection = menu.Browse(entries_RMHD, default_RMHD, options_RMHD)
#        selection = menu.select(entries_RMHD,options_RMHD,default_RMHD,'RMHD MENU')

# ********************************************************************
#    USER_DEF PARAMETERS:
#
#      Read them from definitions.h if the file exists; 
#      assign  'SCRH' otherwise.
# ********************************************************************

  i    = entries.index('USER_DEF_PARAMETERS')
  npar = int(default[i])
  u_def_par = []
  if (os.path.exists(work_dir+'/definitions.h')):
    scrh = file.word_find(work_dir+'/definitions.h','parameters')
    k0   = scrh[0] + 2
    scrh = file.read_lines(work_dir+'/definitions.h', k0, k0 + npar)
    for n in range(npar):
      try:
        x = string.split(scrh[n])
        if (x[0] == "#define"):
          u_def_par.append(x[1])
        else:          
          u_def_par.append('SCRH')
      except IndexError:
        u_def_par.append('SCRH')
#        scrh[n + 1] = '#define SCRH  x'


  else:
    for n in range(npar):
      u_def_par.append('SCRH')


  if AUTO_UPDATE == 0:
#    u_def_par = ['SCRH']
    menu.SetTitle ("User-defined parameters")
    menu.Insert(int(default[i]),u_def_par)
#    menu.put(int(default[i]),u_def_par,'USER DEF SECTION')

# -----------------------------------------------------
#   Create the list 'tmp' that will be used to write
#   the new definitions.h header file
# -----------------------------------------------------

  tmp = []
  for x in entries:
    i = entries.index(x)
    y = default[i]
    tmp.append('#define  '+x.ljust(21)+'   '+y+'\n')

  tmp.append('\n/* -- physics dependent declarations -- */\n\n');

  if (physics_module == 'MHD'):
    for x in entries_MHD:
      i = entries_MHD.index(x)
      tmp.append('#define  '+x.ljust(21)+'   '+default_MHD[i]+'\n')

  if physics_module == 'HD':
    for x in entries_HD:
      i = entries_HD.index(x)
      tmp.append('#define    '+x.ljust(21)+'   '+default_HD[i]+'\n')

  if physics_module == 'RHD':
    for x in entries_RHD:
      i = entries_RHD.index(x)
      tmp.append('#define    '+x.ljust(21)+'   '+default_RHD[i]+'\n')

  if physics_module == 'RMHD':
    for x in entries_RMHD:
      i = entries_RMHD.index(x)
      tmp.append('#define    '+x.ljust(21)+'   '+default_RMHD[i]+'\n')

# *****************************************
#     add Chombo-AMR specific flags 
# *****************************************

  if (WITH_CHOMBO and os.path.exists(work_dir+'/definitions.h')):
    scrh = file.string_list(work_dir+'/definitions.h','AMR_EN_SWITCH')
    tmp.append('\n/* -- Chombo-AMR flags -- */\n\n');
    if (len(scrh) != 0): 
      strsplit = string.split(scrh[0])
      value    = strsplit[2]
      tmp.append('#define  AMR_EN_SWITCH   '+value+'\n')
    else:
      tmp.append('#define  AMR_EN_SWITCH   NO\n')

# *******************************************************
#     add pointer names to user defined parameters
# *******************************************************

  tmp.append('\n/* -- pointers to user-def parameters -- */\n\n');

  for x in u_def_par:
    i = u_def_par.index(x)
    tmp.append('#define  '+x.ljust(16)+'   '+repr(i)+'\n')

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  #   In this section, also, udpate the pluto.ini 
  #   initialization file by appending the correct 
  #   sequence of user defined parameters
  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

#  menu.RestoreScreen()
  plutoini = work_dir+"/pluto.ini"
  scrh = file.string_find (plutoini, 'Parameters')
  ipos = scrh[0] + 2  # start reading/writing pluto.ini at this point  
                      # to build a list of the userdef parameters
  scrh = file.read_lines(plutoini,ipos,999) # read until end of file
    
  pname  = []
  pvalue = []

  for x in scrh:
    y = string.split(x)  # pname and pvalue contain the list of parameter
    if (len(y) == 0): continue  # skip blank lines 
    pname.append (y[0])  # names and their respective values as present
    pvalue.append(y[1])  # in pluto.ini

  for x in u_def_par:    # loop on the actual list of parameters;
    par_exist = 0        # is the parameter already present in pluto.ini ?
    for y in pname:
      if (x == y):       # if yes, use the original value instead of '0'
        par_exist = 1
        i = pname.index(y)
        file.insert (plutoini, pname[i] + "    " + pvalue[i] + "\n", ipos)
        break

    if (par_exist == 0):  # if not, set default value to 0
      file.insert (plutoini, x+'    0\n',ipos)

    ipos = ipos + 1

  # delete all other lines in pluto.ini

  file.delete_lines(plutoini, ipos, ipos + 256) 

# ***************************************************************
#    check dependencies for conditional inclusion
#    of additional object files; this is useful 
#    for makefile creation
# ***************************************************************

# additional files will be compiled 
# depending on the user's choice of
# time integration scheme
 
# the next line removes all elements from additional_files
# and pluto_path so the list can be built from scratch

#  for x in additional_files: additional_files.remove(x)
#  for x in pluto_path      : pluto_path.remove(x)

  additional_files[:] = []
  additional_flags[:] = []
  pluto_path[:] = []

  divb = ' '

  # **********************************************
  #   physics module & parabolic term treatment
  # **********************************************

  sts_flag = 0 # if changed to 1, include the super-time-stepping driver
  rkc_flag = 0 # if changed to 1, include the runge-kutta-Chebyshev driver
  exp_flag = 0 # if changed to 1, include explicit parabolic time-stepping
  cur_flag = 0 # if changed to 1, include current calculation

  if (physics_module == 'HD'):
    pluto_path.append('HD/')
    entries_MOD = entries_HD
    default_MOD = default_HD

    n = entries_MOD.index('THERMAL_CONDUCTION')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('Thermal_Conduction/')
      if   (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
      elif (default_MOD[n] == 'RK_CHEBYSHEV'):        rkc_flag = 1
      elif (default_MOD[n] == 'EXPLICIT'):            exp_flag = 1

    n = entries_MOD.index('VISCOSITY')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('Viscosity/')
      if   (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
      elif (default_MOD[n] == 'RK_CHEBYSHEV'):        rkc_flag = 1
      elif (default_MOD[n] == 'EXPLICIT'):            exp_flag = 1
      
  elif (physics_module == 'RHD'):
    pluto_path.append('RHD/')
    entries_MOD = entries_RHD
    default_MOD = default_RHD

  elif (physics_module == 'MHD'):
    pluto_path.append('MHD/')
    entries_MOD = entries_MHD
    default_MOD = default_MHD
    n    = entries_MOD.index('MHD_FORMULATION')
    divb = default_MOD[n]
    if (divb == 'CONSTRAINED_TRANSPORT'):
      pluto_path.append('MHD/CT/')
    elif (divb == 'DIV_CLEANING'):
      pluto_path.append('MHD/GLM/')

    n = entries_MOD.index('RESISTIVE_MHD')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('MHD/Resistive/')
      cur_flag = 1
      if   (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
      elif (default_MOD[n] == 'RK_CHEBYSHEV'):        rkc_flag = 1
      elif (default_MOD[n] == 'EXPLICIT'):            exp_flag = 1
      
    n = entries_MOD.index('HALL_MHD')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('MHD/Hall/')
      if   (default_MOD[n] == 'RIEMANN'):			  cur_flag = 1
      
    n = entries_MOD.index('AMBIPOLAR_DIFFUSION')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('MHD/Ambipolar/')
      cur_flag = 1

    n = entries_MOD.index('THERMAL_CONDUCTION')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('Thermal_Conduction/')
      if   (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
      elif (default_MOD[n] == 'RK_CHEBYSHEV'):        rkc_flag = 1
      elif (default_MOD[n] == 'EXPLICIT'):            exp_flag = 1
      
    n = entries_MOD.index('VISCOSITY')
    if (default_MOD[n] != 'NO'):
      pluto_path.append('Viscosity/')
      if   (default_MOD[n] == 'SUPER_TIME_STEPPING'): sts_flag = 1
      elif (default_MOD[n] == 'RK_CHEBYSHEV'):        rkc_flag = 1
      elif (default_MOD[n] == 'EXPLICIT'):            exp_flag = 1
  
    if ( cur_flag == 1):
      pluto_path.append('MHD/Current/')
      additional_flags.append(' -DNEED_CURRENT')
    # ***************************
    #  need shearingbox module ?
    # ***************************

    if (WITH_SB == 1):
      pluto_path.append('MHD/ShearingBox/')
      additional_flags.append(' -DSHEARINGBOX')
       
  
  elif (physics_module == 'RMHD'):
    pluto_path.append('RMHD/')
    entries_MOD = entries_RMHD
    default_MOD = default_RMHD
    n    = entries_MOD.index('MHD_FORMULATION')
    divb = default_MOD[n]
    if (divb == 'CONSTRAINED_TRANSPORT'):
      pluto_path.append('MHD/CT/')
    elif (divb == 'DIV_CLEANING'):
      pluto_path.append('MHD/GLM/')

  # *****************************
  #       Interpolation   
  # *****************************

  if (interpolation == 'FLAT'):
    additional_files.append('states_flat.o')
  elif   (interpolation == 'LINEAR'):
    additional_files.append('states_plm.o')
  elif (interpolation == 'PARABOLIC'):
    additional_files.append('states_ppm.o')
  elif (interpolation == 'LimO3'):
    additional_files.append('states_limo3.o')
  elif (interpolation == 'WENO3'):
    additional_files.append('states_weno3.o')

  elif (WITH_FD):    # Finite Difference

    additional_files.append('states_fd.o')
    additional_files.append('fd_reconstruct.o')
    additional_files.append('fd_flux.o')
    additional_flags.append(' -DFINITE_DIFFERENCE')
    

  # *****************************
  #       Time Stepping
  # *****************************

  if (WITH_CHOMBO):     # ** AMR file inclusion ** 

    if (dimensions == 1): additional_files.append('PatchCTU.1D.o')
    else:                 
      if (time_stepping == 'RK_MIDPOINT'): 
        additional_files.append('PatchRK.3D.o')
      elif (time_stepping == 'EULER'):
        additional_files.append('PatchEuler.3D.o')
      elif (time_stepping == 'RK2'):
        additional_files.append('PatchEuler.3D.o')
      else:
        additional_files.append('PatchCTU.3D.o')

  else:
    if (time_stepping == 'CHARACTERISTIC_TRACING'):
       if (dim_splitting == 'YES'): additional_files.append('sweep.o')
       else:                        additional_files.append('unsplit_ctu.o')
    elif (time_stepping == 'HANCOCK'):
       if (dim_splitting == 'YES'): additional_files.append('sweep.o')
       else:                        additional_files.append('unsplit_ctu.o')
    elif (time_stepping == 'RK_MIDPOINT'):
       additional_files.append('rk_midpoint.o')
    else:
       if (dim_splitting == 'YES'): additional_files.append('sweep.o')
       else:                        additional_files.append('unsplit.o')


  if (time_stepping == 'CHARACTERISTIC_TRACING'):
    additional_files.append('char_tracing.o')
  elif (time_stepping == 'HANCOCK'):
    additional_files.append('hancock.o')


#  if (interpolation != 'LINEAR'):
#    if (time_stepping == 'CHARACTERISTIC_TRACING'):
#      additional_files.append('states_ppm_char.o')
#    else:
#      additional_files.append('rk_states.o')


  # *****************************
  #      FARGO Scheme 
  # *****************************
 
  if (WITH_FARGO):  
    pluto_path.append('Fargo/')
    additional_flags.append(' -DFARGO')

  # *****************************
  #      Geometry 
  # *****************************

 #  additional_files.append('rhs.o')
 #   additional_files.append('rhs.o')

#  if (geometry == "CARTESIAN"):
#    additional_files.append('rhs_cart.o')
#  if (geometry == "AXISYM"):
#    additional_files.append('cylsource.o')

  # *****************************
  #         Cooling 
  # *****************************

  n = entries.index('COOLING')
    
  if (default[n] == 'POWER_LAW'):
    pluto_path.append('Cooling/Power_Law/')
  elif (default[n] == 'TABULATED'):
    pluto_path.append('Cooling/Tab/')
    additional_files.append('cooling_source.o')
    additional_files.append('cooling_ode_solver.o')
  elif (default[n] == 'SNEq'):
    pluto_path.append('Cooling/SNEq/')
    additional_files.append('cooling_source.o')
    additional_files.append('cooling_ode_solver.o')
  elif (default[n] == 'MINEq'):
    pluto_path.append('Cooling/MINEq/')
    additional_files.append('cooling_source.o')
    additional_files.append('cooling_ode_solver.o')
  elif (default[n] == 'H2_COOL'):
    pluto_path.append('Cooling/H2_COOL/')
    additional_files.append('cooling_source.o')
    additional_files.append('cooling_ode_solver.o')
    

  # **********************************
  #   parabolic flux: file inclusion
  # **********************************

  if (sts_flag == 1): 
    additional_files.append('sts.o')
    additional_files.append('parabolic_rhs.o')

  if (rkc_flag == 1): 
    additional_files.append('rkc.o')
    additional_files.append('parabolic_rhs.o')

  if (exp_flag == 1): 
    additional_files.append('parabolic_flux.o')

  # **********************************************
  #          Vector potential
  # **********************************************

  if (physics_module == 'MHD' or physics_module == 'RMHD'):
    additional_files.append('vec_pot_diff.o')
    if (WITH_CHOMBO == 0): additional_files.append('vec_pot_update.o')
  
  # *****************************
  #          Particles
  # *****************************

#  n = entries.index('INCLUDE_PARTICLES')
#  if (default[n] == 'YES'):
#    pluto_path.append('Particles/')

# ****************************************************************
#       DEFINE ALL NON-USER FRIENDLY CONSTANTS
# ****************************************************************

  tmp.append('\n/* -- supplementary constants (user editable) -- */ \n\n')

  no_us_fr = []

  no_us_fr.append('#define  INITIAL_SMOOTHING     NO\n')
  no_us_fr.append('#define  WARNING_MESSAGES      NO\n')
  no_us_fr.append('#define  PRINT_TO_FILE         NO\n')
  no_us_fr.append('#define  INTERNAL_BOUNDARY     NO\n')
  no_us_fr.append('#define  SHOCK_FLATTENING      NO\n')
  if (not WITH_FD): 
    no_us_fr.append('#define  ARTIFICIAL_VISCOSITY  NO\n')
    no_us_fr.append('#define  CHAR_LIMITING         NO\n')
    no_us_fr.append('#define  LIMITER               DEFAULT\n')

# add geometry-dependent switches

  if (geometry == "AXISYM"):
    no_us_fr.append('#define  ADD_CYLSOURCE            1\n')

#  if (geometry == "POLAR" and physics_module == "HD"):
#    no_us_fr.append('#define  FARGO_SCHEME          NO\n')

# add flux ct switches for MHD or RMHD
  
  if (divb == "CONSTRAINED_TRANSPORT"):
    no_us_fr.append('#define  CT_EMF_AVERAGE           UCT_HLL\n')
    no_us_fr.append('#define  CT_EN_CORRECTION         NO\n')
    no_us_fr.append('#define  ASSIGN_VECTOR_POTENTIAL  YES\n')  
  elif (physics_module == "MHD" or physics_module == "RMHD"):
    no_us_fr.append('#define  ASSIGN_VECTOR_POTENTIAL  NO\n')  
    
     
  if (physics_module == "MHD" or physics_module == "RMHD"):
    if (not WITH_CHOMBO): 
      no_us_fr.append('#define  UPDATE_VECTOR_POTENTIAL  NO\n')  

  if (time_stepping == 'HANCOCK'):
    if (physics_module == 'RMHD'):
      no_us_fr.append('#define  PRIMITIVE_HANCOCK     NO\n')
    else:
      no_us_fr.append('#define  PRIMITIVE_HANCOCK     YES\n')

# add definition of STS_NU

  if (sts_flag == 1):
    no_us_fr.append('#define  STS_nu                0.01\n')
    
# ***************************************************************
#    Read pre-existing non-user-editable defaults;
#    Use the default value if they exist
# ***************************************************************

  if (os.path.exists(work_dir+'/definitions.h')):
    for x in no_us_fr:
      try:
        xl   = string.split(x)
        scrh = file.string_list(work_dir+'/definitions.h',xl[1])
        no_us_fr[no_us_fr.index(x)] = scrh[0]
      except IndexError:
        continue


# add elements of no_us_fr to tmp 

  for x in no_us_fr:
    tmp.append(x)

# -- create definitions.h --
    
  file.create_file(work_dir+'/definitions.h',tmp)

  return
Пример #12
0
#Comment
try:
    answer = 1
    while answer < 3 and answer > 0:

        answer = int(input("What would you like to do? \n(1) Simple Calculator \n(2) Create / Edit / Read a File \n(3) Nothing \nAnswer: "))

        if answer == 1:
            print("\nYou chose '1'.")
            num1 = float(input("First number: "))
            num2 = float(input("Second number: "))
            operator = input ("What to do with it: ")
            calculator.simple_calculator(num1,num2,operator)

        elif answer == 2:
            print("\nYou chose '2'.")
            option = input("Create, Edit, or Read a file: ")
            if option.lower() == "create":
                file.create_file()
            elif option.lower() == "edit":
                file.edit_file()
            elif option.lower() == "read":
                file.read_file()
            else:
                print("That is not an option.\n")

        else:
            print("\nYou chose '3' or a number that is out of range. Bye.")

except:
    print("\nYou have entered an invalid answer. Bye.")