Esempio n. 1
0
def convert(src, tgt, txt, nativize, preoptions, postoptions):
    txt = PreProcess.PreProcess(txt, src, tgt)

    if 'siddhamUnicode' in postoptions and tgt == 'Siddham':
        tgt = 'SiddhamUnicode'
    if 'LaoNative' in postoptions and tgt == 'Lao':
        tgt = 'Lao2'
    if 'siddhamUnicode' in preoptions and src == 'Siddham':
        src = 'SiddhamUnicode'
    if 'egrantamil' in preoptions and src == 'Grantha':
        src = 'GranthaGrantamil'
    if 'egrantamil' in postoptions and tgt == 'Grantha':
        tgt = 'GranthaGrantamil'

    for options in preoptions:
        txt = getattr(PreProcess, options)(txt)

    transliteration = Convert.convertScript(txt, src, tgt)

    if nativize:
        transliteration = PostOptions.ApplyScriptDefaults(
            transliteration, src, tgt)
        if tgt != 'Tamil':
            transliteration = PostProcess.RemoveDiacritics(transliteration)
        else:
            transliteration = PostProcess.RemoveDiacriticsTamil(
                transliteration)

    for options in postoptions:
        transliteration = getattr(PostProcess, options)(transliteration)

    return transliteration
Esempio n. 2
0
def fetch_site():
    url = request.args['url']
    r = requests.get(url)
    if "UTF-8" not in r.encoding:
        r.encoding = r.apparent_encoding

    htmlcontent = r.text

    #htmlcontent = htmlcontent.replace('href="/', 'href="' + url + '/')

    baseurl = re.sub('(https*://)([^/]+)/*.*', r'\1'+ r'\2', url,flags=re.IGNORECASE)
    baseurl = baseurl.replace('‍','')

    #print('Base URL')
    #print(baseurl)

    htmlcontent = convert(request.args['source'], request.args['target'], htmlcontent, json.loads(request.args['nativize']),
        json.loads(request.args['preOptions']), json.loads(request.args['postOptions']))

    # Replace relative paths with absolute paths
    htmlcontent=re.sub("(\")/",r"\1"+baseurl+"/",htmlcontent)
    htmlcontent=re.sub("(\.\")/",r"\1"+baseurl+"/",htmlcontent)
    htmlcontent=re.sub("(url\()\/",r"\1"+baseurl+"/",htmlcontent)

    ## Parameters

    params = 'source=' + request.args['source'] + '&target=' + request.args['target'] + '&preOptions=' + request.args['preOptions'] + '&postOptions=' + request.args['postOptions'] + '&nativize=' + request.args['nativize']

    transurl = html.escape("http://aksharamukha.appspot.com/api/website?"+params+'&url=')

    # fix double dot
    urlparts = url.split("/")
    doubledot =""
    for  i in range(0, len(urlparts)-2):
        doubledot = doubledot + urlparts[i]+ "/"

    htmlcontent=htmlcontent.replace("../",doubledot)

    ## Replace links

    htmlcontent=re.sub("(<a href\=\"?)",r"\1"+transurl,htmlcontent)
    htmlcontent=re.sub("(<a class=.*? href\=\"?)",r"\1"+transurl,htmlcontent)
    htmlcontent=re.sub("(<a target\=\"\_blank\" href\=\")",r"\1"+transurl,htmlcontent)
    htmlcontent=re.sub("(<a target\=\"\_self\" href\=\")",r"\1"+transurl,htmlcontent)

    ## Replace with native numerals

    htmlcontent = PostProcess.RetainIndicNumerals(htmlcontent, request.args['target'], True)

    ## Retain Dandas

    htmlcontent = PostProcess.RetainDandasIndic(htmlcontent, request.args['target'], True)

    return htmlcontent
Esempio n. 3
0
def convert(src, tgt, txt, nativize, preoptions, postoptions):
    txt = PreProcess.PreProcess(txt, src, tgt)

    if 'siddhammukta' in postoptions and tgt == 'Siddham':
        tgt = 'SiddhamDevanagari'
    if 'siddhamap' in postoptions and tgt == 'Siddham':
        tgt = 'SiddhamDevanagari'
    if 'siddhammukta' in preoptions and src == 'Siddham':
        src = 'SiddhamDevanagari'
    if 'LaoNative' in postoptions and tgt == 'Lao':
        tgt = 'Lao2'
    if 'egrantamil' in preoptions and src == 'Grantha':
        src = 'GranthaGrantamil'
    if 'egrantamil' in postoptions and tgt == 'Grantha':
        tgt = 'GranthaGrantamil'
    if 'nepaldevafont' in postoptions and tgt == 'Newa':
        tgt = 'Devanagari'
    if 'ranjanalantsa' in postoptions and tgt == 'Ranjana':
        tgt = 'Tibetan'
        nativize = False
    if 'ranjanawartu' in postoptions and tgt == 'Ranjana':
        tgt = 'Tibetan'
        nativize = False

    for options in preoptions:
        txt = getattr(PreProcess, options)(txt)

    transliteration = Convert.convertScript(txt, src, tgt)

    if nativize:
        transliteration = PostOptions.ApplyScriptDefaults(
            transliteration, src, tgt)
        if tgt != 'Tamil':
            transliteration = PostProcess.RemoveDiacritics(transliteration)
        else:
            transliteration = PostProcess.RemoveDiacriticsTamil(
                transliteration)

    for options in postoptions:
        transliteration = getattr(PostProcess, options)(transliteration)

    if src == "Tamil" and tgt == "IPA":
        r = requests.get("http://anunaadam.appspot.com/api?text=" + txt +
                         "&method=2")
        r.encoding = r.apparent_encoding
        transliteration = r.text

    return transliteration
Esempio n. 4
0
def GranthaPrakrit(Strng):
    ## Reverse Gemination
    Strng = PostProcess.ReverseGeminationSign(Strng, 'Grantha')

    Strng = Strng.replace("𑌀", "𑌂")

    return Strng
Esempio n. 5
0
def main(dataArray):

    print("start")
    input_x = int(dataArray[0])
    input_y = int(dataArray[1])
    terrain_count = int(dataArray[2])
    grass_prob = dataArray[3]
    cellular_iter_num = int(dataArray[4])
    lamb = dataArray[5]
    snow_size = dataArray[6]

    #맵의 사이즈를 정한다.
    map_size = msize.getSize(input_x, input_y)
    print("complete : map_size_detection")

    #선언되어 있는 타일 및 지형 ID를 읽어온다.

    terrain_id = dm.readTerrainData(terrain_count)
    print("complete : read tileId and terrainId")

    #셀룰러 오토마타를 이용해 물 지형과 땅 지형을 구분한다.

    map_tile = cauto.tileMaker(map_size[0], map_size[1], grass_prob,
                               cellular_iter_num)
    map_tile = cauto.snowMaker(map_size[0], map_size[1], map_tile, snow_size)
    print("complete : tile making by cellularautomata")

    #CellularAutomata
    #포아송 프로세스를 통해 돌과 나무를 뿌린다.

    map_terrain = ppp.terrainMaker(map_size[0], map_size[1], lamb)
    print("complete : terrain making by poisson point process")

    #PoissonPointProcess
    #맵 후처리를 하고 ID를 매핑한다.
    map_tile_real = post.tilePostProcess(map_size[0], map_size[1], map_tile)
    map_terrain_real = post.terrainPostProcess(map_size[0], map_size[1],
                                               terrain_id, map_terrain)
    map_terrain_real = post.deleteTerrain(map_size[0], map_size[1],
                                          map_tile_real, map_terrain_real)
    print("complete : post processing")

    #엑셀 파일로 저장한다.
    #DataManager
    dm.writeMapData(map_size[0], map_size[1], map_tile_real, map_terrain_real)
    print("complete : save the file")
Esempio n. 6
0
 def __init__(self, xml_file):
     self.xml_file = xml_file
     self.tree = etree.parse(xml_file)
     self.postproc = PostProcess.PostProcess()
     self.option = {
         'Little Endian': False,
         'Byte Expand': True,
         'Remove Reserved': True
     }
Esempio n. 7
0
 def OnShow(self):                             #结构图片实时显示
     post.UncalculatedPostProcess('temp.txt')
     image = wx.Image('fig.PNG', wx.BITMAP_TYPE_PNG)
     temp = image.ConvertToBitmap()
     w = temp.GetWidth()
     h = temp.GetHeight()
     w = w/7
     h = h/7
     temp=temp.ConvertToImage().Scale(w,h)
     temp=temp.ConvertToBitmap()
     size = (w,h)
     self.bmp = wx.StaticBitmap(self.panel,-1,temp,pos=(0, 200),size=size)
     self.panel.Refresh()
Esempio n. 8
0
def MalayalamPrakrit(Strng):
    ## Reverse Gemination
    Strng = PostProcess.ReverseGeminationSign(Strng, 'Malayalam')
    Strng = Strng.replace("ഀ", "ം")

    return Strng
Esempio n. 9
0
def SinhalaPali(Strng):
    Strng = PostProcess.SinhalaPali(Strng, reverse=True)

    return Strng
Esempio n. 10
0
    help=
    'Plot the imaginary part as well and save in the same directory as the real part.'
)

(options, args) = parser.parse_args()

if len(args) < 2:
    parser.error('You must specify SIGMAPPATH and FIGPATH! ')

sigmappath, figpath = args[:2]

file = open(sigmappath, 'rb')
sigmamap = cpkl.load(file)
file.close()
Smapdata = AS.get_lmax_subset_from(sigmamap.xlm, options.lmax)
Smap = AS.xlmSkyMap(xlm=options.mapnorm * Smapdata)
Smap.xlm_to_plm()
Smap.xlm_to_qlm()
Smap.create_sky(nlon=options.nlon, nlat=options.nlat)
Smap.plm_to_P()
Smap.qlm_to_Q()

figdir = os.path.dirname(figpath)
if figdir not in glob.glob(figdir):
    os.system('mkdir -p %s' % figdir)
if options.plot_imag:
    Qpath = figdir + '/S_imag.png'
else:
    Qpath = None
PP.project_SkyMap(Smap, Ppath=figpath, Qpath=Qpath)
Esempio n. 11
0
    terrain_id = dm.readTerrainData(terrain_count)
    print("complete : read tileId and terrainId")

    #셀룰러 오토마타를 이용해 물 지형과 땅 지형을 구분한다.

    map_tile = cauto.tileMaker(map_size[0], map_size[1], grass_prob,
                               cellular_iter_num)
    map_tile = cauto.snowMaker(map_size[0], map_size[1], map_tile, snow_size)
    print("complete : tile making by cellularautomata")

    #CellularAutomata
    #포아송 프로세스를 통해 돌과 나무를 뿌린다.

    map_terrain = ppp.terrainMaker(map_size[0], map_size[1], lamb)
    print("complete : terrain making by poisson point process")

    #PoissonPointProcess
    #맵 후처리를 하고 ID를 매핑한다.
    map_tile_real = post.tilePostProcess(map_size[0], map_size[1], map_tile)
    map_terrain_real = post.terrainPostProcess(map_size[0], map_size[1],
                                               terrain_id, map_terrain)
    map_terrain_real = post.deleteTerrain(map_size[0], map_size[1],
                                          map_tile_real, map_terrain_real)
    print("complete : post processing")

    #엑셀 파일로 저장한다.
    #DataManager
    dm.writeMapData(map_size[0], map_size[1], map_tile_real, map_terrain_real)
    print("complete : save the file")
Esempio n. 12
0
P0lm = AS.get_lmax_subset_from( np.copy( P0.xlm ) , lmax )

workdir = os.getcwd() + '/'

for slope in GWslopes :
    for IJ in IJs :
        print 'GWslope = %d , IJ = %s' % ( slope , IJ )
        Gpath = workdir + 'GW_slope_%d/%s/G/G.pkl' % ( slope , IJ )
        fish = AS.FisherMatrix( Gpath , lmax = lmax )
        Xlm = np.dot( fish.fish , P0lm )
        X0path = workdir + 'GW_slope_%d/%s/X/X.pkl' % ( slope , IJ )
        file = open( X0path ) ; X0 = cpkl.load( file ) ; file.close()
        X0lm = AS.get_lmax_subset_from( np.copy( X0.xlm ) , lmax )
        print 'The obtained X is the same as the product of the obtained Fisher mastrix and the injected P.' , np.allclose( Xlm , X0lm )
        print 'X0lm.shape , Xlm.shape = '  , X0lm.shape , ',' , Xlm.shape 
        print 'X0lm[ :10 ]'
        print X0lm[ :10 ]
        print 'Xlm[ :10 ]'
        print Xlm[ :10 ]
        X = AS.xlmSkyMap( xlm = GPnorm * Xlm )
        X.xlm_to_plm() ; X.xlm_to_qlm()
        X.create_sky( nlon = nlon , nlat = nlat )
        X.plm_to_P() ; X.qlm_to_Q() ; X.PQ_to_X()
        figpath = workdir + 'GW_slope_%d/%s/figures_X/GP_real.png' % ( slope , IJ )
        figdir = os.path.dirname( figpath )
        if figdir not in glob.glob( figdir ) :
            os.system( 'mkdir -p %s' % figdir )

        PP.project_SkyMap( X , Ppath = figpath )

Esempio n. 13
0
def convertScript(Strng, Source, Target):
    #print(Target)
    #print(Target in GM.IndicScripts)

    charPairs = []
    Schwa = '\uF000'
    DepV = '\u1E7F'

    if Source in GM.LatinScripts and Target in GM.IndicScripts:
        try:
            Strng = getattr(__import__('ConvertFix'),
                            "Fix" + Source)(Strng, reverse=True)
        except AttributeError:
            pass
            #print #"Fix"+Target+" doesn't exist - Reverse"

        ## Support joiners for HK, Itrans and Velthuis

        if Source == 'Aksharaa':
            Strng = Strng.replace("__", "\u200C")
            Strng = Strng.replace("++", "\u200D")

        punc = '(' + '|'.join(
            ["\u005C" + x for x in list(string.punctuation)] + ['\s'] + [
                x.replace('.', '\.')
                for x in GM.CrunchSymbols(GM.Signs, Source)[1:3]
            ]) + ')'

        sOm, tOm = GM.CrunchList('OmMap',
                                 Source)[0], GM.CrunchList('OmMap', Target)[0]

        Strng = re.sub(punc + sOm + punc, r'\1' + tOm + r'\2', Strng)
        Strng = re.sub('^' + sOm + punc, tOm + r'\1', Strng)
        Strng = re.sub(punc + sOm + '$', r'\1' + tOm, Strng)
        Strng = re.sub('^' + sOm + '$', tOm, Strng)

        SourceOld = Source

        Strng = convertInter(Strng, Source)
        Source = GM.Inter
        Strng = PrP.RomanPreFix(Strng, Source)

        ## HK l_R l_RR

        Strng = Strng.replace("ṿ×_", "ṿ")
        Strng = Strng.replace("ṿ×_", "ṿ")

        ha = GM.CrunchSymbols(GM.Consonants, Source)[32]
        charPairs = []

        for charList in GM.ScriptAll:
            # Crunch all related characters into a list
            TargetScript = GM.CrunchSymbols(GM.retCharList(charList), Target)
            if charList == 'VowelSigns':
                # Add DepVSign to all VowelSigns to differentiate from Independent Vowels
                SourceScript = [
                    DepV + x for x in GM.CrunchSymbols(GM.VowelSigns, Source)
                ]
            else:
                SourceScript = GM.CrunchSymbols(GM.retCharList(charList),
                                                Source)
            # Create a Tuple for the conversion pair
            ScriptMap = list(zip(SourceScript, TargetScript))
            # Sort the mapping in descending order. Longer Characters are to be replaced first. ऍˇ > ऍ
            ScriptMap.sort(reverse=True)
            charPairs = charPairs + ScriptMap

        charPairs = sorted(charPairs, key=cmp_to_key(lenSort))

        # Perform replacement sequentially for each character group
        for x, y in charPairs:
            #print x,y
            Strng = Strng.replace(x, y)

        ## a_i => a<dev>i<dev> ; a_u = a<dev>u<dev>
        Strng = Strng.replace('_' + GM.CrunchSymbols(GM.Vowels, Target)[2],
                              GM.CrunchSymbols(GM.Vowels, Target)[2])
        Strng = Strng.replace('_' + GM.CrunchSymbols(GM.Vowels, Target)[4],
                              GM.CrunchSymbols(GM.Vowels, Target)[4])

        if SourceOld == 'Aksharaa':
            vir = GM.CrunchList('ViramaMap', Target)[0]
            Strng = Strng.replace(vir + "**", "\u200D" + vir)

        #print Strng
        # Apply Fixes on the Output based on the Script
        Strng = CF.FixIndicOutput(Strng, Source, Target)

    elif Source in GM.LatinScripts and Target in GM.LatinScripts:
        try:
            Strng = getattr(__import__('ConvertFix'),
                            "Fix" + Source)(Strng, reverse=True)
        except AttributeError:
            pass
            #print #"Fix"+Target+" doesn't exist - Reverse"

        ScriptAll = GM.Vowels + GM.Consonants + GM.CombiningSigns + GM.Numerals + GM.Signs + GM.Aytham

        Strng = convertInter(Strng, Source)

        SourceScript = GM.CrunchSymbols(ScriptAll, GM.Inter)
        TargetScript = GM.CrunchSymbols(ScriptAll, Target)
        ScriptMapAll = list(zip(SourceScript, TargetScript))

        for x, y in ScriptMapAll:
            Strng = Strng.replace(x, y)

        Strng = CF.PostFixRomanOutput(Strng, Source, Target)

    elif Source in GM.IndicScripts and Target in GM.IndicScripts:
        Strng = CF.ShiftDiacritics(Strng, Source, reverse=True)
        try:
            Strng = getattr(__import__('ConvertFix'),
                            "Fix" + Source)(Strng, reverse=True)
        except AttributeError:
            pass
            #print #"Fix"+Target+" doesn't exist - Reverse"

        punc = '(' + '|'.join(
            ["\u005C" + x for x in list(string.punctuation)] + ['\s'] + [
                x.replace('.', '\.')
                for x in GM.CrunchSymbols(GM.Signs, Source)[1:3]
            ]) + ')'

        sOm, tOm = GM.CrunchList('OmMap',
                                 Source)[0], GM.CrunchList('OmMap', Target)[0]

        if len(sOm) != 1:
            Strng = re.sub(punc + sOm + punc, r'\1' + tOm + r'\2', Strng)
            Strng = re.sub('^' + sOm + punc, tOm + r'\1', Strng)
            Strng = re.sub(punc + sOm + '$', r'\1' + tOm, Strng)
            Strng = re.sub('^' + sOm + '$', tOm, Strng)

        if len(sOm) == 1:
            Strng = Strng.replace(sOm, tOm)

        # Iterate for each character group
        for charList in GM.ScriptAll:
            # Crunch all related characters into a list
            SourceScript = GM.CrunchSymbols(GM.retCharList(charList), Source)
            TargetScript = GM.CrunchSymbols(GM.retCharList(charList), Target)
            # Create a Tuple for the conversion pair
            ScriptMap = list(zip(SourceScript, TargetScript))
            # Sort the mapping in descending order. why ?
            ScriptMap.sort(reverse=True)
            charPairs = charPairs + ScriptMap

        #Sort based on Length - Longest first
        charPairs = sorted(charPairs, key=cmp_to_key(lenSort))

        # Perform replacement sequentially for each character group
        for x, y in charPairs:
            #print x,y
            Strng = Strng.replace(x, y)
            #print Strng

        #Strng = Strng.replace(GM.CrunchList('OmMap', Source)[0],GM.CrunchList('OmMap', Target)[0])
        # Apply Fixes on the Output based on the Script
        Strng = CF.FixIndicOutput(Strng, Source, Target)

    elif Source in GM.IndicScripts and Target in GM.LatinScripts:
        Strng = CF.ShiftDiacritics(Strng, Source, reverse=True)
        try:
            Strng = getattr(__import__('ConvertFix'),
                            "Fix" + Source)(Strng, reverse=True)
        except AttributeError:
            pass
            #print #"Fix"+Target+" doesn't exist - Reverse"

        sOm, tOm = GM.CrunchList('OmMap',
                                 Source)[0], GM.CrunchList('OmMap', Target)[0]

        Strng = Strng.replace(sOm, tOm)

        # Iterate for each character group
        for charList in GM.ScriptAll:
            # Crunch all related characters into a list
            SourceScript = GM.CrunchSymbols(GM.retCharList(charList), Source)
            if charList == 'Consonants':
                # Add Schwa to all Roman consonants. Basically, the Roman script is "Indianized"
                TargetScript = [
                    x + Schwa for x in GM.CrunchSymbols(GM.Consonants, Target)
                ]
            elif charList == 'Vowels':
                # Add DepVSign to all Independent vowel to differentiate from vowel sign.
                TargetScript = [
                    DepV + x for x in GM.CrunchSymbols(GM.Vowels, Target)
                ]
            else:
                TargetScript = GM.CrunchSymbols(GM.retCharList(charList),
                                                Target)
            # Create a Tuple for the conversion pair
            ScriptMap = list(zip(SourceScript, TargetScript))
            # Sort the mapping in descending order. Longer Characters are to be replaced first. ऍˇ > ऍ
            ScriptMap.sort(reverse=True)
            charPairs = charPairs + ScriptMap

        charPairs = sorted(charPairs, key=cmp_to_key(lenSort))

        # Perform replacement sequentially for each character group
        for x, y in charPairs:
            Strng = Strng.replace(x, y)

        # Remove all intermediate characters and fix Output
        Strng = CF.FixRomanOutput(Strng, Target)

        Strng = CF.PostFixRomanOutput(Strng, Source, Target)

        # Convert Syllabic lR -> l_R Important !!!

    elif Source in GM.SiddhamRanjana:
        Strng = SR.SiddhRanjConv(Strng, Source, reverse=True)
        Strng = convertScript(Strng, "HK", Target)

    elif Target in GM.SiddhamRanjana:
        Strng = convertScript(Strng, Source, "HK")
        Strng = SR.SiddhRanjConv(Strng, Target)

    Strng = PP.default(Strng)

    return Strng
Esempio n. 14
0
    mapnorm = 1.
    Xpath = Xdir + 'X.pkl'
    file = open(Xpath, 'rb')
    map_X = cpkl.load(file)
    file.close()
    Xlm = AS.get_lmax_subset_from(map_X.xlm, lmax)
    Xmap = AS.xlmSkyMap(xlm=mapnorm * Xlm)
    Xmap.xlm_to_plm()
    Xmap.xlm_to_qlm()
    Xmap.create_sky(nlon=nlon, nlat=nlat)
    Xmap.plm_to_P()
    Xmap.qlm_to_Q()
    projdir = 'post_process/figures/X/'
    if projdir not in glob.glob(projdir):
        os.system('mkdir -p %s' % projdir)
    PP.project_SkyMap(Xmap, Ppath=projdir + 'Xreal.png')

if True in [
        proj_P, save_P, proj_sigmamap, save_sigmamap, proj_SNRmap, save_SNRmap,
        proj_stdP
]:
    print "Calculating regularised inverse of Fisher matrix"
    Gpath = Gdir + 'G.pkl'
    fish = AS.FisherMatrix(Gpath, lmax=lmax)
    fish.regularise(regMethod=regMethod, regCutoff=regCutoff)
    regfishinv = fish.reginvert()

    if regMethod == None:
        regdir = 'post_process/nonreg/'
    else:
        regdir = 'post_process/reg%d_%.5f/' % (regMethod, regCutoff)
def post_process():
    global probabilities
    message, game_res, moves = PostProcess.post_process(probabilities)
    probabilities = []
    return message + 'delimiter' + game_res + 'delimiter' + moves
Esempio n. 16
0
    print "Nothing to do."

if proj_X :
    print "Plotting X"
    mapnorm = 1.
    Xpath = Xdir + 'X.pkl'
    file = open( Xpath , 'rb' ) ; map_X = cpkl.load( file ) ; file.close()
    Xlm = AS.get_lmax_subset_from( map_X.xlm , lmax )
    Xmap = AS.xlmSkyMap( xlm = mapnorm * Xlm )
    Xmap.xlm_to_plm() ; Xmap.xlm_to_qlm()
    Xmap.create_sky( nlon=nlon , nlat=nlat )
    Xmap.plm_to_P() ; Xmap.qlm_to_Q()
    projdir = 'post_process/figures/X/'
    if projdir not in glob.glob( projdir ) :
        os.system( 'mkdir -p %s' % projdir )
    PP.project_SkyMap( Xmap , Ppath = projdir + 'Xreal.png' )
    


if True in [ proj_P , save_P ,
             proj_sigmamap , save_sigmamap ,
             proj_SNRmap , save_SNRmap ,
             proj_stdP ] :
    print "Calculating regularised inverse of Fisher matrix"
    Gpath = Gdir + 'G.pkl'
    fish = AS.FisherMatrix( Gpath , lmax=lmax )
    fish.regularise( regMethod=regMethod , regCutoff=regCutoff )
    regfishinv = fish.reginvert()

    if regMethod == None :
        regdir = 'post_process/nonreg/'
Esempio n. 17
0
        print 'GWslope = %d , IJ = %s' % (slope, IJ)
        Gpath = workdir + 'GW_slope_%d/%s/G/G.pkl' % (slope, IJ)
        fish = AS.FisherMatrix(Gpath, lmax=lmax)
        Xlm = np.dot(fish.fish, P0lm)
        X0path = workdir + 'GW_slope_%d/%s/X/X.pkl' % (slope, IJ)
        file = open(X0path)
        X0 = cpkl.load(file)
        file.close()
        X0lm = AS.get_lmax_subset_from(np.copy(X0.xlm), lmax)
        print 'The obtained X is the same as the product of the obtained Fisher mastrix and the injected P.', np.allclose(
            Xlm, X0lm)
        print 'X0lm.shape , Xlm.shape = ', X0lm.shape, ',', Xlm.shape
        print 'X0lm[ :10 ]'
        print X0lm[:10]
        print 'Xlm[ :10 ]'
        print Xlm[:10]
        X = AS.xlmSkyMap(xlm=GPnorm * Xlm)
        X.xlm_to_plm()
        X.xlm_to_qlm()
        X.create_sky(nlon=nlon, nlat=nlat)
        X.plm_to_P()
        X.qlm_to_Q()
        X.PQ_to_X()
        figpath = workdir + 'GW_slope_%d/%s/figures_X/GP_real.png' % (slope,
                                                                      IJ)
        figdir = os.path.dirname(figpath)
        if figdir not in glob.glob(figdir):
            os.system('mkdir -p %s' % figdir)

        PP.project_SkyMap(X, Ppath=figpath)
Esempio n. 18
0
Amplitude = 1e-38          #Real number only please!

nlon = 360
nlat = 181

ntrunc = 20
skymap = AS.xlmSkyMap( ntrunc=ntrunc )
if m % 2 == 0 :
    if m == 0:
        skymap.alter_ml( False , (m,l,Amplitude) )
    else:
        skymap.alter_ml( False , (m,l,Amplitude/2.) , (-m,l,Amplitude/2.) )
else:
    skymap.alter_ml( False , (m,l,Amplitude/2.) , (-m,l,-Amplitude/2.) )
skymap.xlm_to_plm()
skymap.xlm_to_qlm()
skymap.create_sky( nlon=nlon , nlat=nlat )
skymap.plm_to_P()
skymap.qlm_to_Q()
skymap.PQ_to_X()


mapname = 'Y_l%d_m%d.pkl' % ( l , m )
mappath = mapdir + mapname
file = open( mappath , 'wb' )
cpkl.dump( skymap , file , -1 )
file.close()


PP.project_SkyMap( skymap )
Esempio n. 19
0
def Run_Cpp_Solver_VLM(VMOPTS, VMINPUT, VMUNST=None, AELOPTS=None):

    # init grid
    if VMUNST == None:
        # Set up variables assuming no unsteady motion
        VMUNST = MyStruct()
        VMUNST.PsiA_G = np.array([0.0, 0.0, 0.0])
        VMUNST.VelA_G = np.array([0.0, 0.0, 0.0])
        VMUNST.OmegaA_G = np.array([0.0, 0.0, 0.0])
        VMUNST.OriginA_G = np.array([0.0, 0.0, 0.0])

    if AELOPTS == None:
        # Set up defaults for grid generation.
        AELOPTS = MyStruct()
        AELOPTS.ElasticAxis = 0.0

    # Initialise DerivedTypes for PyBeam initialization.
    XBOPTS = DerivedTypes.Xbopts()
    XBINPUT = DerivedTypes.Xbinput(2, VMOPTS.N.value, VMINPUT.b)
    # Create a dummy stiffness matrix to avoid errors.
    XBINPUT.BeamStiffness = np.eye(6, dtype=ct.c_double)
    # Use PyBeam to define reference beam (elastic axis).
    XBINPUT, XBOPTS, NumNodes_tot, XBELEM, PosIni, PsiIni,\
            XBNODE, NumDof = BeamInit.Static(XBINPUT, XBOPTS)
    # Delete unnecessary variables.
    del XBELEM, XBNODE, NumDof
    # Copy reference beam to current (deformed) variables.
    PosDefor = PosIni.copy(order='F')
    PsiDefor = PsiIni.copy(order='F')
    # Declare empty array for beam DoF rates.
    PosDotDef = np.zeros_like(PosDefor, ct.c_double, 'F')
    PsiDotDef = np.zeros_like(PsiDefor, ct.c_double, 'F')

    # Check the specified inputs from the PyAero have been properly applied.
    assert NumNodes_tot.value - 1 == VMOPTS.N.value, "Initialisation wrong"

    # Initialise section coordinates.
    Section = InitSection(VMOPTS, VMINPUT, AELOPTS.ElasticAxis)

    # Initialise origin and orientation of surface velocities in a-frame
    CGa = Psi2TransMat(VMUNST.PsiA_G)
    VelA_A = np.dot(CGa.T, VMUNST.VelA_G)
    OmegaA_A = np.dot(CGa.T, VMUNST.OmegaA_G)

    # Declare empty array for aerodynamic grid and velocities.
    Zeta = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3), ct.c_double,
                    'C')
    ZetaDot = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3),
                       ct.c_double, 'C')

    # Initialise aerodynamic grid and velocities.
    CoincidentGrid(PosDefor, PsiDefor, Section, VelA_A, OmegaA_A, PosDotDef,
                   PsiDotDef, XBINPUT, Zeta, ZetaDot, VMUNST.OriginA_G,
                   VMUNST.PsiA_G, VMINPUT.ctrlSurf)

    # init wake
    ZetaStar, GammaStar = InitSteadyWake(VMOPTS, VMINPUT, Zeta)

    # init external velocities
    Uext = InitSteadyExternalVels(VMOPTS, VMINPUT)

    # Solver variables.
    Gamma = np.zeros((VMOPTS.M.value, VMOPTS.N.value), ct.c_double, 'C')
    Forces = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3), ct.c_double,
                      'C')

    # Solve
    UVLMLib.Cpp_Solver_VLM(Zeta, ZetaDot, Uext, ZetaStar, VMOPTS, Forces,
                           Gamma, GammaStar)

    # Print tecplot file to check wake and grid etc
    Variables = ['X', 'Y', 'Z', 'Gamma']

    # write header

    Filename = Settings.OutputDir + Settings.OutputFileRoot + 'AeroGrid.dat'

    FileObject = PostProcess.WriteAeroTecHeader(Filename, 'Default', Variables)

    # write surface zone data
    PostProcess.WriteAeroTecZone(FileObject, 'Surface', Zeta, -1, 0, 0.0,
                                 Variables, False, Gamma)

    # write wake data
    PostProcess.WriteAeroTecZone(FileObject, 'Wake', ZetaStar, -1, 0, 0.0,
                                 Variables, False, GammaStar)

    # close file
    PostProcess.CloseAeroTecFile(FileObject)

    if Settings.WriteUVLMdebug == True:
        debugFile = Settings.OutputDir + 'gamma_1degBeta.dat'
        np.savetxt(debugFile, Gamma.flatten('C'))

    # post process to get coefficients
    return PostProcess.GetCoeffs(VMOPTS, Forces, VMINPUT, VMUNST.VelA_G)
Esempio n. 20
0
def Run_Cpp_Solver_UVLM(VMOPTS, VMINPUT, VMUNST, AELOPTS):
    """@brief UVLM solver with prescribed inputs."""

    # Initialise DerivedTypes for PyBeam initialisation.
    XBOPTS = DerivedTypes.Xbopts()
    XBINPUT = DerivedTypes.Xbinput(2, VMOPTS.N.value, VMINPUT.b)
    # Create a dummy stiffness matrix to avoid errors.
    XBINPUT.BeamStiffness = np.eye(6, 6, 0, ct.c_double)
    # Use PyBeam to define reference beam (elastic axis).
    XBINPUT, XBOPTS, NumNodes_tot, XBELEM, PosIni, PsiIni,\
            XBNODE, NumDof = BeamInit.Static(XBINPUT, XBOPTS)
    # Delete unnecessary variables.
    del XBELEM, XBNODE, NumDof
    # Copy reference beam to current (deformed) variables.
    PosDefor = PosIni.copy(order='F')
    PsiDefor = PsiIni.copy(order='F')
    # Declare empty array for beam DoF rates.
    PosDotDef = np.zeros_like(PosDefor, ct.c_double, 'F')
    PsiDotDef = np.zeros_like(PsiDefor, ct.c_double, 'F')

    # Check the specified inputs from the PyAero have been properly applied.
    assert NumNodes_tot.value - 1 == VMOPTS.N.value, "Initialisation wrong"

    # Initialise section coordinates.
    Section = InitSection(VMOPTS, VMINPUT, AELOPTS.ElasticAxis)

    # Initialise origin and orientation of surface velocities in a-frame
    CGa = Psi2TransMat(VMUNST.PsiA_G)
    VelA_A = np.dot(CGa.T, VMUNST.VelA_G)
    OmegaA_A = np.dot(CGa.T, VMUNST.OmegaA_G)

    # Declare empty array for aerodynamic grid and velocities.
    Zeta = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3), ct.c_double,
                    'C')
    ZetaDot = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3),
                       ct.c_double, 'C')

    # Initialise aerodynamic grid and velocities.
    CoincidentGrid(PosDefor, PsiDefor, Section, VelA_A, OmegaA_A, PosDotDef,
                   PsiDotDef, XBINPUT, Zeta, ZetaDot, VMUNST.OriginA_G,
                   VMUNST.PsiA_G, VMINPUT.ctrlSurf)

    # Initialise wake for unsteady solution.
    ZetaStar, GammaStar = InitSteadyWake(VMOPTS, VMINPUT, Zeta, VMUNST.VelA_G)

    # Initialise external velocities.
    Uext = InitSteadyExternalVels(VMOPTS, VMINPUT)

    # Declare empty solver variables.
    Forces = np.zeros_like(Zeta, ct.c_double, 'C')
    Gamma = np.zeros((VMOPTS.M.value, VMOPTS.N.value), ct.c_double, 'C')
    AIC = np.zeros(
        (VMOPTS.M.value * VMOPTS.N.value, VMOPTS.M.value * VMOPTS.N.value),
        ct.c_double, 'C')
    BIC = np.zeros(
        (VMOPTS.M.value * VMOPTS.N.value, VMOPTS.M.value * VMOPTS.N.value),
        ct.c_double, 'C')

    # Open tecplot file object."
    Variables = ['X', 'Y', 'Z', 'Gamma']
    Filename = Settings.OutputDir + Settings.OutputFileRoot + 'AeroGrid.dat'
    FileObject = PostProcess.WriteAeroTecHeader(Filename, 'Default', Variables)

    # Initialise vector of time steps.
    Time = np.arange(0.0, VMUNST.FinalTime + VMUNST.DelTime, VMUNST.DelTime)
    # Create Array for storing time and coefficient data.
    CoeffHistory = np.zeros((len(Time), 4))

    # Loop through time steps.
    for iTimeStep in range(len(Time)):

        # Set forces array to zero (+= operator used in C++ library).
        Forces[:, :, :] = 0.0

        if iTimeStep > 0:

            # Update geometry.
            VMUNST.OriginA_G[:] += VMUNST.VelA_G[:] * VMUNST.DelTime
            # TODO: update OmegaA_A in pitching problem.

            # Update control surface defintion.
            if VMINPUT.ctrlSurf != None:
                VMINPUT.ctrlSurf.update(Time[iTimeStep])

            # Update aerodynamic surface.
            CoincidentGrid(PosDefor, PsiDefor, Section, VelA_A, OmegaA_A,
                           PosDotDef, PsiDotDef, XBINPUT, Zeta, ZetaDot,
                           VMUNST.OriginA_G, VMUNST.PsiA_G, VMINPUT.ctrlSurf)

            # Convect wake downstream.
            ZetaStar = np.roll(ZetaStar, 1, axis=0)
            GammaStar = np.roll(GammaStar, 1, axis=0)
            # Overwrite 1st row with with new trailing-edge position.
            ZetaStar[0, :] = Zeta[VMOPTS.M.value, :]
            # Overwrite Gamma with TE value from previous time step.
            GammaStar[0, :] = Gamma[VMOPTS.M.value - 1, :]

            # set NewAIC to false.
            if VMINPUT.ctrlSurf == False:
                VMOPTS.NewAIC = ct.c_bool(False)

        # END if iTimeStep > 1

        # Calculate forces on aerodynamic grid.
        UVLMLib.Cpp_Solver_VLM(Zeta, ZetaDot, Uext, ZetaStar, VMOPTS, Forces,
                               Gamma, GammaStar, AIC, BIC)

        #print(PostProcess.GetCoeffs(VMOPTS, Forces, VMINPUT, VMUNST.VelA_G))

        CoeffHistory[iTimeStep, 0] = Time[iTimeStep]
        CoeffHistory[iTimeStep,
                     1:] = PostProcess.GetCoeffs(VMOPTS, Forces, VMINPUT,
                                                 VMUNST.VelA_G)

        # Write aerodynamic surface data as tecplot zone data.
        PostProcess.WriteAeroTecZone(FileObject, 'Surface', Zeta,\
                                     iTimeStep, len(Time),\
                                     Time[iTimeStep], Variables, False, Gamma)

        # Write wake data as tecplot zone data.
        PostProcess.WriteAeroTecZone(FileObject, 'Wake', ZetaStar,\
                                    iTimeStep, len(Time),\
                                    Time[iTimeStep], \
                                    Variables, False, GammaStar)

        # Rollup due to external velocities.
        ZetaStar[:, :] += VMINPUT.U_infty * VMOPTS.DelTime.value

    # END for iTimeStep

    # Close tecplot file object.
    PostProcess.CloseAeroTecFile(FileObject)

    return CoeffHistory
Esempio n. 21
0
parser.add_option( '--nlat' , action='store' , dest='nlat' , type='int' , default=91 ,
                   help='Number of latitudes to plot in the sky.' )

parser.add_option( '--plot_imag' , action='store_true' ,
                   help='Plot the imaginary part as well and save in the same directory as the real part.' )

( options , args ) = parser.parse_args()

if len( args ) < 2 :
    parser.error( 'You must specify SIGMAPPATH and FIGPATH! ' )

sigmappath , figpath = args[ :2 ]

file = open( sigmappath , 'rb' ) ; sigmamap = cpkl.load( file ) ; file.close()
Smapdata = AS.get_lmax_subset_from( sigmamap.xlm , options.lmax )
Smap = AS.xlmSkyMap( xlm = options.mapnorm * Smapdata )
Smap.xlm_to_plm() ; Smap.xlm_to_qlm()
Smap.create_sky( nlon=options.nlon , nlat=options.nlat ) ; Smap.plm_to_P() ; Smap.qlm_to_Q()

figdir = os.path.dirname( figpath )
if figdir not in glob.glob( figdir ) :
    os.system( 'mkdir -p %s' % figdir )
if options.plot_imag :
    Qpath = figdir + '/S_imag.png'
else :
    Qpath = None
PP.project_SkyMap( Smap , Ppath = figpath , Qpath = Qpath )


Esempio n. 22
0
 def OnStart(self, event):  #主程序启动
     pp.preprocess()
     ana.analyzer()
     post.CalculatedPostProcess('temp.txt')
     frame = Result(parent=None, id=-1)
     frame.Show()
Esempio n. 23
0
def conjuncts_list():
    script1 = request.json['script1']
    script2 = request.json['script2']
    vowel = request.json['vowel']

    postoptions = request.json['postoptions']

    print('The post options are :: ')
    print(postoptions)

    if script1[0:3] < 'Tir':
        index = '1'
    else:
        index = '2'

    """
    for key, value in conj.items():
        result_script1 = list(unique_everseen([convert('IAST', script1, x, False,[],[]) for x in value]))
        result_iast = [convert(script1, 'IAST', x, False,['removeChillus'],[]) for x in result_script1]
        actual_result = sorted(set(value) & set(result_iast), key=value.index)

        results[key] = [convert('IAST', script1, x, False,[], postoptions) for x in actual_result]
        results[key[:-1] + '2'] = [convert('IAST', script2, x, False,[], []) for x in actual_result]
    """

    if script1 == 'Sinhala':
        if 'SinhalaConjuncts' in postoptions:
            file = 'resources/conjuncts'+ index + '/conjuncts_' + script1 + '_' + vowel + '_all' + '.json'
        else:
            file = 'resources/conjuncts'+ index + '/conjuncts_' + script1 +  '_' + vowel + '.json'
    elif script1 == 'Chakma':
        if 'ChakmaEnableAllConjuncts' in postoptions:
            file = 'resources/conjuncts'+ index + '/conjuncts_' + script1 + '_' + vowel + '_all' + '.json'
        else:
            file = 'resources/conjuncts'+ index + '/conjuncts_' + script1 +  '_' + vowel + '.json'
    else:
        file = 'resources/conjuncts'+ index + '/conjuncts_' + script1 +  '_' + vowel + '.json'

    f = open (file, 'r', encoding='utf-8')
    conjuncts = f.read()
    conjuncts = conjuncts.replace('،', ',').replace(" ", "")
    f.close()

    if script2 != 'Velthuis':
        conjuncts_guide = convert(script1, script2, conjuncts, False,[],[])
        conjuncts_guide = PostProcess.RetainIndicNumerals(conjuncts_guide, script2, True)
        conjuncts_guide = json.loads(conjuncts_guide.replace('،', ','))
    else:
        conjuncts_guide = convert(script1, script2, conjuncts, False,[],[]).replace('""', '"\\"').replace('&"', '&\\"')
        conjuncts_guide = json.loads(PostProcess.RetainIndicNumerals(conjuncts_guide, script2, True))

    conjuncts = json.loads(conjuncts)

    results = {}

    results['conjuncts1S1'] = conjuncts['conjuncts1S1']
    results['conjuncts2S1'] = conjuncts['conjuncts2S1']
    results['conjuncts3S1'] = conjuncts['conjuncts3S1']
    results['conjuncts4S1'] = conjuncts['conjuncts4S1']
    results['conjuncts5S1'] = conjuncts['conjuncts5S1']

    results['conjuncts1S2'] = conjuncts_guide['conjuncts1S1']
    results['conjuncts2S2'] = conjuncts_guide['conjuncts2S1']
    results['conjuncts3S2'] = conjuncts_guide['conjuncts3S1']
    results['conjuncts4S2'] = conjuncts_guide['conjuncts4S1']
    results['conjuncts5S2'] = conjuncts_guide['conjuncts5S1']

    return jsonify(results)
Esempio n. 24
0
    help=
    'Plot the imaginary part as well and save in the same directory as the real part.'
)

(options, args) = parser.parse_args()

if len(args) < 2:
    parser.error('You must specify PPATH and FIGPATH! ')

Ppath, figpath = args[:2]

file = open(Ppath, 'rb')
map_P = cpkl.load(file)
file.close()
Plm = AS.get_lmax_subset_from(map_P.xlm, options.lmax)
Pmap = AS.xlmSkyMap(xlm=options.mapnorm * Plm)
Pmap.xlm_to_plm()
Pmap.xlm_to_qlm()
Pmap.create_sky(nlon=options.nlon, nlat=options.nlat)
Pmap.plm_to_P()
Pmap.qlm_to_Q()

figdir = os.path.dirname(figpath)
PP.SkyMap_to_datfile(Pmap, 'temporary.dat')
if options.plot_imag:
    PP.project_SkyMap('temporary.dat',
                      Ppath=figpath,
                      Qpath=figdir + '/P_imag.png')
else:
    PP.project_SkyMap('temporary.dat', Ppath=figpath)
Esempio n. 25
0
l = 0  #of Ylm
m = 0  #of Ylm
Amplitude = 1e-38  #Real number only please!

nlon = 360
nlat = 181

ntrunc = 20
skymap = AS.xlmSkyMap(ntrunc=ntrunc)
if m % 2 == 0:
    if m == 0:
        skymap.alter_ml(False, (m, l, Amplitude))
    else:
        skymap.alter_ml(False, (m, l, Amplitude / 2.), (-m, l, Amplitude / 2.))
else:
    skymap.alter_ml(False, (m, l, Amplitude / 2.), (-m, l, -Amplitude / 2.))
skymap.xlm_to_plm()
skymap.xlm_to_qlm()
skymap.create_sky(nlon=nlon, nlat=nlat)
skymap.plm_to_P()
skymap.qlm_to_Q()
skymap.PQ_to_X()

mapname = 'Y_l%d_m%d.pkl' % (l, m)
mappath = mapdir + mapname
file = open(mappath, 'wb')
cpkl.dump(skymap, file, -1)
file.close()

PP.project_SkyMap(skymap)
Esempio n. 26
0
def Run_Cpp_Solver_UVLM(VMOPTS,
                        VMINPUT,
                        VMUNST,
                        AELOPTS,
                        vOmegaHist=None,
                        eta0=None,
                        numNodesElem=2,
                        delEtaHist=None):
    """@brief UVLM solver with prescribed inputs.
       @param vOmegaHist None, or np.array history of velocities of the A-frame, expressed in A-frame.
       @param eta0 None, or tuple containing reference disps, rots, and gamma.
       @param delEtaHist None, or tuple of np.array histories of underlying beam disps, rotations, vels, and rotvels in A-frame."""

    # Initialise DerivedTypes for PyBeam initialisation.
    XBOPTS = DerivedTypes.Xbopts()
    if numNodesElem == 2:
        beamElems = VMOPTS.N.value
    elif numNodesElem == 3:
        beamElems = int(VMOPTS.N.value / 2)
    else:
        raise ValueError('numNodesElem should be 2 or 3')

    XBINPUT = DerivedTypes.Xbinput(numNodesElem, beamElems, VMINPUT.b)
    # Create a dummy stiffness matrix to avoid errors.
    XBINPUT.BeamStiffness = np.eye(6, 6, 0, ct.c_double)
    # Use PyBeam to define reference beam (elastic axis).
    XBINPUT, XBOPTS, NumNodes_tot, XBELEM, PosIni, PsiIni,\
            XBNODE, NumDof = BeamInit.Static(XBINPUT, XBOPTS)
    # Delete unnecessary variables.
    del XBELEM, XBNODE, NumDof
    # Copy reference beam to current (deformed) variables.
    if eta0 is None:
        PosDefor = PosIni.copy(order='F')
        PsiDefor = PsiIni.copy(order='F')
    else:
        PosDefor = eta0[0]  #+delEtaHist[0][:,:,0]
        PsiDefor = eta0[1]  #+delEtaHist[1][:,:,:,0]

    if delEtaHist is None:
        # Declare empty array for beam DoF rates.
        PosDotDef = np.zeros_like(PosDefor, ct.c_double, 'F')
        PsiDotDef = np.zeros_like(PsiDefor, ct.c_double, 'F')
    else:
        PosDotDef = delEtaHist[2][:, :, 0]
        PsiDotDef = delEtaHist[3][:, :, :, 0]

    # Check the specified inputs from the PyAero have been properly applied.
    assert NumNodes_tot.value - 1 == VMOPTS.N.value, "Initialisation wrong"

    # Initialise section coordinates.
    Section = InitSection(VMOPTS, VMINPUT, AELOPTS.ElasticAxis)

    # Initialise origin and orientation of surface velocities in a-frame
    CGa = Psi2TransMat(VMUNST.PsiA_G)
    if vOmegaHist is None:
        VelA_A = np.dot(CGa.T, VMUNST.VelA_G)
        OmegaA_A = np.dot(CGa.T, VMUNST.OmegaA_G)
    else:
        VelA_A = np.dot(CGa.T, vOmegaHist[0, 1:4])
        OmegaA_A = np.dot(CGa.T, vOmegaHist[0, 4:7])

    # Declare empty array for aerodynamic grid and velocities.
    Zeta = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3), ct.c_double,
                    'C')
    ZetaDot = np.zeros((VMOPTS.M.value + 1, VMOPTS.N.value + 1, 3),
                       ct.c_double, 'C')

    # Initialise aerodynamic grid and velocities.
    CoincidentGrid(PosDefor, PsiDefor, Section, VelA_A, OmegaA_A, PosDotDef,
                   PsiDotDef, XBINPUT, Zeta, ZetaDot, VMUNST.OriginA_G,
                   VMUNST.PsiA_G, VMINPUT.ctrlSurf)

    # Initialise wake for unsteady solution.
    if vOmegaHist is None:
        velForWake = VMUNST.VelA_G
    else:
        velForWake = vOmegaHist[0, 1:4]

    ZetaStar, GammaStar = InitSteadyWake(VMOPTS, VMINPUT, Zeta, velForWake)

    # Initialise external velocities.
    Uext = InitSteadyExternalVels(VMOPTS, VMINPUT)

    # Declare empty solver variables.
    Forces = np.zeros_like(Zeta, ct.c_double, 'C')
    Gamma = np.zeros((VMOPTS.M.value, VMOPTS.N.value), ct.c_double, 'C')
    AIC = np.zeros(
        (VMOPTS.M.value * VMOPTS.N.value, VMOPTS.M.value * VMOPTS.N.value),
        ct.c_double, 'C')
    BIC = np.zeros(
        (VMOPTS.M.value * VMOPTS.N.value, VMOPTS.M.value * VMOPTS.N.value),
        ct.c_double, 'C')

    if type(eta0) is tuple:
        Gamma[:, :] = eta0[2]
        for j in range(VMOPTS.N.value):
            GammaStar[:, j] = Gamma[VMOPTS.M.value - 1, j]

    # Open tecplot file object."
    Variables = ['X', 'Y', 'Z', 'Gamma']
    Filename = Settings.OutputDir + Settings.OutputFileRoot + 'AeroGrid.dat'
    FileObject = PostProcess.WriteAeroTecHeader(Filename, 'Default', Variables)

    # Initialise vector of time steps.
    Time = np.arange(0.0, VMUNST.FinalTime, VMOPTS.DelTime.value)
    # Create Array for storing time and coefficient data.
    CoeffHistory = np.zeros((len(Time), 4))

    # Loop through time steps.
    for iTimeStep in range(len(Time)):

        # Set forces array to zero (+= operator used in C++ library).
        Forces[:, :, :] = 0.0

        if iTimeStep > 0:

            # Update geometry.
            if vOmegaHist is None:
                VMUNST.OriginA_G[:] += VMUNST.VelA_G[:] * VMOPTS.DelTime.value
                # TODO: update OmegaA_A, PsiA_A in pitching problem.
            else:
                VMUNST.OriginA_G[:] += vOmegaHist[iTimeStep,
                                                  1:4] * VMOPTS.DelTime.value
                VelA_A = vOmegaHist[iTimeStep, 1:4]
                # TODO: update OmegaA_A, PsiA_G in pitching problem.

            if type(eta0) is tuple:
                PosDefor = eta0[0]
                PsiDefor = eta0[1]

            if type(delEtaHist) is tuple:
                PosDefor = PosDefor + delEtaHist[0][:, :, iTimeStep]
                PsiDefor = PsiDefor + delEtaHist[1][:, :, :, iTimeStep]
                PosDotDef = delEtaHist[
                    2][:, :, iTimeStep]  #TODO: PosDefor seems to be correct!
                PsiDotDef = delEtaHist[3][:, :, :, iTimeStep]

            # Update control surface defintion.
            if VMINPUT.ctrlSurf is not None:
                VMINPUT.ctrlSurf.update(Time[iTimeStep])

            # Update aerodynamic surface.
            CoincidentGrid(PosDefor, PsiDefor, Section, VelA_A, OmegaA_A,
                           PosDotDef, PsiDotDef, XBINPUT, Zeta, ZetaDot,
                           VMUNST.OriginA_G, VMUNST.PsiA_G, VMINPUT.ctrlSurf)

            # Convect wake downstream.
            ZetaStar = np.roll(ZetaStar, 1, axis=0)
            GammaStar = np.roll(GammaStar, 1, axis=0)
            # Overwrite 1st row with with new trailing-edge position.
            ZetaStar[0, :] = Zeta[VMOPTS.M.value, :]
            # Overwrite Gamma with TE value from previous time step.
            GammaStar[0, :] = Gamma[VMOPTS.M.value - 1, :]

        # END if iTimeStep > 1

        # Calculate forces on aerodynamic grid.
        if iTimeStep == 0:
            sav = VMOPTS.NewAIC
            VMOPTS.NewAIC = ct.c_bool(True)

        UVLMLib.Cpp_Solver_VLM(Zeta, ZetaDot, Uext, ZetaStar, VMOPTS, Forces,
                               Gamma, GammaStar, AIC, BIC)

        if iTimeStep == 0:
            VMOPTS.NewAIC = sav
            del sav

        #print(PostProcess.GetCoeffs(VMOPTS, Forces, VMINPUT, VMUNST.VelA_G))

        CoeffHistory[iTimeStep, 0] = Time[iTimeStep]
        CoeffHistory[iTimeStep,
                     1:] = PostProcess.GetCoeffs(VMOPTS, Forces, VMINPUT,
                                                 VMUNST.VelA_G)

        # Write aerodynamic surface data as tecplot zone data.
        PostProcess.WriteAeroTecZone(FileObject, 'Surface', Zeta,\
                                     iTimeStep, len(Time),\
                                     Time[iTimeStep], Variables, False, Gamma)

        # Write wake data as tecplot zone data.
        PostProcess.WriteAeroTecZone(FileObject, 'Wake', ZetaStar,\
                                    iTimeStep, len(Time),\
                                    Time[iTimeStep], \
                                    Variables, False, GammaStar)

        # Rollup due to external velocities.
        ZetaStar[:, :] += VMINPUT.U_infty * VMOPTS.DelTime.value

    # END for iTimeStep

    # Close tecplot file object.
    PostProcess.CloseAeroTecFile(FileObject)

    # write geometry and circ dist. to file for matlab
    if iTimeStep == len(Time) - 1 and False:
        savemat('/home/rjs10/Desktop/uvlmOut.mat', {
            'zeta': Zeta.flatten('C'),
            'zetaW': ZetaStar.flatten('C'),
            'gamma': Gamma.flatten('C'),
            'gammaW': GammaStar.flatten('C')
        },
                False,
                oned_as='column')

    return CoeffHistory
Esempio n. 27
0
parser.add_option( '--plot_imag' , action='store_true' ,
                   help='Plot the imaginary part as well and save in the same directory as the real part.' )

( options , args ) = parser.parse_args()

if len( args ) < 2 :
    parser.error( 'You must specify PPATH and FIGPATH! ' )

Ppath , figpath = args[ :2 ]



file = open( Ppath , 'rb' ) ; map_P = cpkl.load( file ) ; file.close()
Plm = AS.get_lmax_subset_from( map_P.xlm , options.lmax )
Pmap = AS.xlmSkyMap( xlm = options.mapnorm * Plm )
Pmap.xlm_to_plm() ; Pmap.xlm_to_qlm()
Pmap.create_sky( nlon=options.nlon , nlat=options.nlat )
Pmap.plm_to_P() ; Pmap.qlm_to_Q()

figdir = os.path.dirname(figpath)
PP.SkyMap_to_datfile(Pmap, 'temporary.dat')
if options.plot_imag:
    PP.project_SkyMap('temporary.dat', Ppath = figpath, Qpath = figdir + '/P_imag.png') 
else:
    PP.project_SkyMap('temporary.dat', Ppath = figpath)