Example #1
0
    def test_SimpleMatchAbsoluteNeighbor(self):
        points, dummy = Utils.getSimplePatterns()

        pointsAsNpArray = np.array(points)
        R = Utils.getRotationMatrix(35 + 180)
        translation = np.array([[0.11, -0.03]])
        points2 = Utils.transform(1.0, R, translation, pointsAsNpArray)

        c = AbsoluteNeighborFitnessComputer(points2, 0.1)
        m = SimulatedAnnealingPointMatcher2D(c)

        Utils.addPointsToAnnealer(points, m)
        m.setSlowMovementBreakpoint(0.75)
        m.setInitialRotationSigma(360)
        m.setInitialTranslationSigma(0.2)
        m.setSlowTranslationSigma(0.1)
        m.setStartTemperature(0.0)
        m.setNumIterations(200)

        scale, rotation, translation, fitness = m.match()

        self.assertAlmostEqual(fitness[0, 0], 0.0)
        self.assertAlmostEqual(scale[0, 0], 1.0)
        numDigits = 1
        self.assertMatrixAlmostEquals(rotation, R, numDigits)
        self.assertMatrixAlmostEquals(translation, translation, numDigits)
    def test_SimpleMatch(self):
        m = CoherentPointDriftMatcher2D()

        p2, p1 = Utils.getSimplePatterns()
        Utils.addPointsToDrifter(p1, m, 1)
        Utils.addPointsToDrifter(p2, m, 2)

        scale, rotation, translation = m.match()
        self.assertAlmostEqual(scale, 2.0)
    def test_SameMatch(self):
        m = CoherentPointDriftMatcher2D()

        pattern1, _ = Utils.getSimplePatterns()
        Utils.addPointsToDrifter(pattern1, m, 1)
        Utils.addPointsToDrifter(pattern1, m, 2)

        scale, rotation, translation = m.match()
        self.assertAlmostEqual(scale[0][0], 1.0)
        self.assertMatrixAlmostEquals(rotation, np.eye(2))
        self.assertMatrixAlmostEquals(translation, np.zeros((1, 2)))
Example #4
0
    def test_SimpleMatch(self):
        refCloud = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
        scale = 1.0
        rotation = Utils.getRotationMatrix(90)
        translation = np.array([[1.0, 2.0]])
        matchCloud = Utils.transform(scale, rotation, translation, refCloud)

        c = MeanShortestDistanceFitnessComputer(refCloud)
        m = BruteForceMatcher(c, refCloud)
        m.setCandidateKeepRatio(1)
        scale, rotation, translation, fitness = m.match(matchCloud)

        self.assertAlmostEqual(fitness[0, 0], 0.0)
        self.assertEqual(scale[0, 0], 1.0)
        self.assertAlmostEqual(rotation[0, 0], 0.0)
        self.assertAlmostEqual(rotation[0, 1], 1.0)
        self.assertAlmostEqual(rotation[1, 0], -1.0)
        self.assertAlmostEqual(rotation[1, 1], 0.0)
Example #5
0
 def test_zone_properties_from_id(self):
   hPk = dbHelp.setup_test_hero_using_default_values()
   z = dbHelp.create_test_zone_obj()
   testZoneKey = ZoneDefinitionFields.EMPTY_SPACE
   z.save_changes(hPk)
   zPk = z.get_pk()
   z2 = z.construct_model_from_pk(zPk)
   self.assertEqual(z.definitionKey, testZoneKey)
   self.assertEqual(z.get_fullName(), ZoneDefinition.get_name_for_key(testZoneKey) + " Alpha")
   self.assertEqual(z.suffix,"Alpha")
   self.assertEqual(z.monstersKilled, 2)
   self.assertEqual(z.maxMonsters,15)
   self.assertEqual(z.lvl, 3)
   self.assertEqual(z.get_description(),ZoneDefinition.get_description_for_key(testZoneKey))
   oldCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
   z.save_changes(hPk)
   newCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
   self.assertEqual(oldCount , newCount)
Example #6
0
  def test_monster_properties_from_dict(self):
    hpk = dbHelp.setup_test_hero_using_default_values()
    md = dbHelp.create_test_monster_dict()
    m = Monster.construct_model_from_dict(md)

    self.assertEqual(m.nowHp,100)
    self.assertEqual(m.maxHp,150)
    self.assertEqual(m.get_baseXpReward(),1)
    self.assertEqual(m.get_treasureDropRate(),.1)
    self.assertEqual(m.definitionKey,MonsterDefinitionFields.AMBUSH_PIRATES)
    self.assertEqual(len(m.get_treasureDrops()), 0)
    self.assertEqual(m.get_name(),"Sneaky Ambush Pirates")
    self.assertEqual(m.get_description(),"These Sneaky Pirates hide behind asteroids "
        "and surprise you. They're sorta like deadlines.")

    oldCount = tu.get_record_count_from_table(MonsterDbFields.COLLECTION_NAME)

    m.save_changes(hpk)
    newcount = tu.get_record_count_from_table(MonsterDbFields.COLLECTION_NAME)
    self.assertEqual(oldCount,newcount)
Example #7
0
 def test_zone_properties_from_id(self):
     hPk = dbHelp.setup_test_hero_using_default_values()
     z = dbHelp.create_test_zone_obj()
     testZoneKey = ZoneDefinitionFields.EMPTY_SPACE
     z.save_changes(hPk)
     zPk = z.get_pk()
     z2 = z.construct_model_from_pk(zPk)
     self.assertEqual(z.definitionKey, testZoneKey)
     self.assertEqual(
         z.get_fullName(),
         ZoneDefinition.get_name_for_key(testZoneKey) + " Alpha")
     self.assertEqual(z.suffix, "Alpha")
     self.assertEqual(z.monstersKilled, 2)
     self.assertEqual(z.maxMonsters, 15)
     self.assertEqual(z.lvl, 3)
     self.assertEqual(z.get_description(),
                      ZoneDefinition.get_description_for_key(testZoneKey))
     oldCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
     z.save_changes(hPk)
     newCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
     self.assertEqual(oldCount, newCount)
Example #8
0
def ac_response(test):
    """Measure the ac response of the opamp"""

    # create the test utility object
    test_utilities_obj = TestUtilities.TestUtilities()
    test_utilities_obj.netlist_generation(config['ac_response']['netlist'],
                                          "rundir")

    # create the spice interface
    spice_interface_obj = SpiceInterface.SpiceInterface(
        netlist_path="rundir/" +
        config['ac_response']['netlist'].split('.')[0] + ".spice")

    # append the simulation command
    spice_interface_obj.set_sim_command(config['ac_response']['sim_command'])

    # loop through all corners
    for corner in config['pvt']['corners']:

        # set corner
        spice_interface_obj.set_corner(corner)

        for temperature in config['pvt']['temperatures']:

            # set temperaure
            spice_interface_obj.set_temperature(temperature)

            # run the simulation
            spice_interface_obj.run_simulation()

            # save the response
            node = 'v(ac)'
            spice_interface_obj.plot_ac(node,
                                        display=False,
                                        title="AC Response",
                                        linewidth=1,
                                        alpha=0.5,
                                        append=True)

            # get the dc gain and gainbandwidth prodcut
            dc_gain, unity_bandwidth = spice_interface_obj.measure_gain_bandwidth(
                node)

            print("DC Gain: %0.1f dB, Unity Bandwidth: %0.3f MHz" %
                  (dc_gain, unity_bandwidth / 1e6))

            # test the margins
            test.measurements.dc_gain = dc_gain
            test.measurements.unity_bandwidth = unity_bandwidth

    # save the plot to file
    spice_interface_obj.fig.savefig("outputs/ac_response.svg")
Example #9
0
def stability_ptat(test):
    """Measure the stability margins of the PTAT control loop"""

    # create the test utility object
    test_utilities_obj = TestUtilities.TestUtilities()
    test_utilities_obj.netlist_generation(config['stability_ptat']['netlist'],
                                          "rundir")

    # create the spice interface
    spice_interface_obj = SpiceInterface.SpiceInterface(
        netlist_path="rundir/" +
        config['stability_ptat']['netlist'].split('.')[0] + ".spice")

    # loop through all corners
    for corner in config['pvt']['corners']:

        # set corner
        spice_interface_obj.set_corner(corner)

        # run the simulation
        spice_interface_obj.run_simulation()

        # save the response
        node = 'v(ac)'
        spice_interface_obj.plot_bode(node,
                                      display=False,
                                      title="PTAT Open Loop Response",
                                      linewidth=1,
                                      alpha=0.5,
                                      append=True,
                                      invert=True)
        # linewidth=1, alpha=0.5, append=True)

        # get the signal and test DC gain
        signal = spice_interface_obj.get_signal(node, complex_out=True)
        test.measurements.dc_gain = 20 * np.log10(abs(signal[0]))

        # get the phase and gain margin
        # phase_margin, gain_margin, unity_bandwidth, inverted_frequency = spice_interface_obj.measure_phase_gain_margin(node)
        phase_margin, gain_margin, unity_bandwidth, inverted_frequency = spice_interface_obj.measure_phase_gain_margin(
            node, invert=True)
        print(phase_margin)

        # test the margins
        test.measurements.phase_margin = phase_margin
        test.measurements.gain_margin = gain_margin

    # save the plot to file
    spice_interface_obj.fig.savefig("outputs/stability_ptat.svg")
Example #10
0
    def test_monster_properties_from_dict(self):
        hpk = dbHelp.setup_test_hero_using_default_values()
        md = dbHelp.create_test_monster_dict()
        m = Monster.construct_model_from_dict(md)

        self.assertEqual(m.nowHp, 100)
        self.assertEqual(m.maxHp, 150)
        self.assertEqual(m.get_baseXpReward(), 1)
        self.assertEqual(m.get_treasureDropRate(), .1)
        self.assertEqual(m.definitionKey,
                         MonsterDefinitionFields.AMBUSH_PIRATES)
        self.assertEqual(len(m.get_treasureDrops()), 0)
        self.assertEqual(m.get_name(), "Sneaky Ambush Pirates")
        self.assertEqual(
            m.get_description(), "These Sneaky Pirates hide behind asteroids "
            "and surprise you. They're sorta like deadlines.")

        oldCount = tu.get_record_count_from_table(
            MonsterDbFields.COLLECTION_NAME)

        m.save_changes(hpk)
        newcount = tu.get_record_count_from_table(
            MonsterDbFields.COLLECTION_NAME)
        self.assertEqual(oldCount, newcount)
Example #11
0
  def test_save_counts(self):
    hDict = dbHelp.create_test_hero_dict()
    h = Hero.construct_model_from_dict(hDict)
    oldHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME)
    oldZoneCOunt = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
    h.save_changes()
    newHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME)
    newZoneCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
    self.assertEqual(oldHeroCount+1,newHeroCount)
    self.assertEqual(oldZoneCOunt+1,newZoneCount)

    oldHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME)
    oldZoneCOunt = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
    h.save_changes()
    newHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME)
    newZoneCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME)
    self.assertEqual(oldHeroCount,newHeroCount)
    self.assertEqual(oldZoneCOunt,newZoneCount)
import os
import sys
import traceback

import TestUtilities

try:
    print("Testing ArcPy")
    arcpy.AddMessage("ArcPy works")

    # WORKAROUND: delete scratch db (having problems with scratch read-only "scheme lock" errors
    # print "Deleting Scratch Workspace (Workaround)"
    # TestUtilities.deleteScratch()

    if not arcpy.Exists(TestUtilities.scratchGDB):
        TestUtilities.createScratch()

    print("Testing Necessary Paths")

    print("Running from: " + str(TestUtilities.currentPath))

    paths2Check = []
    paths2Check.extend([
        TestUtilities.geodatabasePath, TestUtilities.scratchPath,
        TestUtilities.toolboxesPath
    ])

    for path2check in paths2Check:
        if os.path.exists(path2check):
            print("Valid Path: " + path2check)
        else:
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: RangeFans")
        
        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")        
        
        # WORKAROUND
        print "Creating New Scratch Workspace (Workaround)"    
        TestUtilities.createScratch()
            
        # Verify the expected configuration exists
        inputPointsFC =  os.path.join(TestUtilities.inputGDB, "sampleRangePoints")
        inputSurface =  os.path.join(TestUtilities.inputGDB, "Jbad_SRTM_USGS_EROS")
        outputRangeFansFC =  os.path.join(TestUtilities.outputGDB, "RangeFans")
        outputRangeVizFC =  os.path.join(TestUtilities.outputGDB, "RangeViz") 
        toolbox = TestUtilities.toolbox
        sr = arcpy.SpatialReference(32642) #WGS_1984_UTM_Zone_42N using factoryCode
        
        # Check For Valid Input
        objects2Check = []
        objects2Check.extend([inputPointsFC, inputSurface, toolbox])
        for object2Check in objects2Check :
            desc = arcpy.Describe(object2Check)
            if desc == None :
                raise Exception("Bad Input")
            else :
                print("Valid Object: " + desc.Name)
        
        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "VandR")
    
        inputFeatureCount = int(arcpy.GetCount_management(inputPointsFC).getOutput(0)) 
        print("Input FeatureClass: " + str(inputPointsFC))
        print("Input Feature Count: " +  str(inputFeatureCount))
            
        if (inputFeatureCount < 1) :
            print("Invalid Input Feature Count: " +  str(inputFeatureCount))
                       
        maximumRange = 1000.0
        bearing = 150.0
        traversal = 22.0
           
        ########################################################3
        # Execute the Model under test:
        arcpy.RangeFan_VandR(inputPointsFC, maximumRange, bearing, traversal, inputSurface, outputRangeFansFC, outputRangeVizFC, sr)
        ########################################################3
    
        # Verify the results    
        outputFeatureCountFans = int(arcpy.GetCount_management(outputRangeFansFC).getOutput(0)) 
        print("Output FeatureClass: " + str(outputRangeFansFC))
        print("Output Feature Count: " +  str(outputFeatureCountFans))
    
        outputFeatureCountViz = int(arcpy.GetCount_management(outputRangeVizFC).getOutput(0))
        print("Output FeatureClass: " + str(outputRangeVizFC))
        print("Output Feature Count: " +  str(outputFeatureCountViz))
                
        if (outputFeatureCountFans < 1) or (outputFeatureCountViz < 1):
            print("Invalid Output Feature Count: " +  str(outputFeatureCountFans) + ":" + str(outputFeatureCountViz))
            raise Exception("Test Failed")
            
        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()        
        
        print("Test Successful")
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
        
    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")        
Example #14
0
from openhtf.plugs.user_input import UserInput
from spintop_openhtf import TestPlan
from openhtf.util import conf

import SpiceInterface
import TestUtilities

from criteria import get_criteria

# import test parameters
# from config import PVT
with open(r'config.yml') as file:
    config = yaml.load(file, Loader=yaml.FullLoader)

# create the test utility object
test_utilities_obj = TestUtilities.TestUtilities()
test_utilities_obj.netlist_generation(config['stability_ptat']['netlist'],
                                      "rundir")

# create the spice interface
spice_interface_obj = SpiceInterface.SpiceInterface(
    netlist_path="rundir/" +
    config['stability_ptat']['netlist'].split('.')[0] + ".spice")

# set corner
# spice_interface_obj.set_corner(current_corner)

# run the simulation
spice_interface_obj.run_simulation()

# save the response
Example #15
0
def operating_point(test):
    """Test the trimming control functionality"""

    # create the test utility object
    test_utilities_obj = TestUtilities.TestUtilities()
    test_utilities_obj.netlist_generation(
        config['temperature_sweep']['netlist'], "rundir")

    # create the spice interface
    spice_interface_obj = SpiceInterface.SpiceInterface(
        netlist_path="rundir/" +
        config['temperature_sweep']['netlist'].split('.')[0] + ".spice")
    spice_interface_obj.config['simulator']['shared'] = True
    spice_interface_obj.config['simulator']['silent'] = True

    # append the simulation command
    spice_interface_obj.set_sim_command(
        config['operating_point']['sim_command'])

    # prepopulate
    results = np.zeros(
        (len(config['pvt']['corners']), len(config['pvt']['vdd']), 101))

    # find all the devices
    devices = spice_interface_obj.find_all_mosfets()

    # insert the command to save the devices
    spice_interface_obj.insert_op_save(devices, ['vsat_marg'])

    exempt_list = [
        'xdut.xbmr.XMdiff_n3',
        'xdut.XMcap_ptat',
        'xdut.XMcap_ctat',
        'xdut.xtrim_ptat.XMcurr_3',
        'xdut.xtrim_ptat.XMcurr_2',
        'xdut.xtrim_ptat.XMcurr_1',
        'xdut.xtrim_ptat.XMcurr_0',
        'xdut.xtrim_ctat.XMcurr_3',
        'xdut.xtrim_ctat.XMcurr_2',
        'xdut.xtrim_ctat.XMcurr_1',
        'xdut.xtrim_ctat.XMcurr_0',
    ]

    # loop through all corners
    for corner_i, corner in enumerate(config['pvt']['corners']):

        # set corner
        spice_interface_obj.set_corner(corner)

        # reload the circuit
        spice_interface_obj.restart_simulation()

        # loop through the supply voltages
        for vdd_i, vdd in enumerate(config['pvt']['vdd']):

            # set the vdd voltage
            spice_interface_obj.set_parameters([['vdd', vdd], ['en', vdd],
                                                ['start_n', vdd]])

            # check device operating regions
            spice_interface_obj.check_op_region('temp-sweep',
                                                exempt_list=exempt_list,
                                                skip_insertion=True,
                                                devices=devices)
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: TestCreateRangeFanIndexFeatures")
        
        # WORKAROUND
        print "Creating New Scratch Workspace (Workaround)"    
        TestUtilities.createScratch()
            
        inputPolygonFC =  os.path.join(TestUtilities.inputGDB, "RangeFans")
        outputExtentBoxes =  os.path.join(TestUtilities.outputGDB, "OutputExtentBoxes")
        outputRangeVertices =  os.path.join(TestUtilities.outputGDB, "RangeVertices")
        toolbox = TestUtilities.toolbox
                
        # Set environment settings
        print "Running from: " + str(TestUtilities.currentPath)
        print "Geodatabase path: " + str(TestUtilities.geodatabasePath)
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "RFT")
    
        inputFeatureCount = int(arcpy.GetCount_management(inputPolygonFC).getOutput(0)) 
        print "Input FeatureClass: " + str(inputPolygonFC)
        print "Input Feature Count: " +  str(inputFeatureCount)
            
        if (inputPolygonFC < 1) :
            print "Invalid Input Feature Count: " +  str(inputPolygonFC)                       
                   
        ########################################################3
        # Execute the Model under test:   
        arcpy.CreateRangeFanIndexFeatures_RFT(inputPolygonFC, outputExtentBoxes, outputRangeVertices)
        ########################################################3
    
        # Verify the results    
        outputFeatureCountExtent = int(arcpy.GetCount_management(outputExtentBoxes).getOutput(0)) 
        print "Output FeatureClass: " + str(outputExtentBoxes)
        print "Output Feature Count: " +  str(outputFeatureCountExtent)
    
        outputFeatureCountPoints = int(arcpy.GetCount_management(outputRangeVertices).getOutput(0))
        print "Output FeatureClass: " + str(outputRangeVertices)
        print "Output Feature Count: " +  str(outputFeatureCountPoints)
                
        if (outputFeatureCountExtent < 1) or (outputFeatureCountPoints < 1) :
            print "Invalid Output Feature Count: " +  str(outputFeatureCountExtent) + ":" + str(outputFeatureCountPoints)
            raise Exception("Test Failed")                                  
            
        # WORKAROUND: delete scratch db
        print "Deleting Scratch Workspace (Workaround)"    
        TestUtilities.deleteScratch()        
        
        print "Test Successful"        
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: LocalPeaks")

        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")

        # WORKAROUND
        print "Creating New Scratch Workspace (Workaround)"
        TestUtilities.createScratch()

        # Verify the expected configuration exists
        inputPolygonFC = os.path.join(TestUtilities.inputGDB, "samplePolygonArea")
        inputSurface = os.path.join(TestUtilities.defaultGDB, "Jbad_SRTM_USGS_EROS")
        outputPointsFC = os.path.join(TestUtilities.outputGDB, "LocalPeaks")
        toolbox = TestUtilities.toolbox

        # Check For Valid Input
        objects2Check = []
        objects2Check.extend([inputPolygonFC, inputSurface, toolbox])
        for object2Check in objects2Check:
            desc = arcpy.Describe(object2Check)
            if desc == None:
                raise Exception("Bad Input")
            else:
                print "Valid Object: " + desc.Name

        # Set environment settings
        print "Running from: " + str(TestUtilities.currentPath)
        print "Geodatabase path: " + str(TestUtilities.geodatabasePath)

        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "VandR")

        inputFeatureCount = int(arcpy.GetCount_management(inputPolygonFC).getOutput(0))
        print "Input FeatureClass: " + str(inputPolygonFC)
        print "Input Feature Count: " + str(inputFeatureCount)

        if inputFeatureCount < 1:
            print "Invalid Input Feature Count: " + str(inputFeatureCount)

        numberOfPeaks = 3

        ########################################################3
        # Execute the Model under test:
        arcpy.FindLocalPeaks_VandR(inputPolygonFC, numberOfPeaks, inputSurface, outputPointsFC)
        ########################################################3

        # Verify the results
        outputFeatureCount = int(arcpy.GetCount_management(outputPointsFC).getOutput(0))
        print "Output FeatureClass: " + str(outputPointsFC)
        print "Output Feature Count: " + str(outputFeatureCount)

        if outputPointsFC < 3:
            print "Invalid Output Feature Count: " + str(outputFeatureCount)
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print "Deleting Scratch Workspace (Workaround)"
        TestUtilities.deleteScratch()

        print "Test Successful"

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: RangeRings")
        
        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()
            
        # Verify the expected configuration exists
        inputPointsFC =  os.path.join(TestUtilities.inputGDB, "sampleRangePoints")
        outputRangeRingsFC =  os.path.join(TestUtilities.outputGDB, "RangeRings")
        outputRangeRadialsFC =  os.path.join(TestUtilities.outputGDB, "RangeRadials") 
        toolbox = TestUtilities.toolbox
        
        # Check For Valid Input
        objects2Check = []
        objects2Check.extend([inputPointsFC, toolbox])
        for object2Check in objects2Check :
            desc = arcpy.Describe(object2Check)
            if desc == None :
                raise Exception("Bad Input")
            else :
                print("Valid Object: " + desc.Name)
        
        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "VandR")
    
        inputFeatureCount = int(arcpy.GetCount_management(inputPointsFC).getOutput(0)) 
        print("Input FeatureClass: " + str(inputPointsFC))
        print("Input Feature Count: " +  str(inputFeatureCount))
            
        if (inputFeatureCount < 1) :
            print("Invalid Input Feature Count: " +  str(inputFeatureCount))
                       
        numberOfRings = 5
        ringInterval = 1000.0
        distanceUnits = "METERS"
        numberOfRadials = 8
           
        ########################################################3
        # Execute the Model under test:   
        arcpy.RangeRings_VandR(inputPointsFC, numberOfRings, ringInterval, distanceUnits, numberOfRadials, outputRangeRingsFC, outputRangeRadialsFC)
        ########################################################3
    
        # Verify the results    
        outputFeatureCountRings = int(arcpy.GetCount_management(outputRangeRingsFC).getOutput(0)) 
        print("Output FeatureClass: " + str(outputRangeRingsFC))
        print("Output Feature Count: " +  str(outputFeatureCountRings))
    
        outputFeatureCountRadials = int(arcpy.GetCount_management(outputRangeRadialsFC).getOutput(0))
        print("Output FeatureClass: " + str(outputRangeRadialsFC))
        print("Output Feature Count: " +  str(outputFeatureCountRadials))
                
        if (outputFeatureCountRings < 1) or (outputFeatureCountRadials < 1) :
            print("Invalid Output Feature Count: " +  str(outputFeatureCountRings) + ":" + str(outputFeatureCountRadials))
            raise Exception("Test Failed")            
            
        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()        
        
        print("Test Successful")
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: TestLocalPeaks")

        #TEST_IMPLEMENTED = False
        #
        #if not TEST_IMPLEMENTED :
        #    arcpy.AddWarning("***Test Not Yet Implemented***")
        #    return

        # TODO: once model has a version that works with local surface data 
        # (rather than image service), then finish this test/implementation below
        #
        # alternately you can add an image service connection in Catalog and 
        # fill in the parameter below

        if arcpy.CheckExtension("Spatial") == "Available":
            print("Checking out Spatial Analyst license...")
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")

        if arcpy.CheckExtension("3D") == "Available":
            print("Checking out 3D Analyst license...")
            arcpy.CheckOutExtension("3D")
        else:
            raise Exception("LicenseError")

        try:
            print("Getting Advanced license...")
            import arcinfo
        except ImportError:
            print("Could not use ArcGIS Advanced license...")
            raise Exception
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB

        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()

        # Getting inputs
        print("Getting inputs...")
        print("inputPolygonFC...")
        inputPolygonFC = os.path.join(TestUtilities.inputGDB, "samplePolygonArea")
        print("inputSurface...")
        inputSurface = TestUtilities.inputElevationURL
        print("outputPointsFC")
        outputPointsFC = os.path.join(TestUtilities.outputGDB, "LocalPeaks")
        print("ImportToolbox--MAoT...")
        arcpy.ImportToolbox(TestUtilities.toolbox, "MAoT")

        # mf - these have been tested
        # # Check For Valid Input
        # print("Checking valid inputs...")
        # objects2Check = []
        # #objects2Check.extend([inputPolygonFC, inputSurface, toolbox])
        # objects2Check.extend([inputPolygonFC, toolbox])
        # for object2Check in objects2Check :
        #     desc = arcpy.Describe(object2Check)
        #     if desc == None :
        #         raise Exception("Bad Input")
        #     else :
        #         print("Valid Object: " + desc.Name)

        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
        inputFeatureCount = int(arcpy.GetCount_management(inputPolygonFC).getOutput(0)) 
        print("Input FeatureClass: " + str(inputPolygonFC))
        print("Input Feature Count: " +  str(inputFeatureCount))
        # if (inputFeatureCount < 1):
        #     print("Invalid Input Polygon Feature Count: " +  str(inputFeatureCount))

        # Convert input elevation service to local dataset surface
        print("Converting input image service into a local raster surface")
        polygonExtent = arcpy.Describe(inputPolygonFC).extent
        print("Using extent: " + str(polygonExtent))
        cellSize = CellSize(inputPolygonFC)
        print("Using cell size: " + str(cellSize))
        localSurf = None
        srWGS84 = arcpy.SpatialReference(4326) # GCS_WGS_1984
        srWebMerc = arcpy.SpatialReference(3857) #Web_Mercator_Auxiliary_Sphere
        print("Reworking inputs from image service...")
        try:
            tempClipExtent = os.path.join(TestUtilities.scratchGDB,"tempClipExtent")
            localSurf = os.path.join(TestUtilities.scratchGDB,"localSurf")
            print("     projecting input clip to WGS 1984 to match service...")
            arcpy.Project_management(inputPolygonFC,tempClipExtent,srWGS84)
            tempCellSize = CellSize(tempClipExtent)
            #MakeImageServerLayer_management (in_image_service, out_imageserver_layer, {template},
            #{band_index}, {mosaic_method}, {order_field},
            #{order_base_value}, {lock_rasterid}, {cell_size},
            #{where_clause}, {processing_template})
            print("     getting image service layer with cell size " + str(tempCellSize) + "...")
            arcpy.MakeImageServerLayer_management(inputSurface, "inputSurface", tempClipExtent,
                                                  "#", "#", "#",
                                                  "#", "#", tempCellSize)
            print("     projecting image service layer to match target data...")
            arcpy.ProjectRaster_management("inputSurface",localSurf,srWebMerc)
            #arcpy.CopyRaster_management("inputSurface", localSurf)
        except arcpy.ExecuteError:
            print("Error converting image service...")
            msgs = arcpy.GetMessages()
            print(msgs)
            sys.exit(-1)

        numberOfPeaks = 3

        ########################################################
        # Execute the Model under test:
        arcpy.FindLocalPeaks_MAoT(inputPolygonFC, numberOfPeaks, localSurf, outputPointsFC)
        ########################################################

        # Verify the results
        outputFeatureCount = int(arcpy.GetCount_management(outputPointsFC).getOutput(0)) 
        print("Output FeatureClass: " + str(outputPointsFC))
        print("Output Feature Count: " +  str(outputFeatureCount))

        if (outputPointsFC < 3):
            print("Invalid Output Feature Count: " +  str(outputFeatureCount))
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()
        print("Test Successful")

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")
        arcpy.CheckInExtension("3D")
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: CoordinateConversion")

        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()

        inputTable = os.path.join(TestUtilities.csvPath, "SigActs.csv")
        outputDbf = os.path.join(TestUtilities.scratchPath,
                                 "test_coordinate_cc.dbf")
        toolbox = TestUtilities.toolbox

        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))

        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "Position")

        inputFeatureCount = int(
            arcpy.GetCount_management(inputTable).getOutput(0))
        print("Input FeatureClass: " + str(inputTable))
        print("Input Feature Count: " + str(inputFeatureCount))

        if (inputFeatureCount < 1):
            print("Invalid Input Feature Count: " + str(inputFeatureCount))

        coordinateConversionFrom = 'MGRS'
        coordinateFieldX = 'Location'
        coordinateFieldY = None

        ########################################################3
        arcpy.ConvertCoordinates_Position(inputTable, coordinateConversionFrom,
                                          coordinateFieldX, coordinateFieldY,
                                          outputDbf)
        ########################################################3

        # Verify the results
        outputFeatureCount = int(
            arcpy.GetCount_management(outputDbf).getOutput(0))
        print("Output FeatureClass: " + str(outputDbf))
        print("Output Feature Count: " + str(outputFeatureCount))

        if (outputFeatureCount <> inputFeatureCount):
            print("Input / Output Feature Count don't match: " +
                  str(inputFeatureCount) + ":" + str(outputFeatureCount))
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()

        print("Test Successful")

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
            sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: CoordinateConversion")
        
        # WORKAROUND
        print "Creating New Scratch Workspace (Workaround)"    
        TestUtilities.createScratch()
            
        inputTable =  os.path.join(TestUtilities.csvPath, "SigActs.csv")
        outputDbf =  os.path.join(TestUtilities.dbfPath, "test_coordinate_cc.dbf")
        toolbox = TestUtilities.toolbox        
        
        # Set environment settings
        print "Running from: " + str(TestUtilities.currentPath)
        print "Geodatabase path: " + str(TestUtilities.geodatabasePath)
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "MyAlias")
    
        inputFeatureCount = int(arcpy.GetCount_management(inputTable).getOutput(0)) 
        print "Input FeatureClass: " + str(inputTable)
        print "Input Feature Count: " +  str(inputFeatureCount)
            
        if (inputFeatureCount < 1) :
            print "Invalid Input Feature Count: " +  str(inputFeatureCount)
                       
        coordinateConversionFrom = 'MGRS'
        coordinateFieldX = 'Location'
        coordinateFieldY = '#'
        
        ########################################################3
        # Execute the Model under test:   
        
        # sample params:
        # 'data\csv\SigActs.csv', 'MGRS', 'Location', '#', 'data\test_coordinate_cc.dbf', 
        
        arcpy.ConvertCoordinates_MyAlias(inputTable, coordinateConversionFrom, coordinateFieldX, coordinateFieldY, outputDbf)
        ########################################################3
    
        # Verify the results    
        outputFeatureCount = int(arcpy.GetCount_management(outputDbf).getOutput(0)) 
        print "Output FeatureClass: " + str(outputDbf)
        print "Output Feature Count: " +  str(outputFeatureCount)
                    
        if (outputFeatureCount <>  inputFeatureCount) :
            print "Input / Output Feature Count don't match: " +  str(inputFeatureCount) + ":" + str(outputFeatureCount)
            raise Exception("Test Failed")            
            
        # WORKAROUND: delete scratch db
        print "Deleting Scratch Workspace (Workaround)"    
        TestUtilities.deleteScratch()        
        
        print "Test Successful"        
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
Example #22
0
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: TestLocalPeaks")
        
        #TEST_IMPLEMENTED = False
        #
        #if not TEST_IMPLEMENTED :
        #    arcpy.AddWarning("***Test Not Yet Implemented***")
        #    return
        
        # TODO: once model has a version that works with local surface data 
        # (rather than image service), then finish this test/implementation below
        #
        # alternately you can add an image service connection in Catalog and 
        # fill in the parameter below
        
        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")        
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
                
        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()
            
        # Verify the expected configuration exists
        inputPolygonFC =  os.path.join(TestUtilities.inputGDB, "samplePolygonArea")
        inputSurface =  TestUtilities.inputElevationURL
        outputPointsFC =  os.path.join(TestUtilities.outputGDB, "LocalPeaks")
        toolbox = TestUtilities.toolbox
        arcpy.ImportToolbox(toolbox, "MAoT")        
        
        # Check For Valid Input
        objects2Check = []
        #objects2Check.extend([inputPolygonFC, inputSurface, toolbox])
        objects2Check.extend([inputPolygonFC, toolbox])
        for object2Check in objects2Check :
            desc = arcpy.Describe(object2Check)
            if desc == None :
                raise Exception("Bad Input")
            else :
                print("Valid Object: " + desc.Name)
        
        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
    
        inputFeatureCount = int(arcpy.GetCount_management(inputPolygonFC).getOutput(0)) 
        print("Input FeatureClass: " + str(inputPolygonFC))
        print("Input Feature Count: " +  str(inputFeatureCount))
            
        if (inputFeatureCount < 1) :
            print("Invalid Input Feature Count: " +  str(inputFeatureCount))
           
        numberOfPeaks = 3
           
        ########################################################3
        # Execute the Model under test:   
        arcpy.FindLocalPeaks_MAoT(inputPolygonFC, numberOfPeaks, inputSurface, outputPointsFC)
        ########################################################3
    
        # Verify the results    
        outputFeatureCount = int(arcpy.GetCount_management(outputPointsFC).getOutput(0)) 
        print("Output FeatureClass: " + str(outputPointsFC))
        print("Output Feature Count: " +  str(outputFeatureCount))
                
        if (outputPointsFC < 3) :
            print("Invalid Output Feature Count: " +  str(outputFeatureCount))
            raise Exception("Test Failed")
            
        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()        
        
        print("Test Successful")
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
        
    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")        
Example #23
0
def temperature_sweep(test):
    """Measure the response over temperature"""

    # create the test utility object
    test_utilities_obj = TestUtilities.TestUtilities()
    test_utilities_obj.netlist_generation(
        config['temperature_sweep']['netlist'], "rundir")

    # create the spice interface
    spice_interface_obj = SpiceInterface.SpiceInterface(
        netlist_path="rundir/" +
        config['temperature_sweep']['netlist'].split('.')[0] + ".spice")
    spice_interface_obj.config['simulator']['shared'] = True
    spice_interface_obj.config['simulator']['silent'] = True

    # append the simulation command
    spice_interface_obj.set_sim_command(
        config['temperature_sweep']['sim_command'])

    # prepopulate
    results = np.zeros(
        (len(config['pvt']['corners']), len(config['pvt']['vdd']), 101))

    # loop through all corners
    for corner_i, corner in enumerate(config['pvt']['corners']):

        # set corner
        spice_interface_obj.set_corner(corner)

        # reload the circuit
        spice_interface_obj.restart_simulation()

        # loop through the supply voltages
        for vdd_i, vdd in enumerate(config['pvt']['vdd']):

            # set the vdd voltage
            spice_interface_obj.set_parameters([['vdd', vdd], ['en', vdd],
                                                ['start_n', vdd]])

            # run the simulation
            spice_interface_obj.run_simulation(new_instance=False)

            # save the response
            node = 'i(viout)'
            sweepvar = 'temp-sweep'
            spice_interface_obj.plot_dc_sweep(
                sweepvar,
                node,
                display=False,
                title="Output Current Over Temperature",
                linewidth=1,
                alpha=0.5,
                append=True)

            # get the output current
            output_current = spice_interface_obj.get_signal(node)
            temp = spice_interface_obj.get_signal(sweepvar)

            test_signal = spice_interface_obj.get_signal('i(v.xdut.vmeas3)')

            # print("   %0.1fC: %0.3f uA, %0.1fC: %0.3f uA, %0.1fC: %0.3f uA, " % (temp[0], output_current[0]*1e6, temp[40], output_current[40]*1e6, temp[-1], output_current[-1]*1e6))
            print("   %0.1fC: %0.3f uA, %0.1fC: %0.3f uA, %0.1fC: %0.3f uA, " %
                  (temp[0], 2 * test_signal[0] * 1e6, temp[40], 2 *
                   test_signal[40] * 1e6, temp[-1], 2 * test_signal[-1] * 1e6))

            # record the measurement
            for i, value in enumerate(output_current):
                dimensions = (corner, vdd, temp[i])
                test.measurements['current'][dimensions] = value

            # validate
            test.measurements.current_regulation_temp[(corner,
                                                       vdd)] = output_current
            test.measurements.current_regulation_process[(
                corner, vdd)] = output_current

    # save the plot to file
    spice_interface_obj.fig.savefig("outputs/temperature_sweep.svg")
Example #24
0
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: LocalPeaks")
        
        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")        
        
        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()
            
        # Verify the expected configuration exists
        inputPolygonFC =  os.path.join(TestUtilities.inputGDB, "samplePolygonArea")
        inputSurface =  os.path.join(TestUtilities.inputGDB, "Jbad_SRTM_USGS_EROS")
        outputPointsFC =  os.path.join(TestUtilities.outputGDB, "LocalPeaks")
        toolbox = TestUtilities.toolbox
        
        # Check For Valid Input
        objects2Check = []
        objects2Check.extend([inputPolygonFC, inputSurface, toolbox])
        for object2Check in objects2Check :
            desc = arcpy.Describe(object2Check)
            if desc == None :
                raise Exception("Bad Input")
            else :
                print("Valid Object: " + desc.Name)
        
        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "VandR")
    
        inputFeatureCount = int(arcpy.GetCount_management(inputPolygonFC).getOutput(0)) 
        print("Input FeatureClass: " + str(inputPolygonFC))
        print("Input Feature Count: " +  str(inputFeatureCount))
            
        if (inputFeatureCount < 1) :
            print("Invalid Input Feature Count: " +  str(inputFeatureCount))
           
        numberOfPeaks = 3
           
        ########################################################3
        # Execute the Model under test:   
        arcpy.FindLocalPeaks_VandR(inputPolygonFC, numberOfPeaks, inputSurface, outputPointsFC)
        ########################################################3
    
        # Verify the results    
        outputFeatureCount = int(arcpy.GetCount_management(outputPointsFC).getOutput(0)) 
        print("Output FeatureClass: " + str(outputPointsFC))
        print("Output Feature Count: " +  str(outputFeatureCount))
                
        if (outputPointsFC < 3) :
            print("Invalid Output Feature Count: " +  str(outputFeatureCount))
            raise Exception("Test Failed")
            
        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()        
        
        print("Test Successful")
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
        
    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")        
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: RangeFan")

        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")

        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB

        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()

        # Verify the expected configuration exists
        inputPointsFC = os.path.join(TestUtilities.inputGDB,
                                     "sampleRangePoints")
        outputRangeFansFC = os.path.join(TestUtilities.outputGDB, "RangeFans")
        toolbox = TestUtilities.toolbox

        arcpy.ImportToolbox(toolbox, "MAoT")

        # Check For Valid Input
        objects2Check = []
        objects2Check.extend([inputPointsFC, toolbox])
        for object2Check in objects2Check:
            desc = arcpy.Describe(object2Check)
            if desc == None:
                raise Exception("Bad Input")
            else:
                print("Valid Object: " + desc.Name)

        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))

        inputFeatureCount = int(
            arcpy.GetCount_management(inputPointsFC).getOutput(0))
        print("Input FeatureClass: " + str(inputPointsFC))
        print("Input Feature Count: " + str(inputFeatureCount))

        if (inputFeatureCount < 1):
            print("Invalid Input Feature Count: " + str(inputFeatureCount))

        maximumRange = 1000.0
        bearing = 150.0
        traversal = 22.0
        projection = arcpy.SpatialReference(32642)  # WGS_1984_UTM_Zone_42N

        ########################################################3
        # Execute the Model under test:
        arcpy.sourceRangeFan_MAoT(inputPointsFC, maximumRange, bearing,
                                  traversal, outputRangeFansFC, projection)
        ########################################################3

        outputFeatureCountFans = int(
            arcpy.GetCount_management(outputRangeFansFC).getOutput(0))
        print("Output FeatureClass: " + str(outputRangeFansFC))
        print("Output Feature Count: " + str(outputFeatureCountFans))

        if (outputFeatureCountFans < 1):
            print("Invalid Output Feature Count: " +
                  str(outputFeatureCountFans))
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()

        print("Test Successful")

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
            sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")
Example #26
0
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: RangeRings")

        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()

        # Verify the expected configuration exists
        inputPointsFC = os.path.join(TestUtilities.inputGDB,
                                     "sampleRangePoints")
        outputRangeRingsFC = os.path.join(TestUtilities.outputGDB,
                                          "RangeRings")
        outputRangeRadialsFC = os.path.join(TestUtilities.outputGDB,
                                            "RangeRadials")
        toolbox = TestUtilities.toolbox

        # Check For Valid Input
        objects2Check = []
        objects2Check.extend([inputPointsFC, toolbox])
        for object2Check in objects2Check:
            desc = arcpy.Describe(object2Check)
            if desc == None:
                raise Exception("Bad Input")
            else:
                print("Valid Object: " + desc.Name)

        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))

        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "VandR")

        inputFeatureCount = int(
            arcpy.GetCount_management(inputPointsFC).getOutput(0))
        print("Input FeatureClass: " + str(inputPointsFC))
        print("Input Feature Count: " + str(inputFeatureCount))

        if (inputFeatureCount < 1):
            print("Invalid Input Feature Count: " + str(inputFeatureCount))

        numberOfRings = 5
        ringInterval = 1000.0
        distanceUnits = "METERS"
        numberOfRadials = 8

        ########################################################3
        # Execute the Model under test:
        arcpy.RangeRings_VandR(inputPointsFC, numberOfRings, ringInterval,
                               distanceUnits, numberOfRadials,
                               outputRangeRingsFC, outputRangeRadialsFC)
        ########################################################3

        # Verify the results
        outputFeatureCountRings = int(
            arcpy.GetCount_management(outputRangeRingsFC).getOutput(0))
        print("Output FeatureClass: " + str(outputRangeRingsFC))
        print("Output Feature Count: " + str(outputFeatureCountRings))

        outputFeatureCountRadials = int(
            arcpy.GetCount_management(outputRangeRadialsFC).getOutput(0))
        print("Output FeatureClass: " + str(outputRangeRadialsFC))
        print("Output Feature Count: " + str(outputFeatureCountRadials))

        if (outputFeatureCountRings < 1) or (outputFeatureCountRadials < 1):
            print("Invalid Output Feature Count: " +
                  str(outputFeatureCountRings) + ":" +
                  str(outputFeatureCountRadials))
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()

        print("Test Successful")

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
            sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)
    else:
        raise LicenseError
    
    arcpy.ImportToolbox(TestUtilities.toolbox)
    arcpy.env.overwriteOutput = True
    arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
    
    inputPolyArea = os.path.join(TestUtilities.inputGDB, "samplePolygonArea")
    inputRoads = os.path.join(TestUtilities.inputGDB, "roads")
    inputSurface = os.path.join(TestUtilities.inputGDB, "Jbad_SRTM_USGS_EROS")
    psOutputRV = os.path.join(TestUtilities.outputGDB, "PathSlopeOutputRV")
    classValue = '0 3 1;3 10 2;10 15 3;15 20 4;20 30 5;30 45 6;45 60 7;60 85 8;85 10000000000000 9;NODATA 0'
    
    #Testing Path Slope by Reclass Values
    arcpy.AddMessage("Starting Test: Path Slope by Reclass Values")
    TestUtilities.createScratch()
    arcpy.PathSlopeByRanges_path(inputPolyArea, inputRoads, inputSurface, 'DEGREE', classValue, psOutputRV)

    
    #Test for Feature Outpu
    outputFeatureCount = int(arcpy.GetCount_management(psOutputRV).getOutput(0)) 
    print("Output FeatureClass: " + str(psOutputRV))
    print("Output Feature Count: " +  str(outputFeatureCount))
            
    if (outputFeatureCount < 1):
        print("Invalid Output Feature Count: " +  str(outputFeatureCount))
        raise Exception("Test Failed")  

    print("Test Passed")

except LicenseError:
Example #28
0
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: TestRangeFanByBearingAndTraversal")
        
        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)"    )
        TestUtilities.createScratch()
            
        inputPointsFC =  os.path.join(TestUtilities.inputGDB, "sampleRangePoints")
        outputRangeFansFC =  os.path.join(TestUtilities.outputGDB, "RangeFansBearingAndTraversal")
        toolbox = TestUtilities.toolbox
                
        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
        
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "Range")
    
        inputFeatureCount = int(arcpy.GetCount_management(inputPointsFC).getOutput(0)) 
        print("Input FeatureClass: " + str(inputPointsFC))
        print("Input Feature Count: " +  str(inputFeatureCount))
            
        if (inputFeatureCount < 1) :
            print("Invalid Input Feature Count: " +  str(inputFeatureCount))
                       
        maximumRangeInMeters = 2000
        centralBearingInDegrees = 320
        traversalWidthInDegrees = 30
                   
        ########################################################3
        # Execute the Model under test:
        # mfunk 8/12/2014: Tool parameters have been modified, this test is no longer valid
        #arcpy.RangeFanByBearingAndTraversal_Range(inputPointsFC, maximumRangeInMeters, centralBearingInDegrees, traversalWidthInDegrees, outputRangeFansFC)
        ########################################################3
    
        # Verify the results    
        outputFeatureCount = int(arcpy.GetCount_management(outputRangeFansFC).getOutput(0)) 
        print("Output FeatureClass: " + str(outputRangeFansFC))
        print("Output Feature Count: " +  str(outputFeatureCount))
                
        if (outputFeatureCount < 1) :
            print("Invalid Output Feature Count: " +  str(outputFeatureCount))
            raise Exception("Test Failed")            
            
        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()        
        
        print("Test Successful")
                
    except arcpy.ExecuteError: 
        # Get the tool error messages 
        msgs = arcpy.GetMessages() 
        arcpy.AddError(msgs) 
    
        # return a system error code
        sys.exit(-1)
        
    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # return a system error code
        sys.exit(-1)
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: TestCreateRangeFanIndexFeatures")

        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()

        inputPolygonFC = os.path.join(TestUtilities.inputGDB, "RangeFans")
        outputExtentBoxes = os.path.join(TestUtilities.outputGDB,
                                         "OutputExtentBoxes")
        outputRangeVertices = os.path.join(TestUtilities.outputGDB,
                                           "RangeVertices")
        toolbox = TestUtilities.toolbox

        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))

        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB
        arcpy.ImportToolbox(toolbox, "Range")

        inputFeatureCount = int(
            arcpy.GetCount_management(inputPolygonFC).getOutput(0))
        print("Input FeatureClass: " + str(inputPolygonFC))
        print("Input Feature Count: " + str(inputFeatureCount))

        if (inputPolygonFC < 1):
            print("Invalid Input Feature Count: " + str(inputPolygonFC))

        ########################################################3
        # Execute the Model under test:
        arcpy.CreateRangeFanIndexFeatures_Range(inputPolygonFC,
                                                outputExtentBoxes,
                                                outputRangeVertices)
        ########################################################3

        # Verify the results
        outputFeatureCountExtent = int(
            arcpy.GetCount_management(outputExtentBoxes).getOutput(0))
        print("Output FeatureClass: " + str(outputExtentBoxes))
        print("Output Feature Count: " + str(outputFeatureCountExtent))

        outputFeatureCountPoints = int(
            arcpy.GetCount_management(outputRangeVertices).getOutput(0))
        print("Output FeatureClass: " + str(outputRangeVertices))
        print("Output Feature Count: " + str(outputFeatureCountPoints))

        if (outputFeatureCountExtent < 1) or (outputFeatureCountPoints < 1):
            print("Invalid Output Feature Count: " +
                  str(outputFeatureCountExtent) + ":" +
                  str(outputFeatureCountPoints))
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print "Deleting Scratch Workspace (Workaround)"
        TestUtilities.deleteScratch()

        print("Test Successful")

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
            sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)
def RunTest():
    try:
        arcpy.AddMessage("Starting Test: TestLocalPeaks")

        #TEST_IMPLEMENTED = False
        #
        #if not TEST_IMPLEMENTED :
        #    arcpy.AddWarning("***Test Not Yet Implemented***")
        #    return

        # TODO: once model has a version that works with local surface data
        # (rather than image service), then finish this test/implementation below
        #
        # alternately you can add an image service connection in Catalog and
        # fill in the parameter below

        if arcpy.CheckExtension("Spatial") == "Available":
            print("Checking out Spatial Analyst license...")
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            raise Exception("LicenseError")

        if arcpy.CheckExtension("3D") == "Available":
            print("Checking out 3D Analyst license...")
            arcpy.CheckOutExtension("3D")
        else:
            raise Exception("LicenseError")

        try:
            print("Getting Advanced license...")
            import arcinfo
        except ImportError:
            print("Could not use ArcGIS Advanced license...")
            raise Exception
        arcpy.env.overwriteOutput = True
        arcpy.env.scratchWorkspace = TestUtilities.scratchGDB

        # WORKAROUND
        print("Creating New Scratch Workspace (Workaround)")
        TestUtilities.createScratch()

        # Getting inputs
        print("Getting inputs...")
        print("inputPolygonFC...")
        inputPolygonFC = os.path.join(TestUtilities.inputGDB,
                                      "samplePolygonArea")
        print("inputSurface...")
        inputSurface = TestUtilities.inputElevationURL
        print("outputPointsFC")
        outputPointsFC = os.path.join(TestUtilities.outputGDB, "LocalPeaks")
        print("ImportToolbox--MAoT...")
        arcpy.ImportToolbox(TestUtilities.toolbox, "MAoT")

        # mf - these have been tested
        # # Check For Valid Input
        # print("Checking valid inputs...")
        # objects2Check = []
        # #objects2Check.extend([inputPolygonFC, inputSurface, toolbox])
        # objects2Check.extend([inputPolygonFC, toolbox])
        # for object2Check in objects2Check :
        #     desc = arcpy.Describe(object2Check)
        #     if desc == None :
        #         raise Exception("Bad Input")
        #     else :
        #         print("Valid Object: " + desc.Name)

        # Set environment settings
        print("Running from: " + str(TestUtilities.currentPath))
        print("Geodatabase path: " + str(TestUtilities.geodatabasePath))
        inputFeatureCount = int(
            arcpy.GetCount_management(inputPolygonFC).getOutput(0))
        print("Input FeatureClass: " + str(inputPolygonFC))
        print("Input Feature Count: " + str(inputFeatureCount))
        # if (inputFeatureCount < 1):
        #     print("Invalid Input Polygon Feature Count: " +  str(inputFeatureCount))

        # Convert input elevation service to local dataset surface
        print("Converting input image service into a local raster surface")
        polygonExtent = arcpy.Describe(inputPolygonFC).extent
        print("Using extent: " + str(polygonExtent))
        cellSize = CellSize(inputPolygonFC)
        print("Using cell size: " + str(cellSize))
        localSurf = None
        srWGS84 = arcpy.SpatialReference(4326)  # GCS_WGS_1984
        srWebMerc = arcpy.SpatialReference(
            3857)  #Web_Mercator_Auxiliary_Sphere
        print("Reworking inputs from image service...")
        try:
            tempClipExtent = os.path.join(TestUtilities.scratchGDB,
                                          "tempClipExtent")
            localSurf = os.path.join(TestUtilities.scratchGDB, "localSurf")
            print("     projecting input clip to WGS 1984 to match service...")
            arcpy.Project_management(inputPolygonFC, tempClipExtent, srWGS84)
            tempCellSize = CellSize(tempClipExtent)
            #MakeImageServerLayer_management (in_image_service, out_imageserver_layer, {template},
            #{band_index}, {mosaic_method}, {order_field},
            #{order_base_value}, {lock_rasterid}, {cell_size},
            #{where_clause}, {processing_template})
            print("     getting image service layer with cell size " +
                  str(tempCellSize) + "...")
            arcpy.MakeImageServerLayer_management(inputSurface, "inputSurface",
                                                  tempClipExtent, "#", "#",
                                                  "#", "#", "#", tempCellSize)
            print(
                "     projecting image service layer to match target data...")
            arcpy.ProjectRaster_management("inputSurface", localSurf,
                                           srWebMerc)
            #arcpy.CopyRaster_management("inputSurface", localSurf)
        except arcpy.ExecuteError:
            print("Error converting image service...")
            msgs = arcpy.GetMessages()
            print(msgs)
            sys.exit(-1)

        numberOfPeaks = 3

        ########################################################
        # Execute the Model under test:
        arcpy.FindLocalPeaks_MAoT(inputPolygonFC, numberOfPeaks, localSurf,
                                  outputPointsFC)
        ########################################################

        # Verify the results
        outputFeatureCount = int(
            arcpy.GetCount_management(outputPointsFC).getOutput(0))
        print("Output FeatureClass: " + str(outputPointsFC))
        print("Output Feature Count: " + str(outputFeatureCount))

        if (outputPointsFC < 3):
            print("Invalid Output Feature Count: " + str(outputFeatureCount))
            raise Exception("Test Failed")

        # WORKAROUND: delete scratch db
        print("Deleting Scratch Workspace (Workaround)")
        TestUtilities.deleteScratch()
        print("Test Successful")

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    except Exception as e:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
            sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # return a system error code
        sys.exit(-1)

    finally:
        # Check in the 3D Analyst extension
        arcpy.CheckInExtension("Spatial")
        arcpy.CheckInExtension("3D")