def test_sync(self): with ScratchDir('.'): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df.csv')) # Construct and start campaign new_campaign = Campaign(df, AgentStabilityML5(), ATFSampler(df), StabilityAnalyzer(), create_seed=10, s3_prefix="test") new_campaign.auto_loop(n_iterations=3, save_iterations=True, initialize=True) # Test iteration read s3 = boto3.resource('s3') obj = s3.Object(CAMD_S3_BUCKET, "test/iteration.json") loaded = json.loads(obj.get()['Body'].read()) self.assertEqual(loaded, 2) # Test save directories for iteration in [-1, 0, 1, 2]: obj = s3.Object(CAMD_S3_BUCKET, f"test/{iteration}/iteration.json") loaded = json.loads(obj.get()['Body'].read()) self.assertEqual(loaded, iteration)
def test_random_agent_loop(self): df = load_default_atf_data() n_seed = 200 # Starting sample size agent = RandomAgent(n_query=10) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(dataframe=df) candidate_data = df new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.initialize() self.assertFalse(new_loop.create_seed) for _ in range(6): new_loop.run() self.assertTrue(True) # Testing the continuation new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) self.assertTrue(new_loop.initialized) self.assertEqual(new_loop.iteration, 6) self.assertEqual(new_loop.loop_state, None) new_loop.run() self.assertTrue(True) self.assertEqual(new_loop.iteration, 7)
def test_mp_loop(self): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df_analysis.csv')) df['id'] = [int(mp_id.replace("mp-", "").replace('mvc-', '')) for mp_id in df['id']] df.set_index("id") df['Composition'] = df['formula'] # Just use the Ti-O-N chemsys seed = df.iloc[:38] candidates = df.iloc[38:209] agent = RandomAgent(n_query=20) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(dataframe=df) new_loop = Campaign( candidates, agent, experiment, analyzer, seed_data=seed ) new_loop.initialize() for iteration in range(6): new_loop.run() self.assertTrue(os.path.isfile("hull.png")) if iteration >= 1: self.assertTrue( os.path.isfile("history.pickle")) # Testing the continuation new_loop = Campaign(df, agent, experiment, analyzer) self.assertTrue(new_loop.initialized) self.assertEqual(new_loop.iteration, 6) self.assertEqual(new_loop.loop_state, None) new_loop.run() self.assertTrue(True) self.assertEqual(new_loop.iteration, 7)
def test_sync(self): with ScratchDir('.'): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df.csv')) # Construct and start campaign new_campaign = Campaign(df, AgentStabilityML5(), ATFSampler(df), StabilityAnalyzer(), create_seed=10, s3_prefix="test") new_campaign.initialize() s3 = boto3.resource('s3') obj = s3.Object(CAMD_S3_BUCKET, "test/iteration.json") loaded = json.loads(obj.get()['Body'].read()) self.assertEqual(loaded, 0)
def update_run(folder): """ Updates existing runs in s3 to include plots Returns: List of modified chemsys """ required_files = ["seed_data.pickle", "report.log"] with cd(folder): if os.path.isfile("error.json"): error = loadfn("error.json") print("{} ERROR: {}".format(folder, error)) if not all([os.path.isfile(fn) for fn in required_files]): print("{} ERROR: no seed data, no analysis to be done") else: analyzer = StabilityAnalyzer(hull_distance=0.2) # Generate report plots for iteration in range(0, 25): print("{}: {}".format(folder, iteration)) if not os.path.isdir(str(iteration)) or not os.path.isdir( str(iteration - 1)): continue with open(os.path.join(str(iteration), "seed_data.pickle"), "rb") as f: result_df = pickle.load(f) all_result_ids = loadfn( os.path.join(str(iteration - 1), "consumed_candidates.json")) new_result_ids = loadfn( os.path.join(str(iteration - 1), "submitted_experiment_requests.json")) analyzer.plot_hull(df=result_df, new_result_ids=new_result_ids, all_result_ids=all_result_ids, filename="hull_{}.png".format(iteration), finalize=False) Campaign.generate_report_plot()
def test_agent(self, agent): """ Runs a simulation of a given agent according to the class attributes Args: agent (HypothesisAgent): Returns: None """ campaign = Campaign( candidate_data=self.atf_dataframe, seed_data=self.seed_data, agent=agent, analyzer=self.analyzer, experiment=ATFSampler(dataframe=self.atf_dataframe), ) campaign.auto_loop(n_iterations=self.iterations, initialize=True) return campaign
def test_gp_bagging(self): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df.csv')) df_sub = df[df['N_species'] <= 3] n_seed = 200 # Starting sample size agent = BaggedGaussianProcessStabilityAgent( n_query=10, hull_distance=0.05, alpha=0.5, # Fraction of std to include in expected improvement n_estimators=2, max_samples=195, parallel=False) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(df_sub) candidate_data = df_sub new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.initialize() self.assertTrue(new_loop.initialized) new_loop.auto_loop(6) self.assertTrue(True)
def test_svgp_loop(self): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df.csv')) df_sub = df[df['N_species'] <= 3] n_seed = 200 # Starting sample size agent = SVGProcessStabilityAgent(n_query=10, hull_distance=0.05, alpha=0.5, M=100) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(df_sub) candidate_data = df_sub new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.initialize() self.assertTrue(new_loop.initialized) new_loop.auto_loop(3) self.assertTrue(True)
def test_qbc_agent_loop(self): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df.csv')) df_sub = df[df['N_species'] <= 3] n_seed = 200 # Starting sample size agent = QBCStabilityAgent(model=MLPRegressor(hidden_layer_sizes=(84, 50)), n_query=10, hull_distance=0.05, alpha=0.5) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(dataframe=df_sub) candidate_data = df_sub new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.initialize() self.assertTrue(new_loop.initialized) new_loop.auto_loop(3) self.assertTrue(True)
def test_random_agent_loop(self): df = load_dataframe("oqmd1.2_exp_based_entries_featurized_v2") n_seed = 5000 agent = RandomAgent(n_query=200) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(dataframe=df) candidate_data = df new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.initialize() self.assertFalse(new_loop.create_seed) for _ in range(6): new_loop.run() self.assertTrue(True)
def test_simple_gp_loop(self): df = pd.read_csv(os.path.join(CAMD_TEST_FILES, 'test_df.csv')) df_sub = df[df['N_species'] <= 3] n_seed = 200 # Starting sample size n_query = 10 # This many new candidates are "calculated with DFT" (i.e. requested from Oracle -- DFT) agent = GaussianProcessStabilityAgent(n_query=n_query, hull_distance=0.05, alpha=0.5, parallel=False) analyzer = StabilityAnalyzer(hull_distance=0.05, parallel=False) experiment = ATFSampler(dataframe=df_sub) candidate_data = df_sub new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.initialize() self.assertTrue(new_loop.initialized) new_loop.auto_loop(2) self.assertTrue(True)
def test_gp_ucb_generic(self): def f(x): return np.sin(x) * np.sin(x) * (x ** 2) x = np.linspace(0, 10, 500) y = f(x) df = pd.DataFrame({'x': x, 'target': y}) N_query = 2 # This many experiments are requested in each iteration N_seed = 5 # This many samples are randomly acquired in the beginning to form a seed. agent = GenericGPUCB(n_query=2,kernel=ConstantKernel(100.0) + RBF(10.0) * ConstantKernel(1.0)) analyzer = GenericMaxAnalyzer(threshold=58) experiment = ATFSampler(dataframe=df) candidate_data = df new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=N_seed) new_loop.initialize(random_state=20) self.assertTrue(new_loop.initialized) new_loop.run() self.assertTrue(True)
from sklearn.neural_network import MLPRegressor from camd.agent.stability import AgentStabilityML5 from camd.analysis import StabilityAnalyzer from camd.experiment.base import ATFSampler from camd.utils.data import load_default_atf_data ########################################################## # Load dataset and filter by N_species of 2 or less ########################################################## df = load_default_atf_data() ## Epsilon-Greedy n_seed = 5000 # Starting sample size - a seed of this size will be randomly chosen. n_query = 200 # This many new candidates are "calculated with DFT" (i.e. requested from Oracle -- DFT) agent = AgentStabilityML5(model=MLPRegressor(hidden_layer_sizes=(84, 50)), n_query=n_query, hull_distance=0.05, exploit_fraction=0.5) analyzer = StabilityAnalyzer(hull_distance=0.05) experiment = ATFSampler(dataframe=df) candidate_data = df ########################################################## new_loop = Campaign(candidate_data, agent, experiment, analyzer, create_seed=n_seed) new_loop.auto_loop(n_iterations=4, initialize=True)
from camd.campaigns.base import Campaign from camd.agent.stability import QBCStabilityAgent from camd.analysis import StabilityAnalyzer from camd.experiment.dft import OqmdDFTonMC1 from sklearn.neural_network import MLPRegressor # Let's create our search domain as Ir-Fe-O ternary. We restrict our search to structures with max 10 atoms. # We further restrict the possible stoichiometry coefficients to integers to [1,4). domain = StructureDomain.from_bounds(["Ir", "Fe", "O"], charge_balanced=True, n_max_atoms = 10, **{"grid": range(1,4)}) candidate_data = domain.candidates() structure_dict = domain.hypo_structures_dict # Setup the loop for this campaign. agent = QBCStabilityAgent(MLPRegressor(hidden_layer_sizes=(84, 50)), n_query=3, hull_distance=0.1, training_fraction=0.5, n_members=10) analyzer = StabilityAnalyzer(hull_distance=0.05) experiment = OqmdDFTonMC1 # This is the Experiment method to run OQMD compatible DFT on AWS-MC1 experiment_params = {'structure_dict': structure_dict, # Parameters of this experiment class include structures. 'candidate_data': candidate_data, 'timeout': 30000} # Campaign class puts all the above pieces together. new_loop = Campaign(candidate_data, agent, experiment, analyzer, agent_params=agent_params, analyzer_params=analyzer_params, experiment_params=experiment_params) # Let's start the campaign! new_loop.auto_loop_in_directories(n_iterations=3, timeout=1, monitor=True, initialize=True, with_icsd=True)