Exemplo n.º 1
0
    def test_honor_Rprange(self):
        """
        Tests that the input range for planet radius is properly set 
        and is used when generating radius samples.
        """

        exclude_setrange = [
            'EarthTwinHabZone1', 'EarthTwinHabZone2', 'JupiterTwin',
            'AlbedoByRadiusDulzPlavchan', 'DulzPlavchan'
        ]

        Rprangein = np.sort(np.random.rand(2) * 10.0)

        for mod in self.allmods:
            if mod.__name__ not in exclude_setrange:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(Rprange=Rprangein, **self.spec)

                #test that the correct input Rprange is used
                self.assertTrue(
                    obj.Rprange[0].value == Rprangein[0],
                    'Rp low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.Rprange[1].value == Rprangein[1],
                    'Rp high bound set failed for %s' % mod.__name__)

                # test that incorrect input Rprange is corrected
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(Rprange=Rprangein[::-1], **self.spec)
                self.assertTrue(
                    obj.Rprange[0].value == Rprangein.min(),
                    'Rp low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.Rprange[1].value == Rprangein.max(),
                    'Rp high bound set failed for %s' % mod.__name__)
Exemplo n.º 2
0
    def test_honor_prange(self):
        """
        Tests that the input range for albedo is properly set.
        """

        exclude_setrange = [
            'EarthTwinHabZone1', 'EarthTwinHabZone2', 'JupiterTwin',
            'AlbedoByRadius', 'AlbedoByRadiusDulzPlavchan',
            'EarthTwinHabZone1SDET', 'EarthTwinHabZone3',
            'EarthTwinHabZoneSDET'
        ]

        tmp = np.random.rand(1) * 0.5
        prangein = np.hstack((tmp, np.random.rand(1) * 0.5 + 0.5))

        for mod in self.allmods:
            if mod.__name__ not in exclude_setrange:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(prange=prangein, **self.spec)

                #test that the correct input prange is used
                self.assertTrue(obj.prange[0] == prangein[0],
                                'p low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.prange[1] == prangein[1],
                    'p high bound set failed for %s' % mod.__name__)

                # test that incorrect input prange is corrected
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(prange=prangein[::-1], **self.spec)
                self.assertTrue(obj.prange[0] == prangein.min(),
                                'p low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.prange[1] == prangein.max(),
                    'p high bound set failed for %s' % mod.__name__)
Exemplo n.º 3
0
    def test_honor_arange(self):
        """
        Tests that the input range for semi-major axis is properly set.
        """

        exclude_setrange = [
            'EarthTwinHabZone1', 'EarthTwinHabZone2', 'JupiterTwin',
            'AlbedoByRadiusDulzPlavchan', 'DulzPlavchan'
        ]

        arangein = np.sort(np.random.rand(2) * 10.0)

        for mod in self.allmods:
            if mod.__name__ not in exclude_setrange:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(arange=arangein, **self.spec)

                #test that the correct input arange is used
                self.assertTrue(
                    obj.arange[0].value == arangein[0],
                    'sma low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.arange[1].value == arangein[1],
                    'sma high bound set failed for %s' % mod.__name__)

                # test that an incorrect input arange is corrected
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(arange=arangein[::-1], **self.spec)
                self.assertTrue(
                    obj.arange[0].value == arangein.min(),
                    'sma low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.arange[1].value == arangein.max(),
                    'sma high bound set failed for %s' % mod.__name__)
Exemplo n.º 4
0
    def test_honor_Orange(self):
        """
        Tests that the input range for long. of ascending node is properly set.
        """

        exclude_setrange = []
        exclude_checkrange = []

        tmp = np.random.rand(1) * 180
        Orangein = np.hstack((tmp, np.random.rand(1) * 180 + 180))

        for mod in self.allmods:
            if (mod.__name__ not in exclude_setrange) and (
                    mod.__name__
                    not in exclude_checkrange) and ('gen_angles'
                                                    in mod.__dict__):
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(Orange=Orangein, **self.spec)

                #test that the correct input Orange is used
                self.assertTrue(obj.Orange[0].value == Orangein[0],
                                'O low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.Orange[1].value == Orangein[1],
                    'O high bound set failed for %s' % mod.__name__)

                # test that incorrect input Orange is corrected
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(Orange=Orangein[::-1], **self.spec)
                self.assertTrue(obj.Orange[0].value == Orangein.min(),
                                'O low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.Orange[1].value == Orangein.max(),
                    'O high bound set failed for %s' % mod.__name__)
Exemplo n.º 5
0
    def test_honor_erange(self):
        """
        Tests that the input range for eccentricity is properly set.
        """

        exclude_setrange = [
            'EarthTwinHabZone1', 'EarthTwinHabZone1SDET', 'EarthTwinHabZone3',
            'EarthTwinHabZoneSDET'
        ]

        tmp = np.random.rand(1) * 0.5
        erangein = np.hstack((tmp, np.random.rand(1) * 0.5 + 0.5))

        for mod in self.allmods:
            if mod.__name__ not in exclude_setrange:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(erange=erangein, **self.spec)

                #test that the correct input erange is used
                self.assertTrue(obj.erange[0] == erangein[0],
                                'e low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.erange[1] == erangein[1],
                    'e high bound set failed for %s' % mod.__name__)

                # test that an incorrect input erange is corrected
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod(erange=erangein[::-1], **self.spec)
                self.assertTrue(obj.erange[0] == erangein.min(),
                                'e low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.erange[1] == erangein.max(),
                    'e high bound set failed for %s' % mod.__name__)
Exemplo n.º 6
0
    def test_next_target(self):
        r"""Test next_target method.

        Approach: Ensure the next target is selected OK, and is a valid integer.
        Deficiencies: We are not checking that the occulter slew works.
        """

        exclude_mods = ['SS_det_only']
        exclude_mod_type = 'sotoSS'

        for mod in self.allmods:
            if mod.__name__ in exclude_mods or exclude_mod_type in mod.__name__:
                continue

            if 'next_target' in mod.__dict__:
                if 'tieredScheduler' in mod.__name__:
                    self.script = resource_path('test-scripts/simplest_occ.json')
                    with open(self.script) as f:
                        spec = json.loads(f.read())
                    spec['occHIPs'] = resource_path('SurveySimulation/top100stars.txt')
                    with RedirectStreams(stdout=self.dev_null):
                        sim = mod(**spec)
                        if 'tieredScheduler_DD' in mod.__name__:
                            DRM_out, sInd, occ_sInd, intTime, sd, occ_sInds, det_mode = sim.next_target(None, None, 
                                        sim.OpticalSystem.observingModes, sim.OpticalSystem.observingModes[0])
                        else:
                            DRM_out, sInd, occ_sInd, intTime, sd, occ_sInds = sim.next_target(None, None, 
                                        sim.OpticalSystem.observingModes[0], sim.OpticalSystem.observingModes[0])
                        self.assertIsInstance(occ_sInd, (int,np.int8,np.int16,np.int32,np.int64), 'occ_sInd is not an integer for %s'%mod.__name__)
                        self.assertEqual(occ_sInd - int(occ_sInd), 0, 'occ_sInd is not an integer for %s'%(mod.__name__))
                        self.assertGreaterEqual(occ_sInd, 0, 'occ_sInd is not a valid index for %s'%mod.__name__)
                        self.assertLess(occ_sInd, sim.TargetList.nStars, 'occ_sInd is not a valid index for %s'%mod.__name__)
                elif 'linearJScheduler_DDPC' in mod.__name__ or 'linearJScheduler_3DDPC' in mod.__name__:
                    self.script = resource_path('test-scripts/simplest_3DDPC.json')
                    with open(self.script) as f:
                        spec = json.loads(f.read())
                    with RedirectStreams(stdout=self.dev_null):
                        sim = mod(**spec)
                        DRM_out, sInd, intTime, waitTime, det_mode = sim.next_target(None, sim.OpticalSystem.observingModes)
                else:
                    with RedirectStreams(stdout=self.dev_null):
                        sim = mod(scriptfile=self.script)

                        DRM_out, sInd, intTime, waitTime = sim.next_target(None, sim.OpticalSystem.observingModes[0])

                # result index is a scalar numpy ndarray, that is a valid integer
                # in a valid range
                self.assertIsInstance(sInd, (int,np.int8,np.int16,np.int32,np.int64), 'sInd is not an integer for %s'%mod.__name__)
                self.assertEqual(sInd - int(sInd), 0, 'sInd is not an integer for %s'%mod.__name__)
                self.assertGreaterEqual(sInd, 0, 'sInd is not a valid index for %s'%mod.__name__)
                self.assertLess(sInd, sim.TargetList.nStars, 'sInd is not a valid index for %s'%mod.__name__)

                # resulting DRM is a dictionary -- contents unimportant
                self.assertIsInstance(DRM_out, dict, 'DRM_out is not a dict for %s'%mod.__name__)
Exemplo n.º 7
0
    def test_honor_Mprange(self):
        """
        Tests that the input range for planet mass is properly set 
        and is used when generating mass samples.
        """

        exclude_setrange = [
            'EarthTwinHabZone1', 'EarthTwinHabZone2', 'JupiterTwin',
            'AlbedoByRadiusDulzPlavchan', 'DulzPlavchan',
            "EarthTwinHabZone1SDET", 'EarthTwinHabZone3',
            'EarthTwinHabZoneSDET'
        ]
        exclude_checkrange = ['KeplerLike1']

        Mprangein = np.sort(np.random.rand(2) * 10.0)

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(Mprange=Mprangein, **self.spec)

            #test that the input Mprange is used
            if mod.__name__ not in exclude_setrange:
                self.assertTrue(
                    obj.Mprange[0].value == Mprangein[0],
                    'Mp low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.Mprange[1].value == Mprangein[1],
                    'Mp high bound set failed for %s' % mod.__name__)

            # test that incorrect input Mprange is corrected
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(Mprange=Mprangein[::-1], **self.spec)
            if mod.__name__ not in exclude_setrange:
                self.assertTrue(
                    obj.Mprange[0].value == Mprangein.min(),
                    'Mp low bound set failed for %s' % mod.__name__)
                self.assertTrue(
                    obj.Mprange[1].value == Mprangein.max(),
                    'Mp high bound set failed for %s' % mod.__name__)

            #test that generated values honor range
            if (mod.__name__ not in exclude_checkrange) and ('gen_mass'
                                                             in mod.__dict__):
                x = 10000
                Mp = obj.gen_mass(x)
                self.assertEqual(
                    len(Mp), x,
                    'Incorrect number of samples generated for %s' %
                    mod.__name__)
                self.assertTrue(np.all(Mp.value <= obj.Mprange[1].value),
                                'Mp high bound failed for %s' % mod.__name__)
                self.assertTrue(np.all(Mp.value >= obj.Mprange[0].value),
                                'Mp low bound failed for %s' % mod.__name__)
Exemplo n.º 8
0
    def test_honor_Min(self):
        """
        Test that gen_M0 assigns constant or random value to mean anomaly
        
        Because some implementations depend on a specific planet population,
        there needs to be additional logic in the setup
        """

        whitelist = ['KnownRVPlanetsUniverse']
        # Test Min = None first
        for mod in self.allmods:
            if mod.__name__ in whitelist:
                continue
            with RedirectStreams(stdout=self.dev_null):
                spec = copy.deepcopy(self.spec)
                spec['modules'][
                    'PlanetPhysicalModel'] = 'FortneyMarleyCahoyMix1'
                spec['modules']['StarCatalog'] = 'EXOCAT1'
                if 'Kepler' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'KeplerLike1'
                elif 'SAG13' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'SAG13'
                    spec['Rprange'] = [1, 10]
                elif 'DulzPlavchan' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'DulzPlavchan'

                obj = mod(**spec)

            self.assertTrue(obj.M0[0] != obj.M0[1],
                            "Initial M0 must be randomly set")

        # Test Min = 20
        for mod in self.allmods:
            if mod.__name__ in whitelist:
                continue
            with RedirectStreams(stdout=self.dev_null):
                spec = copy.deepcopy(self.spec)
                spec['modules'][
                    'PlanetPhysicalModel'] = 'FortneyMarleyCahoyMix1'
                spec['modules']['StarCatalog'] = 'EXOCAT1'
                if 'Kepler' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'KeplerLike1'
                elif 'SAG13' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'SAG13'
                    spec['Rprange'] = [1, 10]
                elif 'DulzPlavchan' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'DulzPlavchan'
                spec['Min'] = 20
                obj = mod(**spec)

            self.assertTrue(np.all(obj.M0.to('deg').value == 20),
                            "Initial M0 must be 20")
Exemplo n.º 9
0
    def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """

        atts_list = [
            'obscurFac', 'shapeFac', 'pupilDiam', 'intCutoff', 'dMag0',
            'ref_dMag', 'ref_Time', 'pupilArea', 'haveOcculter', 'IWA', 'OWA',
            'WA0', 'koAngles_Sun', 'koAngles_Earth', 'koAngles_Moon',
            'koAngles_Small'
        ]

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                if 'SotoStarshade' in mod.__name__:
                    obj = mod(f_nStars=4, **copy.deepcopy(self.spec))
                else:
                    obj = mod(**copy.deepcopy(self.spec))
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            for att in atts_list:
                self.assertIn(att, contents,
                              '{} missing for {}'.format(att, mod.__name__))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout
Exemplo n.º 10
0
    def test_honor_constrainOrbits(self):
        """
        Test that constrainOrbits is consistently applied

        Generated orbital radii must be within the rrange, which 
        is the original arange.
        """

        exclude_check = []

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(constrainOrbits=True, **self.spec)
            self.assertTrue(obj.constrainOrbits,
                            'constrainOrbits not set for %s' % mod.__name__)
            self.assertTrue(
                np.all(obj.arange == obj.rrange),
                'arange and rrange do not match with constrainOrbits set for %s'
                % mod.__name__)

            #ignore any cases where gen_plan_params is inherited
            if (mod.__name__ not in exclude_check) and ('gen_plan_params'
                                                        in mod.__dict__):
                x = 10000
                a, e, p, Rp = obj.gen_plan_params(x)
                rp = a * (1. + e)
                rm = a * (1. - e)
                high = (obj.rrange[1] - rp).to('AU').value
                low = (rm - obj.rrange[0]).to('AU').value
                self.assertTrue(
                    np.all(high > -1e-12),
                    'constrainOrbits high bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(low > -1e-12),
                    'constrainOrbits low bound failed for %s' % mod.__name__)
Exemplo n.º 11
0
    def test_calcfZmin(self):
        """
        Test calcfZmin method
        """

        for mod in self.allmods:
            if 'calcfZmin' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod()
                sInds = np.asarray([0])
                currentTimeAbs = self.TK.currentTimeAbs
                OS = self.sim.OpticalSystem
                allModes = OS.observingModes
                mode = list(
                    filter(lambda mode: mode['detectionMode'] == True,
                           allModes))[0]
                hashname = self.sim.SurveySimulation.cachefname
                self.sim.ZodiacalLight.fZ_startSaved = obj.generate_fZ(
                    self.Obs, self.TL, self.TK, mode, hashname)
                fZQuads = obj.calcfZmin(sInds, self.Obs, self.TL, self.TK,
                                        mode, hashname)
                [valfZmin, timefZmin] = obj.extractfZmin_fZQuads(fZQuads)
                self.assertTrue(len(valfZmin) == len(sInds))
                self.assertTrue(len(timefZmin) == len(sInds))
                self.assertTrue(valfZmin[0].unit == 1 / u.arcsec**2)
                self.assertTrue(timefZmin[0].format == currentTimeAbs.format)
Exemplo n.º 12
0
    def test_init(self):
        """
        Test of initialization and __init__.
        """

        req_atts = [
            'koAngleMin', 'koAngleMinMoon', 'koAngleMinEarth', 'koAngleMax',
            'koAngleSmall', 'ko_dtStep', 'settlingTime', 'thrust', 'slewIsp',
            'scMass', 'dryMass', 'coMass', 'occulterSep', 'skIsp',
            'defburnPortion', 'checkKeepoutEnd', 'forceStaticEphem',
            'constTOF', 'occ_dtmin', 'occ_dtmax', 'maxdVpct', 'dVtot', 'dVmax',
            'flowRate', 'havejplephem'
        ]

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                if 'SotoStarshade' in mod.__name__:
                    obj = mod(f_nStars=4, **copy.deepcopy(self.spec))
                else:
                    obj = mod(**copy.deepcopy(self.spec))

            # verify that all attributes are there
            for att in req_atts:
                self.assertTrue(
                    hasattr(obj, att),
                    'Missing attribute {} for {}'.format(att, mod.__name__))
Exemplo n.º 13
0
    def test_log_occulterResults(self):
        """
        Test that log_occulter_results returns proper dictionary with keys
        """

        atts_list = [
            'slew_time', 'slew_angle', 'slew_dV', 'slew_mass_used', 'scMass'
        ]
        for mod in self.allmods:
            if 'log_occulterResults' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    if 'SotoStarshade' in mod.__name__:
                        obj = mod(f_nStars=4, **copy.deepcopy(self.spec))
                    else:
                        obj = mod(**copy.deepcopy(self.spec))
                DRM = {}
                slewTimes = np.ones((5, )) * u.day
                sInds = np.arange(5)
                sd = np.ones((5, )) * u.rad
                dV = np.ones((5, )) * u.m / u.s

                DRM = obj.log_occulterResults(DRM, slewTimes, sInds, sd, dV)

                for att in atts_list:
                    self.assertTrue(
                        att in DRM,
                        'Missing key in log_occulterResults for %s' %
                        mod.__name__)
Exemplo n.º 14
0
 def test_str(self):
     """
     Test __str__ method, for full coverage and check that all modules have required attributes.
     """
     atts_list = [
         'PlanetPhysicalModel', 'arange', 'erange', 'Irange', 'Orange',
         'wrange', 'prange', 'Rprange', 'Mprange', 'rrange', 'scaleOrbits',
         'constrainOrbits', 'eta'
     ]
     for mod in self.allmods:
         with RedirectStreams(stdout=self.dev_null):
             obj = mod(**self.spec)
         original_stdout = sys.stdout
         sys.stdout = StringIO()
         # call __str__ method
         result = obj.__str__()
         # examine what was printed
         contents = sys.stdout.getvalue()
         self.assertEqual(type(contents), type(''))
         # attributes from ICD
         for att in atts_list:
             self.assertIn(att, contents,
                           '{} missing for {}'.format(att, mod.__name__))
         sys.stdout.close()
         # it also returns a string, which is not necessary
         self.assertEqual(type(result), type(''))
         # put stdout back
         sys.stdout = original_stdout
Exemplo n.º 15
0
    def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """
        atts_list = ['magZ', 'magEZ', 'varEZ', 'fZ0', 'fEZ0']
        exclude_mods=[]

        for mod in self.allmods:
            if mod.__name__ in exclude_mods:
                continue
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(**self.spec)
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            for att in atts_list:
                self.assertIn(att,contents,'{} missing for {}'.format(att,mod.__name__))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout
Exemplo n.º 16
0
    def test_generate_fZ(self):
        """
        Test generate fZ method
        """

        for mod in self.allmods:
            if 'generate_fZ' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod()
                #Check if File Exists and if it does, delete it
                #if os.path.isfile(self.sim.SurveySimulation.cachefname+'starkfZ'):
                #    os.remove(self.sim.SurveySimulation.cachefname+'starkfZ')
                OS = self.sim.OpticalSystem
                allModes = OS.observingModes
                mode = list(
                    filter(lambda mode: mode['detectionMode'] == True,
                           allModes))[0]
                hashname = self.sim.SurveySimulation.cachefname
                self.sim.ZodiacalLight.fZ_startSaved = obj.generate_fZ(
                    self.Obs, self.TL, self.TK, mode, hashname)
                self.assertEqual(self.sim.ZodiacalLight.fZ_startSaved.shape[0],
                                 self.nStars)
                #Should also check length of fZ_startSaved??
                self.assertEqual(self.sim.ZodiacalLight.fZ_startSaved.shape[1],
                                 1000)  #This was arbitrarily selected.
Exemplo n.º 17
0
    def test_dist_albedo(self):
        """
        Test that albedos outside of the range have zero probability

        """

        exclude_mods = [
            'KeplerLike1', 'AlbedoByRadiusDulzPlavchan', 'DulzPlavchan'
        ]
        for mod in self.allmods:
            if (mod.__name__ not in exclude_mods) and ('dist_albedo'
                                                       in mod.__dict__):
                with RedirectStreams(stdout=self.dev_null):
                    pp = mod(**self.spec)

                p = np.linspace(pp.prange[0] - 1, pp.prange[1] + 1, 100)

                fp = pp.dist_albedo(p)
                self.assertTrue(
                    np.all(fp[p < pp.prange[0]] == 0),
                    'dist_albedo high bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(fp[p > pp.prange[1]] == 0),
                    'dist_albedo low bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(fp[(p >= pp.prange[0]) & (p <= pp.prange[1])] > 0),
                    'dist_albedo generates zero probabilities within range for %s'
                    % mod.__name__)
Exemplo n.º 18
0
    def test_init(self):
        """
        Test of initialization and __init__.
        """

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(**copy.deepcopy(self.spec))

            self.assertTrue(hasattr(obj, 'dMagLim'))
            self.assertTrue(hasattr(obj, 'minComp'))

            with RedirectStreams(stdout=self.dev_null):
                obj = mod(dMagLim=5, minComp=0.5, **copy.deepcopy(self.spec))
            self.assertEqual(obj.dMagLim, 5)
            self.assertEqual(obj.minComp, 0.5)
Exemplo n.º 19
0
    def test_random_seed_initialize_full(self):
        r"""Test random_seed_initialize method (longer).

        Method: Initialize with a specific random seed, and ensure the numpy
        RNG seeding mechanism was indeed called by the __init__ function.
        """
        # Note: the mission.__init__() method, in building up planets, etc., calls
        # the numpy RNG many times.  All these calls make it impossible to check the
        # RNG state just after the object is again available to this test code.
        # So, to test, we have to ensure that np.random.seed is
        # called correctly instead of checking the RNG state after __init__ returns.

        # set up the seed, and the specs addition that includes it
        seed = 1234567890
        specs = {'seed': seed}

        # plugs in our own mock object to monitor calls to np.random.seed()
        with assertMethodIsCalled(np.random, "seed") as rng_seed_mock:
            # initialize the object
            with RedirectStreams(stdout=self.dev_null):
                mission = self.fixture(scriptfile=SimpleScript, **specs)
            # ensure np.random.seed was called once, with the given seed provided
            self.assertEqual(len(rng_seed_mock.method_args), 1,
                             'RNG was not seeded.')
            self.assertEqual(len(rng_seed_mock.method_args[0]), 1,
                             'RNG seed arguments incorrect.')
            self.assertEqual(rng_seed_mock.method_args[0][0], seed)
            # keyword argument should be an empty dictionary
            self.assertEqual(len(rng_seed_mock.method_kwargs), 1,
                             'RNG seeded with unexpected arguments.')
            self.assertDictEqual(rng_seed_mock.method_kwargs[0], {},
                                 'RNG seeded with unexpected arguments.')
        # might as well validate the object
        self.validate_object(mission)
Exemplo n.º 20
0
    def test_load_systems(self):
        """
        Test that load systems loads correctly
        """

        with open(self.script) as f:
            spec = json.loads(f.read())
        spec['modules']['StarCatalog'] = 'EXOCAT1'
        with RedirectStreams(stdout=self.dev_null):
            SU = SimulatedUniverse(**spec)

        # dictionary of planetary parameter keys
        param_keys = ['a', 'e', 'I', 'O', 'w', 'M0', 'Mp', 'Rp', 'p', 'plan2star']
        systems = {'a': np.array([5.])*u.AU,
                   'e': np.array([0.]),
                   'I': np.array([0.])*u.deg,
                   'O': np.array([0.])*u.deg,
                   'w': np.array([0.])*u.deg,
                   'M0': np.array([0.])*u.deg,
                   'Mp': np.array([300.])*u.earthMass,
                   'Rp': np.array([10.])*u.earthRad,
                   'p': np.array([0.6]),
                   'plan2star': np.array([0], dtype=int)}
        SU.load_systems(systems)
        for key in param_keys:
            self.assertTrue(systems[key] == getattr(SU, key), 'Value for %s not assigned with load_systems'%key)
Exemplo n.º 21
0
    def test_honor_scaleOrbit(self):
        """
        Test that scaleOrbit flag is honored

        Because some implementations depend on a specific planet population,
        there needs to be additional logic in the setup
        """

        whitelist = ['KeplerLikeUniverse','KnownRVPlanetsUniverse','SAG13Universe']
        for mod in self.allmods:
            if mod.__name__ in whitelist:
                continue
            with RedirectStreams(stdout=self.dev_null):
                spec = copy.deepcopy(self.spec)
                spec['modules']['PlanetPhysicalModel']='FortneyMarleyCahoyMix1'
                spec['modules']['StarCatalog']='EXOCAT1'
                if 'Kepler' in mod.__name__:
                    spec['modules']['PlanetPopulation']='KeplerLike1'
                elif 'KnownRV' in mod.__name__:
                    spec['modules']['PlanetPopulation']='KnownRVPlanets'
                    spec['modules']['TargetList']='KnownRVPlanetsTargetList'
                elif 'KnownRV' in mod.__name__:
                    spec['modules']['PlanetPopulation']='SAG13'
                elif 'SAG13' in mod.__name__:
                    spec['modules']['PlanetPopulation']='SAG13'
                elif 'DulzPlavchan' in mod.__name__:
                    spec['modules']['PlanetPopulation'] = 'DulzPlavchan'

                obj = mod(scaleOrbits=True,**spec)

            self.assertTrue(obj.PlanetPopulation.scaleOrbits,"scaleOrbits not set in %s"%mod.__name__)

            aeff = obj.a/np.sqrt(obj.TargetList.L[obj.plan2star])
            self.assertTrue(np.all(aeff <= obj.PlanetPopulation.arange[1]),"scaled sma out of bounds in %s"%mod.__name__)
            self.assertTrue(np.all(aeff >= obj.PlanetPopulation.arange[0]),"scaled sma out of bounds in %s"%mod.__name__)
Exemplo n.º 22
0
    def test_init(self):
        r"""Test of initialization and __init__.
        """
        tk = self.fixture()
        self.assertEqual(tk.currentTimeNorm.to(u.day).value, 0.0)
        self.assertEqual(type(tk._outspec), type({}))
        # check for presence of one class attribute
        self.assertGreater(tk.missionLife.value, 0.0)

        exclude_mods=['KnownRVSurvey', 'ZodiacalLight','BackgroundSources', 'Completeness'\
        'PlanetPhysicalModel', 'PlanetPopulation', 'PostProcessing']

        required_modules = [\
            'Observatory', 'OpticalSystem',\
            'SimulatedUniverse', 'TargetList', 'TimeKeeping']

        for mod in self.allmods:
            if mod.__name__ in exclude_mods:
                continue

            with RedirectStreams(stdout=self.dev_null):
                sim = mod(scriptfile=self.script1)

            self.assertIsInstance(sim._outspec, dict)
            # check for presence of a couple of class attributes
            self.assertIn('DRM', sim.__dict__)

            for rmod in required_modules:
                self.assertIn(rmod, sim.__dict__)
                self.assertEqual(getattr(sim, rmod)._modtype, rmod)
Exemplo n.º 23
0
    def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """

        atts_list = [
            'koAngles_SolarPanel', 'ko_dtStep', 'settlingTime', 'thrust',
            'slewIsp', 'scMass', 'dryMass', 'coMass', 'occulterSep', 'skIsp',
            'defburnPortion', 'checkKeepoutEnd', 'forceStaticEphem',
            'constTOF', 'occ_dtmin', 'occ_dtmax', 'maxdVpct', 'dVtot', 'dVmax',
            'flowRate', 'havejplephem'
        ]

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                if 'SotoStarshade' in mod.__name__:
                    obj = mod(f_nStars=4, **copy.deepcopy(self.spec))
                else:
                    obj = mod(**copy.deepcopy(self.spec))
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            for att in atts_list:
                self.assertIn(att, contents,
                              '{} missing for {}'.format(att, mod.__name__))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout
Exemplo n.º 24
0
    def setUp(self):
        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/template_prototype_testing.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())

        with RedirectStreams(stdout=self.dev_null):
            self.sim = MissionSim.MissionSim(self.script)
        self.TL = self.sim.TargetList
        self.nStars = self.TL.nStars
        self.star_index = np.array(range(0, self.nStars))
        self.Obs = self.sim.Observatory
        self.mode = self.sim.OpticalSystem.observingModes[0]
        self.TK = self.sim.TimeKeeping
        assert self.nStars > 10, "Need at least 10 stars in the target list for the unit test."
        self.unit = 1./u.arcsec**2

        modtype = getattr(EXOSIMS.Prototypes.ZodiacalLight.ZodiacalLight, '_modtype')
        pkg = EXOSIMS.ZodiacalLight
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1], modtype)
                self.assertTrue(mod._modtype is modtype, '_modtype mismatch for %s' % mod.__name__)
                self.allmods.append(mod)
Exemplo n.º 25
0
    def test_dist_sma(self):
        """
        Test that smas outside of the range have zero probability

        """

        for mod in self.allmods:
            if 'dist_sma' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    pp = mod(**self.spec)

                a = np.logspace(np.log10(pp.arange[0].value / 10.),
                                np.log10(pp.arange[1].value * 10.), 100)

                fa = pp.dist_sma(a)
                self.assertTrue(
                    np.all(fa[a < pp.arange[0].value] == 0),
                    'dist_sma high bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(fa[a > pp.arange[1].value] == 0),
                    'dist_sma low bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(fa[(a >= pp.arange[0].value)
                              & (a <= pp.arange[1].value)] >= 0.),
                    'dist_sma generates negative densities within range for %s'
                    % mod.__name__)
Exemplo n.º 26
0
    def test_target_completeness_constrainOrbits(self):
        """
        Compare calculated completenesses for multiple targets with constrain orbits set to true
        """

        with RedirectStreams(stdout=self.dev_null):
            TL = TargetList(ntargs=100,
                            constrainOrbits=True,
                            **copy.deepcopy(self.spec))

            mode = filter(lambda mode: mode['detectionMode'] == True,
                          TL.OpticalSystem.observingModes)[0]
            IWA = mode['IWA']
            OWA = mode['OWA']
            rrange = TL.PlanetPopulation.rrange
            maxd = (rrange[1] / np.tan(IWA)).to(u.pc).value
            mind = (rrange[0] / np.tan(OWA)).to(u.pc).value

            #want distances to span from outer edge below IWA to inner edge above OWA
            TL.dist = np.logspace(np.log10(mind / 10.), np.log10(maxd * 10.),
                                  TL.nStars) * u.pc

        Brown = EXOSIMS.Completeness.BrownCompleteness.BrownCompleteness(
            constrainOrbits=True, **copy.deepcopy(self.spec))
        Garrett = EXOSIMS.Completeness.GarrettCompleteness.GarrettCompleteness(
            constrainOrbits=True, **copy.deepcopy(self.spec))

        cBrown = Brown.target_completeness(TL)
        cGarrett = Garrett.target_completeness(TL)

        np.testing.assert_allclose(cGarrett, cBrown, rtol=0.1, atol=1e-6)
Exemplo n.º 27
0
    def test_dist_radius(self):
        """
        Test that radii outside of the range have zero probability

        """
        for mod in self.allmods:
            if 'dist_radius' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    pp = mod(**self.spec)

                Rp = np.logspace(np.log10(pp.Rprange[0].value / 10.),
                                 np.log10(pp.Rprange[1].value * 100.), 100)

                fr = pp.dist_radius(Rp)
                self.assertTrue(
                    np.all(fr[Rp < pp.Rprange[0].value] == 0),
                    'dist_radius high bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(fr[Rp > pp.Rprange[1].value] == 0),
                    'dist_radius high bound failed for %s' % mod.__name__)
                self.assertTrue(
                    np.all(fr[(Rp >= pp.Rprange[0].value)
                              & (Rp <= pp.Rprange[1].value)] > 0),
                    'dist_radius generates zero probabilities within range for %s'
                    % mod.__name__)
Exemplo n.º 28
0
    def test_str(self):
        """
        Test __str__ method, for full coverage and check that all modules have required attributes.
        """
        atts_list = [
            'Name', 'Spec', 'parx', 'Umag', 'Bmag', 'Vmag', 'Rmag', 'Imag',
            'Jmag', 'Hmag', 'Kmag', 'dist', 'BV', 'MV', 'BC', 'L', 'coords',
            'pmra', 'pmdec', 'rv', 'Binary_Cut'
        ]

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod()
            original_stdout = sys.stdout
            sys.stdout = StringIO()
            # call __str__ method
            result = obj.__str__()
            # examine what was printed
            contents = sys.stdout.getvalue()
            self.assertEqual(type(contents), type(''))
            # attributes from ICD
            for att in atts_list:
                self.assertIn(att, contents,
                              '{} missing for {}'.format(att, mod.__name__))
            sys.stdout.close()
            # it also returns a string, which is not necessary
            self.assertEqual(type(result), type(''))
            # put stdout back
            sys.stdout = original_stdout
Exemplo n.º 29
0
    def test_genoutspec(self):
        r"""Test of the genOutSpec method (results output).

        Method: This is the key test of genOutSpec.  We set up a sim
        object, write it to JSON using genOutSpec, and then both check the
        compiled outspec dictionary, and re-load the generated JSON and test
        it back against the sim object.
        """
        # the with clause allows the chatter on stdout during
        # object creation to be suppressed
        with RedirectStreams(stdout=self.dev_null):
            sim = self.fixture(SimpleScript)
 
        out_filename = 'dummy_gen_outspec.json'
        outspec_orig = sim.genOutSpec(out_filename)
        # ensure the compiled outspec is correct and complete
        self.validate_outspec(outspec_orig, sim)
        # ensure the JSON file was written
        self.assertTrue(os.path.isfile(out_filename), "Could not find outspec file `%s'" % out_filename)
        # re-load the JSON file
        with open(out_filename, 'r') as fp:
            outspec_new = json.load(fp)
        # ensure all keys are present
        self.assertListEqual(sorted(list(outspec_orig)),
                             sorted(list(outspec_new)))
        # furthermore, ensure the re-loaded outspec is OK
        # this is a rather stringent test
        self.validate_outspec(outspec_new, sim)
        os.remove(out_filename)
Exemplo n.º 30
0
    def test_calcfZmax(self):
        """
        Test calcfZmax method
        """

        for mod in self.allmods:
            if 'calcfZmax' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    obj = mod()

                #Check if File Exists and if it does, delete it
                if os.path.isfile(self.sim.SurveySimulation.cachefname+'fZmax'):
                    os.remove(self.sim.SurveySimulation.cachefname+'fZmax')
                sInds = np.asarray([0])
                currentTimeAbs = self.sim.TimeKeeping.currentTimeAbs
                OS = self.sim.OpticalSystem
                allModes = OS.observingModes
                mode = list(filter(lambda mode: mode['detectionMode'] == True, allModes))[0]
                hashname = self.sim.SurveySimulation.cachefname
                self.sim.ZodiacalLight.fZ_startSaved = obj.generate_fZ(self.Obs, self.TL, self.TK, mode, hashname)
                valfZmax = np.zeros(sInds.shape[0])
                timefZmax = np.zeros(sInds.shape[0])
                [valfZmax, timefZmax] = obj.calcfZmax(sInds, self.Obs, self.TL, self.TK, mode, hashname)
                self.assertTrue(len(valfZmax) == len(sInds))
                self.assertTrue(len(timefZmax) == len(sInds))
                self.assertTrue(valfZmax[0].unit == self.unit)
                self.assertTrue(timefZmax[0].format == currentTimeAbs.format)