code stringlengths 17 6.64M |
|---|
def planetMassType(mass):
" Returns the planet masstype given the mass and using planetAssumptions['massType']\n "
if (mass is np.nan):
return None
for (massLimit, massType) in planetAssumptions['massType']:
if (mass < massLimit):
return massType
|
def planetRadiusType(radius):
" Returns the planet radiustype given the mass and using planetAssumptions['radiusType']\n "
if (radius is np.nan):
return None
for (radiusLimit, radiusType) in planetAssumptions['radiusType']:
if (radius < radiusLimit):
return radiusType
|
def planetTempType(temperature):
" Returns the planet masstype given the temperature and using planetAssumptions['tempType']\n "
for (tempLimit, tempType) in planetAssumptions['tempType']:
if (temperature < tempLimit):
return tempType
|
def planetType(temperature, mass, radius):
" Returns the planet type as 'temperatureType massType'\n "
if (mass is not np.nan):
sizeType = planetMassType(mass)
elif (radius is not np.nan):
sizeType = planetRadiusType(radius)
else:
return None
return '{0} {1}'.format(plan... |
def planetMu(sizeType):
return planetAssumptions['mu'][sizeType]
|
def planetAlbedo(tempType):
return planetAssumptions['albedo'][tempType]
|
def planetDensity(radiusType):
return planetAssumptions['density'][radiusType]
|
class OECDatabase(object):
' This Class Handles the OEC database including search functions.\n '
def __init__(self, databaseLocation, stream=False):
' Holds the Open Exoplanet Catalogue database in python\n\n :param databaseLocation: file path to the Open Exoplanet Catalogue systems folder ... |
def load_db_from_url(url='https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz'):
' Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo\n in the OpenExoplanetCatalogue GitHub group.\n\n The database is loaded from the url in... |
class LoadDataBaseError(IOError):
pass
|
def genExampleSystem():
systemPar = Parameters()
systemPar.addParam('name', ('Example System ' + str(ac._ExampleSystemCount)))
systemPar.addParam('distance', 58)
systemPar.addParam('declination', '+04 05 06')
systemPar.addParam('rightascension', '01 02 03')
exampleSystem = System(systemPar.par... |
def genExampleBinary():
binaryPar = BinaryParameters()
binaryPar.addParam('name', 'Example Binary {0}AB'.format(ac._ExampleSystemCount))
binaryPar.addParam('semimajoraxis', 10)
binaryPar.addParam('period', 10)
exampleBinary = Binary(binaryPar.params)
exampleBinary.flags.addFlag('Fake')
exa... |
def genExampleStar(binaryLetter='', heirarchy=True):
' generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a\n system and link everything up\n '
starPar = StarParameters()
starPar.addParam('age', '7.6')
starPar.addParam('magB', '9.8')
... |
def genExamplePlanet(binaryLetter=''):
' Creates a fake planet with some defaults\n :param `binaryLetter`: host star is part of a binary with letter binaryletter\n :return:\n '
planetPar = PlanetParameters()
planetPar.addParam('discoverymethod', 'transit')
planetPar.addParam('discoveryyear', ... |
class Flags(object):
def __init__(self):
self.flags = set()
def addFlag(self, flag):
if (flag in allowedFlags):
self.flags.add(flag)
else:
raise InvalidFlag
def removeFlag(self, flag):
self.flags.remove(flag)
def __repr__(self):
retur... |
class InvalidFlag(BaseException):
pass
|
class ExoDataError(Exception):
pass
|
class _GlobalFigure(object):
' sets up the figure and subfigure object with all the global parameters.\n '
def __init__(self, size='small'):
self.setup_fig(size)
def setup_fig(self, size='small'):
self.set_size(size)
def set_size(self, size):
" choose a preset size for th... |
class _AstroObjectFigs(_GlobalFigure):
' contains extra functions for dealing with input of astro objects\n '
def __init__(self, objectList, size='small'):
_GlobalFigure.__init__(self, size)
self.objectList = objectList
self._objectType = self._getInputObjectTypes()
def _getIn... |
class _BaseDataPerClass(_AstroObjectFigs):
' Base class for plots counting the results by a attribute. Child classes must modify\n * _classVariables (self._allowedKeys, )\n * _getSortKey (take the planet, turn it into a key)\n '
def __init__(self, astroObjectList, unit=None, size='small'):
_... |
class DataPerParameterBin(_BaseDataPerClass):
' Generates Data for planets per parameter bin'
def __init__(self, results, planetProperty, binLimits, unit=None, size='small'):
"\n :param planetProperty: property of planet to bin. IE 'e' for eccentricity, 'star.magV' for magV\n :param bin... |
class GeneralPlotter(_AstroObjectFigs):
' This class should be able to create a plot with lots of options like the online visual plots. In future it\n should be turned into a GUI\n '
def __init__(self, objectList, xaxis=None, yaxis=None, xunit=None, yunit=None, xaxislog=False, yaxislog=False, size='sma... |
class DiscoveryMethodByYear(object):
def __init__(self, planet_list, methods_to_plot=('RV', 'transit', 'Other'), skip_solar_system_planets=True):
" Produces a labelled stacked bar chart of planet discovery methods\n\n\n :param planet_list: list of planet objects\n :param methods_to_plot: li... |
def _sortValueIntoGroup(groupKeys, groupLimits, value):
" returns the Key of the group a value belongs to\n :param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+']\n :param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute\n ... |
class OutOfLimitsError(Exception):
pass
|
class BelowLimitsError(Exception):
pass
|
class AboveLimitsError(Exception):
pass
|
def accept(f):
def test_works(self, T_eff=not_set, mu=not_set, g=not_set):
return f(self=self, T_eff=T_eff, mu=mu, g=g)
return test_works
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, R_p=not_set, R_s=not_set):
return f(self=self, R_p=R_p, R_s=R_s)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, T_eff=not_set, mu=not_set, g=not_set):
return f(self=self, T_eff=T_eff, mu=mu, g=g)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, A, T_s=not_set, R_s=not_set, a=not_set, epsilon=not_set):
return f(self=self, A=A, T_s=T_s, R_s=R_s, a=a, epsilon=epsilon)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, a=not_set, M_s=not_set, M_p=not_set):
return f(self=self, a=a, M_s=M_s, M_p=M_p)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, M=not_set, R=not_set):
return f(self=self, M=M, R=R)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, T=not_set, R=not_set):
return f(self=self, T=T, R=R)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, A=not_set, T_s=not_set, R_s=not_set, a=not_set, epsilon=not_set):
return f(self=self, A=A, T_s=T_s, R_s=R_s, a=a, epsilon=epsilon)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_works(self, T_eff=not_set, mu=not_set, g=not_set, H=not_set):
return f(self=self, T_eff=T_eff, mu=mu, g=g, H=H)
return test_works
|
class TestCase(unittest.TestCase):
' adds the assertItemsEqual back in python 3 by referencing assertCountEqual. This should by subclassed over\n unitest.Testcase by all test classes now\n '
def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
if (sys.hexversion < 50331648):
... |
class Test_planetAssumptions(TestCase):
def test_MassType(self):
pass
|
class TestListFiles(TestCase):
def create_Parameter_object(self):
params = {'RA': 111111, 'DEC': 222222, 'name': 'monty'}
paramObj = Parameters()
paramObj.params.update(params)
return paramObj
def test_addParam_works_no_duplicate(self):
paramObj = self.create_Paramete... |
class TestAstroObject__eq__method(TestCase):
def setUp(self):
self.object1 = _BaseObject()
self.object1.params = {'name': 'name1', 'radius': (10 * aq.km), 'd': 1}
def test_astroObject_same_object_is_eq(self):
self.assertEqual(self.object1, self.object1)
def test_astroObject_is_e... |
class TestStarParameters(TestCase):
def test_getLimbdarkeningCoeff_works(self):
pass
def test_distance_estimation_fails_invalid_spectral_type(self):
' If theres no distance, will try to calculate based on spectral type\n '
planet = genExamplePlanet()
star = planet.star... |
class TestFindNearest(TestCase):
def setUp(self):
self.arr = np.array([1.2, 4, 6, 7.0, 9.5, 10, 11, 12])
def test_exact_value_returns_exact(self):
self.assertEqual(_findNearest(self.arr, 6), 6)
def test_below_first_value_works(self):
self.assertEqual(_findNearest(self.arr, 0.8),... |
class TestSpectralType(TestCase):
def test_classType_and_Type(self):
A8V = SpectralType('')
A8V.lumType = 'V'
A8V.classNumber = '8'
A8V.classLetter = 'A'
self.assertEqual(A8V.specClass, 'A8')
self.assertEqual(A8V.specType, 'A8V')
def test_works_normal_full_typ... |
class TestPlanetClass(TestCase):
def test_isTransiting_is_true_if_tag_present(self):
planet = genExamplePlanet()
planet.params['istransiting'] = '1'
self.assertTrue(planet.isTransiting)
def test_isTransiting_fails_with_missing_tag_or_incorrect_value(self):
planet = genExample... |
class Test_Planet_Parameter_Estimation(TestCase):
def test_sma_estimation(self):
planet = genExamplePlanet()
planet.params.pop('semimajoraxis')
self.assertAlmostEqual(planet.a, (0.449636494929 * aq.au), 5)
|
class Test_PlanetAndBinaryCommon(TestCase):
def setUp(self):
self.common_class = PlanetAndBinaryCommon()
def test_setting_of_sma(self):
initial_sma = self.common_class.a
new_sma = (1 * aq.m)
self.assertNotEqual(initial_sma, new_sma)
self.common_class.a = new_sma
... |
class Test_Magnitude(TestCase):
def test_convert_works_magV_to_magK_auto(self):
mag = Magnitude('B6', magV=12.0)
self.assertEqual(mag.convert('K'), (12 + 0.43))
def test_convert_works_magK_to_magJ_auto(self):
mag = Magnitude('F5', magK=10.0)
self.assertEqual(mag.convert('J'),... |
class Test_isNanOrNone(TestCase):
def test_np_nan(self):
self.assertTrue(isNanOrNone(np.nan))
def test_math_nan(self):
self.assertTrue(isNanOrNone(float('nan')))
def test_float(self):
self.assertFalse(isNanOrNone((- 1.0)))
def test_int(self):
self.assertFalse(isNanO... |
class TestCatalogue_Planet(TestCase):
def test_isTransiting(self):
x = [planet.isTransiting for planet in exocat.planets]
def test_calcTransitDuration(self):
x = [planet.calcTransitDuration() for planet in exocat.planets]
def test_calcTransitDuration_circular(self):
x = [planet.... |
class TestCatalogue_Star(TestCase):
def test_magV(self):
x = [star.magV for star in exocat.stars]
def test_T(self):
x = [star.T for star in exocat.stars]
def test_calcTemperature(self):
x = [star.calcTemperature() for star in exocat.stars]
|
class TestDataBaseLoading(TestCase):
def setUp(self):
self.tempDir = mkdtemp()
self._createFakeXML()
self.oecdb = OECDatabase((self.tempDir + '/'))
def _createFakeXML(self):
xmlCases = ['<system><name>System 1</name><star><name>Star 1</name></star></system>', '<system><name>S... |
class TestDataBaseFailing(TestCase):
def setUp(self):
self.tempDir = mkdtemp()
def test_raises_LoadDataBaseError_in_empty_folder(self):
with self.assertRaises(LoadDataBaseError):
OECDatabase(self.tempDir)
def test_raises_LoadDataBaseError_without_system_tag(self):
xm... |
class Test_load_db_from_url(TestCase):
def test_autoload(self):
exocat = load_db_from_url()
self.assertTrue((len(exocat.planets) > 1000))
self.assertTrue((len(exocat.systems) > 1000))
self.assertTrue((len(exocat.stars) > 1000))
|
class Test__ExoDataEqn(TestCase):
def test__repr__(self):
eqn = _ExoDataEqn()
self.assertEqual(eqn.__repr__(), '_ExoDataEqn()')
|
class Test_ScaleHeight(TestCase):
def test__repr__works(self):
eqn = ScaleHeight((100 * aq.K), (1 * aq.atomic_mass_unit), ((9.81 * aq.m) / (aq.s ** 2)))
answer = 'ScaleHeight(H=None, T_eff=100.0 K, mu=1.0 u, g=9.81 m/s**2)'
self.assertEqual(eqn.__repr__(), answer)
def test_works_eart... |
class Test_MeanPlanetTemp(TestCase):
def test_works_mars(self):
a = (1.524 * aq.au)
A = 0.25
T_s = (5800 * aq.K)
R_s = (1 * aq.R_s)
answer = (231.1 * aq.K)
result = MeanPlanetTemp(A, T_s, R_s, a, 0.7).T_p
self.assertAlmostEqual(answer, result, 1)
@unit... |
class Test_StellarLuminosity(TestCase):
def test_works_sun(self):
R_s = (1 * aq.R_s)
T_eff_s = (5780 * aq.degK)
answer = (3.89144e+26 * aq.W)
result = StellarLuminosity(R_s, T_eff_s).L
self.assertAlmostEqual(answer, result, delta=1e+23)
@given(T=floats(0.0001, 100000)... |
class Test_KeplersThirdLaw(TestCase):
def test_works_gj1214(self):
a = (0.014 * aq.au)
M_s = (0.153 * aq.M_s)
result = KeplersThirdLaw(a, M_s).P
answer = (1.546 * aq.day)
self.assertAlmostEqual(answer, result, 3)
@given(a=floats(0.0001, 1000), M_s=floats(0.0001, 10000... |
class Test_SurfaceGravity(TestCase):
def test_works_earth(self):
R = (1 * aq.R_e)
M = (1 * aq.M_e)
answer = ((9.823 * aq.m) / (aq.s ** 2))
result = SurfaceGravity(M, R).g
self.assertAlmostEqual(answer, result, 2)
@given(M=floats(0.0001, 10000), R=floats(0.0001, 10000)... |
class Test_logg(TestCase):
def test_works_wasp10(self):
' Christian et al. 2009 values\n '
answer = 4.51
result = eq.Logg((0.703 * aq.M_s), (0.775 * aq.R_s)).logg
self.assertAlmostEqual(answer, result, 1)
@given(M=floats(0.0001, 10000), R=floats(0.0001, 10000))
def... |
class Test_transitDepth(TestCase):
def test_works_gj1214(self):
'Charbonneau et. al. 2009 values'
answer = (0.1162 ** 2)
result = TransitDepth((0.211 * aq.R_s), (2.678 * aq.R_e)).depth
self.assertAlmostEqual(answer, result, 2)
@given(R_p=floats(0.0001, 10000), R_s=floats(0.00... |
class Test_density(TestCase):
def test_works_water(self):
M = (1 * aq.kg)
R = (1 * aq.m)
answer = ((0.2387 * aq.kg) / (aq.m ** 3))
result = Density(M, R).density.rescale((aq.kg / (aq.m ** 3)))
self.assertAlmostEqual(answer, result, 3)
def test_works_hd189(self):
... |
class Test_ratioTerminatorToStar(TestCase):
def test_works_earth(self):
H_p = (8500 * aq.m)
R_p = (1 * aq.R_e)
R_s = (1 * aq.R_s)
answer = (1.12264e-06 * aq.dimensionless)
result = ratioTerminatorToStar(H_p, R_p, R_s)
self.assertTrue(((answer - result) < 0.001))
|
class Test_SNRPlanet(TestCase):
def test_works(self):
params = {'SNRStar': 400, 'starPlanetFlux': 1.12e-06, 'Nobs': 200, 'pixPerbin': 5, 'NVisits': 1}
answer = 0.01417
result = SNRPlanet(**params)
self.assertAlmostEqual(answer, result, 5)
|
class Test_transitDurationCircular(TestCase):
def test_works_gj1214(self):
R_p = (0.02 * aq.R_j)
R_s = (0.21 * aq.R_s)
i = (88.17 * aq.deg)
a = (0.014 * aq.au)
P = (1.58040482 * aq.day)
answer = (45.8329 * aq.min)
result = transitDurationCircular(P, R_s, R_... |
class Test_transitDuration(TestCase):
def test_works_gj1214(self):
R_p = (0.02 * aq.R_j)
R_s = (0.21 * aq.R_s)
i = (88.17 * aq.deg)
a = (0.014 * aq.au)
P = (1.58040482 * aq.day)
answer = (45.8329 * aq.min)
result = TransitDuration(P, a, R_p, R_s, i, 0.0, 0.... |
class Test_starTemperature(TestCase):
def test_works_sun(self):
answer = (5800 * aq.K)
result = eq.estimateStellarTemperature((1 * aq.M_s))
self.assertAlmostEqual(answer, result, 0)
def test_works_hd189(self):
answer = (4939 * aq.K)
result = eq.estimateStellarTemperat... |
@unittest.skip('Not written')
class Test_estimateStellarMass(TestCase):
def test_works_gj1214(self):
assert False
|
class Test_impactParameter(TestCase):
def test_works_wasp10b(self):
' Christian et al. 2009 values\n '
result = eq.ImpactParameter((0.0369 * aq.au), (0.775 * aq.R_s), (86.9 * aq.deg)).b
answer = 0.568
self.assertAlmostEqual(result, answer, 1)
@given(floats(0.001, 10000... |
class Test_estimateDistance(TestCase):
def test_works_online_example(self):
m = 14
M = 0
result = estimateDistance(m, M, 0)
answer = (6309.6 * aq.pc)
self.assertAlmostEqual(answer, result, 1)
|
class Test_createAbsMagEstimationDict(TestCase):
def test_works(self):
(magTable, LClassRef) = eq._createAbsMagEstimationDict()
self.assertEqual(magTable['O'][8][LClassRef['V']], (- 4.9))
self.assertEqual(magTable['A'][1][LClassRef['III']], 0.2)
self.assertTrue(math.isnan(magTable... |
class Test_estimateAbsoluteMagnitude(TestCase):
def test_works_no_interp(self):
self.assertEqual(estimateAbsoluteMagnitude('O9'), (- 4.5))
self.assertEqual(estimateAbsoluteMagnitude('B5'), (- 1.2))
self.assertEqual(estimateAbsoluteMagnitude('A5'), 1.95)
def test_works_no_classnum(sel... |
class Test_createMagConversionDict(TestCase):
def test_works(self):
magTable = eq._createMagConversionDict()
self.assertEqual(magTable['A6'][10], '0.44')
self.assertEqual(magTable['B0'][0], '30000')
self.assertEqual(magTable['M6'][14], 'nan')
|
class TestExampleInstances(TestCase):
def setUp(self):
ac._ExampleSystemCount = 1
self.examplePlanet = examplePlanet
self.exampleStar = exampleStar
self.exampleSystem = exampleSystem
def test_system_object(self):
exampleSystem = self.exampleSystem
self.assertE... |
class TestExampleInstancesWithBinary(TestCase):
def setUp(self):
ac._ExampleSystemCount = 2
self.examplePlanet = genExamplePlanet(binaryLetter='A')
self.exampleStarA = self.examplePlanet.star
self.exampleBinary = self.examplePlanet.binary
self.exampleStarB = self.exampleBi... |
class Test_Flag(TestCase):
def test_flag__iter__(self):
flagobj = flags.Flags()
flagobj.addFlag('Calculated Temperature')
flagobj.addFlag('Estimated Mass')
self.assertTrue(('Calculated Temperature' in flagobj))
self.assertTrue(('Estimated Mass' in flagobj))
self.as... |
class estimateMissingValues(TestCase):
def tearDown(self):
' reset back to default after\n '
params.estimateMissingValues = True
|
class estimateMissingValuesPlanet(estimateMissingValues):
def setUp(self):
self.planet = ex.genExamplePlanet()
def testSMAEstimatedWhenTrue(self):
del self.planet.params['semimajoraxis']
self.assertAlmostEqual(self.planet.a, (0.4496365 * aq.au), 7)
self.assertTrue(('Calculate... |
class estimateMissingValuesStar(estimateMissingValues):
def setUp(self):
self.star = ex.genExampleStar()
def test_magVEstimatedWhenTrue(self):
del self.star.params['magV']
self.assertAlmostEqual(self.star.magV, 9.14, 3)
self.assertTrue(('Estimated magV' in self.star.flags.fla... |
class estimateMissingValuesBinary(estimateMissingValues):
def setUp(self):
self.binary = ex.genExampleBinary()
@unittest.skip('Currently the calculation is not implemented')
def testSMAEstimatedWhenTrue(self):
del self.binary.params['semimajoraxis']
self.assertAlmostEqual(self.bi... |
class Test_GlobalFigure(TestCase):
def test_set_y_axis_log(self):
fig = _GlobalFigure()
fig.set_y_axis_log()
def test_set_x_axis_log(self):
fig = _GlobalFigure()
fig.set_x_axis_log()
|
class Test_AstroObjectFigs(TestCase):
@unittest.skip('Tested through others but should probably be done here aswell')
def test_getInputObjectTypes(self):
assert False
@unittest.skip('Tested through others but should probably be done here aswell')
def test_getParLabelAndUnit(self):
as... |
class Test_DataPerParameterBin(TestCase):
def testDataGeneratesCorrectly(self):
planets = []
planetInfoList = (0, 0.1, 0.2, 0.3, 0.45, 0.5, 0.6, np.nan)
for planetInfo in planetInfoList:
planet = genExamplePlanet()
planet.params['eccentricity'] = planetInfo
... |
def generate_list_of_planets(number):
planetList = []
for i in range(number):
planetList.append(genExamplePlanet())
return planetList
|
class Test_GeneralPlotter(TestCase):
def test__init__(self):
x = GeneralPlotter(generate_list_of_planets(3))
def test_set_axis_with_variables(self):
planetlist = generate_list_of_planets(3)
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
for (i, radius) in enumera... |
def find_version(*file_paths):
with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:
version_file = f.read()
version_match = re.search('^__version__ = [\'\\"]([^\'\\"]*)[\'\\"]', version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Un... |
def g(x, a):
'\n TBSS kernel applicable to the rBergomi variance process.\n '
return (x ** a)
|
def b(k, a):
'\n Optimal discretisation of TBSS process for minimising hybrid scheme error.\n '
return ((((k ** (a + 1)) - ((k - 1) ** (a + 1))) / (a + 1)) ** (1 / a))
|
def cov(a, n):
'\n Covariance matrix for given alpha and n, assuming kappa = 1 for\n tractability.\n '
cov = np.array([[0.0, 0.0], [0.0, 0.0]])
cov[(0, 0)] = (1.0 / n)
cov[(0, 1)] = (1.0 / (((1.0 * a) + 1) * (n ** ((1.0 * a) + 1))))
cov[(1, 1)] = (1.0 / (((2.0 * a) + 1) * (n ** ((2.0 * a)... |
def bs(F, K, V, o='call'):
'\n Returns the Black call price for given forward, strike and integrated\n variance.\n '
w = 1
if (o == 'put'):
w = (- 1)
elif (o == 'otm'):
w = ((2 * (K > 1.0)) - 1)
sv = np.sqrt(V)
d1 = ((np.log((F / K)) / sv) + (0.5 * sv))
d2 = (d1 - ... |
def bsinv(P, F, K, t, o='call'):
'\n Returns implied Black vol from given call price, forward, strike and time\n to maturity.\n '
w = 1
if (o == 'put'):
w = (- 1)
elif (o == 'otm'):
w = ((2 * (K > 1.0)) - 1)
P = np.maximum(P, np.maximum((w * (F - K)), 0))
def error(s)... |
def compute_masked_mses(templates, masks, imgs):
mses = np.zeros((len(imgs), len(templates)))
for (imgi, img) in enumerate(imgs):
for (ti, (t, m)) in enumerate(zip(templates, masks)):
mse = ((((t * m) - (img * m)) ** 2).sum() / m.mean())
mses[(imgi, ti)] = mse.item()
return... |
def compute_pairwise_mses(imgs1, imgs2):
mses = np.zeros((len(imgs1), len(imgs2)))
for (imgi, img1) in enumerate(imgs1):
for (ti, img2) in enumerate(imgs2):
mse = ((img1 - img2) ** 2).sum()
mses[(imgi, ti)] = mse.item()
return mses
|
def get_templates_and_masks(template_folder='templates/'):
template_parquet = pd.read_parquet(f'{template_folder}metadata.parquet')
t_urls = np.array(template_parquet['url'])
mask_files = list(template_parquet['mask_file'])
template_files = list(template_parquet['img_file'])
(template_imgs, mask_i... |
def get_retrieved_imgs_and_urls(ret_folder='retrieved/'):
md_ret = pd.read_parquet('retrieved/metadata.parquet')
ret_imgs = []
ret_urls = []
for (imgf, imgu) in zip(md_ret['img_file'], md_ret['url']):
ret_imgs += [processing_utils.pil_img_to_torch(Image.open(imgf).resize((256, 256)))]
... |
def get_files_from_path(folder_path, prefix, postfix):
files = []
for (root, _, filenames) in os.walk(folder_path):
for filename in filenames:
if (filename.startswith(prefix) and filename.endswith(postfix)):
files.append(os.path.join(root, filename))
files = sorted(file... |
def prompt_to_folder(prompt, ml=200):
return prompt.replace('/', '_')[:min(len(prompt), ml)]
|
def gather_groundtruths(parquet_file='sdv1_wb_groundtruth.parquet', out_parquet_file='test.parquet', gen_folder='memb_top500_synthall/', matching_real_folder='matched_and_real_images/matched/', recompute_real_img_mse=True, N_imgs_gen=(- 1), n_imgs_template_thresh=0, download_templates=True, download_reals=True):
... |
@torch.no_grad()
def run_bb_attack(out_parquet_file, parquet_file=None, n_seeds=4, seed_offset=0, make_grid_every=0, outfolder='bb_attack_vis/', caption_offset=0, n_captions=(- 1), model='runwayml/stable-diffusion-v1-5', dl_parquet_repo='fraisdufour/sd-stuff', dl_parquet_name='membership_attack_top30k.parquet', compu... |
@torch.no_grad()
def run_wb_attack(out_parquet_file, parquet_file=None, n_seeds=1, seed_offset=0, outfolder='gen_synthall/', caption_offset=0, n_captions=(- 1), model='runwayml/stable-diffusion-v1-5', dl_parquet_repo='fraisdufour/sd-stuff', dl_parquet_name='membership_attack_top30k.parquet', compute_images=False, loc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.