Example #1
0
def load_project(pname, globals_dict=None):
    """Load the model from the named project into the current
    globals dict so that the model can be used as part of a
    python script outside of the GUI.  pname can either be an
    absolute or relative path to a project directory, or just
    a project name.  If it's a project name, the project directory
    will be searched for in PATH, and if not found there will be
    searched for in $HOME/.openmdao/gui/projects.
    """

    abspname = os.path.abspath(pname)
    if os.path.isdir(abspname):
        ppath = abspname
    else:
        ppath = find_in_path(pname)
        hpath = os.path.join(PROJ_HOME, pname)
        if ppath is None and os.path.isdir(hpath):
            ppath = hpath

    if ppath is None:
        raise RuntimeError("can't locate project '%s'" % pname)

    proj = Project(ppath, gui=False, globals_dict=globals_dict)
    proj.activate()

    return proj
Example #2
0
    def setUp(self):
        """ Called before each test in this class. """

        if not find_in_path(VSP_PATH):
            raise nose.SkipTest('VSP must be installed to run this test.')
        os.chdir(TestCase.directory)
        SimulationRoot.chroot(os.getcwd())
Example #3
0
 def setUp(self):
     """ Called before each test in this class. """
     
     if not find_in_path(VSP_PATH):
         raise nose.SkipTest('VSP needs to be installed to run this test.')
     
     os.chdir(TestCase.directory)
Example #4
0
 def setUp(self):
     """ Called before each test in this class. """
     
     if not find_in_path(VSP_PATH):
         raise nose.SkipTest('VSP must be installed to run this test.')
     os.chdir(TestCase.directory)
     SimulationRoot.chroot(os.getcwd())
Example #5
0
    def setUp(self):
        """ Called before each test in this class. """

        if not find_in_path(VSP_PATH):
            raise nose.SkipTest('VSP needs to be installed to run this test.')

        os.chdir(TestCase.directory)
 def test_find_in_path(self):
     if sys.platform == 'win32':
         path=r'C:\a\b\c;top;top\blah;top\foo'
     else:
         path = '/a/b/c:top:top/blah:top/foo'
     fname = find_in_path('bar', path)
     self.assertEqual(fname, None)
     # search for a file with an extension
     fname = find_in_path('bar', path, exts=('.exe',))
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'bar.exe')
     # search for a file without an extension
     fname = find_in_path('somefile', path)
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'somefile')
     # make sure we don't find directories
     fname = find_in_path('blah', path)
     self.assertEqual(fname, None)
Example #7
0
 def test_find_in_path(self):
     if sys.platform == 'win32':
         path = r'C:\a\b\c;d1;d1\d1d1;d1\d1d2'
     else:
         path = '/a/b/c:d1:d1/d1d1:d1/d1d2'
     fname = find_in_path('bar', path)
     self.assertEqual(fname, None)
     # search for a file with an extension
     fname = find_in_path('d1d1f1', path, exts=('.exe', ))
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'd1d1f1.exe')
     # search for a file without an extension
     fname = find_in_path('d1d2f2', path)
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'd1d2f2')
     # make sure we don't find directories
     fname = find_in_path('d1d2', path)
     self.assertEqual(fname, None)
 def test_find_in_path(self):
     if sys.platform == 'win32':
         path = r'C:\a\b\c;d1;d1\d1d1;d1\d1d2'
     else:
         path = '/a/b/c:d1:d1/d1d1:d1/d1d2'
     fname = find_in_path('bar', path)
     self.assertEqual(fname, None)
     # search for a file with an extension
     fname = find_in_path('d1d1f1', path, exts=('.exe',))
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'd1d1f1.exe')
     # search for a file without an extension
     fname = find_in_path('d1d2f2', path)
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'd1d2f2')
     # make sure we don't find directories
     fname = find_in_path('d1d2', path)
     self.assertEqual(fname, None)
Example #9
0
 def test_find_in_path(self):
     if sys.platform == 'win32':
         path = r'C:\a\b\c;top;top\blah;top\foo'
     else:
         path = '/a/b/c:top:top/blah:top/foo'
     fname = find_in_path('bar', path)
     self.assertEqual(fname, None)
     # search for a file with an extension
     fname = find_in_path('bar', path, exts=('.exe', ))
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'bar.exe')
     # search for a file without an extension
     fname = find_in_path('somefile', path)
     self.assertTrue(fname is not None)
     self.assertEqual(os.path.basename(fname), 'somefile')
     # make sure we don't find directories
     fname = find_in_path('blah', path)
     self.assertEqual(fname, None)
Example #10
0
def run_wing():
    """Runs the Wing IDE using our template project file."""
    wingpath = None
    projpath = ""
    for arg in sys.argv[1:]:
        if arg.startswith("--wingpath="):
            wingpath = arg.split("=")[1]
        elif arg.startswith("--proj="):
            projpath = arg.split("=")[1]
    if not wingpath:
        if sys.platform == "win32":
            wname = "wing.exe"
            locs = [r"C:\Program Files (x86)\WingIDE 3.2"]
        elif sys.platform == "darwin":
            wname = "wing"
            locs = ["/Applications/WingIDE.app/Contents/MacOS", "/Applications/Wing/WingIDE.app/Contents/MacOS"]
        else:
            wname = "wing3.2"
            locs = ["/usr/bin", "/usr/sbin", "/usr/local/bin"]

        wingpath = find_in_path(wname)  # searches PATH
        if not wingpath:
            wingpath = find_in_dir_list(wname, locs)  # look in common places
        if not wingpath:
            raise OSError("%s was not found in PATH or in any of the common places." % wname)

    if not os.path.isfile(projpath):
        venvdir = os.path.dirname(os.path.dirname(sys.executable))
        projpath = os.path.join(venvdir, "etc", "wingproj.wpr")

    if sys.platform == "darwin":
        _modify_wpr_file(projpath)  # have to put virtualenv sys path info in wing project file on Mac

    # in order to find all of our shared libraries,
    # put their directories in LD_LIBRARY_PATH
    env = os.environ
    if sys.platform != "win32":
        libs = env.get("LD_LIBRARY_PATH", "").split(os.pathsep)
        rtop = find_up(".git")
        if not rtop:
            rtop = find_up(".git")
        if rtop:
            rtop = os.path.dirname(rtop)
            sodirs = set([os.path.dirname(x) for x in find_files(rtop, "*.so")])
            libs.extend(sodirs)
            env["LD_LIBRARY_PATH"] = os.pathsep.join(libs)

    try:
        Popen([wingpath, projpath], env=env)
    except Exception as err:
        print "Failed to run wing executable (%s) using project (%s)." % (wingpath, projpath)
Example #11
0
    def execute(self):
        
        if not os.path.isfile(self.supin_exec) and find_in_path(self.supin_exec) is None:
            raise RuntimeError("SUPIN executable '%s' not found" % self.supin_exec)

        # --------------------------------------
        # --- Execute file-wrapped component --- 
        # --------------------------------------
        self.command = [self.supin_exec]

        split = '\n---------------------------------------------------------------------------\n'

        # --------------------
        # --- Header Input ---
        # --------------------       
        header_input = ['SUPIN Input File']
        header_input.append(' '.join(['2D Axisymnmetric Pitot inlet.']))
        header_input.append(' '.join(['GE F404 Conditions.']))                                                                                     
        header_input.append(split)

        # ------------------
        # --- Main Input ---
        # ------------------
        main_input = [_2str('DataID')] 
        main_input.append(' '.join([_2str(self.DataID)]))
        main_input.append(' '.join([_2str(x) for x in ['Kmode', 'Ktype', 'Kcomp', 'Ksurf', 'KgCFD']]))
        main_input.append(' '.join([_2str(x) for x in [self.Kmode, self.Ktype, self.Kcomp, self.Ksurf, self.KgCFD]]))
        main_input.append(' '.join([_2str(x) for x in ['KWinp', 'FWinp', 'KWunit', 'Flapeng']]))
        main_input.append(' '.join([_2str(x) for x in [self.KWinp, self.FWinp, self.KWunit, self.Flapeng]]))
        main_input.append(' '.join([_2str(x) for x in ['WRspill', 'WRbleed', 'WRbypass', 'WRother']]))
        main_input.append(' '.join([_2str(x) for x in [self.WRspill, self.WRbleed, self.WRbypass, self.WRother]]))
        main_input.append(split)

        # ------------------------
        # --- Freestream Input --- 
        # ------------------------   
        freestream_input = [_2str('DataID')] 
        freestream_input.append(' '.join([_2str(self.Freestream.DataID)]))
        freestream_input.append(' '.join([_2str(x) for x in ['Kfs', 'Mach', 'Pres (psf)', 'Temp (R)', 'Alpha (deg)', 'Beta (deg)', 'Alt (ft)']]))
        freestream_input.append(' '.join([_2str(x) for x in [self.Freestream.Kfs, self.Freestream.Mach, self.Freestream.Pres, self.Freestream.Temp, self.Freestream.Alpha, self.Freestream.Beta, self.Freestream.Alt]]))               
        freestream_input.append(split)    

        # ---------------------------
        # --- Approach Flow Input ---
        # ---------------------------    
        approach_input = [_2str('DataID')] 
        approach_input.append(' '.join([_2str(self.Approach.DataID)]))
        approach_input.append(' '.join([_2str(x) for x in ['Kapp', 'Nsapp', 'Alpha_Inlet (deg)', 'Beta_Inlet (deg)']]))
        approach_input.append(' '.join([_2str(x) for x in [self.Approach.Kapp, self.Approach.Nsapp, self.Approach.IAlpha, self.Approach.IBeta]]))
        approach_input.append(' '.join([_2str(x) for x in ['Mach_L', 'pt_L/pt_0', 'Alpha_L (deg)', 'Beta_L (deg)']]))
        approach_input.append(' '.join([_2str(x) for x in [self.Freestream.Mach*1.01, self.Approach.ptL_pt0, self.Approach.LAlpha, self.Approach.LBeta]]))                
        approach_input.append(split)                     

        # -------------------------------
        # --- Capture X-Section Input ---
        # ------------------------------- 
        capture_input = [_2str('DataID')] 
        capture_input.append(' '.join([_2str(self.Capture.DataID)]))
        capture_input.append(' '.join([_2str(x) for x in ['FAcap', 'Fhclip', 'Fwclip']]))
        capture_input.append(' '.join([_2str(x) for x in [self.Capture.FAcap, self.Capture.Fhclip, self.Capture.Fwclip]]))
        capture_input.append(' '.join([_2str(x) for x in ['Xinlet', 'Yinlet', 'ThetaInlet']]))
        capture_input.append(' '.join([_2str(x) for x in [self.Capture.Xinlet, self.Capture.Yinlet, self.Capture.Thetinlet]]))
        capture_input.append(' '.join([_2str(x) for x in ['ARtopcap', 'ptopcap', 'ARbotcap', 'pbotcap']]))
        capture_input.append(' '.join([_2str(x) for x in [self.Capture.ARtopcap, self.Capture.ptopcap, self.Capture.ARbotcap, self.Capture.pbotcap]]))
        capture_input.append(split)

        # ----------------------
        # --- Cowl Lip Input ---
        # ----------------------   
        cowllip_input = [_2str('DataID')] 
        cowllip_input.append(' '.join([_2str(self.CowlLip.DataID)]))
        cowllip_input.append(' '.join([_2str(x) for x in ['Kclip', 'Kclin', 'Kclex']]))
        cowllip_input.append(' '.join([_2str(x) for x in [self.CowlLip.Kclip, self.CowlLip.Kclin, self.CowlLip.Kclex]]))
        cowllip_input.append(' '.join([_2str(x) for x in ['bclin', 'ARclin', 'thclin']]))
        cowllip_input.append(' '.join([_2str(x) for x in [self.CowlLip.bclin, self.CowlLip.ARclin, self.CowlLip.thclin]]))
        cowllip_input.append(' '.join([_2str(x) for x in ['bclex', 'ARclex', 'thclex']]))
        cowllip_input.append(' '.join([_2str(x) for x in [self.CowlLip.bclex, self.CowlLip.ARclex, self.CowlLip.thclex]]))
        cowllip_input.append(split)

        # ---------------------------
        # --- Cowl Exterior Input ---
        # ---------------------------   
        cowlext_input = [_2str('DataID')] 
        cowlext_input.append(' '.join([_2str(self.CowlExt.DataID)]))
        cowlext_input.append(' '.join([_2str(x) for x in ['Kcex', 'Frcex', 'FXcext', 'Thswex']]))
        cowlext_input.append(' '.join([_2str(x) for x in [self.CowlExt.Kcex, self.CowlExt.Frcex, self.CowlExt.FXcext, self.CowlExt.Thswex]]))
        cowlext_input.append(split)

        # --------------------
        # --- Throat Input ---
        # --------------------
        throat_input = [_2str('DataID')] 
        throat_input.append(' '.join([_2str(self.Throat.DataID)]))
        throat_input.append(' '.join([_2str(x) for x in ['Kthrt']]))
        throat_input.append(' '.join([_2str(x) for x in [self.Throat.Kthrt]]))
        throat_input.append(' '.join([_2str(x) for x in ['Kthcw']]))
        throat_input.append(' '.join([_2str(x) for x in [self.Throat.Kthcw]]))
        throat_input.append(' '.join([_2str(x) for x in ['dxcwTH', 'aTHaS1', 'thcwTH', 'machTH']]))
        throat_input.append(' '.join([_2str(x) for x in [self.Throat.dxcwTH, self.Throat.aTHaS1, self.Throat.thcwTH, self.Throat.machTH]]))
        throat_input.append(' '.join([_2str(x) for x in ['dxcwSD', 'aSDaS1', 'thcwSD', 'machSD']]))
        throat_input.append(' '.join([_2str(x) for x in [self.Throat.dxcwSD, self.Throat.aSDaS1, self.Throat.thcwSD, self.Throat.machSD]]))
        throat_input.append(split)

        # -------------------------------
        # --- Subsonic Diffuser Input ---
        # -------------------------------
        subdiff_input = [_2str('DataID')] 
        subdiff_input.append(' '.join([_2str(self.SubDiff.DataID)]))
        subdiff_input.append(' '.join([_2str(x) for x in ['Ksubd', 'KLsubd', 'FLsubd', 'theqsd', 'dptsubd']]))
        subdiff_input.append(' '.join([_2str(x) for x in [self.SubDiff.Ksubd, self.SubDiff.KLsubd, self.SubDiff.FLsubd, self.SubDiff.theqsd, self.SubDiff.dptsubd]]))
        subdiff_input.append(' '.join([_2str(x) for x in ['Ksdcw']]))
        subdiff_input.append(' '.join([_2str(x) for x in [self.SubDiff.Ksdcw]]))        
        subdiff_input.append(' '.join([_2str(x) for x in ['FncwSD', 'FncwX', 'FLcwX']]))
        subdiff_input.append(' '.join([_2str(x) for x in [self.SubDiff.FncwSD, self.SubDiff.FncwX, self.SubDiff.FLcwX]]))
        subdiff_input.append(split)

        # -------------------------
        # --- Engine Face Input ---
        # -------------------------
        engineface_input = [_2str('DataID')] 
        engineface_input.append(' '.join([_2str(self.EngineFace.DataID)]))
        engineface_input.append(' '.join([_2str(x) for x in ['KxEF', 'FxEF', 'KyEF', 'FyEF', 'ThetEF']]))
        engineface_input.append(' '.join([_2str(x) for x in [self.EngineFace.KxEF, self.EngineFace.FxEF, self.EngineFace.KyEF, self.EngineFace.FyEF, self.EngineFace.ThetEF]]))
        engineface_input.append(' '.join([_2str(x) for x in ['Kef']]))        
        engineface_input.append(' '.join([_2str(x) for x in [self.EngineFace.Kef]]))        
        engineface_input.append(' '.join([_2str(x) for x in ['diamEF', 'Hubtip']]))
        engineface_input.append(' '.join([_2str(x) for x in [self.EngineFace.diamEF, self.EngineFace.Hubtip]]))
        engineface_input.append(' '.join([_2str(x) for x in ['Kspin']]))        
        engineface_input.append(' '.join([_2str(x) for x in [self.EngineFace.Kspin]]))        
        engineface_input.append(' '.join([_2str(x) for x in ['ARspin']]))        
        engineface_input.append(' '.join([_2str(x) for x in [self.EngineFace.ARspin]]))        
        engineface_input.append(split)

        # --------------------------
        # --- Grid Spacing Input ---
        # --------------------------
        gridspacing_input = [_2str('DataID')]
        gridspacing_input.append(' '.join([_2str(self.GridSpacing.DataID)]))
        gridspacing_input.append(' '.join([_2str(x) for x in ['Fgdds', 'Rgsmax', 'Fdswall', 'Fdssym', 'Fdscex', 'Fdsthrt']]))
        gridspacing_input.append(' '.join([_2str(x) for x in [self.GridSpacing.Fgdds, self.GridSpacing.Rgsmax, self.GridSpacing.Fdswall, self.GridSpacing.Fdssym, self.GridSpacing.Fdscex, self.GridSpacing.Fdsthrt]]))
        gridspacing_input.append(' '.join([_2str(x) for x in ['Ddinf', 'Ddfar', 'Ddnoz', 'Ddclp', 'thfar', 'Fgnoz']]))
        gridspacing_input.append(' '.join([_2str(x) for x in [self.GridSpacing.Ddinf, self.GridSpacing.Ddfar, self.GridSpacing.Ddnoz, self.GridSpacing.Ddclp, self.GridSpacing.thfar, self.GridSpacing.Fgnoz]]))
        gridspacing_input.append(split)

        # ---------------------------------------
        # --- Write Header Output to SUPIN.in ---
        # ---------------------------------------         
        filename = 'SUPIN.1.in'    
        file_handle = open(filename, 'w')
        file_handle.write("\n".join(header_input))

        # ------------------------------------
        # --- Write Input to SUPIN.in ---
        # ------------------------------------             
        file_handle.write("\n".join(main_input))           
        file_handle.write("\n".join(freestream_input))           
        file_handle.write("\n".join(approach_input))        
        file_handle.write("\n".join(capture_input))                        
        file_handle.write("\n".join(cowllip_input))           
        file_handle.write("\n".join(cowlext_input))             
        file_handle.write("\n".join(throat_input))          
        file_handle.write("\n".join(subdiff_input))            
        file_handle.write("\n".join(engineface_input))            
        file_handle.write("\n".join(gridspacing_input))
        file_handle.close()

        # -------------------------------
        # --- Execute SUPIN Component ---
        # -------------------------------
        super(SUPIN, self).execute()

        # -------------------------
        # --- Parse Output File ---
        # -------------------------       
        with open('SUPIN.out') as f:
            lines = f.readlines()
       
        for line in lines:
            if "pt_2 / pt_L    =" in line:
                self.Outputs.pt2_ptL = float(line.split("=")[-1])
            elif "Tt2 / TtL  =" in line:
                self.Outputs.tt2_ttL = float(line.split("=")[-1])                
            elif "Mach_2         =" in line:
                self.Outputs.M2 = float(line.split("=")[-1])
            elif "rhub   (ft)  =" in line:
                self.Outputs.Rspin = float(line.split("=")[-1])      
            elif "diamEF (ft)  =" in line:
                self.Outputs.diamEF = float(line.split("=")[-1])
            elif "Inlet Drag Coefficient, cdrag" in line:
                self.Outputs.Cd = float(line.split("=")[-1])   
            elif "Wa2 (actual)                       =" in line: 
                self.Outputs.mdot = float(line.split("=")[-1])  
            elif "A_2  (ft)      =" in line: 
                self.Outputs.A2 = float(line.split("=")[-1])
            elif "y_EF (ft)      =" in line: 
                self.Outputs.yEF = float(line.split("=")[-1])
            elif "rhub   (ft)  =" in line: 
                self.Outputs.Rspin = float(line.split("=")[-1])                                
            else:
                pass

        if not self.Outputs.pt2_ptL: self.Outputs.pt2_ptL = 0.8
        if not self.Outputs.Cd: self.Outputs.Cd = 1.0

        try:
            src_file = 'Solid.p3d'
            dst_folder = os.path.join(os.getcwd(), str(self.exec_count))
            shutil.copy2(src_file, dst_folder)
        except:
            pass

        print "---------------------------------"
        print "------- SUPIN Parameters --------"
        print "---------------------------------"           
        
        print '---Outputs---'
        print 'Precov: ', self.Outputs.pt2_ptL
        print 'CdWave: ', self.Outputs.Cd
        print 'Obj: ', -1.0*self.Outputs.pt2_ptL + 0.5*self.Outputs.Cd
Example #12
0
    def execute(self):
        """ Execute VSP to perform one or more operations. """
        if self.generate_cfd_mesh and self.write_nascart:
            self.raise_exception(
                'CFD meshing and NASCART output use the same'
                ' output filenames', RuntimeError)

        if not os.path.isfile(
                self.vsp_path) and find_in_path(self.vsp_path) is None:
            raise RuntimeError("VSP executable '%s' not found" % self.vsp_path)

        # Write XML input file.
        filename = os.path.basename(self.xml_filename)
        if filename.endswith('.vsp'):
            base_filename = filename[:-4]
        else:  # .xml input files leave the .new in the output filenames ????
            base_filename = filename + '.new'
        filename += '.new'
        self.write_input(filename)

        # Determine command line and output files.
        cmd = [self.vsp_path, '-batch', filename]
        output_files = []

        if self.comp_geom:
            cmd.append('-compgeom')
            output_files.extend((base_filename + '_CompGeom.txt',
                                 base_filename + '_CompGeom.csv'))

        if self.generate_cfd_mesh:
            cmd.append('-cfdmesh')
            output_files.extend(
                ('bodyin.dat', 'bodyin.key', 'cfdmesh.bez', 'cfdmesh.stl'))
        if self.slice:
            cmd.extend([
                '-slice',
                str(self.num_slices),
                str(self.mach),
                str(self.cone_sections)
            ])

        if self.write_xsec:
            cmd.append('-xsec')
            output_files.append('%s.hrm' % base_filename)

        if self.write_felisa:
            cmd.append('-felisa')
            for ext in ('fel', 'bsf', 'bac'):
                output_files.append('%s.%s' % (base_filename, ext))

        if self.write_stereo:
            cmd.append('-stereo')
            output_files.append('%s.stl' % base_filename)

        if self.write_rhino:
            cmd.append('-rhino')
            output_files.append('%s.3dm' % base_filename)

        if self.write_nascart:
            cmd.append('-nascart')
            output_files.extend(('bodyin.dat', 'bodyin.key'))

        if self.write_tecplot:
            cmd.append('-tecplot')

        if self.write_stecplot:
            cmd.append('-stecplot')

        for name in output_files:
            if os.path.exists(name):
                os.remove(name)

        # Run VSP.
        self.command = cmd
        self.stdout = os.path.basename(self.xml_filename) + '.log'
        self.stderr = ExternalCode.STDOUT
        super(VSP, self).execute()

        # Read from -compgeom output.
        if self.comp_geom:
            reader = csv.reader(open(base_filename + '_CompGeom.csv', 'r'))
            next(reader)
            row = []
            wet_areas = {
                'Horizontal_Tail': 0,
                'Vertical_Tail': 0,
                'Wing': 0,
                'Fuselage': 0
            }
            for row in reader:
                if row[0] in wet_areas:
                    wet_areas[row[0]] = wet_areas.get(row[0]) + float(row[2])
            self.horiz_wet_area = wet_areas.get('Horizontal_Tail')
            self.vert_wet_area = wet_areas.get('Vertical_Tail')
            self.wing_wet_area = wet_areas.get('Wing')
            self.fuse_wet_area = wet_areas.get('Fuselage')
            if len(row) == 5:
                self.theoretical_area = float(row[1])
                self.wetted_area = float(row[2])
                self.theoretical_volume = float(row[3])
                self.wetted_volume = float(row[4])
            else:
                self.raise_exception('comp_geom.csv invalid', RuntimeError)
        else:
            self.theoretical_area = 0
            self.wetted_area = 0
            self.theoretical_volume = 0
            self.wetted_volume = 0

        # Check CFD meshing if requested.
        if self.generate_cfd_mesh:
            mesh_ok = False

        with open(self.stdout, 'r') as out:
            for line in out:
                if 'xmlGetNode: Cant find' in line:
                    self._logger.warning(line[:-1])
                if self.generate_cfd_mesh:
                    if 'Total Num Tris' in line:
                        mesh_ok = True
        if self.generate_cfd_mesh and not mesh_ok:
            self.raise_exception('Meshing failed', RuntimeError)
Example #13
0
    def test_basic(self):
        logging.debug('')
        logging.debug('test_basic')

        # Just run through a complete cycle.
        orig_dir = os.getcwd()
        orig_stdout = sys.stdout
        orig_stderr = sys.stderr

        # Quickstart.
        logging.debug('')
        logging.debug('quickstart')
        os.chdir(self.tdir)
        try:
            argv = ['quickstart', 'foobar']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_quickstart(parser, options, args)
            self.assertEqual(retval, 0)
            fandd = find_files(self.tdir, showdirs=True)
            self.assertEqual(
                set([os.path.basename(f) for f in fandd]),
                set([
                    'foobar', 'src', 'docs', 'setup.cfg', 'setup.py',
                    'MANIFEST.in', '__init__.py', 'conf.py', 'usage.rst',
                    'index.rst', 'srcdocs.rst', 'pkgdocs.rst', 'foobar.py',
                    'README.txt', 'test', 'test_foobar.py'
                ]))
        finally:
            os.chdir(orig_dir)

        # Makedist.
        logging.debug('')
        logging.debug('makedist')
        sys.stdout = cStringIO.StringIO()
        sys.stderr = cStringIO.StringIO()
        logdata = ''
        os.chdir(os.path.join(self.tdir, 'foobar'))
        try:
            argv = ['makedist']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_makedist(parser,
                                     options,
                                     args,
                                     capture='makedist.out')
            with open('makedist.out', 'r') as inp:
                logdata = inp.read()
            self.assertEqual(retval, 0)
            if sys.platform == 'win32':
                self.assertTrue(os.path.exists('foobar-0.1.zip'))
            else:
                self.assertTrue(os.path.exists('foobar-0.1.tar.gz'))
        finally:
            captured_stdout = sys.stdout.getvalue()
            captured_stderr = sys.stderr.getvalue()
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            os.chdir(orig_dir)
            logging.debug('captured stdout:')
            logging.debug(captured_stdout)
            logging.debug('captured stderr:')
            logging.debug(captured_stderr)
            logging.debug('captured subprocess output:')
            logging.debug(logdata)

        # Existing distribution error.
        logging.debug('')
        logging.debug('makedist error')
        sys.stdout = cStringIO.StringIO()
        sys.stderr = cStringIO.StringIO()
        os.chdir(os.path.join(self.tdir, 'foobar'))
        try:
            argv = ['makedist']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_makedist(parser,
                                     options,
                                     args,
                                     capture='makedist.out')
            with open('makedist.out', 'r') as inp:
                logdata = inp.read()
            self.assertEqual(retval, -1)
        finally:
            captured_stdout = sys.stdout.getvalue()
            captured_stderr = sys.stderr.getvalue()
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            os.chdir(orig_dir)
            logging.debug('captured stdout:')
            logging.debug(captured_stdout)
            logging.debug('captured stderr:')
            logging.debug(captured_stderr)
            logging.debug('captured subprocess output:')
            logging.debug(logdata)
        self.assertTrue('already exists' in captured_stderr)

        # Install
        logging.debug('')
        logging.debug('install')
        sys.stdout = cStringIO.StringIO()
        sys.stderr = cStringIO.StringIO()
        logdata = ''
        os.chdir(self.tdir)
        try:
            argv = ['install', 'foobar']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_install(parser,
                                    options,
                                    args,
                                    capture='install.out')
            with open('install.out', 'r') as inp:
                logdata = inp.read()
            self.assertEqual(retval, 0)
        finally:
            captured_stdout = sys.stdout.getvalue()
            captured_stderr = sys.stderr.getvalue()
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            os.chdir(orig_dir)
            logging.debug('captured stdout:')
            logging.debug(captured_stdout)
            logging.debug('captured stderr:')
            logging.debug(captured_stderr)
            logging.debug('captured subprocess output:')
            logging.debug(logdata)

        try:
            # List in subprocess to grab updated package environment.
            logging.debug('')
            logging.debug('list')
            os.chdir(self.tdir)
            stdout = open('list.out', 'w')
            try:
                check_call(('plugin', 'list', '-g', 'driver', '-g',
                            'component', '--external'),
                           stdout=stdout,
                           stderr=STDOUT)
            finally:
                stdout.close()
                with open('list.out', 'r') as inp:
                    captured_stdout = inp.read()
                os.remove('list.out')
                os.chdir(orig_dir)
                logging.debug('captured subprocess output:')
                logging.debug(captured_stdout)
            self.assertTrue('foobar.foobar.Foobar' in captured_stdout)

            # Docs.
            logging.debug('')
            logging.debug('docs')
            argv = ['docs', 'foobar']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            url = find_docs_url(options.plugin_dist_name)
            # Strip off the file protocol header
            url = url.replace('file://', '')
            expected = os.path.join(self.tdir, 'foobar', 'src', 'foobar',
                                    'sphinx_build', 'html', 'index.html')
            self.assertEqual(os.path.realpath(url), os.path.realpath(expected))
        finally:
            # Uninstall
            logging.debug('')
            logging.debug('uninstall')
            pip_in = os.path.join(self.tdir, 'pip.in')
            pip_out = os.path.join(self.tdir, 'pip.out')
            with open(pip_in, 'w') as out:
                out.write('y\n')
            stdin = open(pip_in, 'r')
            stdout = open(pip_out, 'w')
            # On EC2 Windows, 'pip' generates an absurdly long temp directory
            # name, apparently to allow backing-out of the uninstall.
            # The name is so long Windows can't handle it. So we try to
            # avoid that by indirectly influencing mkdtemp().
            env = os.environ.copy()
            env['TMP'] = os.path.expanduser('~')
            try:
                # the following few lines are to prevent the system level pip
                # from being used instead of the local virtualenv version.
                pipexe = 'pip-%d.%d' % (sys.version_info[0],
                                        sys.version_info[1])
                pipexe = find_in_path(pipexe)
                if pipexe is None:
                    pipexe = 'pip'
                check_call((pipexe, 'uninstall', 'foobar'),
                           env=env,
                           stdin=stdin,
                           stdout=stdout,
                           stderr=STDOUT)
            finally:
                stdin.close()
                stdout.close()
                with open(pip_out, 'r') as inp:
                    captured_stdout = inp.read()
                logging.debug('captured stdout:')
                logging.debug(captured_stdout)

        # Show removed.
        logging.debug('')
        logging.debug('list removed')
        os.chdir(self.tdir)
        stdout = open('list.out', 'w')
        try:
            check_call(('plugin', 'list', '--external'),
                       stdout=stdout,
                       stderr=STDOUT)
        finally:
            stdout.close()
            with open('list.out', 'r') as inp:
                captured_stdout = inp.read()
            os.remove('list.out')
            os.chdir(orig_dir)
            logging.debug('captured subprocess output:')
            logging.debug(captured_stdout)
        self.assertFalse('foobar.foobar.Foobar' in captured_stdout)
Example #14
0
    def execute(self):
        """ Execute VSP to perform one or more operations. """
        if self.generate_cfd_mesh and self.write_nascart:
            self.raise_exception('CFD meshing and NASCART output use the same'
                                 ' output filenames', RuntimeError)

        if not os.path.isfile(self.vsp_path) and find_in_path(self.vsp_path) is None:
            raise RuntimeError("VSP executable '%s' not found" % self.vsp_path)

        # Write XML input file.
        filename = os.path.basename(self.xml_filename)
        if filename.endswith('.vsp'):
            base_filename = filename[:-4]
        else:  # .xml input files leave the .new in the output filenames ????
            base_filename = filename + '.new'
        filename += '.new'
        self.write_input(filename)

        # Determine command line and output files.
        cmd = [self.vsp_path, '-batch', filename]
        output_files = []

        if self.comp_geom:
            cmd.append('-compgeom')
            output_files.extend((base_filename + '_CompGeom.txt', base_filename + '_CompGeom.csv'))

        if self.generate_cfd_mesh:
            cmd.append('-cfdmesh')
            output_files.extend(('bodyin.dat', 'bodyin.key',
                                 'cfdmesh.bez', 'cfdmesh.stl'))
        if self.slice:
            cmd.extend(['-slice', str(self.num_slices),
                        str(self.mach), str(self.cone_sections)])

        if self.write_xsec:
            cmd.append('-xsec')
            output_files.append('%s.hrm' % base_filename)

        if self.write_felisa:
            cmd.append('-felisa')
            for ext in ('fel', 'bsf', 'bac'):
                output_files.append('%s.%s' % (base_filename, ext))

        if self.write_stereo:
            cmd.append('-stereo')
            output_files.append('%s.stl' % base_filename)

        if self.write_rhino:
            cmd.append('-rhino')
            output_files.append('%s.3dm' % base_filename)

        if self.write_nascart:
            cmd.append('-nascart')
            output_files.extend(('bodyin.dat', 'bodyin.key'))

        if self.write_tecplot:
            cmd.append('-tecplot')

        if self.write_stecplot:
            cmd.append('-stecplot')

        for name in output_files:
            if os.path.exists(name):
                os.remove(name)

        # Run VSP.
        self.command = cmd
        self.stdout = os.path.basename(self.xml_filename)+'.log'
        self.stderr = ExternalCode.STDOUT
        super(VSP, self).execute()

        # Read from -compgeom output.
        if self.comp_geom:
            reader = csv.reader(open(base_filename + '_CompGeom.csv', 'r'))
            next(reader)
            row = []
            wet_areas = {'Horizontal_Tail':0, 'Vertical_Tail':0, 'Wing':0, 'Fuselage':0}
            for row in reader:
                if row[0] in wet_areas:
                    wet_areas[row[0]] = wet_areas.get(row[0]) + float(row[2])
            self.horiz_wet_area = wet_areas.get('Horizontal_Tail')
            self.vert_wet_area = wet_areas.get('Vertical_Tail')
            self.wing_wet_area = wet_areas.get('Wing')
            self.fuse_wet_area = wet_areas.get('Fuselage')
            if len(row) == 5:
                self.theoretical_area = float(row[1])
                self.wetted_area = float(row[2])
                self.theoretical_volume = float(row[3])
                self.wetted_volume = float(row[4])
            else:
                self.raise_exception('comp_geom.csv invalid', RuntimeError)
        else:
            self.theoretical_area = 0
            self.wetted_area = 0
            self.theoretical_volume = 0
            self.wetted_volume = 0

        # Check CFD meshing if requested.
        if self.generate_cfd_mesh:
            mesh_ok = False

        with open(self.stdout, 'r') as out:
            for line in out:
                if 'xmlGetNode: Cant find' in line:
                    self._logger.warning(line[:-1])
                if self.generate_cfd_mesh:
                    if 'Total Num Tris' in line:
                        mesh_ok = True
        if self.generate_cfd_mesh and not mesh_ok:
            self.raise_exception('Meshing failed', RuntimeError)
Example #15
0
    def execute(self):

        if not os.path.isfile(self.supin_exec) and find_in_path(self.supin_exec) is None:
            raise RuntimeError("SUPIN executable '%s' not found" % self.supin_exec)

        # --------------------------------------
        # --- Execute file-wrapped component ---
        # --------------------------------------
        self.command = [self.supin_exec]

        split = "\n---------------------------------------------------------------------------\n"

        # --------------------
        # --- Header Input ---
        # --------------------
        header_input = ["SUPIN Input File"]
        header_input.append(" ".join(["2D AxiSpike Inlet."]))
        header_input.append(" ".join(["GE F404 Conditions."]))
        header_input.append(split)

        # ------------------
        # --- Main Input ---
        # ------------------
        main_input = [_2str("DataID")]
        main_input.append(" ".join([_2str(self.DataID)]))
        main_input.append(" ".join([_2str(x) for x in ["Kmode", "Ktype", "Kcomp", "Ksurf", "KgCFD"]]))
        main_input.append(" ".join([_2str(x) for x in [self.Kmode, self.Ktype, self.Kcomp, self.Ksurf, self.KgCFD]]))
        main_input.append(" ".join([_2str(x) for x in ["KWinp", "FWinp", "KWunit", "Flapeng"]]))
        main_input.append(" ".join([_2str(x) for x in [self.KWinp, self.FWinp, self.KWunit, self.Flapeng]]))
        main_input.append(" ".join([_2str(x) for x in ["WRspill", "WRbleed", "WRbypass", "WRother"]]))
        main_input.append(" ".join([_2str(x) for x in [self.WRspill, self.WRbleed, self.WRbypass, self.WRother]]))
        main_input.append(split)

        # ------------------------
        # --- Freestream Input ---
        # ------------------------
        freestream_input = [_2str("DataID")]
        freestream_input.append(" ".join([_2str(self.Freestream.DataID)]))
        freestream_input.append(
            " ".join(
                [_2str(x) for x in ["Kfs", "Mach", "Pres (psf)", "Temp (R)", "Alpha (deg)", "Beta (deg)", "Alt (ft)"]]
            )
        )
        freestream_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.Freestream.Kfs,
                        self.Freestream.Mach,
                        self.Freestream.Pres,
                        self.Freestream.Temp,
                        self.Freestream.Alpha,
                        self.Freestream.Beta,
                        self.Freestream.Alt,
                    ]
                ]
            )
        )
        freestream_input.append(split)

        # -------------------------------
        # --- Capture X-Section Input ---
        # -------------------------------
        capture_input = [_2str("DataID")]
        capture_input.append(" ".join([_2str(self.Capture.DataID)]))
        capture_input.append(" ".join([_2str(x) for x in ["FAcap", "Fhclip", "Fwclip"]]))
        capture_input.append(
            " ".join([_2str(x) for x in [self.Capture.FAcap, self.Capture.Fhclip, self.Capture.Fwclip]])
        )
        capture_input.append(" ".join([_2str(x) for x in ["Xinlet", "Yinlet", "ThetaInlet"]]))
        capture_input.append(
            " ".join([_2str(x) for x in [self.Capture.Xinlet, self.Capture.Yinlet, self.Capture.Thetinlet]])
        )
        capture_input.append(" ".join([_2str(x) for x in ["ARtopcap", "ptopcap", "ARbotcap", "pbotcap"]]))
        capture_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [self.Capture.ARtopcap, self.Capture.ptopcap, self.Capture.ARbotcap, self.Capture.pbotcap]
                ]
            )
        )
        capture_input.append(split)

        # ---------------------------
        # --- Approach Flow Input ---
        # ---------------------------
        approach_input = [_2str("DataID")]
        approach_input.append(" ".join([_2str(self.Approach.DataID)]))
        approach_input.append(" ".join([_2str(x) for x in ["Kapp", "Nsapp", "Alpha_Inlet (deg)", "Beta_Inlet (deg)"]]))
        approach_input.append(
            " ".join(
                [_2str(x) for x in [self.Approach.Kapp, self.Approach.Nsapp, self.Approach.IAlpha, self.Approach.IBeta]]
            )
        )
        approach_input.append(" ".join([_2str(x) for x in ["Mach_L", "pt_L/pt_0", "Alpha_L (deg)", "Beta_L (deg)"]]))
        approach_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.Freestream.Mach * 1.01,
                        self.Approach.ptL_pt0,
                        self.Approach.LAlpha,
                        self.Approach.LBeta,
                    ]
                ]
            )
        )
        approach_input.append(split)

        # ------------------------------------------
        # --- External Supersonic Diffuser Input ---
        # ------------------------------------------
        extsupdiff_input = [_2str("DataID")]
        extsupdiff_input.append(" ".join([_2str(self.ExtSupDiff.DataID)]))
        extsupdiff_input.append(" ".join([_2str(x) for x in ["Kexd"]]))
        extsupdiff_input.append(" ".join([_2str(x) for x in [self.ExtSupDiff.Kexd]]))
        extsupdiff_input.append(" ".join([_2str(x) for x in ["Kmatch", "Fmatch", "Kfocal", "Tcap"]]))
        extsupdiff_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.ExtSupDiff.Kmatch,
                        self.ExtSupDiff.Fmatch,
                        self.ExtSupDiff.Kfocal,
                        self.ExtSupDiff.Tcap,
                    ]
                ]
            )
        )
        extsupdiff_input.append(" ".join([_2str(x) for x in ["Knose", "Xnose", "Rnose"]]))
        extsupdiff_input.append(
            " ".join([_2str(x) for x in [self.ExtSupDiff.Knose, self.ExtSupDiff.Xnose, self.ExtSupDiff.Rnose]])
        )
        extsupdiff_input.append(" ".join([_2str(x) for x in ["Stage", "Angle", "Xstage", "Dyfocal"]]))
        for j in [0, 1, 2]:
            extsupdiff_input.append(
                " ".join(
                    [
                        _2str(x)
                        for x in [
                            self.ExtSupDiff.Stage[0][j],
                            self.ExtSupDiff.Angle[0][j],
                            self.ExtSupDiff.Xstage[0][j],
                            self.ExtSupDiff.Dyfocal[0][j],
                        ]
                    ]
                )
            )
        extsupdiff_input.append(split)

        # ----------------------
        # --- Cowl Lip Input ---
        # ----------------------
        cowllip_input = [_2str("DataID")]
        cowllip_input.append(" ".join([_2str(self.CowlLip.DataID)]))
        cowllip_input.append(" ".join([_2str(x) for x in ["Kclip", "Kclin", "Kclex"]]))
        cowllip_input.append(" ".join([_2str(x) for x in [self.CowlLip.Kclip, self.CowlLip.Kclin, self.CowlLip.Kclex]]))
        cowllip_input.append(" ".join([_2str(x) for x in ["bclin", "ARclin", "thclin"]]))
        cowllip_input.append(
            " ".join([_2str(x) for x in [self.CowlLip.bclin, self.CowlLip.ARclin, self.CowlLip.thclin]])
        )
        cowllip_input.append(" ".join([_2str(x) for x in ["bclex", "ARclex", "thclex"]]))
        cowllip_input.append(
            " ".join([_2str(x) for x in [self.CowlLip.bclex, self.CowlLip.ARclex, self.CowlLip.thclex]])
        )
        cowllip_input.append(split)

        # ---------------------------
        # --- Cowl Exterior Input ---
        # ---------------------------
        cowlext_input = [_2str("DataID")]
        cowlext_input.append(" ".join([_2str(self.CowlExt.DataID)]))
        cowlext_input.append(" ".join([_2str(x) for x in ["Kcex", "Frcex", "FXcext", "Thswex"]]))
        cowlext_input.append(
            " ".join(
                [_2str(x) for x in [self.CowlExt.Kcex, self.CowlExt.Frcex, self.CowlExt.FXcext, self.CowlExt.Thswex]]
            )
        )
        cowlext_input.append(split)

        # --------------------
        # --- Throat Input ---
        # --------------------
        throat_input = [_2str("DataID")]
        throat_input.append(" ".join([_2str(self.Throat.DataID)]))
        throat_input.append(" ".join([_2str(x) for x in ["Kthrt"]]))
        throat_input.append(" ".join([_2str(x) for x in [self.Throat.Kthrt]]))
        throat_input.append(" ".join([_2str(x) for x in ["Kthcb"]]))
        throat_input.append(" ".join([_2str(x) for x in [self.Throat.Kthcb]]))
        throat_input.append(" ".join([_2str(x) for x in ["dthcb1", "dxcbSD", "dycbSD", "thcbSD", "Fncb1", "FncbSD"]]))
        throat_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.Throat.dthcb1,
                        self.Throat.dxcbSD,
                        self.Throat.dycbSD,
                        self.Throat.thcbSD,
                        self.Throat.Fncb1,
                        self.Throat.FncbSD,
                    ]
                ]
            )
        )
        throat_input.append(" ".join([_2str(x) for x in ["Kthcw"]]))
        throat_input.append(" ".join([_2str(x) for x in [self.Throat.Kthcw]]))
        throat_input.append(" ".join([_2str(x) for x in ["aTHa1", "thcwTH", "machTH"]]))
        throat_input.append(" ".join([_2str(x) for x in [self.Throat.aTHa1, self.Throat.thcwTH, self.Throat.machTH]]))
        throat_input.append(" ".join([_2str(x) for x in ["aSDa1", "thcwSD", "machSD"]]))
        throat_input.append(" ".join([_2str(x) for x in [self.Throat.aSDa1, self.Throat.thcwSD, self.Throat.machSD]]))
        throat_input.append(split)

        # -------------------------------
        # --- Subsonic Diffuser Input ---
        # -------------------------------
        subdiff_input = [_2str("DataID")]
        subdiff_input.append(" ".join([_2str(self.SubDiff.DataID)]))
        subdiff_input.append(" ".join([_2str(x) for x in ["Ksubd", "KLsubd", "FLsubd", "theqsd", "dptsubd"]]))
        subdiff_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.SubDiff.Ksubd,
                        self.SubDiff.KLsubd,
                        self.SubDiff.FLsubd,
                        self.SubDiff.theqsd,
                        self.SubDiff.dptsubd,
                    ]
                ]
            )
        )
        subdiff_input.append(" ".join([_2str(x) for x in ["Ksdcb"]]))
        subdiff_input.append(" ".join([_2str(x) for x in [self.SubDiff.Ksdcb]]))
        subdiff_input.append(" ".join([_2str(x) for x in ["Ksdcb", "FdcbX", "thcbX", "FLcbX"]]))
        subdiff_input.append(
            " ".join(
                [_2str(x) for x in [self.SubDiff.Ksdcb, self.SubDiff.FdcbX, self.SubDiff.thcbX, self.SubDiff.FLcbX]]
            )
        )
        subdiff_input.append(" ".join([_2str(x) for x in ["Ksdcw"]]))
        subdiff_input.append(" ".join([_2str(x) for x in [self.SubDiff.Ksdcw]]))
        subdiff_input.append(" ".join([_2str(x) for x in ["FncwSD", "FncwX", "FLcwX"]]))
        subdiff_input.append(
            " ".join([_2str(x) for x in [self.SubDiff.FncwSD, self.SubDiff.FncwX, self.SubDiff.FLcwX]])
        )
        subdiff_input.append(split)

        # -------------------------
        # --- Engine Face Input ---
        # -------------------------
        engineface_input = [_2str("DataID")]
        engineface_input.append(" ".join([_2str(self.EngineFace.DataID)]))
        engineface_input.append(" ".join([_2str(x) for x in ["KxEF", "FxEF", "KyEF", "FyEF", "ThetEF"]]))
        engineface_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.EngineFace.KxEF,
                        self.EngineFace.FxEF,
                        self.EngineFace.KyEF,
                        self.EngineFace.FyEF,
                        self.EngineFace.ThetEF,
                    ]
                ]
            )
        )
        engineface_input.append(" ".join([_2str(x) for x in ["Kef"]]))
        engineface_input.append(" ".join([_2str(x) for x in [self.EngineFace.Kef]]))
        engineface_input.append(" ".join([_2str(x) for x in ["diamEF", "Hubtip"]]))
        engineface_input.append(" ".join([_2str(x) for x in [self.EngineFace.diamEF, self.EngineFace.Hubtip]]))
        engineface_input.append(" ".join([_2str(x) for x in ["Kspin"]]))
        engineface_input.append(" ".join([_2str(x) for x in [self.EngineFace.Kspin]]))
        engineface_input.append(split)

        # --------------------------
        # --- Grid Spacing Input ---
        # --------------------------
        gridspacing_input = [_2str("DataID")]
        gridspacing_input.append(" ".join([_2str(self.GridSpacing.DataID)]))
        gridspacing_input.append(
            " ".join([_2str(x) for x in ["Fgdds", "Rgsmax", "Fdswall", "Fdssym", "Fdscex", "Fdsthrt"]])
        )
        gridspacing_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.GridSpacing.Fgdds,
                        self.GridSpacing.Rgsmax,
                        self.GridSpacing.Fdswall,
                        self.GridSpacing.Fdssym,
                        self.GridSpacing.Fdscex,
                        self.GridSpacing.Fdsthrt,
                    ]
                ]
            )
        )
        gridspacing_input.append(" ".join([_2str(x) for x in ["Ddinf", "Ddfar", "Ddnoz", "Ddclp", "thfar", "Fgnoz"]]))
        gridspacing_input.append(
            " ".join(
                [
                    _2str(x)
                    for x in [
                        self.GridSpacing.Ddinf,
                        self.GridSpacing.Ddfar,
                        self.GridSpacing.Ddnoz,
                        self.GridSpacing.Ddclp,
                        self.GridSpacing.thfar,
                        self.GridSpacing.Fgnoz,
                    ]
                ]
            )
        )
        gridspacing_input.append(split)

        # ---------------------------------------
        # --- Write Header Output to SUPIN.in ---
        # ---------------------------------------
        filename = "SUPIN.in"
        file_handle = open(filename, "w")
        file_handle.write("\n".join(header_input))

        # ------------------------------------
        # --- Write Input to SUPIN.in ---
        # ------------------------------------
        file_handle.write("\n".join(main_input))
        file_handle.write("\n".join(freestream_input))
        file_handle.write("\n".join(approach_input))
        file_handle.write("\n".join(capture_input))
        file_handle.write("\n".join(extsupdiff_input))
        file_handle.write("\n".join(cowllip_input))
        file_handle.write("\n".join(cowlext_input))
        file_handle.write("\n".join(throat_input))
        file_handle.write("\n".join(subdiff_input))
        file_handle.write("\n".join(engineface_input))
        file_handle.write("\n".join(gridspacing_input))
        file_handle.close()

        # -------------------------------
        # --- Execute SUPIN Component ---
        # -------------------------------
        super(SUPIN, self).execute()

        # -------------------------
        # --- Parse Output File ---
        # -------------------------
        with open("SUPIN.out") as f:
            lines = f.readlines()

        for line in lines:
            if "pt_2 / pt_L    =" in line:
                self.Outputs.pt2_ptL = float(line.split("=")[-1])
            elif "Tt2 / TtL  =" in line:
                self.Outputs.tt2_ttL = float(line.split("=")[-1])
            elif "Mach_2         =" in line:
                self.Outputs.M2 = float(line.split("=")[-1])
            elif "rhub   (ft)  =" in line:
                self.Outputs.Rspin = float(line.split("=")[-1])
            elif "diamEF (ft)  =" in line:
                self.Outputs.diamEF = float(line.split("=")[-1])
            elif "Inlet Drag Coefficient, cdrag" in line:
                self.Outputs.Cd = float(line.split("=")[-1])
            elif "Wa2 (actual)                       =" in line:
                self.Outputs.mdot = float(line.split("=")[-1])
            elif "A_2  (ft)      =" in line:
                self.Outputs.A2 = float(line.split("=")[-1])
            elif "y_EF (ft)      =" in line:
                self.Outputs.yEF = float(line.split("=")[-1])
            elif "rhub   (ft)  =" in line:
                self.Outputs.Rspin = float(line.split("=")[-1])
            else:
                pass

        if not self.Outputs.pt2_ptL:
            self.Outputs.pt2_ptL = 0.8
        if not self.Outputs.Cd:
            self.Outputs.Cd = 1.0

        try:
            src_file = "Solid.p3d"
            dst_folder = os.path.join(os.getcwd(), str(self.exec_count))
            shutil.copy2(src_file, dst_folder)
        except:
            pass

        print "---------------------------------"
        print "------- SUPIN Parameters --------"
        print "---------------------------------"

        print "---Outputs---"
        print "Precov: ", self.Outputs.pt2_ptL
        print "CdWave: ", self.Outputs.Cd
        print "Obj: ", -1.0 * self.Outputs.pt2_ptL + 0.5 * self.Outputs.Cd
Example #16
0
    def test_basic(self):
        logging.debug('')
        logging.debug('test_basic')

        # Just run through a complete cycle.
        orig_dir = os.getcwd()
        orig_stdout = sys.stdout
        orig_stderr = sys.stderr

        # Quickstart.
        logging.debug('')
        logging.debug('quickstart')
        os.chdir(self.tdir)
        try:
            argv = ['quickstart', 'foobar']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_quickstart(parser, options, args)
            self.assertEqual(retval, 0)
            fandd = find_files(self.tdir, showdirs=True)
            self.assertEqual(set([os.path.basename(f) for f in fandd]),
                             set(['foobar', 'src', 'docs', 'setup.cfg', 'setup.py',
                                  'MANIFEST.in', '__init__.py', 'conf.py',
                                  'usage.rst', 'index.rst',
                                  'srcdocs.rst', 'pkgdocs.rst', 'foobar.py',
                                  'README.txt',
                                  'test', 'test_foobar.py']))
        finally:
            os.chdir(orig_dir)

        # Makedist.
        logging.debug('')
        logging.debug('makedist')
        sys.stdout = cStringIO.StringIO()
        sys.stderr = cStringIO.StringIO()
        logdata = ''
        os.chdir(os.path.join(self.tdir, 'foobar'))
        try:
            argv = ['makedist']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_makedist(parser, options, args, capture='makedist.out')
            with open('makedist.out', 'r') as inp:
                logdata = inp.read()
            self.assertEqual(retval, 0)
            if sys.platform == 'win32':
                self.assertTrue(os.path.exists('foobar-0.1.zip'))
            else:
                self.assertTrue(os.path.exists('foobar-0.1.tar.gz'))
        finally:
            captured_stdout = sys.stdout.getvalue()
            captured_stderr = sys.stderr.getvalue()
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            os.chdir(orig_dir)
            logging.debug('captured stdout:')
            logging.debug(captured_stdout)
            logging.debug('captured stderr:')
            logging.debug(captured_stderr)
            logging.debug('captured subprocess output:')
            logging.debug(logdata)

        # Existing distribution error.
        logging.debug('')
        logging.debug('makedist error')
        sys.stdout = cStringIO.StringIO()
        sys.stderr = cStringIO.StringIO()
        os.chdir(os.path.join(self.tdir, 'foobar'))
        try:
            argv = ['makedist']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_makedist(parser, options, args, capture='makedist.out')
            with open('makedist.out', 'r') as inp:
                logdata = inp.read()
            self.assertEqual(retval, -1)
        finally:
            captured_stdout = sys.stdout.getvalue()
            captured_stderr = sys.stderr.getvalue()
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            os.chdir(orig_dir)
            logging.debug('captured stdout:')
            logging.debug(captured_stdout)
            logging.debug('captured stderr:')
            logging.debug(captured_stderr)
            logging.debug('captured subprocess output:')
            logging.debug(logdata)
        self.assertTrue('already exists' in captured_stderr)

        # Install
        logging.debug('')
        logging.debug('install')
        sys.stdout = cStringIO.StringIO()
        sys.stderr = cStringIO.StringIO()
        logdata = ''
        os.chdir(self.tdir)
        try:
            argv = ['install', 'foobar']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            retval = plugin_install(parser, options, args, capture='install.out')
            with open('install.out', 'r') as inp:
                logdata = inp.read()
            self.assertEqual(retval, 0)
        finally:
            captured_stdout = sys.stdout.getvalue()
            captured_stderr = sys.stderr.getvalue()
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            os.chdir(orig_dir)
            logging.debug('captured stdout:')
            logging.debug(captured_stdout)
            logging.debug('captured stderr:')
            logging.debug(captured_stderr)
            logging.debug('captured subprocess output:')
            logging.debug(logdata)

        try:
            # List in subprocess to grab updated package environment.
            logging.debug('')
            logging.debug('list')
            os.chdir(self.tdir)
            stdout = open('list.out', 'w')
            try:
                check_call(('plugin', 'list', '-g', 'driver', '-g', 'component',
                            '--external'), stdout=stdout, stderr=STDOUT)
            finally:
                stdout.close()
                with open('list.out', 'r') as inp:
                    captured_stdout = inp.read()
                os.remove('list.out')
                os.chdir(orig_dir)
                logging.debug('captured subprocess output:')
                logging.debug(captured_stdout)
            self.assertTrue('foobar.foobar.Foobar' in captured_stdout)

            # Docs.
            logging.debug('')
            logging.debug('docs')
            argv = ['docs', 'foobar']
            parser = _get_plugin_parser()
            options, args = parser.parse_known_args(argv)
            url = find_docs_url(options.plugin_dist_name)
            # Strip off the file protocol header
            url = url.replace('file://', '')
            expected = os.path.join(self.tdir, 'foobar', 'src', 'foobar',
                                    'sphinx_build', 'html', 'index.html')
            self.assertEqual(os.path.realpath(url), os.path.realpath(expected))
        finally:
            # Uninstall
            logging.debug('')
            logging.debug('uninstall')
            pip_in = os.path.join(self.tdir, 'pip.in')
            pip_out = os.path.join(self.tdir, 'pip.out')
            with open(pip_in, 'w') as out:
                out.write('y\n')
            stdin = open(pip_in, 'r')
            stdout = open(pip_out, 'w')
            # On EC2 Windows, 'pip' generates an absurdly long temp directory
            # name, apparently to allow backing-out of the uninstall.
            # The name is so long Windows can't handle it. So we try to
            # avoid that by indirectly influencing mkdtemp().
            env = os.environ.copy()
            env['TMP'] = os.path.expanduser('~')
            try:
                # the following few lines are to prevent the system level pip
                # from being used instead of the local virtualenv version.
                pipexe = 'pip-%d.%d' % (sys.version_info[0], sys.version_info[1])
                pipexe = find_in_path(pipexe)
                if pipexe is None:
                    pipexe = 'pip'
                check_call((pipexe, 'uninstall', 'foobar'), env=env,
                           stdin=stdin, stdout=stdout, stderr=STDOUT)
            finally:
                stdin.close()
                stdout.close()
                with open(pip_out, 'r') as inp:
                    captured_stdout = inp.read()
                logging.debug('captured stdout:')
                logging.debug(captured_stdout)

        # Show removed.
        logging.debug('')
        logging.debug('list removed')
        os.chdir(self.tdir)
        stdout = open('list.out', 'w')
        try:
            check_call(('plugin', 'list', '--external'),
                       stdout=stdout, stderr=STDOUT)
        finally:
            stdout.close()
            with open('list.out', 'r') as inp:
                captured_stdout = inp.read()
            os.remove('list.out')
            os.chdir(orig_dir)
            logging.debug('captured subprocess output:')
            logging.debug(captured_stdout)
        self.assertFalse('foobar.foobar.Foobar' in captured_stdout)