Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/Bin-Cao/Bgolearn
Browse files Browse the repository at this point in the history
  • Loading branch information
Bin-Cao committed Dec 27, 2023
2 parents faa5434 + 0ea6ae8 commit b4c660b
Show file tree
Hide file tree
Showing 125 changed files with 206 additions and 47,994 deletions.
Binary file removed .DS_Store
Binary file not shown.
162 changes: 162 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
Test/
.Python
.DS_Store
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
Binary file removed Bgolearn/.DS_Store
Binary file not shown.
68 changes: 42 additions & 26 deletions Bgolearn/BGOmin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import copy
import copy, os
import warnings
import numpy as np
from scipy.stats import norm
import multiprocess as mp

# cal norm prob.
def norm_des(x):
Expand All @@ -24,6 +25,7 @@ def __init__(self,Kriging_model,data_matrix, Measured_response, virtual_samples,
self.ret_noise = ret_noise
self.row_features = row_features
warnings.filterwarnings('ignore')
os.environ["PYTHONWARNINGS"] = "ignore"



Expand Down Expand Up @@ -299,36 +301,50 @@ def PES(self, sam_num = 500):
print('The input para. opt_num must be an int')
return PES_list,np.array(return_x)


def Knowledge_G(self,MC_num = 50):
def __Knowledge_G_per_sample(self, func_bytes:bytes, MC_num:int, virtual_samples, v_sample_mean, v_sample_std, archive_sample_x, archive_sample_y, x_value, fea_num, ret_noise):
MC_batch_min = 0
for _ in range(MC_num):
# generate y value
y_value = np.random.normal(loc = v_sample_mean, scale = v_sample_std)
# update the sample x and sample y
archive_sample_x[-len(x_value):] = x_value
if isinstance(y_value, float):
archive_sample_y[-1] = y_value
elif isinstance(y_value, np.ndarray):
archive_sample_y[-len(y_value):] = y_value
# calculate the post mean
if ret_noise == True:
# return a callable model
post_mean, _ = func_bytes.fit_pre(archive_sample_x.reshape(-1, fea_num), archive_sample_y, virtual_samples, v_sample_std)
else:
post_mean, _ = func_bytes.fit_pre(archive_sample_x.reshape(-1, fea_num), archive_sample_y, virtual_samples)
MC_batch_min += post_mean.min()
return MC_batch_min

def Knowledge_G(self,MC_num = 50, Proc_num:int=None):
"""
:param MC_num: number of Monte carol, default 50
:param Proc_num: number of Processor, default None (0)
"""
current_min = self.virtual_samples_mean.min()
KD_list = []
vir_num = len(self.virtual_samples)
for i in range(vir_num):
x_value = self.virtual_samples[i]
MC_batch_min = 0
for j in range(MC_num):
y_value = np.random.normal(loc = self.virtual_samples_mean[i],scale = self.virtual_samples_std[i])
archive_sample_x = copy.deepcopy(self.data_matrix)
archive_sample_y = copy.deepcopy(self.Measured_response)

archive_sample_x = np.append(archive_sample_x, x_value)
archive_sample_y = np.append(archive_sample_y, y_value)
fea_num = len(self.data_matrix[0])
if self.ret_noise == True:
# return a callable model
post_mean, _ = self.Kriging_model().fit_pre(archive_sample_x.reshape(-1, fea_num),archive_sample_y,self.virtual_samples,self.virtual_samples_std[i])
else:
post_mean, _ = self.Kriging_model().fit_pre(archive_sample_x.reshape(-1, fea_num),archive_sample_y,self.virtual_samples)
MC_batch_min += post_mean.min()
MC_times = i * MC_num + j+1
if MC_times % 2000 == 0:
print('The {num}-th Monte carol simulation'.format(num = MC_times))
MC_result = MC_batch_min / MC_num
KD_list.append( current_min - MC_result)
fea_num = len(self.data_matrix[0])
archive_sample_x = np.append(self.data_matrix[:], self.virtual_samples[0])
archive_sample_y = np.append(self.Measured_response[:], self.virtual_samples_mean[0])
K_model = self.Kriging_model()
results = []
if not Proc_num:
for x_value, v_sample_mean, v_sample_std in zip(self.virtual_samples, self.virtual_samples_mean, self.virtual_samples_std):
MC_batch_min= self.__Knowledge_G_per_sample(K_model, MC_num, self.virtual_samples, v_sample_mean, v_sample_std, archive_sample_x, archive_sample_y, x_value, fea_num, self.ret_noise)
MC_result = MC_batch_min / MC_num
KD_list.append( current_min - MC_result)
else:
with mp.get_context("spawn").Pool(Proc_num) as pool:
results=[pool.apply_async(self.__Knowledge_G_per_sample, args=(K_model, MC_num, self.virtual_samples, v_sample_mean, v_sample_std, archive_sample_x, archive_sample_y, x_value, fea_num, self.ret_noise)) for x_value, v_sample_mean, v_sample_std in zip(self.virtual_samples, self.virtual_samples_mean, self.virtual_samples_std)]
for idx, rst in enumerate(results):
MC_batch_min = rst.get()
MC_result = MC_batch_min / MC_num
KD_list.append( current_min - MC_result)
KD_list = np.array(KD_list)

return_x = []
Expand Down
3 changes: 2 additions & 1 deletion Bgolearn/BGOsampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import numpy as np
import pandas as pd
import copy
from typing import Union
from .BGOmax import Global_max
from .BGOmin import Global_min
from .BGOclf import Boundary
Expand All @@ -19,7 +20,7 @@
from sklearn.model_selection import KFold

class Bgolearn(object):
def fit(self,data_matrix, Measured_response, virtual_samples, Mission ='Regression', Classifier = 'GaussianProcess',noise_std = None, Kriging_model = None, opt_num = 1 ,min_search = True, CV_test = False, ):
def fit(self,data_matrix, Measured_response, virtual_samples, Mission ='Regression', Classifier = 'GaussianProcess',noise_std = None, Kriging_model = None, opt_num = 1 ,min_search = True, CV_test = False, )-> Union[Boundary, Global_max, Global_min]:

"""
================================================================
Expand Down
Binary file removed Bgolearn/__pycache__/BGO_eval.cpython-39.pyc
Binary file not shown.
Binary file removed Bgolearn/__pycache__/BGOclf.cpython-39.pyc
Binary file not shown.
Binary file removed Bgolearn/__pycache__/BGOmax.cpython-39.pyc
Binary file not shown.
Binary file removed Bgolearn/__pycache__/BGOmin.cpython-39.pyc
Binary file not shown.
Binary file removed Bgolearn/__pycache__/BGOsampling.cpython-39.pyc
Binary file not shown.
Binary file removed Bgolearn/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file removed Example/.DS_Store
Binary file not shown.
Binary file removed Example/Example of version V1.1/.DS_Store
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit b4c660b

Please sign in to comment.