Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code scanning alerts #406

Merged
merged 55 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from 52 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
d00e4a8
reprted by code scanning
DavidPCoster Nov 10, 2023
32d0682
Removed unused variables (comment below describes them already).
djgroen Nov 10, 2023
d23c9d8
reprted by code scanning: print a message rather than completely ignore
DavidPCoster Nov 10, 2023
2365f3b
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
DavidPCoster Nov 10, 2023
dd2a983
reported by code scanning
DavidPCoster Nov 10, 2023
d636994
reported by code scanning
DavidPCoster Nov 10, 2023
0a73190
reported by code scanning
DavidPCoster Nov 10, 2023
b8793d7
reported by code scanning
DavidPCoster Nov 10, 2023
6cb5238
Fixed test_sobol and made it a proper pytest.
djgroen Nov 10, 2023
2f9f39d
Sharpened the assert criterion in test_sobol.
djgroen Nov 10, 2023
f627cbb
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
djgroen Nov 10, 2023
5dd2841
reported by code scanning
DavidPCoster Nov 10, 2023
63be3ea
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
DavidPCoster Nov 10, 2023
1947eda
Removed several more code scanning issues.
djgroen Nov 10, 2023
0adb5cc
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
djgroen Nov 10, 2023
ebea00c
Code scanning.
djgroen Nov 10, 2023
73ab8ce
remove unnecessary import of CleanUp
DavidPCoster Dec 1, 2023
f9e5618
fix problem from code scanning report
DavidPCoster Dec 1, 2023
986f0b7
state_file was removed as an option
DavidPCoster Dec 1, 2023
885e882
minor cleanup for .gitignore
DavidPCoster Dec 1, 2023
52ebc5d
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
djgroen Dec 4, 2023
da44ce8
decreased the number of cases from 1010 to 910 so that the limit of 9…
DavidPCoster Dec 4, 2023
a87239a
Attempted fix to #409.
djgroen Dec 4, 2023
0960178
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
djgroen Dec 4, 2023
63d76b2
Set autoescape to True. D'oh!
djgroen Dec 4, 2023
29d87e9
Update of installation instructions process for EasyVVUQ, remove defu…
JonMcCullough Dec 4, 2023
46695a9
Merge branch 'code_scanning_alerts' of https://github.com/UCL-CCS/Eas…
JonMcCullough Dec 4, 2023
b8343a0
Attempt to remove one warning.
djgroen Dec 4, 2023
cab3168
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
djgroen Dec 4, 2023
4d1d5d5
Update coveralls.yml
JonMcCullough Dec 4, 2023
5c6c117
Update python-package.yml
JonMcCullough Dec 4, 2023
f152d70
Addressing code scanning alert #146.
djgroen Dec 4, 2023
b7e310a
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
djgroen Dec 4, 2023
80067d7
Code scanning issue #147.
djgroen Dec 4, 2023
134dd30
Fixed several unused variable issues.
djgroen Dec 4, 2023
256d835
Update sql.py to remove legacy implementation warnings
JonMcCullough Dec 4, 2023
c09cc37
Merge branch 'code_scanning_alerts' of https://github.com/UCL-CCS/Eas…
JonMcCullough Dec 4, 2023
6d33000
Clean sql.py file
JonMcCullough Dec 4, 2023
aa13ffc
Edit qmc.py to correct legacy deprecation warning
JonMcCullough Dec 4, 2023
99aa7c2
only print diagnostic information when EasyVVUQ_Debug set
DavidPCoster Dec 4, 2023
1614a29
only print diagnostic information when EasyVVUQ_Debug set
DavidPCoster Dec 4, 2023
c477522
replace .append by .concat
DavidPCoster Dec 4, 2023
bb5c017
only print diagnostic information when EasyVVUQ_Debug set
DavidPCoster Dec 4, 2023
0dba9c5
got this one working again
DavidPCoster Dec 4, 2023
7f8ea9b
tomli seems to be required
DavidPCoster Dec 4, 2023
9f70130
Modify test value of N to remove warning on number of samples not bei…
JonMcCullough Dec 4, 2023
39911e1
Merge branch 'code_scanning_alerts' of https://github.com/UCL-CCS/Eas…
JonMcCullough Dec 4, 2023
232d1e9
drop a nuisance field from the params
DavidPCoster Dec 4, 2023
2cc076c
Merge branch 'code_scanning_alerts' of github.com:UCL-CCS/EasyVVUQ in…
DavidPCoster Dec 4, 2023
f690e2c
add fipy as a requirement for one of the tests
DavidPCoster Dec 4, 2023
f4c2a88
test case now works
DavidPCoster Dec 4, 2023
5511dc0
Simple typo fix.
djgroen Dec 5, 2023
dcecc7a
place the 'Sensitivity Analysis: Derivative based' code in a try/exce…
DavidPCoster Dec 5, 2023
12c1737
get the path to the campaign.db from an environment variable DIR; upd…
DavidPCoster Dec 5, 2023
185c5a8
resolve conflict
DavidPCoster Dec 5, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/coveralls.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ jobs:
python -m pip install --upgrade pip
python -m pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
python setup.py develop
python setup.py build_cannonsim
python -m pip install --editable .
cd tests/cannonsim/src; make; cd ../../..
pip install pytest-cov
pip install coveralls
- name: Create coverage report
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ jobs:
python -m pip install --upgrade pip
python -m pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
python setup.py develop
python setup.py build_cannonsim
python -m pip install --editable .
cd tests/cannonsim/src; make; cd ../../..
pip install pytest-cov
pip install coveralls
- name: Lint with flake8
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,3 @@ pep.sh
*.csv
env/
.ipynb_checkpoints/
fusion_pce.*/
9 changes: 2 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,11 @@ git clone https://github.com/UCL-CCS/EasyVVUQ.git

Note: As above, you need to be sure you are installing for Python 3 - if necessary replace `pip` with `pip3` and `python` with `python3` in the commands below.

We are trying to keep dependencies at a minimum but a few are inevitable, to install them use:
We are trying to keep dependencies at a minimum but a few are inevitable, to install these, install the EasyVVUQ library itself and build a test case use:
```
cd EasyVVUQ/

pip install --use-feature=2020-resolver -r requirements.txt
```

Then the library can be installed using:
```buildoutcfg
python setup.py install
bash install_EasyVVUQ.sh
```

## API
Expand Down
33 changes: 16 additions & 17 deletions easyvvuq/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,23 +138,22 @@ def git_get_keywords(versionfile_abs):
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
with open(versionfile_abs, "r") as f:
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
except EnvironmentError:
pass
if os.getenv("EasyVVUQ_Debug"): print('EnvironmentError raised and ignored')
return keywords


Expand Down Expand Up @@ -513,7 +512,7 @@ def get_versions():
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
if os.getenv("EasyVVUQ_Debug"): print('NotThisMethod raised and ignored')

return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
Expand Down
6 changes: 5 additions & 1 deletion easyvvuq/actions/execute_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def start(self, previous=None):
try:
previous['encoder_filename'] = self.encoder.target_filename
except AttributeError:
pass
if os.getenv("EasyVVUQ_Debug"): print('AttributeError raised and ignored')
return previous

def finished(self):
Expand Down Expand Up @@ -233,6 +233,8 @@ def start(self, previous=None):
self.ret = subprocess.run(
self.full_cmd, cwd=target_dir,
stdout=stdout, stderr=stderr)
if isinstance(self.stdout, str): close(stdout)
if isinstance(self.stderr, str): close(stderr)
return previous

def finished(self):
Expand All @@ -241,6 +243,8 @@ def finished(self):
def finalise(self):
"""Performs clean-up if necessary. In this case it isn't. I think.
"""
stdout.close()
stderr.close()
pass

def succeeded(self):
Expand Down
4 changes: 1 addition & 3 deletions easyvvuq/analysis/mcmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ def plot_hist(self, input_parameter, chain=None, skip=0, merge=True):
input_parameter = (input_parameter, 0)
if merge:
chain_keys = list(self.chains.keys())
df = self.chains[chain_keys[0]][input_parameter].iloc[skip:]
for chain in chain_keys[1:]:
df.append(self.chains[chain][input_parameter].iloc[skip:])
df = pd.concat([self.chains[ck][input_parameter].iloc[skip:] for ck in chain_keys])
plt.hist(df, 20)
else:
plt.hist(self.chains[chain][input_parameter].iloc[skip:], 20)
Expand Down
12 changes: 5 additions & 7 deletions easyvvuq/db/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@
import numpy as np
from sqlalchemy.sql import case
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import text
from sqlalchemy.engine import Engine
from sqlalchemy import event
Expand Down Expand Up @@ -321,7 +319,7 @@ def update_sampler(self, sampler_id, sampler_element):
The sampler that should be used as the new state
"""

selected = self.session.query(SamplerTable).get(sampler_id)
selected = self.session.get(SamplerTable,sampler_id)
selected.sampler = easyvvuq_serialize(sampler_element)
self.session.commit()

Expand All @@ -340,7 +338,7 @@ def resurrect_sampler(self, sampler_id):
The 'live' sampler object, deserialized from the state in the db
"""
try:
serialized_sampler = self.session.query(SamplerTable).get(sampler_id).sampler
serialized_sampler = self.session.get(SamplerTable,sampler_id).sampler
sampler = easyvvuq_deserialize(serialized_sampler.encode('utf-8'))
except AttributeError:
sampler = None
Expand Down Expand Up @@ -581,7 +579,7 @@ def get_sampler_id(self, campaign_id):
int
The id of the sampler set for the specified campaign
"""
sampler_id = self.session.query(CampaignTable).get(campaign_id).sampler
sampler_id = self.session.get(CampaignTable,campaign_id).sampler
return sampler_id

def set_sampler(self, campaign_id, sampler_id):
Expand All @@ -594,7 +592,7 @@ def set_sampler(self, campaign_id, sampler_id):
sampler_id: int
ID of the sampler.
"""
self.session.query(CampaignTable).get(campaign_id).sampler = sampler_id
self.session.get(CampaignTable,campaign_id).sampler = sampler_id
self.session.commit()

def campaign_dir(self, campaign_name=None):
Expand Down
2 changes: 1 addition & 1 deletion easyvvuq/encoders/jinja_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def encode(self, params={}, target_dir=''):
try:
with open(self.template_fname, 'r') as template_file:
template_txt = template_file.read()
self.template = Template(template_txt)
self.template = Template(template_txt, autoescape=True)
except FileNotFoundError:
raise RuntimeError(
"the template file specified ({}) does not exist".format(self.template_fname))
Expand Down
4 changes: 1 addition & 3 deletions easyvvuq/sampling/mc_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ def __init__(self, vary, n_mc_samples, **kwargs):
None.

"""
super().__init__(vary=vary, max_num=n_mc_samples, **kwargs)
super().__init__(vary=vary, count=0, max_num=n_mc_samples, **kwargs)
# the number of uncertain inputs
self.n_params = len(vary)
# the number of MC samples, for each of the n_params + 2 input matrices
self.n_mc_samples = n_mc_samples
self.vary = Vary(vary)
self.count = 0
# joint distribution
self.joint = cp.J(*list(vary.values()))
# create the Saltelli sampling plan
Expand Down
6 changes: 3 additions & 3 deletions easyvvuq/sampling/mcmc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .base import BaseSamplingElement
import numpy as np

import os

class MCMCSampler(BaseSamplingElement, sampler_name='mcmc_sampler'):
"""A Metropolis-Hastings MCMC Sampler.
Expand Down Expand Up @@ -142,12 +142,12 @@ def update(self, result, invalid):
ignored_runs += list(result.loc[result[('chain_id', 0)]
== chain_id]['run_id'].values)
except KeyError:
pass
if os.getenv("EasyVVUQ_Debug"): print('KeyError raised and ignored')
try:
ignored_runs += list(invalid.loc[invalid[('chain_id', 0)]
== chain_id]['run_id'].values)
except KeyError:
pass
if os.getenv("EasyVVUQ_Debug"): print('KeyError raised and ignored')
ignored_runs = [run[0] for run in ignored_runs]
self.iteration += 1
return ignored_runs
Expand Down
5 changes: 3 additions & 2 deletions easyvvuq/sampling/qmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"""

import chaospy as cp
from SALib.sample import saltelli
from SALib.sample import sobol
#from SALib.sample import saltelli
from .base import BaseSamplingElement, Vary
import logging

Expand Down Expand Up @@ -80,7 +81,7 @@ def __init__(self, vary, n_mc_samples, count=0):
"bounds": [[0, 1]] * self.n_params
}

nodes = saltelli.sample(problem, n_mc_samples, calc_second_order=False)
nodes = sobol.sample(problem, n_mc_samples, calc_second_order=False,scramble=True)

self._samples = self.distribution.inv(dist_U.fwd(nodes.transpose()))

Expand Down
13 changes: 13 additions & 0 deletions install_EasyVVUQ.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#1) Install Requirements
echo 'Install Requirements'
pip install -r requirements.txt

#2) Install EasyVVUQ
echo 'Installing EasyVVUQ'
python -m pip install .

#3) Build cannonsim test
echo 'Building cannonsim'
cd tests/cannonsim/src
make
cd ../../..
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ dill
tqdm
qcg-pilotjob~=0.13.0
qcg-pilotjob-executor-api~=0.13.0
h5py
h5py
tomli
fipy
35 changes: 0 additions & 35 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,6 @@
import versioneer
import subprocess


class BuildCannonsimCommand(distutils.cmd.Command):
description = 'build cannonsim'
user_options = []

def initialize_options(self):
pass

def finalize_options(self):
pass

def run(self):
self.announce('Building cannonsim')
subprocess.check_call(['make'], cwd=path.abspath('./tests/cannonsim/src'))


class BuildNotebooks(distutils.cmd.Command):
description = 'build tutorials as Jupyter notebooks'
user_options = []

def initialize_options(self):
pass

def finalize_options(self):
pass

def run(self):
self.announce('Building tutorial as Jupyter notebooks')
tutorials = ['basic_tutorial.rst', 'cooling_coffee_cup.rst']
for tutorial in tutorials:
subprocess.check_call(['rst2ipynb', tutorial, '-o', path.splitext(tutorial)[0] + '.ipynb'], cwd=path.abspath('./docs'))


class BuildPyCommand(setuptools.command.build_py.build_py):
def run(self):
setuptools.command.build_py.build_py.run(self)
Expand All @@ -48,8 +15,6 @@ def run(self):
long_description = f.read()

cmdclass = versioneer.get_cmdclass()
cmdclass['build_cannonsim'] = BuildCannonsimCommand
cmdclass['build_notebooks'] = BuildNotebooks
cmdclass['build_py'] = BuildPyCommand

setup(
Expand Down
Loading
Loading