input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>sarah-hanus/massbalance-sandbox
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 12:28:37 2020
@author: lilianschuster
different temperature index mass balance types added that are working with the Huss flowlines
this is the faster version
"""
# jax_true = True
# if jax_true:
# import jax.numpy as np
# import numpy as onp
# else: problem: nan values, where stuff ...
import numpy as np
from scipy.interpolate import interp1d
import pandas as pd
import xarray as xr
import os
import netCDF4
import datetime
import warnings
import scipy.stats as stats
import logging
import copy
# import oggm
# imports from oggm
from oggm import entity_task
from oggm import cfg, utils
from oggm.cfg import SEC_IN_YEAR, SEC_IN_MONTH, SEC_IN_DAY
from oggm.utils import (floatyear_to_date, date_to_floatyear, ncDataset,
lazy_property, monthly_timeseries,
clip_min, clip_array)
from oggm.utils._funcs import haversine
from oggm.utils._workflow import global_task
from oggm.exceptions import InvalidParamsError, InvalidWorkflowError
from oggm.shop.ecmwf import get_ecmwf_file, BASENAMES
from oggm.core.massbalance import MassBalanceModel
# Module logger
log = logging.getLogger(__name__)
ECMWF_SERVER = 'https://cluster.klima.uni-bremen.de/~oggm/climate/'
# %%
# add era5_daily dataset, this only works with process_era5_daily_data
BASENAMES['ERA5_daily'] = {
'inv': 'era5/daily/v1.0/era5_glacier_invariant_flat.nc',
'tmp': 'era5/daily/v1.0/era5_daily_t2m_1979-2018_flat.nc'
# only glacier-relevant gridpoints included!
}
BASENAMES['WFDE5_CRU_daily'] = {
'inv': 'wfde5_cru/daily/v1.1/wfde5_cru_glacier_invariant_flat.nc',
'tmp': 'wfde5_cru/daily/v1.1/wfde5_cru_tmp_1979-2018_flat.nc',
'prcp': 'wfde5_cru/daily/v1.1/wfde5_cru_prcp_1979-2018_flat.nc',
}
BASENAMES['W5E5_daily'] = {
'inv': 'w5e5v2.0/flattened/daily/w5e5v2.0_glacier_invariant_flat.nc',
'tmp': 'w5e5v2.0/flattened/daily/w5e5v2.0_tas_global_daily_flat_glaciers_1979_2019.nc',
'prcp': 'w5e5v2.0/flattened/daily/w5e5v2.0_pr_global_daily_flat_glaciers_1979_2019.nc',
}
BASENAMES['MSWEP_daily'] = {
'prcp': 'mswepv2.8/flattened/daily/mswep_pr_global_daily_flat_glaciers_1979_2019.nc'
# there is no orography file for MSWEP!!! (and also no temperature file)
}
BASENAMES['W5E5_daily_dw'] = {
'inv': 'ISIMIP3a/flattened/daily/gswp3-w5e5_obsclim_glacier_invariant_flat.nc',
'tmp': 'ISIMIP3a/flattened/daily/gswp3-w5e5_obsclim_tas_global_daily_flat_glaciers_1979_2019.nc',
'prcp': 'ISIMIP3a/flattened/daily/gswp3-w5e5_obsclim_pr_global_daily_flat_glaciers_1979_2019.nc',
}
def get_w5e5_file(dataset='W5E5_daily', var=None,
server='https://cluster.klima.uni-bremen.de/~lschuster/'):
"""returns a path to desired WFDE5_CRU or W5E5 or MSWEP
baseline climate file.
If the file is not present, downloads it
... copy of get_ecmwf_file but with different ECMWF_SERVER ...
"""
# Be sure input makes sense
if dataset not in BASENAMES.keys():
raise InvalidParamsError('ECMWF dataset {} not '
'in {}'.format(dataset, BASENAMES.keys()))
if var not in BASENAMES[dataset].keys():
raise InvalidParamsError('ECMWF variable {} not '
'in {}'.format(var,
BASENAMES[dataset].keys()))
# File to look for
return utils.file_downloader(server + BASENAMES[dataset][var])
def write_climate_file(gdir, time, prcp, temp,
ref_pix_hgt, ref_pix_lon, ref_pix_lat,
ref_pix_lon_pr=None, ref_pix_lat_pr=None,
gradient=None, temp_std=None,
time_unit=None, calendar=None,
source=None, long_source=None,
file_name='climate_historical',
filesuffix='',
temporal_resol='monthly'):
"""Creates a netCDF4 file with climate data timeseries.
this could be used in general
Parameters
----------
gdir:
glacier directory
time : ndarray
the time array, in a format understood by netCDF4
prcp : ndarray
the precipitation array (unit: 'kg m-2')
temp : ndarray
the temperature array (unit: 'degC')
ref_pix_hgt : float
the elevation of the dataset's reference altitude
(for correction). In practice it is the same altitude as the
baseline climate (if MSWEP prcp used, only of temp. climate file).
ref_pix_lon : float
the location of the gridded data's grid point
(if MSWEP prcp used, only of temp. climate file)
ref_pix_lat : float
the location of the gridded data's grid point
(if MSWEP prcp used, only of temp. climate file)
ref_pix_lon_pr : float
default is None, only if MSWEP prcp used, it is the
location of the gridded prcp data grid point
ref_pix_lat_pr : float
default is None, only if MSWEP prcp used, it is the
location of the gridded prcp data grid point
gradient : ndarray, optional
whether to use a time varying gradient
temp_std : ndarray, optional
the daily standard deviation of temperature (useful for PyGEM)
time_unit : str
the reference time unit for your time array. This should be chosen
depending on the length of your data. The default is to choose
it ourselves based on the starting year.
calendar : str
If you use an exotic calendar (e.g. 'noleap')
source : str
the climate data source (required)
long_source : str
the climate data source describing origin of
temp, prpc and lapse rate in detail
file_name : str
How to name the file
filesuffix : str
Apply a suffix to the file
temporal_resol : str
temporal resolution of climate file, either monthly (default) or
daily
"""
if source == 'ERA5_daily' and filesuffix == '':
raise InvalidParamsError("filesuffix should be '_daily' for ERA5_daily"
"file_name climate_historical is normally"
"monthly data")
elif (source == 'WFDE5_CRU_daily' and filesuffix == ''
and temporal_resol == 'daily'):
raise InvalidParamsError("filesuffix should be '_daily' for WFDE5_CRU_daily"
"if daily chosen as temporal_resol"
"file_name climate_historical is normally"
"monthly data")
elif (source == 'W5E5_daily' and filesuffix == ''
and temporal_resol == 'daily'):
raise InvalidParamsError("filesuffix should be '_daily' for W5E5_daily"
"if daily chosen as temporal_resol"
"file_name climate_historical is normally"
"monthly data")
if long_source is None:
long_source = source
if 'MSWEP' in long_source:
prcp_from_mswep = True
else:
prcp_from_mswep = False
# overwrite is default
fpath = gdir.get_filepath(file_name, filesuffix=filesuffix)
if os.path.exists(fpath):
os.remove(fpath)
if source is None:
raise InvalidParamsError('`source` kwarg is required')
zlib = cfg.PARAMS['compress_climate_netcdf']
try:
y0 = time[0].year
y1 = time[-1].year
except AttributeError:
time = pd.DatetimeIndex(time)
y0 = time[0].year
y1 = time[-1].year
if time_unit is None:
# http://pandas.pydata.org/pandas-docs/stable/timeseries.html
# #timestamp-limitations
if y0 > 1800:
time_unit = 'days since 1801-01-01 00:00:00'
elif y0 >= 0:
time_unit = ('days since {:04d}-01-01 '
'00:00:00'.format(time[0].year))
else:
raise InvalidParamsError('Time format not supported')
with ncDataset(fpath, 'w', format='NETCDF4') as nc:
# these are only valid for temperature if MSWEP prcp is used!!!
nc.ref_hgt = ref_pix_hgt
nc.ref_pix_lon = ref_pix_lon
nc.ref_pix_lat = ref_pix_lat
nc.ref_pix_dis = haversine(gdir.cenlon, gdir.cenlat,
ref_pix_lon, ref_pix_lat)
if prcp_from_mswep:
# there is no reference height given!!!
if ref_pix_lon_pr is None or ref_pix_lat_pr is None:
raise InvalidParamsError('if MSWEP is used for prcp, need to add'
'precipitation lon/lat gridpoints')
nc.ref_pix_lon_pr = np.round(ref_pix_lon_pr,3)
nc.ref_pix_lat_pr = np.round(ref_pix_lat_pr,3)
nc.climate_source = long_source
if time[0].month == 1:
nc.hydro_yr_0 = y0
else:
nc.hydro_yr_0 = y0 + 1
nc.hydro_yr_1 = y1
nc.createDimension('time', None)
nc.author = 'OGGM'
nc.author_info = 'Open Global Glacier Model'
timev = nc.createVariable('time', 'i4', ('time',))
tatts = {'units': time_unit}
if calendar is None:
calendar = 'standard'
tatts['calendar'] = calendar
try:
numdate = netCDF4.date2num([t for t in time], time_unit,
calendar=calendar)
except TypeError:
# numpy's broken datetime only works for us precision
time = time.astype('M8[us]').astype(datetime.datetime)
numdate = netCDF4.date2num(time, time_unit, calendar=calendar)
timev.setncatts(tatts)
timev[:] = numdate
v = nc.createVariable('prcp', 'f4', ('time',), zlib=zlib)
v.units = 'kg m-2'
# this could be made more beautriful
# just rough estimate
if (len(prcp) > (nc.hydro_yr_1 - nc.hydro_yr_0 + 1) * 28 * 12 and
temporal_resol == 'daily'):
if source == 'ERA5_daily':
v.long_name = ("total daily precipitation amount, "
"assumed same for each day of month")
elif source == 'WFDE5_daily_cru':
v.long_name = ("total daily precipitation amount"
"sum of snowfall and rainfall")
elif source == 'W5E5_daily' and not prcp_from_mswep:
v.long_name = ("total daily precipitation amount")
elif source == 'W5E5_daily' and prcp_from_mswep:
v.long_name = ("total daily precipitation amount, "
"1979-01-01 prcp assumed to be equal to 1979-01-02"
"due to missing data, MSWEP prcp with 0.1deg resolution"
"(finer than temp. data), so refpixhgt, "
"refpixlon and refpixlat not valid for prcp data!!!")
elif (len(prcp) == (nc.hydro_yr_1 - nc.hydro_yr_0 + 1) * 12
and temporal_resol == 'monthly' and not prcp_from_mswep):
v.long_name = 'total monthly precipitation amount'
elif (len(prcp) == (nc.hydro_yr_1 - nc.hydro_yr_0 + 1) * 12
and temporal_resol == 'monthly' and prcp_from_mswep):
v.long_name = ("total monthly precipitation amount, MSWEP prcp with 0.1deg resolution"
"(finer than temp. data), so refpixhgt, "
"refpixlon and refpixlat not valid for prcp data!!!")
else:
raise InvalidParamsError('there is a conflict in the'
'prcp timeseries, '
'please check temporal_resol')
# just to check that it is in kg m-2 per day or per month and not in per second
assert prcp.max() > 1
v[:] = prcp
# check that there are no filling values inside
assert np.all(v[:].data < 1e5)
v = nc.createVariable('temp', 'f4', ('time',), zlib=zlib)
v.units = 'degC'
if ((source == 'ERA5_daily' or source == 'WFDE5_daily_cru' or source =='W5E5_daily') and
len(temp) > (y1 - y0) * 28 * 12 and temporal_resol == 'daily'):
v.long_name = '2m daily temperature at height ref_hgt'
elif source == 'ERA5_daily' and len(temp) <= (y1 - y0) * 30 * 12:
raise InvalidParamsError('if the climate dataset (here source)'
'is ERA5_daily, temperatures should be in'
'daily resolution, please check or set'
'set source to another climate dataset')
elif (source == 'WFDE5_daily_cru' and temporal_resol == 'monthly' and
len(temp) > (y1 - y0) * 28 * 12):
raise InvalidParamsError('something wrong in the implementation')
else:
v.long_name = '2m monthly temperature at height ref_hgt'
v[:] = temp
# no filling values!
assert np.all(v[:].data < 1e5)
if gradient is not None:
v = nc.createVariable('gradient', 'f4', ('time',), zlib=zlib)
| |
False]
[ True True True True True True True True]
[ True True True True True True True True]],
fill_value = 1e+20)
>>> img['IMG'].data[4]
Out[10]:
masked_BaseColumn(data =
[[-- -- -- -- -- -- -- --]
[-- -- -- -- -- -- -- --]
[-- -- -- -- -- -- -- --]
[-- -- -- -- -- -- -- --]
[-- -- -- -- -- -- -- --]
[-- -- -- -- -- -- -- --]
[67.0 61.0 67.0 176.0 99.0 72.0 79.0 88.0]
[70.0 62.0 101.0 149.0 163.0 89.0 60.0 76.0]],
mask =
[[ True True True True True True True True]
[ True True True True True True True True]
[ True True True True True True True True]
[ True True True True True True True True]
[ True True True True True True True True]
[ True True True True True True True True]
[False False False False False False False False]
[False False False False False False False False]],
fill_value = 1e+20)
:param start: timestamp interpreted as a Chandra.Time.DateTime
:param stop: timestamp interpreted as a Chandra.Time.DateTime
:param level0: bool.
Implies combine=True, adjust_time=True, calibrate=True
:param combine: bool.
If True, multiple ACA packets are combined to form an image (depending on size),
If False, ACA packets are not combined, resulting in multiple lines for 6x6 and 8x8 images.
:param adjust_time: bool
If True, half the integration time is subtracted
:param calibrate: bool
If True, pixel values will be 'value * imgscale / 32 - 50' and temperature values will
be: 0.4 * value + 273.15
:param blobs: bool or dict
If set, data is assembled from MAUDE blobs. If it is a dictionary, it must be the
output of maude.get_blobs ({'blobs': ... }).
:param frames: bool or dict
If set, data is assembled from MAUDE frames. If it is a dictionary, it must be the
output of maude.get_frames ({'data': ... }).
:param dtype: np.dtype. Optional.
the dtype to use when creating the resulting table. This is useful to add columns
including MSIDs that are present in blobs. If used with frames, most probably you will get
and empty column. This option is intended to augment the default dtype. If a more
restrictive dtype is used, a KeyError can be raised.
:param maude_kwargs: keyword args passed to maude
:return: astropy.table.Table
"""
if not blobs and not frames:
frames = True
assert (blobs and not frames) or (frames and not blobs), "Specify only one of 'frames' or blobs"
if level0:
adjust_time = True
combine = True
calibrate = True
date_start, date_stop = DateTime(start), DateTime(stop) # ensure input is proper date
if 24 * (date_stop - date_start) > 3:
raise ValueError(f'Requested {24 * (date_stop - date_start)} hours of telemetry. '
'Maximum allowed is 3 hours at a time')
stop_pad = 0
if adjust_time:
stop_pad += 2. / 86400 # time will get shifted...
if combine:
stop_pad += 3.08 / 86400 # there can be trailing frames
if frames:
n = int(np.ceil(86400 * (date_stop - date_start) / 300))
dt = (date_stop - date_start) / n
batches = [(date_start + i * dt, date_start + (i + 1) * dt) for i in range(n)] # 0.0001????
aca_packets = []
for t1, t2 in batches:
maude_result = frames if type(frames) is dict and 'data' in frames else None
raw_aca_packets = get_raw_aca_packets(t1, t2 + stop_pad,
maude_result=maude_result,
**maude_kwargs)
packets = _get_aca_packets(
raw_aca_packets, t1, t2,
combine=combine, adjust_time=adjust_time, calibrate=calibrate, dtype=dtype
)
aca_packets.append(packets)
aca_data = vstack(aca_packets)
else:
maude_result = frames if type(frames) is dict and 'data' in frames else None
merged_blobs = get_raw_aca_blobs(date_start, date_stop,
maude_result=maude_result,
**maude_kwargs)['blobs']
aca_packets = [[blob_to_aca_image_dict(b, i) for b in merged_blobs] for i in range(8)]
aca_data = _get_aca_packets(aca_packets, date_start, date_stop + stop_pad,
combine=combine, adjust_time=adjust_time, calibrate=calibrate,
blobs=True,
dtype=dtype)
return aca_data
def _get_aca_packets(aca_packets, start, stop,
combine=False, adjust_time=False, calibrate=False,
blobs=False, dtype=None):
"""
This is a convenience function that splits get_aca_packets for testing without MAUDE.
Same arguments as get_aca_packets plus aca_packets, the raw ACA 225-byte packets.
NOTE: This function has a side effect. It adds decom_packets to the input aca_packets.
"""
start, stop = DateTime(start), DateTime(stop) # ensure input is proper date
if not blobs:
# this adds TIME, MJF, MNF and VCDUCTR, which is already there in the blob dictionary
aca_packets['decom_packets'] = [unpack_aca_telemetry(a) for a in aca_packets['packets']]
for i in range(len(aca_packets['decom_packets'])):
for j in range(8):
aca_packets['decom_packets'][i][j]['TIME'] = aca_packets['TIME'][i]
aca_packets['decom_packets'][i][j]['MJF'] = aca_packets['MJF'][i]
aca_packets['decom_packets'][i][j]['MNF'] = aca_packets['MNF'][i]
if 'VCDUCTR' in aca_packets:
aca_packets['decom_packets'][i][j]['VCDUCTR'] = aca_packets['VCDUCTR'][i]
aca_packets['decom_packets'][i][j]['IMGNUM'] = j
aca_packets = [[f[i] for f in aca_packets['decom_packets']] for i in range(8)]
if combine:
aca_packets = sum([[_combine_aca_packets(g) for g in _group_packets(p)]
for p in aca_packets], [])
else:
aca_packets = [_combine_aca_packets([row]) for slot in aca_packets for row in slot]
table = _aca_packets_to_table(aca_packets, dtype=dtype)
if calibrate:
for k in ['TEMPCCD', 'TEMPSEC', 'TEMPHOUS', 'TEMPPRIM']:
table[k] = 0.4 * table[k].astype(np.float32) + 273.15
# IMGROW0/COL0 are actually the row/col of pixel A1, so we just copy them
table['IMGROW_A1'] = table['IMGROW0']
table['IMGCOL_A1'] = table['IMGCOL0']
# if the image is embedded in an 8x8 image, row/col of the 8x8 shifts for sizes 4x4 and 6x6
table['IMGROW0_8X8'] = table['IMGROW_A1']
table['IMGCOL0_8X8'] = table['IMGCOL_A1']
table['IMGROW0_8X8'][table['IMGTYPE'] < 4] -= 2
table['IMGCOL0_8X8'][table['IMGTYPE'] < 4] -= 2
# and the usual row/col needs to be adjusted only for 6x6 images
table['IMGROW0'][table['IMGTYPE'] == 1] -= 1
table['IMGCOL0'][table['IMGTYPE'] == 1] -= 1
table['IMGROW0'][table['IMGTYPE'] == 2] -= 1
table['IMGCOL0'][table['IMGTYPE'] == 2] -= 1
if adjust_time:
table['INTEG'] = table['INTEG'] * 0.016
table['TIME'] -= table['INTEG'] / 2 + 1.025
table['END_INTEG_TIME'] = table['TIME'] + table['INTEG'] / 2
if calibrate:
if 'IMG' in table.colnames:
table['IMG'] = table['IMG'] * table['IMGSCALE'][:, np.newaxis, np.newaxis] / 32 - 50
table = table[(table['TIME'] >= start.secs) * (table['TIME'] < stop.secs)]
if dtype:
table = table[dtype.names]
return table
def get_aca_images(start, stop, **maude_kwargs):
"""
Fetch ACA image telemetry
:param start: timestamp interpreted as a Chandra.Time.DateTime
:param stop: timestamp interpreted as a Chandra.Time.DateTime
:param maude_kwargs: keyword args passed to maude
:return: astropy.table.Table
"""
return get_aca_packets(start, stop, level0=True, **maude_kwargs)
######################
# blob-based functions
######################
def get_raw_aca_blobs(start, stop, maude_result=None, **maude_kwargs):
"""
Fetch MAUDE blobs and group them according to the underlying 225-byte ACA packets.
If the first minor frame in a group of four ACA packets is within (start, stop),
the three following minor frames are included if present.
returns a dictionary with keys ['TIME', 'MNF', 'MJF', 'packets', 'flags'].
These correspond to the minor frame time, minor frame count, major frame count,
the list of packets, and flags returned by MAUDE respectively.
This is to blobs what `get_raw_aca_packets` is to frames.
:param start: timestamp interpreted as a Chandra.Time.DateTime
:param stop: timestamp interpreted as a Chandra.Time.DateTime
:param maude_result: the result of calling maude.get_blobs. Optional.
:param maude_kwargs: keyword args passed to maude.get_frames()
:return: dict
{'blobs': [], 'names': np.array([]), 'types': np.array([])}
"""
date_start, date_stop = DateTime(start), DateTime(stop) # ensure input is proper date
stop_pad = 1.5 / 86400 # padding at the end in case of trailing partial ACA packets
if maude_result is None:
maude_blobs = maude.get_blobs(start=date_start,
stop=date_stop + stop_pad,
**maude_kwargs)
else:
maude_blobs = maude_result
aca_block_start = [ACA_SLOT_MSID_LIST[1][3]['sizes'] in [c['n']for c in b['values']]
for b in maude_blobs['blobs']]
if not np.any(aca_block_start):
maude_blobs['blobs'] = []
return maude_blobs
maude_blobs['blobs'] = maude_blobs['blobs'][np.argwhere(aca_block_start).min():]
if len(maude_blobs['blobs']) % 4:
maude_blobs['blobs'] = maude_blobs['blobs'][:-(len(maude_blobs['blobs']) % 4)]
for b in maude_blobs['blobs']:
b['values'] = {v['n']: v['v'] for v in b['values']}
merged_blobs = []
for i in range(0, len(maude_blobs['blobs']), 4):
b = {'time': maude_blobs['blobs'][i]['time']}
# blobs are merged in reverse order so the frame counters are the one in the first blob.
for j in range(4)[::-1]:
b.update(maude_blobs['blobs'][i + j]['values'])
merged_blobs.append(b)
result = {
'blobs': [b for b in merged_blobs if b['time'] < date_stop.secs],
'names': maude_blobs['names'],
'types': maude_blobs['types'],
}
return result
def blob_to_aca_image_dict(blob, imgnum, pea=1):
"""
Assemble ACA image MSIDs from a blob into a dictionary.
This does to blobs what unpack_aca_telemetry does to frames, but for a single image.
:param blob:
:param imgnum:
:param pea:
:return:
"""
global_msids = ACA_MSID_LIST[pea]
slot_msids = ACA_SLOT_MSID_LIST[pea][imgnum]
glbstat_bits = np.unpackbits(np.array(blob[global_msids['status']], dtype=np.uint8))
comm_count_bits = | |
3.1.1 ) Age
# Note that Age is a continuous quantity and therefore we can plot it against the Attrition using a boxplot.
# In[ ]:
sns.factorplot(data=df,y='Age',x='Attrition',size=5,aspect=1,kind='box')
# Note that the median as well the maximum age of the peole with 'No' attrition is higher than that of the 'Yes' category. This shows that peole with higher age have lesser tendency to leave the organisation which makes sense as they may have settled in the organisation.
# #### 3.1.2 ) Department
# Note that both Attrition(Target) as well as the Deaprtment are categorical. In such cases a cross-tabulation is the most reasonable way to analyze the trends; which shows clearly the number of observaftions for each class which makes it easier to analyze the results.
# In[ ]:
df.Department.value_counts()
# In[ ]:
sns.factorplot(data=df,kind='count',x='Attrition',col='Department')
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.Department],margins=True,normalize='index') # set normalize=index to view rowwise %.
# Note that most of the observations corresspond to 'No' as we saw previously also. About 81 % of the people in HR dont want to leave the organisation and only 19 % want to leave. Similar conclusions can be drawn for other departments too from the above cross-tabulation.
# #### 3.1.3 ) Gender
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.Gender],margins=True,normalize='index') # set normalize=index to view rowwise %.
# About 85 % of females want to stay in the organisation while only 15 % want to leave the organisation. All in all 83 % of employees want to be in the organisation with only being 16% wanting to leave the organisation or the company.
# #### 3.1.4 ) Job Level
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.JobLevel],margins=True,normalize='index') # set normalize=index to view rowwise %.
# People in Joblevel 4 have a very high percent for a 'No' and a low percent for a 'Yes'. Similar inferences can be made for other job levels.
# #### 3.1.5 ) Monthly Income
# In[ ]:
sns.factorplot(data=df,kind='bar',x='Attrition',y='MonthlyIncome')
# Note that the average income for 'No' class is quite higher and it is obvious as those earning well will certainly not be willing to exit the organisation. Similarly those employees who are probably not earning well will certainly want to change the company.
# #### 3.1.6 ) Job Satisfaction
# In[ ]:
sns.factorplot(data=df,kind='count',x='Attrition',col='JobSatisfaction')
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.JobSatisfaction],margins=True,normalize='index') # set normalize=index to view rowwise %.
# Note this shows an interesting trend. Note that for higher values of job satisfaction( ie more a person is satisfied with his job) lesser percent of them say a 'Yes' which is quite obvious as highly contented workers will obvioulsy not like to leave the organisation.
# #### 3.1.7 ) Environment Satisfaction
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.EnvironmentSatisfaction],margins=True,normalize='index') # set normalize=index to view rowwise %.
# Again we can notice that the relative percent of 'No' in people with higher grade of environment satisfacftion.
# #### 3.1.8 ) Job Involvement
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.JobInvolvement],margins=True,normalize='index') # set normalize=index to view rowwise %.
# #### 3.1.9 ) Work Life Balance
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.WorkLifeBalance],margins=True,normalize='index') # set normalize=index to view rowwise %.
# Again we notice a similar trend as people with better work life balance dont want to leave the organisation.
# #### 3.1.10 ) RelationshipSatisfaction
# In[ ]:
pd.crosstab(columns=[df.Attrition],index=[df.RelationshipSatisfaction],margins=True,normalize='index') # set normalize=index to view rowwise %.
# ###### Notice that I have plotted just some of the important features against out 'Target' variable i.e. Attrition in our case. Similarly we can plot other features against the 'Target' variable and analye the trends i.e. how the feature effects the 'Target' variable.
# ## 3.2 ) Feature Selection
# The feature Selection is one of the main steps of the preprocessing phase as the features which we choose directly effects the model performance. While some of the features seem to be less useful in terms of the context; others seem to equally useful. The better features we use the better our model will perform.
#
# We can also use the Recusrive Feature Elimination technique (a wrapper method) to choose the desired number of most important features.
# The Recursive Feature Elimination (or RFE) works by recursively removing attributes and building a model on those attributes that remain.
#
# It uses the model accuracy to identify which attributes (and combination of attributes) contribute the most to predicting the target attribute.
#
# We can use it directly from the scikit library by importing the RFE module or function provided by the scikit. But note that since it tries different combinations or the subset of features;it is quite computationally expensive.
# In[ ]:
df.drop(['BusinessTravel','DailyRate','EmployeeCount','EmployeeNumber','HourlyRate','MonthlyRate','NumCompaniesWorked','Over18','StandardHours', 'StockOptionLevel','TrainingTimesLastYear'],axis=1,inplace=True)
#
# <a id="content4"></a>
# ## 4 ) Preparing Dataset
# Before feeding our data into a ML model we first need to prepare the data. This includes encoding all the categorical features (either LabelEncoding or the OneHotEncoding) as the model expects the features to be in numerical form. Also for better performance we will do the feature scaling ie bringing all the features onto the same scale by using the StandardScaler provided in the scikit library.
# ## 4.1 ) Feature Encoding
# I have used the Label Encoder from the scikit library to encode all the categorical features.
# In[ ]:
def transform(feature):
le=LabelEncoder()
df[feature]=le.fit_transform(df[feature])
print(le.classes_)
# In[ ]:
cat_df=df.select_dtypes(include='object')
cat_df.columns
# In[ ]:
for col in cat_df.columns:
transform(col)
# In[ ]:
df.head() # just to verify.
# ## 4.2 ) Feature Scaling
# The scikit library provides various types of scalers including MinMax Scaler and the StandardScaler. Below I have used the StandardScaler to scale the data.
# Note that the neural networks are quite sensitive towards the scale of the features. Hence it is always good to perform feature scaling on the data before feeding it into an Artificial Neural Network.
# In[ ]:
scaler=StandardScaler()
scaled_df=scaler.fit_transform(df.drop('Attrition',axis=1))
X=scaled_df
Y=df['Attrition'].as_matrix()
# ## 4.3 ) One Hot Encoding the Target
# Note that there are two main things to watch out before feeding data into an ANN.
#
# The first is that our data needs to be in the form of numpy arrays (ndarray).
#
# The second that the target variable should be one hot encoded eg 2--> 0010 (assuming 0 based indexing) and so on..
# In this way for a 'n' class classification problems our target variable will have n classes and hence after one hot encoding we shall have n labels with each label corressponding to a particular target class.
# In[ ]:
Y=to_categorical(Y)
Y
# ## 4.4 ) Splitting the data into training and validation sets
# In[ ]:
x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.25,random_state=42)
# <a id="content5"></a>
# ## 5 ) Making Predictions Using an Artificial Neural Network (ANN)
# ## 5.1 ) Handling the Imbalanced dataset
# Note that we have a imbalanced dataset with majority of observations being of one type ('NO') in our case. In this dataset for example we have about 84 % of observations having 'No' and only 16 % of 'Yes' and hence this is an imbalanced dataset.
#
# To deal with such a imbalanced dataset we have to take certain measures, otherwise the performance of our model can be significantly affected. In this section I have discussed two approaches to curb such datasets.
# ## 5.1.1 ) Oversampling the Minority or Undersampling the Majority Class
#
#
# In an imbalanced dataset the main problem is that the data is highly skewed ie the number of observations of certain class is more than that of the other. Therefore what we do in this approach is to either increase the number of observations corressponding to the minority class (oversampling) or decrease the number of observations for the majority class (undersampling).
#
# Note that in our case the number of observations is already pretty low and so oversampling will be more appropriate.
#
# Below I have used an oversampling technique known as the SMOTE(Synthetic Minority Oversampling Technique) which randomly creates some 'Synthetic' instances of the minority class so that the net observations of both the class get balanced out.
#
# One thing more to take of is to use the SMOTE before the cross validation step; just to ensure that our model does not overfit the data; just as in the case of feature selection.
# In[ ]:
# oversampler=SMOTE(random_state=42)
# x_train_smote, y_train_smote = oversampler.fit_sample(x_train,y_train)
# ## 5.1.2 ) Using the Right Evaluation Metric
# Another | |
= weight
self.name = name
@property
def asset_id(self) -> str:
"""Marquee unique identifier"""
return self.__asset_id
@asset_id.setter
def asset_id(self, value: str):
self._property_changed('asset_id')
self.__asset_id = value
@property
def weight(self) -> float:
"""Relative net weight of the given position"""
return self.__weight
@weight.setter
def weight(self, value: float):
self._property_changed('weight')
self.__weight = value
class XRef(Priceable):
@camel_case_translate
def __init__(
self,
ric: str = None,
rcic: str = None,
eid: str = None,
gsideid: str = None,
gsid: str = None,
cid: str = None,
bbid: str = None,
bcid: str = None,
delisted: str = None,
bbid_equivalent: str = None,
cusip: str = None,
gss: str = None,
isin: str = None,
jsn: str = None,
prime_id: str = None,
sedol: str = None,
ticker: str = None,
valoren: str = None,
wpk: str = None,
gsn: str = None,
sec_name: str = None,
cross: str = None,
simon_id: str = None,
em_id: str = None,
cm_id: str = None,
lms_id: str = None,
mdapi: str = None,
mdapi_class: str = None,
mic: str = None,
sf_id: str = None,
dollar_cross: str = None,
mq_symbol: str = None,
primary_country_ric: str = None,
pnode_id: str = None,
name: str = None
):
super().__init__()
self.ric = ric
self.rcic = rcic
self.eid = eid
self.gsideid = gsideid
self.gsid = gsid
self.cid = cid
self.bbid = bbid
self.bcid = bcid
self.delisted = delisted
self.bbid_equivalent = bbid_equivalent
self.cusip = cusip
self.gss = gss
self.isin = isin
self.jsn = jsn
self.prime_id = prime_id
self.sedol = sedol
self.ticker = ticker
self.valoren = valoren
self.wpk = wpk
self.gsn = gsn
self.sec_name = sec_name
self.cross = cross
self.simon_id = simon_id
self.em_id = em_id
self.cm_id = cm_id
self.lms_id = lms_id
self.mdapi = mdapi
self.mdapi_class = mdapi_class
self.mic = mic
self.sf_id = sf_id
self.dollar_cross = dollar_cross
self.mq_symbol = mq_symbol
self.primary_country_ric = primary_country_ric
self.pnode_id = pnode_id
self.name = name
@property
def ric(self) -> str:
"""Reuters Instrument Code identifier"""
return self.__ric
@ric.setter
def ric(self, value: str):
self._property_changed('ric')
self.__ric = value
@property
def rcic(self) -> str:
"""Reuters Composite Instrument Code Identifier"""
return self.__rcic
@rcic.setter
def rcic(self, value: str):
self._property_changed('rcic')
self.__rcic = value
@property
def eid(self) -> str:
"""EID Identifier"""
return self.__eid
@eid.setter
def eid(self, value: str):
self._property_changed('eid')
self.__eid = value
@property
def gsideid(self) -> str:
"""GSID_EID Identifier"""
return self.__gsideid
@gsideid.setter
def gsideid(self, value: str):
self._property_changed('gsideid')
self.__gsideid = value
@property
def gsid(self) -> str:
"""GSID Identifier"""
return self.__gsid
@gsid.setter
def gsid(self, value: str):
self._property_changed('gsid')
self.__gsid = value
@property
def cid(self) -> str:
"""Company Id Identifier"""
return self.__cid
@cid.setter
def cid(self, value: str):
self._property_changed('cid')
self.__cid = value
@property
def bbid(self) -> str:
"""Bloomberg Id Identifier"""
return self.__bbid
@bbid.setter
def bbid(self, value: str):
self._property_changed('bbid')
self.__bbid = value
@property
def bcid(self) -> str:
"""Bloomberg Composite Identifier"""
return self.__bcid
@bcid.setter
def bcid(self, value: str):
self._property_changed('bcid')
self.__bcid = value
@property
def delisted(self) -> str:
"""Whether an asset has been delisted"""
return self.__delisted
@delisted.setter
def delisted(self, value: str):
self._property_changed('delisted')
self.__delisted = value
@property
def bbid_equivalent(self) -> str:
"""Bloomberg Equivalent Identifier"""
return self.__bbid_equivalent
@bbid_equivalent.setter
def bbid_equivalent(self, value: str):
self._property_changed('bbid_equivalent')
self.__bbid_equivalent = value
@property
def cusip(self) -> str:
"""Cusip Identifier"""
return self.__cusip
@cusip.setter
def cusip(self, value: str):
self._property_changed('cusip')
self.__cusip = value
@property
def gss(self) -> str:
"""GS Symbol identifier"""
return self.__gss
@gss.setter
def gss(self, value: str):
self._property_changed('gss')
self.__gss = value
@property
def isin(self) -> str:
"""International Security Number"""
return self.__isin
@isin.setter
def isin(self, value: str):
self._property_changed('isin')
self.__isin = value
@property
def jsn(self) -> str:
"""Japan Security Number"""
return self.__jsn
@jsn.setter
def jsn(self, value: str):
self._property_changed('jsn')
self.__jsn = value
@property
def prime_id(self) -> str:
"""PrimeID Identifier"""
return self.__prime_id
@prime_id.setter
def prime_id(self, value: str):
self._property_changed('prime_id')
self.__prime_id = value
@property
def sedol(self) -> str:
"""Sedol Identifier"""
return self.__sedol
@sedol.setter
def sedol(self, value: str):
self._property_changed('sedol')
self.__sedol = value
@property
def ticker(self) -> str:
"""Ticker Identifier"""
return self.__ticker
@ticker.setter
def ticker(self, value: str):
self._property_changed('ticker')
self.__ticker = value
@property
def valoren(self) -> str:
"""Valoren Identifier"""
return self.__valoren
@valoren.setter
def valoren(self, value: str):
self._property_changed('valoren')
self.__valoren = value
@property
def wpk(self) -> str:
"""Wertpapier Kenn-Nummer"""
return self.__wpk
@wpk.setter
def wpk(self, value: str):
self._property_changed('wpk')
self.__wpk = value
@property
def gsn(self) -> str:
"""Goldman Sachs internal product number"""
return self.__gsn
@gsn.setter
def gsn(self, value: str):
self._property_changed('gsn')
self.__gsn = value
@property
def sec_name(self) -> str:
"""Internal Goldman Sachs security name"""
return self.__sec_name
@sec_name.setter
def sec_name(self, value: str):
self._property_changed('sec_name')
self.__sec_name = value
@property
def cross(self) -> str:
"""Cross identifier"""
return self.__cross
@cross.setter
def cross(self, value: str):
self._property_changed('cross')
self.__cross = value
@property
def simon_id(self) -> str:
"""SIMON product identifier"""
return self.__simon_id
@simon_id.setter
def simon_id(self, value: str):
self._property_changed('simon_id')
self.__simon_id = value
@property
def em_id(self) -> str:
"""Entity Master Identifier"""
return self.__em_id
@em_id.setter
def em_id(self, value: str):
self._property_changed('em_id')
self.__em_id = value
@property
def cm_id(self) -> str:
"""Client Master Party Id"""
return self.__cm_id
@cm_id.setter
def cm_id(self, value: str):
self._property_changed('cm_id')
self.__cm_id = value
@property
def lms_id(self) -> str:
"""Listed Market Symbol"""
return self.__lms_id
@lms_id.setter
def lms_id(self, value: str):
self._property_changed('lms_id')
self.__lms_id = value
@property
def mdapi(self) -> str:
"""MDAPI Asset"""
return self.__mdapi
@mdapi.setter
def mdapi(self, value: str):
self._property_changed('mdapi')
self.__mdapi = value
@property
def mdapi_class(self) -> str:
"""MDAPI Asset Class"""
return self.__mdapi_class
@mdapi_class.setter
def mdapi_class(self, value: str):
self._property_changed('mdapi_class')
self.__mdapi_class = value
@property
def mic(self) -> str:
"""Market Identifier Code"""
return self.__mic
@mic.setter
def mic(self, value: str):
self._property_changed('mic')
self.__mic = value
@property
def sf_id(self) -> str:
"""SalesForce ID"""
return self.__sf_id
@sf_id.setter
def sf_id(self, value: str):
self._property_changed('sf_id')
self.__sf_id = value
@property
def dollar_cross(self) -> str:
"""USD cross identifier for a particular currency"""
return self.__dollar_cross
@dollar_cross.setter
def dollar_cross(self, value: str):
self._property_changed('dollar_cross')
self.__dollar_cross = value
@property
def mq_symbol(self) -> str:
"""Marquee Symbol for generic MQ entities"""
return self.__mq_symbol
@mq_symbol.setter
def mq_symbol(self, value: str):
self._property_changed('mq_symbol')
self.__mq_symbol = value
@property
def primary_country_ric(self) -> str:
"""Reuters Primary Country Instrument Code Identifier"""
return self.__primary_country_ric
@primary_country_ric.setter
def primary_country_ric(self, value: str):
self._property_changed('primary_country_ric')
self.__primary_country_ric = value
@property
def pnode_id(self) -> str:
"""Pricing node identifier sourced from Morningstar"""
return self.__pnode_id
@pnode_id.setter
def pnode_id(self, value: str):
self._property_changed('pnode_id')
self.__pnode_id = value
class CSLCurrency(Base):
"""A currency"""
@camel_case_translate
def __init__(
self,
string_value: Union[Currency, str] = None,
name: str = None
):
super().__init__()
self.string_value = string_value
self.name = name
@property
def string_value(self) -> Union[Currency, str]:
"""Currency, ISO 4217 currency code or exchange quote modifier (e.g. GBP vs GBp)"""
return self.__string_value
@string_value.setter
def string_value(self, value: Union[Currency, str]):
self._property_changed('string_value')
self.__string_value = get_enum_value(Currency, value)
class CSLDateArray(Base):
"""An array of dates"""
@camel_case_translate
def __init__(
self,
date_values: Tuple[CSLDate, ...] = None,
name: str = None
):
super().__init__()
self.date_values = date_values
self.name = name
@property
def date_values(self) -> Tuple[CSLDate, ...]:
"""A date"""
return self.__date_values
@date_values.setter
def date_values(self, value: Tuple[CSLDate, ...]):
self._property_changed('date_values')
self.__date_values = value
class CSLDateArrayNamedParam(Base):
"""A named array of dates"""
@camel_case_translate
def __init__(
self,
date_values: Tuple[CSLDate, ...] = None,
name: str = None
):
super().__init__()
self.date_values = date_values
self.name = name
@property
def date_values(self) -> Tuple[CSLDate, ...]:
"""A date"""
return self.__date_values
@date_values.setter
def date_values(self, value: Tuple[CSLDate, ...]):
self._property_changed('date_values')
self.__date_values = value
@property
def name(self) -> str:
"""A name for the array"""
return self.__name
@name.setter
def name(self, value: str):
self._property_changed('name')
self.__name = value
class CSLDoubleArray(Base):
"""An array of doubles"""
@camel_case_translate
def __init__(
self,
double_values: Tuple[CSLDouble, ...] = None,
name: str = None
):
super().__init__()
self.double_values = double_values
self.name = name
@property
def double_values(self) -> Tuple[CSLDouble, ...]:
"""A double"""
return self.__double_values
@double_values.setter
def double_values(self, value: Tuple[CSLDouble, ...]):
self._property_changed('double_values')
self.__double_values = value
class CSLFXCrossArray(Base):
"""An array of FX crosses"""
@camel_case_translate
def __init__(
self,
fx_cross_values: Tuple[CSLFXCross, ...] = None,
name: str = None
):
super().__init__()
self.fx_cross_values = fx_cross_values
self.name = name
@property
def fx_cross_values(self) -> Tuple[CSLFXCross, ...]:
"""An FX cross"""
return self.__fx_cross_values
@fx_cross_values.setter
def fx_cross_values(self, value: Tuple[CSLFXCross, ...]):
self._property_changed('fx_cross_values')
self.__fx_cross_values = value
class CSLIndexArray(Base):
"""An array of | |
= osxmetadata.OSXMetaData(f)
for attr, value in attributes.items():
islist = osxmetadata.ATTRIBUTES[attr].list
if value:
value = ", ".join(value) if not islist else sorted(value)
file_value = md.get_attribute(attr)
if file_value and islist:
file_value = sorted(file_value)
if (not file_value and not value) or file_value == value:
# if both not set or both equal, nothing to do
# get_attribute returns None if not set and value will be [] if not set so can't directly compare
verbose_(f"Skipping extended attribute {attr} for {f}: nothing to do")
skipped.add(f)
else:
verbose_(f"Writing extended attribute {attr} to {f}")
md.set_attribute(attr, value)
written.add(f)
return list(written), [f for f in skipped if f not in written]
@cli.command(hidden=True)
@DB_OPTION
@DB_ARGUMENT
@click.option(
"--dump",
metavar="ATTR",
help="Name of PhotosDB attribute to print; "
+ "can also use albums, persons, keywords, photos to dump related attributes.",
multiple=True,
)
@click.option(
"--uuid",
metavar="UUID",
help="Use with '--dump photos' to dump only certain UUIDs",
multiple=True,
)
@click.option("--verbose", "-V", "verbose", is_flag=True, help="Print verbose output.")
@click.pass_obj
@click.pass_context
def debug_dump(ctx, cli_obj, db, photos_library, dump, uuid, verbose):
""" Print out debug info """
global VERBOSE
VERBOSE = bool(verbose)
db = get_photos_db(*photos_library, db, cli_obj.db)
if db is None:
click.echo(cli.commands["debug-dump"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
start_t = time.perf_counter()
print(f"Opening database: {db}")
photosdb = osxphotos.PhotosDB(dbfile=db, verbose=verbose_)
stop_t = time.perf_counter()
print(f"Done; took {(stop_t-start_t):.2f} seconds")
for attr in dump:
if attr == "albums":
print("_dbalbums_album:")
pprint.pprint(photosdb._dbalbums_album)
print("_dbalbums_uuid:")
pprint.pprint(photosdb._dbalbums_uuid)
print("_dbalbum_details:")
pprint.pprint(photosdb._dbalbum_details)
print("_dbalbum_folders:")
pprint.pprint(photosdb._dbalbum_folders)
print("_dbfolder_details:")
pprint.pprint(photosdb._dbfolder_details)
elif attr == "keywords":
print("_dbkeywords_keyword:")
pprint.pprint(photosdb._dbkeywords_keyword)
print("_dbkeywords_uuid:")
pprint.pprint(photosdb._dbkeywords_uuid)
elif attr == "persons":
print("_dbfaces_uuid:")
pprint.pprint(photosdb._dbfaces_uuid)
print("_dbfaces_pk:")
pprint.pprint(photosdb._dbfaces_pk)
print("_dbpersons_pk:")
pprint.pprint(photosdb._dbpersons_pk)
print("_dbpersons_fullname:")
pprint.pprint(photosdb._dbpersons_fullname)
elif attr == "photos":
if uuid:
for uuid_ in uuid:
print(f"_dbphotos['{uuid_}']:")
try:
pprint.pprint(photosdb._dbphotos[uuid_])
except KeyError:
print(f"Did not find uuid {uuid_} in _dbphotos")
else:
print("_dbphotos:")
pprint.pprint(photosdb._dbphotos)
else:
try:
val = getattr(photosdb, attr)
print(f"{attr}:")
pprint.pprint(val)
except Exception:
print(f"Did not find attribute {attr} in PhotosDB")
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def keywords(ctx, cli_obj, db, json_, photos_library):
""" Print out keywords found in the Photos library. """
# below needed for to make CliRunner work for testing
cli_db = cli_obj.db if cli_obj is not None else None
db = get_photos_db(*photos_library, db, cli_db)
if db is None:
click.echo(cli.commands["keywords"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
keywords = {"keywords": photosdb.keywords_as_dict}
if json_ or cli_obj.json:
click.echo(json.dumps(keywords, ensure_ascii=False))
else:
click.echo(yaml.dump(keywords, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def albums(ctx, cli_obj, db, json_, photos_library):
""" Print out albums found in the Photos library. """
# below needed for to make CliRunner work for testing
cli_db = cli_obj.db if cli_obj is not None else None
db = get_photos_db(*photos_library, db, cli_db)
if db is None:
click.echo(cli.commands["albums"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
albums = {"albums": photosdb.albums_as_dict}
if photosdb.db_version > _PHOTOS_4_VERSION:
albums["shared albums"] = photosdb.albums_shared_as_dict
if json_ or cli_obj.json:
click.echo(json.dumps(albums, ensure_ascii=False))
else:
click.echo(yaml.dump(albums, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def persons(ctx, cli_obj, db, json_, photos_library):
""" Print out persons (faces) found in the Photos library. """
# below needed for to make CliRunner work for testing
cli_db = cli_obj.db if cli_obj is not None else None
db = get_photos_db(*photos_library, db, cli_db)
if db is None:
click.echo(cli.commands["persons"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
persons = {"persons": photosdb.persons_as_dict}
if json_ or cli_obj.json:
click.echo(json.dumps(persons, ensure_ascii=False))
else:
click.echo(yaml.dump(persons, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def labels(ctx, cli_obj, db, json_, photos_library):
""" Print out image classification labels found in the Photos library. """
# below needed for to make CliRunner work for testing
cli_db = cli_obj.db if cli_obj is not None else None
db = get_photos_db(*photos_library, db, cli_db)
if db is None:
click.echo(cli.commands["labels"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
labels = {"labels": photosdb.labels_as_dict}
if json_ or cli_obj.json:
click.echo(json.dumps(labels, ensure_ascii=False))
else:
click.echo(yaml.dump(labels, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def info(ctx, cli_obj, db, json_, photos_library):
""" Print out descriptive info of the Photos library database. """
db = get_photos_db(*photos_library, db, cli_obj.db)
if db is None:
click.echo(cli.commands["info"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
info = {"database_path": photosdb.db_path, "database_version": photosdb.db_version}
photos = photosdb.photos(movies=False)
not_shared_photos = [p for p in photos if not p.shared]
info["photo_count"] = len(not_shared_photos)
hidden = [p for p in photos if p.hidden]
info["hidden_photo_count"] = len(hidden)
movies = photosdb.photos(images=False, movies=True)
not_shared_movies = [p for p in movies if not p.shared]
info["movie_count"] = len(not_shared_movies)
if photosdb.db_version > _PHOTOS_4_VERSION:
shared_photos = [p for p in photos if p.shared]
info["shared_photo_count"] = len(shared_photos)
shared_movies = [p for p in movies if p.shared]
info["shared_movie_count"] = len(shared_movies)
keywords = photosdb.keywords_as_dict
info["keywords_count"] = len(keywords)
info["keywords"] = keywords
albums = photosdb.albums_as_dict
info["albums_count"] = len(albums)
info["albums"] = albums
if photosdb.db_version > _PHOTOS_4_VERSION:
albums_shared = photosdb.albums_shared_as_dict
info["shared_albums_count"] = len(albums_shared)
info["shared_albums"] = albums_shared
persons = photosdb.persons_as_dict
info["persons_count"] = len(persons)
info["persons"] = persons
if cli_obj.json or json_:
click.echo(json.dumps(info, ensure_ascii=False))
else:
click.echo(yaml.dump(info, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def places(ctx, cli_obj, db, json_, photos_library):
""" Print out places found in the Photos library. """
# below needed for to make CliRunner work for testing
cli_db = cli_obj.db if cli_obj is not None else None
db = get_photos_db(*photos_library, db, cli_db)
if db is None:
click.echo(cli.commands["places"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
place_names = {}
for photo in photosdb.photos(movies=True):
if photo.place:
try:
place_names[photo.place.name] += 1
except Exception:
place_names[photo.place.name] = 1
else:
try:
place_names[_UNKNOWN_PLACE] += 1
except Exception:
place_names[_UNKNOWN_PLACE] = 1
# sort by place count
places = {
"places": {
name: place_names[name]
for name in sorted(
place_names.keys(), key=lambda key: place_names[key], reverse=True
)
}
}
# below needed for to make CliRunner work for testing
cli_json = cli_obj.json if cli_obj is not None else None
if json_ or cli_json:
click.echo(json.dumps(places, ensure_ascii=False))
else:
click.echo(yaml.dump(places, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def folders(ctx, cli_obj, db, json_, photos_library):
""" Print out top-level folders names found in the Photos library. """
# below needed for to make CliRunner work for testing
cli_db = cli_obj.db if cli_obj is not None else None
db = get_photos_db(*photos_library, db, cli_db)
if db is None:
click.echo(cli.commands["folders"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
photosdb = osxphotos.PhotosDB(dbfile=db)
titles = sorted(list(map(lambda f: f.title, photosdb.folder_info)))
# below needed for to make CliRunner work for testing
cli_json = cli_obj.json if cli_obj is not None else None
if json_ or cli_json:
click.echo(json.dumps(titles, ensure_ascii=False))
else:
click.echo(yaml.dump(titles, sort_keys=False, allow_unicode=True))
@cli.command()
@DB_OPTION
@JSON_OPTION
@deleted_options
@DB_ARGUMENT
@click.pass_obj
@click.pass_context
def dump(ctx, cli_obj, db, json_, deleted, deleted_only, photos_library):
""" Print list of all photos & associated info from the Photos library. """
db = get_photos_db(*photos_library, db, cli_obj.db)
if db is None:
click.echo(cli.commands["dump"].get_help(ctx), err=True)
click.echo("\n\nLocated the following Photos library databases: ", err=True)
_list_libraries()
return
# check exclusive options
if deleted and deleted_only:
click.echo("Incompatible dump options", err=True)
click.echo(cli.commands["dump"].get_help(ctx), err=True)
return
photosdb = osxphotos.PhotosDB(dbfile=db)
if deleted or deleted_only:
photos = photosdb.photos(movies=True, intrash=True)
else:
photos = []
if not deleted_only:
photos += photosdb.photos(movies=True)
print_photo_info(photos, json_ or cli_obj.json)
@cli.command(name="list")
@JSON_OPTION
@click.pass_obj
@click.pass_context
def list_libraries(ctx, cli_obj, json_):
""" Print list of Photos libraries found on the system. """
# implemented in _list_libraries so it can be called by other CLI functions
# without errors due to passing ctx and cli_obj
_list_libraries(json_=json_ or cli_obj.json, error=False)
def _list_libraries(json_=False, error=True):
"""Print list of Photos libraries found on the system.
If json_ == True, print output as JSON (default = False)"""
photo_libs = osxphotos.utils.list_photo_libraries()
sys_lib = osxphotos.utils.get_system_library_path()
last_lib = osxphotos.utils.get_last_library_path()
if json_:
libs = {
"photo_libraries": photo_libs,
"system_library": sys_lib,
"last_library": last_lib,
}
click.echo(json.dumps(libs, ensure_ascii=False))
else:
last_lib_flag = sys_lib_flag = False
for lib in photo_libs:
if lib == sys_lib:
click.echo(f"(*)\t{lib}", err=error)
sys_lib_flag = True
elif lib == last_lib:
click.echo(f"(#)\t{lib}", err=error)
last_lib_flag = True
else:
click.echo(f"\t{lib}", err=error)
if sys_lib_flag or last_lib_flag:
click.echo("\n", err=error)
if sys_lib_flag:
click.echo("(*)\tSystem Photos Library", err=error)
if last_lib_flag:
click.echo("(#)\tLast opened Photos Library", err=error)
@cli.command(name="about")
@click.pass_obj
@click.pass_context
def about(ctx, cli_obj):
""" Print information about osxphotos including license. """
license = """
MIT License
Copyright (c) 2019-2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to | |
import tkinter as tk
import tkinter.font as tkf
import tkinter.tix as tkx
import threading as th
from random import shuffle
from time import sleep
from webbrowser import open_new_tab
# Creates the highest-level tkinter widget, a canvas of sorts.
root = tkx.Tk()
# Immediately places focus on the application, as if it were leftclicked.
# Added to fix an issue with tkinter.tix.Balloon, so it wouldn't be necessary if using only the default tkinter.
root.focus()
# Title bar text.
root.title('F1 for help █ hover for tooltips █ ←↑→↓, SPACE, CTRL/ALT')
# Creates a copy of the default font, difference being that all text written in this font will also be underlined.
# This font will be used for hyperlinks in the About popup.
default_underlined = tkf.Font(font='TkDefaultFont')
default_underlined.configure(underline=True)
# Establishes a handle on the default background colour, so that it can be used to "revert to default" a widget's bg.
defaultbg = root.cget('bg')
# Stores rows / columns / mines amounts for use with the Restart button.
previous_board_info = []
def close_popup_delete_reference():
"""Destroy About widget and delete its reference from the global namespace dictionary."""
about.destroy()
del globals()['about']
# event_info_which_is_not_used is something you'll see plenty of here. When using the .bind method of a widget,
# in addition to launching the specified function, .bind also forces some event info onto that function as a positional
# argument. If not handled (received), there would be a TypeError caused by too many positional arguments.
def toggle_about(event_info_which_is_not_used):
"""Initiate destruction of About widget if one is present, otherwise generate one."""
global about
if 'about' in globals().keys():
close_popup_delete_reference()
else:
def open_github(event_info_which_is_not_used):
open_new_tab('https://github.com/aszychlinski/tkinter_minesweeper')
def open_issues(event_info_which_is_not_used):
open_new_tab('https://github.com/aszychlinski/tkinter_minesweeper/issues')
about = tk.Toplevel(root)
about.title('F1 to close help')
about.bind('<F1>', toggle_about)
about_main = tk.Label(
about, justify='left', padx=10, pady=10,
text='Left click a field to reveal it. Right click a field to flag it as containing a mine.'
'\n\nA revealed field may display a number. This number describes the amount of adjacent mines.'
'\nIf there is no number, there are no mines adjacent to this field; a chain reaction will occur.'
'\n\nYou win if every remaining unrevealed field contains a mine (they do not have to be flagged).'
'\n\nYou lose if you reveal a field containing a mine.'
'\n\nThe "Free first move!" button is available only if no field has been revealed yet.'
'\nIt reveals a randomly chosen field from among those containing the least adjacent mines.'
'\n\nThe yellow button above the game board generates a new board with the previously used values.'
'\n\n\nYou can also use the arrow keys to play! Once a board is generated, keyboard focus is on the'
'\n"Free first move!" button. Press Space to use the button, then use the down arrow to get down '
'\nfrom there onto the playing field. Spacebar to reveal a field, left CTRL or any ALT to flag.'
'\nFrom the top row of the minefield you can also get up onto the Restart and first move buttons.\n')
about_main.pack(side='top')
about_visit = tk.Label(about, text='Visit my GitHub!')
about_visit.pack(side='top')
link1_frame, link2_frame = tk.Frame(about), tk.Frame(about)
link1_frame.pack(side='top', fill='x')
link2_frame.pack(side='top', fill='x')
# This is the first line containing a hyperlink.
about_github_link = tk.Label(link1_frame, font=default_underlined, fg='blue',
text='https://github.com/aszychlinski/tkinter_minesweeper')
about_github_link.pack(side='left')
about_github_link.bind("<Button-1>", open_github)
about_github_link_desc = tk.Label(link1_frame, text='- view the repo page and sourcecode files')
about_github_link_desc.pack(side='left')
# This is the second line containing a hyperlink.
about_issues_link = tk.Label(link2_frame, font=default_underlined, fg='blue',
text='https://github.com/aszychlinski/tkinter_minesweeper/issues')
about_issues_link.pack(side='left')
about_issues_link.bind("<Button-1>", open_issues)
about_issues_link_desc = tk.Label(link2_frame, text='- issues, suggestions, feedback')
about_issues_link_desc.pack(side='left')
# Defines a function to use when user clicks X button in top-right of About widget.
# Tkinter provides a default window-closing mechanism, but I also needed to delete from globals().
about.protocol("WM_DELETE_WINDOW", close_popup_delete_reference)
root.bind('<F1>', toggle_about)
class TimerThread(th.Thread):
"""A thread which counts seconds starting with 0 and until interrupted."""
def __init__(self):
th.Thread.__init__(self)
# Amount of elapsed seconds.
self.value = 0
# The restart flag is set to True when the Restart button is pressed and terminates thread on next iteration.
self.restart = False
def run(self):
"""Count elapsed seconds and push the value to a tk.IntVar in the main thread."""
while not FieldButton.game_over and not self.restart:
sleep(1)
if not FieldButton.game_over and not self.restart:
self.value += 1
try:
board.time_elapsed_var.set(self.value)
except RuntimeError:
return None
return None
class ConfigLabel:
"""A wrapper for tk.Label, which was meant to save me some typing."""
def __init__(self, master, text):
self.label = tk.Label(master, text=text)
self.label.pack(side='left')
class ConfigEntry:
"""Another wrapper, this time for the text Entry fields. Inserts 0 by default."""
def __init__(self, master):
self.entry = tk.Entry(master, justify='right')
self.entry.pack(side='left')
self.entry.insert(0, '0')
class ConfigConfirm:
"""Wrapper for tk.Button which also passes row, column and mine amounts to BoardFactory."""
def __init__(self, master, text, preset, *args):
self.button = tk.Button(master, command=self.forward_values, text=text)
self.button.pack(side='left')
# Tuple of values taken from the three Entry fields.
self.bound_entries = args
# Boolean flag which controls flow based on whether values come from Entry fields or one of the preset buttons.
self.preset = preset
def forward_values(self):
global board
global previous_board_info
# Cleans up after the previous board. The two 'for' loops are likely unneeded as 'board.gameframe.destroy()'
# should delete all of its children down through the master / slave hierarchy. But I wanted to be sure.
if 'board' in globals().keys():
for x in board.buttons:
x.button.destroy()
for y in board.rows:
y.frame.destroy()
board.timer.restart = True
board.start_helper.destroy()
board.status_frame.destroy()
board.gameframe.destroy()
# If one of the preset buttons was pressed, delete whatever was written in the Entry fields, insert the preset
# values, then immediately pass those values to BoardFactory (kinda like if Generate was pressed).
if self.preset:
row_entry.entry.delete(0, 'end')
row_entry.entry.insert(0, self.bound_entries[0])
column_entry.entry.delete(0, 'end')
column_entry.entry.insert(0, self.bound_entries[1])
mines_entry.entry.delete(0, 'end')
mines_entry.entry.insert(0, self.bound_entries[2])
previous_board_info = [self.bound_entries[0], self.bound_entries[1], self.bound_entries[2]]
# Resets some class attributes of FieldButton to their initial states in preparation for a new game.
FieldButton.game_over, FieldButton.revealed_buttons = False, 0
board = BoardFactory(self.bound_entries[0], self.bound_entries[1], self.bound_entries[2])
# If Generate was pressed...
else:
try:
for x in self.bound_entries:
errormessage = 'Non-integer argument.'
int(x.entry.get())
if int(x.entry.get()) < 0:
errormessage = 'Negative argument.'
raise ValueError
if int(self.bound_entries[0].entry.get())\
* int(self.bound_entries[1].entry.get())\
< int(self.bound_entries[2].entry.get()):
errormessage = 'More mines than fields.'
raise ValueError
if 0 in (int(self.bound_entries[0].entry.get()), int(self.bound_entries[1].entry.get())):
errormessage = 'Rows and columns cannot be zero.'
raise ValueError
# These maximums are derived from how the game displayed on my 1920x1080 screen. :)
# They represent the safe maximums under which the whole game board can always be displayed on screen.
if int(self.bound_entries[0].entry.get()) > 18 or int(self.bound_entries[1].entry.get()) > 34:
errormessage = 'Argument exceeds maximum.'
raise ValueError
# If any of the tests failed, pushes errormessage to error_label and does not proceed to Board generation.
except ValueError:
error_label.label.config(text=errormessage, bg='red')
# Board creation approved!
else:
values = []
for x in self.bound_entries:
values.append(x.entry.get())
rows, columns, mines = values
# Saves values of board about to be created, to use with Restart button.
previous_board_info = [rows, columns, mines]
# Resets some class attributes of FieldButton to their initial states in preparation for a new game.
FieldButton.game_over, FieldButton.revealed_buttons = False, 0
# Instances BoardFactory, which creates a new game board.
board = BoardFactory(rows, columns, mines)
class GameFrame(tk.Frame):
"""A tk.Frame containing the minefield buttons that BoardFactory creates."""
def __repr__(self):
"""This doesn't really do anything, I had it for debug purposes initially and don't want to refactor it."""
return 'GameFrame'
class GameRow:
"""A tk.Frame representing a horizontal row on the game board."""
def __init__(self, master, name):
self.frame = tk.Frame(master=master, name=name)
self.frame.pack(side='top')
# A list of buttons in the row, into which - early in development - I decided to pass string id's of instanced
# FieldButton objects instead of the whole objects themselves. This was not the greatest idea.
self.mybuttons = []
self.rownum = 0
def __str__(self):
return f'GameRow {self.rownum}'
def __repr__(self):
return f'GameRow {self.rownum}'
class BoardFactory:
"""Create a brand new board."""
def __init__(self, rows, columns, mines):
# target_ attributes store the initial values and are meant to remain unchanged (as a reference).
# undistributed_ attributes are modified in the course of board generation
self.target_rows = int(rows)
self.target_columns, self.undistributed_columns = int(columns), int(columns)
self.target_mines, self.undistributed_mines = int(mines), int(mines)
self.target_buttons = self.target_rows * self.target_columns
# Contains GameRow instances.
self.rows = []
# Contain FieldButton instances.
self.buttons, self.undistributed_buttons = [], []
# Dictionary where comma-separated strings of | |
import concurrent.futures
import datetime
import hashlib
import mimetypes
import re
from dataclasses import dataclass
from functools import cached_property
from itertools import chain
from pathlib import Path
import boto3
import click
from boto3.s3.transfer import S3TransferConfig
from dateutil.tz import UTC
from .constants import (
DEFAULT_CACHE_CONTROL,
HASHED_CACHE_CONTROL,
LOG_EACH_SUCCESSFUL_UPLOAD,
MAX_WORKERS_PARALLEL_UPLOADS,
)
from .utils import StopWatch, fmt_size, iterdir, log
S3_MULTIPART_THRESHOLD = S3TransferConfig().multipart_threshold
S3_MULTIPART_CHUNKSIZE = S3TransferConfig().multipart_chunksize
NO_CACHE_VALUE = "no-store, must-revalidate"
hashed_filename_regex = re.compile(r"\.[a-f0-9]{8,32}\.")
def log_task(task):
if task.error:
if task.is_redirect:
# With redirect upload tasks, we have to embellish the
# error message.
log.error(f"Failed to upload {task}: {task.error}")
else:
# With file upload tasks, the error message says it all.
log.error(task.error)
elif LOG_EACH_SUCCESSFUL_UPLOAD:
log.success(task)
@dataclass
class Totals:
"""Class for keeping track of some useful totals."""
failed: int = 0
skipped: int = 0
uploaded_files: int = 0
uploaded_redirects: int = 0
uploaded_files_size: int = 0
deleted_files: int = 0
def count(self, task):
if task.skipped:
self.skipped += 1
elif task.error:
self.failed += 1
elif task.is_redirect:
self.uploaded_redirects += 1
elif task.is_deletion:
self.deleted_files += 1
else:
self.uploaded_files += 1
self.uploaded_files_size += task.size
class DisplayProgress:
def __init__(self, total_count, show_progress_bar=True):
if show_progress_bar:
self.progress_bar = click.progressbar(
fill_char="▋",
show_pos=True,
show_eta=False,
show_percent=True,
length=total_count,
)
self.failed_tasks = []
else:
self.progress_bar = None
def __enter__(self):
if self.progress_bar:
self.progress_bar.__enter__()
# Forces the progress-bar to show-up immediately.
self.progress_bar.update(0)
return self
def __exit__(self, *exc_args):
if self.progress_bar:
self.progress_bar.__exit__(*exc_args)
# Now that we've left the progress bar, let's report
# any failed tasks.
for task in self.failed_tasks:
log_task(task)
return False
def update(self, task):
if self.progress_bar:
self.progress_bar.update(1)
if task.error:
self.failed_tasks.append(task)
else:
log_task(task)
class UploadTask:
"""
Base class for indicating the common interface for all upload tasks.
"""
error = None
skipped = False
is_redirect = False
is_deletion = False
def upload(self):
raise NotImplementedError()
class UploadFileTask(UploadTask):
"""
Class for file upload tasks.
"""
def __init__(
self,
file_path: Path,
key: str,
dry_run=False,
default_cache_control=DEFAULT_CACHE_CONTROL,
):
self.key = key
self.file_path = file_path
self.dry_run = dry_run
self.default_cache_control = default_cache_control
def __repr__(self):
return f"{self.__class__.__name__}({self.file_path}, {self.key})"
def __str__(self):
return self.key
@property
def size(self) -> int:
return self.file_path.stat().st_size
@property
def etag(self):
"""
Calculates and returns a value equivalent to the file's AWS ETag value.
"""
md5s = []
with self.file_path.open("rb") as f:
def read_chunks():
yield f.read(S3_MULTIPART_THRESHOLD)
while True:
yield f.read(S3_MULTIPART_CHUNKSIZE)
for chunk in read_chunks():
if not chunk:
break
md5s.append(hashlib.md5(chunk))
if not md5s:
return f'"{hashlib.md5().hexdigest()}"'
if len(md5s) == 1:
return f'"{md5s[0].hexdigest()}"'
digests_md5 = hashlib.md5(b"".join(m.digest() for m in md5s))
return f'"{digests_md5.hexdigest()}-{len(md5s)}"'
@property
def content_type(self):
mime_type = (
mimetypes.guess_type(str(self.file_path))[0] or "binary/octet-stream"
)
if mime_type.startswith("text/") or (
mime_type in ("application/json", "application/javascript")
):
mime_type += "; charset=utf-8"
if mime_type == "binary/octet-stream" and self.file_path.suffix == ".woff2":
# See https://github.com/mdn/yari/issues/2017
mime_type = "font/woff2"
return mime_type
@property
def is_hashed(self):
return hashed_filename_regex.search(self.file_path.name)
@property
def cache_control(self):
if self.file_path.name == "service-worker.js":
return NO_CACHE_VALUE
if self.file_path.name == "404.html":
return NO_CACHE_VALUE
if self.file_path.parent.name == "_whatsdeployed":
return NO_CACHE_VALUE
if self.is_hashed:
cache_control_seconds = HASHED_CACHE_CONTROL
else:
cache_control_seconds = self.default_cache_control
if cache_control_seconds == 0:
return "max-age=0, no-cache, no-store, must-revalidate"
else:
return f"max-age={cache_control_seconds}, public"
def upload(self, bucket_manager):
if not self.dry_run:
bucket_manager.client.upload_file(
str(self.file_path),
bucket_manager.bucket_name,
self.key,
ExtraArgs={
"ACL": "public-read",
"ContentType": self.content_type,
"CacheControl": self.cache_control,
},
)
class UploadRedirectTask(UploadTask):
"""
Class for redirect upload tasks.
"""
is_redirect = True
def __init__(self, redirect_from_key, redirect_to_key, dry_run=False):
self.key = redirect_from_key
self.to_key = redirect_to_key
self.dry_run = dry_run
def __repr__(self):
return f"UploadRedirectTask({self.key}, {self.to_key})"
def __str__(self):
return f"{self.key} -> {self.to_key}"
@property
def cache_control(self):
return f"max-age={HASHED_CACHE_CONTROL}, public"
def upload(self, bucket_manager):
if not self.dry_run:
bucket_manager.client.put_object(
Body=b"",
Key=self.key,
ACL="public-read",
CacheControl=self.cache_control,
WebsiteRedirectLocation=self.to_key,
Bucket=bucket_manager.bucket_name,
)
class DeleteTask(UploadTask):
"""
Class for doing deletion by key tasks.
"""
is_deletion = True
def __init__(self, key, dry_run=False):
self.key = key
self.dry_run = dry_run
def __repr__(self):
return f"{self.__class__.__name__}({self.key})"
def __str__(self):
return self.key
def delete(self, bucket_manager):
if not self.dry_run:
bucket_manager.client.delete_object(
Key=str(self.key),
Bucket=bucket_manager.bucket_name,
)
class BucketManager:
def __init__(self, bucket_name, bucket_prefix):
self.bucket_name = bucket_name
self.bucket_prefix = bucket_prefix
@property
def key_prefix(self):
if self.bucket_prefix:
return f"{self.bucket_prefix.lower()}/"
return ""
@cached_property
def client(self):
# According to the boto3 docs, this low-level client is thread-safe.
return boto3.client("s3")
def get_key(self, build_directory, file_path):
if file_path.name == "index.html":
# NOTE: All incoming requests, unless immediately served from the CDN
# cache, are first handled by our "origin-request" Lambda@Edge function,
# which tansforms incoming URL's to S3 keys. This line of code allows
# that function to remain as simple as possible, because we no longer
# have to determine when to add an "/index.html" suffix when transforming
# the incoming URL to it corresponding S3 key. We will simply store
# "/en-us/docs/web/index.html" as "/en-us/docs/web", which mirrors
# its URL. Also, note that the content type is not determined by the
# suffix of the S3 key, but is explicitly set from the full filepath
# when uploading the file.
file_path = file_path.parent
return f"{self.key_prefix}{str(file_path.relative_to(build_directory)).lower()}"
def get_redirect_keys(self, from_url, to_url):
return (
f"{self.key_prefix}{from_url.strip('/').lower()}",
f"/{to_url.strip('/')}" if to_url.startswith("/") else to_url,
)
def get_bucket_objects(self):
result = {}
continuation_token = None
while True:
# Note! You can set a `MaxKeys` parameter here.
# The default is 1,000. Any number larger than 1,000 is ignored
# and it will just fall back to 1,000.
# (Peterbe's note) I've experimented with different numbers (
# e.g. 500 or 100) and the total time difference is insignificant.
# A large MaxKeys means larger batches and fewer network requests
# which has a reduced risk of network failures (automatically retried)
# and there doesn't appear to be any benefit in setting it to a lower
# number. So leave it at 1,000 which is what you get when it's not set.
kwargs = dict(Bucket=self.bucket_name)
if self.key_prefix:
kwargs["Prefix"] = self.key_prefix
if continuation_token:
kwargs["ContinuationToken"] = continuation_token
response = self.client.list_objects_v2(**kwargs)
for obj in response.get("Contents", ()):
result[obj["Key"]] = obj
if response["IsTruncated"]:
continuation_token = response["NextContinuationToken"]
else:
break
return result
def iter_file_tasks(
self,
build_directory,
for_counting_only=False,
dry_run=False,
default_cache_control=DEFAULT_CACHE_CONTROL,
):
# The order matters! In particular the order of static assets compared to
# the HTML files that reference said static assets.
# If you upload the HTML files before we upload the static assets, what
# might happen is this:
#
# ...
# <link rel=stylesheet href=/static/css/main.350fa0c1.css">
# <title>JavaScript MDN Web Docs</title>
# ...
#
# Now if the CDN serves this new HTML file *before*
# the /static/css/main.350fa0c1.css file has been uploaded, you get a busted
# page.
# So explicitly upload all the static assets first.
# I.e. `<build_directory>/static/`
# And since we later processed the whole of `<build_directory>` we'll
# come across these static files again. So that's why we populate a
# `set` so that when we do the second pass, we'll know what we've already
# yielded.
# Origin for this is: https://github.com/mdn/yari/issues/3315
done = set()
# Walk the build_directory/static and yield file upload tasks.
for fp in iterdir(build_directory / "static"):
# Exclude any files that aren't artifacts of the build.
if fp.name.startswith(".") or fp.name.endswith("~"):
continue
key = self.get_key(build_directory, fp)
if for_counting_only:
yield 1
else:
yield UploadFileTask(
fp,
key,
dry_run=dry_run,
default_cache_control=default_cache_control,
)
done.add(key)
# Prepare a computation of what the root /index.html file would be
# called as a S3 key. Do this once so it becomes a quicker operation
# later when we compare *each* generated key to see if it matches this.
root_index_html_as_key = self.get_key(
build_directory, build_directory / "index.html"
)
# Walk the build_directory and yield file upload tasks.
for fp in iterdir(build_directory):
# Exclude any files that aren't artifacts of the build.
if fp.name.startswith(".") or fp.name.endswith("~"):
continue
key = self.get_key(build_directory, fp)
if key in done:
# This can happen since we might have explicitly processed this
# in the for-loop above. See comment at the beginning of this method.
continue
# The root index.html file is never useful. It's not the "home page"
# because the home page is actually `/$locale/` since `/` is handled
# specifically by the CDN.
# The client/build/index.html is actually just a template from
# create-react-app, used to server-side render all the other pages.
# But we don't want to upload it S3. So, delete it before doing the
# deployment step.
if root_index_html_as_key == key:
continue
if for_counting_only:
yield 1
else:
yield UploadFileTask(
fp,
key,
dry_run=dry_run,
default_cache_control=default_cache_control,
)
def iter_redirect_tasks(
self, | |
<filename>paper/mnist.py
import warnings
warnings.filterwarnings('ignore')
warnings.filterwarnings('ignore', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=FutureWarning)
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
import torch
import numpy as np
from models.models import LeNetMadry
from models.hendrycks import MNIST_ConvNet
from laplace import llla, kfla, dla
import laplace.util as lutil
from pycalib.calibration_methods import TemperatureScaling
from util.evaluation import *
from util.tables import *
import util.dataloaders as dl
from util.misc import *
import util.adversarial as adv
from math import *
from tqdm import tqdm, trange
import argparse
import pickle
import os, sys
import matplotlib.pyplot as plt
import seaborn as sns
import tikzplotlib
from tqdm import tqdm, trange
import torch.utils.data as data_utils
from util.plotting import plot_histogram
parser = argparse.ArgumentParser()
parser.add_argument('--type', help='Pick one \\{"plain", "ACET", "OE"\\}', default='plain')
parser.add_argument('--generate_adv', action='store_true', default=False)
parser.add_argument('--compute_hessian', action='store_true', default=False)
parser.add_argument('--generate_histograms', action='store_true', default=False)
parser.add_argument('--generate_figures', action='store_true', default=False)
parser.add_argument('--generate_confmat', action='store_true', default=False)
parser.add_argument('--randseed', type=int, default=123)
args = parser.parse_args()
np.random.seed(args.randseed)
torch.manual_seed(args.randseed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
train_loader = dl.MNIST(train=True, augm_flag=False)
val_loader, test_loader = dl.MNIST(train=False, val_size=2000)
targets = torch.cat([y for x, y in test_loader], dim=0).numpy()
print(len(train_loader.dataset), len(val_loader.dataset), len(test_loader.dataset))
test_loader_EMNIST = dl.EMNIST(train=False)
test_loader_FMNIST = dl.FMNIST(train=False)
delta = 10 if args.type == 'OE' else 1
ood_loader = dl.UniformNoise('MNIST', delta=delta, size=2000)
def load_model():
model = MNIST_ConvNet() if args.type == 'OE' else LeNetMadry()
model = model.cuda()
model.load_state_dict(torch.load(f'./pretrained_models/MNIST_{args.type}.pt'))
model.eval()
return model
tab_ood = {'MNIST - MNIST': [],
'MNIST - EMNIST': [],
'MNIST - FMNIST': [],
'MNIST - FarAway': [],
'MNIST - Adversarial': [],
'MNIST - FarAwayAdv': []}
tab_cal = {'MAP': ([], []),
'Temp': ([], []),
'LLLA': ([], []),
'DLA': ([], []),
'KFLA': ([], [])}
delta = 2000
"""
=============================================================================================
MAP
=============================================================================================
"""
print()
model = load_model()
noise_loader = dl.UniformNoise('MNIST', size=2000)
test_loader_adv_nonasymp = adv.create_adv_loader(model, noise_loader,
f'mnist_adv_{args.type}',
delta=1,
epsilon=0.3,
load=not args.generate_adv,
p='inf')
test_loader_adv_asymp = adv.create_adv_loader(model, noise_loader,
f'mnist_adv_{args.type}',
delta=delta,
epsilon=0.3,
load=not args.generate_adv,
p='inf')
if args.generate_adv:
sys.exit(0)
# In-distribution
py_in, time_pred = timing(lambda: predict(test_loader, model).cpu().numpy())
acc_in = np.mean(np.argmax(py_in, 1) == targets)
conf_in = get_confidence(py_in)
mmc = conf_in.mean()
ece, mce = get_calib(py_in, targets)
save_res_ood(tab_ood['MNIST - MNIST'], mmc)
save_res_cal(tab_cal['MAP'], ece, mce)
print(f'[In, MAP] Time: NA/{time_pred:.1f}s; Accuracy: {acc_in:.3f}; ECE: {ece:.3f}; MCE: {mce:.3f}; MMC: {mmc:.3f}')
# ----------------------------------------------------------------------
# Make a binary classification dataset
if args.generate_confmat:
from sklearn.metrics import confusion_matrix
C = confusion_matrix(targets, py_in.argmax(1))
print(C)
np.fill_diagonal(C, -1)
max_idx = np.unravel_index(C.argmax(), shape=C.shape)
max_val = C.max()
print(f'Most confused index: {max_idx}, value: {max_val}')
sys.exit()
# ----------------------------------------------------------------------
# Out-distribution - EMNIST
py_out = predict(test_loader_EMNIST, model).cpu().numpy()
conf_emnist = get_confidence(py_out)
mmc = conf_emnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - EMNIST'], mmc, auroc)
print(f'[Out-EMNIST, MAP] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FMNIST
py_out = predict(test_loader_FMNIST, model).cpu().numpy()
conf_fmnist = get_confidence(py_out)
mmc = conf_fmnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FMNIST'], mmc, auroc)
print(f'[Out-FMNIST, MAP] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAway
py_out = predict(noise_loader, model, delta=delta).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAway'], mmc, auroc)
print(f'[Out-FarAway, MAP] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - Adversarial
py_out = predict(test_loader_adv_nonasymp, model).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - Adversarial'], mmc, auroc)
print(f'[Out-Adversarial, MAP] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAwayAdversarial
py_out = predict(test_loader_adv_asymp, model).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAwayAdv'], mmc, auroc)
print(f'[Out-FarAwayAdv, MAP] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
print()
if args.generate_histograms:
plot_histogram([conf_in, conf_emnist, conf_farway], ['In - MNIST', 'Out - EMNIST', 'Out - FarAway'], 'hist_confs_mnist_map')
"""
=============================================================================================
Temperature scaling
=============================================================================================
"""
model = load_model()
X = predict_logit(val_loader, model).cpu().numpy()
y = torch.cat([y for x, y in val_loader], dim=0).numpy()
T, time = timing(lambda: TemperatureScaling().fit(X, y).T)
print(f'T = {T:.3f}. Done in {time:.1f}s')
# In-distribution
py_in, time_pred = timing(lambda: predict(test_loader, model, T=T).cpu().numpy())
acc_in = np.mean(np.argmax(py_in, 1) == targets)
conf_in = get_confidence(py_in)
mmc = conf_in.mean()
ece, mce = get_calib(py_in, targets)
save_res_ood(tab_ood['MNIST - MNIST'], mmc)
save_res_cal(tab_cal['Temp'], ece, mce)
print(f'[In, Temp.] Time: NA/{time_pred:.1f}s; Accuracy: {acc_in:.3f}; ECE: {ece:.3f}; MCE: {mce:.3f}; MMC: {mmc:.3f}')
# Out-distribution - EMNIST
py_out = predict(test_loader_EMNIST, model, T=T).cpu().numpy()
conf_emnist = get_confidence(py_out)
mmc = conf_emnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - EMNIST'], mmc, auroc)
print(f'[Out-EMNIST, Temp.] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FMNIST
py_out = predict(test_loader_FMNIST, model, T=T).cpu().numpy()
conf_fmnist = get_confidence(py_out)
mmc = conf_fmnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FMNIST'], mmc, auroc)
print(f'[Out-FMNIST, Temp.] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAway
py_out = predict(noise_loader, model, delta=delta, T=T).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAway'], mmc, auroc)
print(f'[Out-FarAway, Temp.] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - Adversarial
py_out = predict(test_loader_adv_nonasymp, model, T=T).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - Adversarial'], mmc, auroc)
print(f'[Out-Adversarial, MAP] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAwayAdversarial
py_out = predict(test_loader_adv_asymp, model, T=T).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAwayAdv'], mmc, auroc)
print(f'[Out-FarAwayAdv, Temp.] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
print()
if args.generate_histograms:
plot_histogram([conf_in, conf_emnist, conf_farway], ['In - MNIST', 'Out - EMNIST', 'Out - FarAway'], 'hist_confs_mnist_temp')
"""
=============================================================================================
LLLA
=============================================================================================
"""
model = load_model()
if args.compute_hessian:
hessians, time_inf = timing(lambda: llla.get_hessian(model, train_loader, mnist=True))
# interval = torch.logspace(-3, 5, 100).cuda()
# var0 = llla.gridsearch_var0(model, hessians, val_loader, ood_loader, interval, lam=0.25)
if args.type == 'plain':
var0 = torch.tensor(83000).float().cuda()
elif args.type == 'ACET':
var0 = torch.tensor(0.0025).float().cuda()
else:
var0 = torch.tensor(83021).float().cuda()
print(var0)
M_W, M_b, U, V, B = llla.estimate_variance(var0, hessians)
np.save(f'./pretrained_models/MNIST_{args.type}_llla.npy', [M_W, M_b, U, V, B])
else:
time_inf = 0
M_W, M_b, U, V, B = list(np.load(f'./pretrained_models/MNIST_{args.type}_llla.npy', allow_pickle=True))
# In-distribution
py_in, time_pred = timing(lambda: llla.predict(test_loader, model, M_W, M_b, U, V, B).cpu().numpy())
acc_in = np.mean(np.argmax(py_in, 1) == targets)
conf_in = get_confidence(py_in)
mmc = conf_in.mean()
ece, mce = get_calib(py_in, targets)
save_res_ood(tab_ood['MNIST - MNIST'], mmc)
save_res_cal(tab_cal['LLLA'], ece, mce)
print(f'[In, LLLA] Time: {time_inf:.1f}/{time_pred:.1f}s; Accuracy: {acc_in:.3f}; ECE: {ece:.3f}; MCE: {mce:.3f}; MMC: {mmc:.3f}')
# Out-distribution - EMNIST
py_out = llla.predict(test_loader_EMNIST, model, M_W, M_b, U, V, B).cpu().numpy()
conf_emnist = get_confidence(py_out)
mmc = conf_emnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - EMNIST'], mmc, auroc)
print(f'[Out-EMNIST, LLLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FMNIST
py_out = llla.predict(test_loader_FMNIST, model, M_W, M_b, U, V, B).cpu().numpy()
conf_fmnist = get_confidence(py_out)
mmc = conf_fmnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FMNIST'], mmc, auroc)
print(f'[Out-FMNIST, LLLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAway
py_out = llla.predict(noise_loader, model, M_W, M_b, U, V, B, delta=delta).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAway'], mmc, auroc)
print(f'[Out-FarAway, LLLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - Adversarial
py_out = llla.predict(test_loader_adv_nonasymp, model, M_W, M_b, U, V, B).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - Adversarial'], mmc, auroc)
print(f'[Out-Adversarial, LLLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAwayAdversarial
py_out = llla.predict(test_loader_adv_asymp, model, M_W, M_b, U, V, B).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAwayAdv'], mmc, auroc)
print(f'[Out-FarAwayAdv, LLLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
print()
if args.generate_histograms:
plot_histogram([conf_in, conf_emnist, conf_farway], ['In - MNIST', 'Out - EMNIST', 'Out - FarAway'], 'hist_confs_mnist_llla')
if args.generate_figures:
@torch.no_grad()
def get_conf(dataloader, delta, model, T=1, laplace=True):
if laplace:
py = llla.predict(dataloader, model, M_W, M_b, U, V, B, delta=delta)
else:
py = predict(dataloader, model, delta=delta, T=T)
conf = get_confidence(py.cpu().numpy())
return conf
range_max = 20
deltas = np.arange(0, range_max+0.1, 1)
confs_map = np.transpose([get_conf(test_loader, delta, model, laplace=False) for delta in deltas])
confs_temp = np.transpose([get_conf(test_loader, delta, model, T=T, laplace=False) for delta in deltas])
confs_laplace = np.transpose([get_conf(test_loader, delta, model, laplace=True) for delta in deltas])
print(confs_map.shape, confs_laplace.shape)
plt.clf()
cmap = sns.color_palette()
def plot_conf(confs, name='figs/conf_map_cifar10', ylabel='Conf. (MAP)'):
mean = confs.mean(0)
std = confs.std(0)
plt.fill_between(deltas, np.maximum(0.1, mean-3*std), np.minimum(1, mean+3*std), alpha=0.15)
plt.plot(deltas, mean, lw=3)
plt.axhline(0.1, lw=3, ls='--', c='k')
# plt.xticks(range(0, 6))
plt.xlim(1, range_max)
plt.ylim(0, 1.05)
plt.xlabel(r'$\delta$')
plt.ylabel(ylabel)
plt.savefig(f'{name}.pdf', bbox_inches='tight')
tikzplotlib.save(f'{name}.tex')
# plt.show()
plt.clf()
plot_conf(confs_map, 'figs/conf_map_mnist_', 'Conf. (MAP)')
plot_conf(confs_temp, 'figs/conf_temp_mnist_', 'Conf. (Temp.)')
plot_conf(confs_laplace, 'figs/conf_laplace_mnist_', 'Conf. (LLLA)')
sys.exit(0)
"""
=============================================================================================
DiagLaplace
=============================================================================================
"""
model = load_model()
model_dla = dla.DiagLaplace(model)
if args.compute_hessian:
_, time_inf = timing(lambda: model_dla.get_hessian(train_loader))
# interval = torch.logspace(-6, 0, 100)
# var0 = model_dla.gridsearch_var0(val_loader, ood_loader, interval, n_classes=10, lam=0.25)
if args.type == 'plain':
var0 = torch.tensor(0.0020).float().cuda()
elif args.type == 'ACET':
var0 = torch.tensor(2.7826e-06).float().cuda()
else:
var0 = torch.tensor(0.0012).float().cuda()
print(var0)
model_dla.estimate_variance(var0)
torch.save(model_dla.state_dict(), f'./pretrained_models/MNIST_{args.type}_dla.pt')
else:
time_inf = 0
model_dla.load_state_dict(torch.load(f'./pretrained_models/MNIST_{args.type}_dla.pt'))
model_dla.eval()
# In-distribution
py_in, time_pred = timing(lambda: lutil.predict(test_loader, model_dla).cpu().numpy())
acc_in = np.mean(np.argmax(py_in, 1) == targets)
conf_in = get_confidence(py_in)
mmc = conf_in.mean()
ece, mce = get_calib(py_in, targets)
save_res_ood(tab_ood['MNIST - MNIST'], mmc)
save_res_cal(tab_cal['DLA'], ece, mce)
print(f'[In, DLA] Time: {time_inf:.1f}/{time_pred:.1f}s; Accuracy: {acc_in:.3f}; ECE: {ece:.3f}; MCE: {mce:.3f}; MMC: {mmc:.3f}')
# Out-distribution - EMNIST
py_out = lutil.predict(test_loader_EMNIST, model_dla).cpu().numpy()
conf_emnist = get_confidence(py_out)
mmc = conf_emnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - EMNIST'], mmc, auroc)
print(f'[Out-EMNIST, DLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FMNIST
py_out = lutil.predict(test_loader_FMNIST, model_dla).cpu().numpy()
conf_fmnist = get_confidence(py_out)
mmc = conf_fmnist.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FMNIST'], mmc, auroc)
print(f'[Out-FMNIST, DLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAway
py_out = lutil.predict(noise_loader, model_dla, delta=delta).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAway'], mmc, auroc)
print(f'[Out-FarAway, DLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - Adversarial
py_out = lutil.predict(test_loader_adv_nonasymp, model_dla).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - Adversarial'], mmc, auroc)
print(f'[Out-Adversarial, DLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
# Out-distribution - FarAwayAdversarial
py_out = lutil.predict(test_loader_adv_asymp, model_dla).cpu().numpy()
conf_farway = get_confidence(py_out)
mmc = conf_farway.mean()
auroc = get_auroc(py_in, py_out)
save_res_ood(tab_ood['MNIST - FarAwayAdv'], mmc, auroc)
print(f'[Out-FarAwayAdv, DLA] MMC: {mmc:.3f}; AUROC: {auroc:.3f}')
print()
if args.generate_histograms:
plot_histogram([conf_in, conf_emnist, conf_farway], ['In - MNIST', 'Out - EMNIST', 'Out - FarAway'], 'hist_confs_mnist_dla')
"""
=============================================================================================
KFLA
=============================================================================================
"""
model = load_model()
model_kfla = kfla.KFLA(model)
if args.compute_hessian:
_, time_inf = timing(lambda: model_kfla.get_hessian(train_loader))
# interval = torch.logspace(-6, 0, 100)
# var0 = model_kfla.gridsearch_var0(val_loader, ood_loader, interval, n_classes=100, lam=0.25)
if args.type == 'plain':
var0 = torch.tensor(0.0070).float().cuda()
elif args.type == 'ACET':
var0 = torch.tensor(1.3219e-06).float().cuda()
else:
var0 = torch.tensor(0.0115).float().cuda()
print(var0)
model_kfla.estimate_variance(var0)
torch.save(model_kfla.state_dict(), f'./pretrained_models/MNIST_{args.type}_kfla.pt')
else:
time_inf = 0
model_kfla.load_state_dict(torch.load(f'./pretrained_models/MNIST_{args.type}_kfla.pt'))
model_kfla.eval()
# In-distribution
py_in, time_pred = timing(lambda: lutil.predict(test_loader, model_kfla).cpu().numpy())
acc_in = np.mean(np.argmax(py_in, 1) == targets)
conf_in = get_confidence(py_in)
mmc = conf_in.mean()
ece, mce = get_calib(py_in, targets)
save_res_ood(tab_ood['MNIST - MNIST'], mmc)
save_res_cal(tab_cal['KFLA'], ece, mce)
print(f'[In, KFLA] Time: {time_inf:.1f}/{time_pred:.1f}s; Accuracy: {acc_in:.3f}; ECE: {ece:.3f}; MCE: | |
source collection + postfix.
destination_parent_collection_name -- name of the destination parent collection (default None).
This is the collection that would have the copied collection as a child.
use 'Root' for the root collection.
destination_parent_collection_id -- id of the destination parent collection (default None).
This is the collection that would have the copied collection as a child.
deepcopy_dashboards -- whether to duplicate the cards inside the dashboards (default False).
If True, puts the duplicated cards in a collection called "[dashboard_name]'s duplicated cards"
in the same path as the duplicated dashboard.
postfix -- if destination_collection_name is None, adds this string to the end of source_collection_name to make destination_collection_name.
child_items_postfix -- this string is added to the end of the child items' names, when saving them in the destination (default '').
verbose -- prints extra information (default False)
"""
### making sure we have the data that we need
if not source_collection_id:
if not source_collection_name:
raise ValueError('Either the name or id of the source collection must be provided.')
else:
source_collection_id = self.get_item_id('collection', source_collection_name)
if not destination_parent_collection_id:
if not destination_parent_collection_name:
raise ValueError('Either the name or id of the destination parent collection must be provided.')
else:
destination_parent_collection_id = (
self.get_item_id('collection', destination_parent_collection_name)
if destination_parent_collection_name != 'Root'
else None
)
if not destination_collection_name:
if not source_collection_name:
source_collection_name = self.get_item_name(item_type='collection', item_id=source_collection_id)
destination_collection_name = source_collection_name + postfix
### create a collection in the destination to hold the contents of the source collection
res = self.create_collection(destination_collection_name,
parent_collection_id=destination_parent_collection_id,
parent_collection_name=destination_parent_collection_name,
return_results=True
)
destination_collection_id = res['id']
### get the items to copy
items = self.get('/api/collection/{}/items'.format(source_collection_id))
if type(items) == dict: # in Metabase version *.40.0 the format of the returned result for this endpoint changed
items = items['data']
### copy the items of the source collection to the new collection
for item in items:
## copy a collection
if item['model'] == 'collection':
collection_id = item['id']
collection_name = item['name']
destination_collection_name = collection_name + child_items_postfix
self.verbose_print(verbose, 'Copying the collection "{}" ...'.format(collection_name))
self.copy_collection(source_collection_id=collection_id,
destination_parent_collection_id=destination_collection_id,
child_items_postfix=child_items_postfix,
deepcopy_dashboards=deepcopy_dashboards,
verbose=verbose)
## copy a dashboard
if item['model'] == 'dashboard':
dashboard_id = item['id']
dashboard_name = item['name']
destination_dashboard_name = dashboard_name + child_items_postfix
self.verbose_print(verbose, 'Copying the dashboard "{}" ...'.format(dashboard_name))
self.copy_dashboard(source_dashboard_id=dashboard_id,
destination_collection_id=destination_collection_id,
destination_dashboard_name=destination_dashboard_name,
deepcopy=deepcopy_dashboards)
## copy a card
if item['model'] == 'card':
card_id = item['id']
card_name = item['name']
destination_card_name = card_name + child_items_postfix
self.verbose_print(verbose, 'Copying the card "{}" ...'.format(card_name))
self.copy_card(source_card_id=card_id,
destination_collection_id=destination_collection_id,
destination_card_name=destination_card_name)
## copy a pulse
if item['model'] == 'pulse':
pulse_id = item['id']
pulse_name = item['name']
destination_pulse_name = pulse_name + child_items_postfix
self.verbose_print(verbose, 'Copying the pulse "{}" ...'.format(pulse_name))
self.copy_pulse(source_pulse_id=pulse_id,
destination_collection_id=destination_collection_id,
destination_pulse_name=destination_pulse_name)
def search(self, q, item_type=None, archived=False):
"""
Search for Metabase objects and return their basic info.
We can limit the search to a certain item type by providing a value for item_type keyword.
Keyword arguments:
q -- search input
item_type -- to limit the search to certain item types (default:None, means no limit)
archived -- whether to include archived items in the search
"""
assert item_type in [None, 'card', 'dashboard', 'collection', 'table', 'pulse', 'segment', 'metric' ]
assert archived in [True, False]
res = self.get(endpoint='/api/search/', params={'q':q, 'archived':archived})
if type(res) == dict: # in Metabase version *.40.0 the format of the returned result for this endpoint changed
res = res['data']
if item_type is not None:
res = [ item for item in res if item['model'] == item_type ]
return res
def get_card_data(self, card_name=None, card_id=None, collection_name=None, collection_id=None, data_format='json', parameters=None):
'''
Run the query associated with a card and get the results.
The data_format keyword specifies the format of the returned data:
- 'json': every row is a dictionary of <column-header, cell> key-value pairs
- 'csv': the entire result is returned as a string, where rows are separated by newlines and cells with commas.
To pass the filter values use 'parameters' param:
The format is like [{"type":"category","value":["val1","val2"],"target":["dimension",["template-tag","filter_variable_name"]]}]
See the network tab when exporting the results using the web interface to get the proper format pattern.
'''
assert data_format in [ 'json', 'csv' ]
if parameters:
assert type(parameters) == list
if card_id is None:
if card_name is None:
raise ValueError('Either card_id or card_name must be provided.')
card_id = self.get_item_id(item_name=card_name,
collection_name=collection_name,
collection_id=collection_id,
item_type='card')
# add the filter values (if any)
import json
params_json = {'parameters':json.dumps(parameters)}
# get the results
res = self.post("/api/card/{}/query/{}".format(card_id, data_format), 'raw', data=params_json)
# return the results in the requested format
if data_format == 'json':
return json.loads(res.text)
if data_format == 'csv':
return res.text.replace('null', '')
def clone_card(self, card_id
, source_table_id=None, target_table_id=None
, source_table_name=None, target_table_name=None
, new_card_name=None, new_card_collection_id=None
, ignore_these_filters=None
, return_card=False):
"""
*** work in progress ***
Create a new card where the source of the old card is changed from 'source_table_id' to 'target_table_id'.
The filters that were based on the old table would become based on the new table.
In the current version of the function there are some limitations which would be removed in future versions:
- The column names used in filters need to be the same in the source and target table (except the ones that are ignored by 'ignore_these_filters' param).
- The source and target tables need to be in the same DB.
Keyword arguments:
card_id -- id of the card
source_table_id -- The table that the filters of the card are based on
target_table_id -- The table that the filters of the cloned card would be based on
new_card_name -- Name of the cloned card. If not provided, the name of the source card is used.
new_card_collection_id -- The id of the collection that the cloned card should be saved in
ignore_these_filters -- A list of variable names of filters. The source of these filters would not change in the cloning process.
return_card -- Whether to return the info of the created card (default False)
"""
# Make sure we have the data we need
if not source_table_id:
if not source_table_name:
raise ValueError('Either the name or id of the source table needs to be provided.')
else:
source_table_id = self.get_item_id('table', source_table_name)
if not target_table_id:
if not target_table_name:
raise ValueError('Either the name or id of the target table needs to be provided.')
else:
source_table_id = self.get_item_id('table', source_table_name)
if ignore_these_filters:
assert type(ignore_these_filters) == list
# get the card info
card_info = self.get_item_info('card', card_id)
# get the mappings, both name -> id and id -> name
target_table_col_name_id_mapping = self.get_columns_name_id(table_id=target_table_id)
source_table_col_id_name_mapping = self.get_columns_name_id(table_id=source_table_id, column_id_name=True)
# native questions
if card_info['dataset_query']['type'] == 'native':
filters_data = card_info['dataset_query']['native']['template-tags']
# change the underlying table for the card
if not source_table_name:
source_table_name = self.get_item_name('table', source_table_id)
if not target_table_name:
target_table_name = self.get_item_name('table', target_table_id)
card_info['dataset_query']['native']['query'] = card_info['dataset_query']['native']['query'].replace(source_table_name, target_table_name)
# change filters source
for filter_variable_name, data in filters_data.items():
if ignore_these_filters is not None and filter_variable_name in ignore_these_filters:
continue
column_id = data['dimension'][1]
column_name = source_table_col_id_name_mapping[column_id]
target_col_id = target_table_col_name_id_mapping[column_name]
card_info['dataset_query']['native']['template-tags'][filter_variable_name]['dimension'][1] = target_col_id
# simple/custom questions
elif card_info['dataset_query']['type'] == 'query':
filters_data = card_info['dataset_query']['query']
# change the underlying table for the card
filters_data['source-table'] = target_table_id
# change filters source
for index, item in enumerate(filters_data['filter']):
if type(item) == list:
column_id = item[1][1]
column_name = source_table_col_id_name_mapping[column_id]
target_col_id = target_table_col_name_id_mapping[column_name]
card_info['dataset_query']['query']['filter'][index][1][1] = target_col_id
new_card_json = {}
for key in ['dataset_query', 'display', 'visualization_settings']:
new_card_json[key] = card_info[key]
if new_card_name:
new_card_json['name'] = new_card_name
else:
new_card_json['name'] = card_info['name']
if new_card_collection_id:
new_card_json['collection_id'] = new_card_collection_id
else:
new_card_json['collection_id'] = card_info['collection_id']
if return_card:
return self.create_card(custom_json=new_card_json, verbose=True, return_card=return_card)
else:
self.create_card(custom_json=new_card_json, verbose=True)
def move_to_archive(self, item_type, item_name=None, item_id=None
, collection_name=None, collection_id=None, table_id=None, verbose=False):
'''Archive the given item. For deleting the item use the 'delete_item' function.'''
assert item_type in ['card', 'dashboard', 'collection', 'pulse', 'segment']
if not item_id:
if not item_name:
raise ValueError('Either the name or id of the {} must be provided.'.format(item_type))
if item_type == 'collection':
item_id = self.get_item_id('collection', item_name)
elif item_type == 'segment':
item_id = self.get_item_id('segment', item_name, table_id=table_id)
else:
item_id = self.get_item_id(item_type, item_name, collection_id, collection_name)
if item_type == 'segment':
# 'revision_message' is mandatory for archiving segments
res = self.put('/api/{}/{}'.format(item_type, item_id), json={'archived':True, 'revision_message':'archived!'})
else:
res = self.put('/api/{}/{}'.format(item_type, item_id), json={'archived':True})
if | |
and iEra <= iRenaissance:
return "TXT_KEY_CIV_MOORS_ALMOHAD"
if not utils.isPlotInArea(tCapitalCoords, vic.tIberiaTL, vic.tIberiaBR):
return "TXT_KEY_CIV_MOORS_MOROCCAN"
elif iPlayer == iSpain:
bSpain = not pMoors.isAlive() or not utils.isPlotInArea(capitalCoords(iMoors), vic.tIberiaTL, vic.tIberiaBR)
if bSpain:
if not pPortugal.isAlive() or getMaster(iPortugal) == iPlayer or not utils.isPlotInArea(capitalCoords(iPortugal), vic.tIberiaTL, vic.tIberiaBR):
return "TXT_KEY_CIV_SPAIN_IBERIAN"
if isCapital(iPlayer, ["Barcelona", "Valencia"]):
return "TXT_KEY_CIV_SPAIN_ARAGONESE"
if not bSpain:
return "TXT_KEY_CIV_SPAIN_CASTILIAN"
elif iPlayer == iFrance:
if iEra == iMedieval and not pHolyRome.isAlive():
return "TXT_KEY_CIV_FRANCE_FRANKISH"
elif iPlayer == iEngland:
if getColumn(iEngland) >= 11 and countPlayerAreaCities(iPlayer, utils.getPlotList(tBritainTL, tBritainBR)) >= 3:
return "TXT_KEY_CIV_ENGLAND_BRITISH"
elif iPlayer == iHolyRome:
if isCapital(iPlayer, ["Buda"]):
return "TXT_KEY_CIV_HOLY_ROME_HUNGARIAN"
if pGermany.isAlive() and iCivicLegitimacy == iConstitution:
return "TXT_KEY_CIV_HOLY_ROME_AUSTRO_HUNGARIAN"
iVassals = 0
for iLoopPlayer in lCivGroups[0]:
if getMaster(iLoopPlayer) == iPlayer:
iVassals += 1
if iVassals >= 2:
return "TXT_KEY_CIV_HOLY_ROME_HABSBURG"
if not bEmpire and iGameTurn < getTurnForYear(tBirth[iGermany]):
return "TXT_KEY_CIV_HOLY_ROME_GERMAN"
elif iPlayer == iInca:
if bResurrected:
if isCapital(iPlayer, ["La Paz"]):
return "TXT_KEY_CIV_INCA_BOLIVIAN"
elif iPlayer == iItaly:
if bCityStates and bWar:
if not bEmpire:
return "TXT_KEY_CIV_ITALY_LOMBARD"
elif iPlayer == iMongolia:
if not bEmpire and iEra <= iRenaissance:
if capital.getRegionID() == rChina:
return "TXT_KEY_CIV_MONGOLIA_YUAN"
if capital.getRegionID() == rPersia:
return "TXT_KEY_CIV_MONGOLIA_HULAGU"
if capital.getRegionID() == rCentralAsia:
return "TXT_KEY_CIV_MONGOLIA_CHAGATAI"
if bMonarchy:
return "TXT_KEY_CIV_MONGOLIA_MONGOL"
elif iPlayer == iOttomans:
return "TXT_KEY_CIV_OTTOMANS_OTTOMAN"
elif iPlayer == iNetherlands:
if isCapital(iPlayer, ["Brussels", "Antwerpen"]):
return "TXT_KEY_CIV_NETHERLANDS_BELGIAN"
elif iPlayer == iGermany:
if getColumn(iGermany) <= 14 and pHolyRome.isAlive() and not teamHolyRome.isVassal(iGermany):
return "TXT_KEY_CIV_GERMANY_PRUSSIAN"
### Title methods ###
def title(iPlayer):
if isCapitulated(iPlayer):
sVassalTitle = vassalTitle(iPlayer, getMaster(iPlayer))
if sVassalTitle: return sVassalTitle
if isCommunist(iPlayer):
sCommunistTitle = communistTitle(iPlayer)
if sCommunistTitle: return sCommunistTitle
if isFascist(iPlayer):
sFascistTitle = fascistTitle(iPlayer)
if sFascistTitle: return sFascistTitle
if isRepublic(iPlayer):
sRepublicTitle = republicTitle(iPlayer)
if sRepublicTitle: return sRepublicTitle
sSpecificTitle = specificTitle(iPlayer)
if sSpecificTitle: return sSpecificTitle
return defaultTitle(iPlayer)
def vassalTitle(iPlayer, iMaster):
if isCommunist(iMaster):
sCommunistTitle = getOrElse(getOrElse(dCommunistVassalTitles, iMaster, {}), iPlayer)
if sCommunistTitle: return sCommunistTitle
sCommunistTitle = getOrElse(dCommunistVassalTitlesGeneric, iMaster)
if sCommunistTitle: return sCommunistTitle
if isFascist(iMaster):
sFascistTitle = getOrElse(getOrElse(dFascistVassalTitles, iMaster, {}), iPlayer)
if sFascistTitle: return sFascistTitle
sFascistTitle = getOrElse(dFascistVassalTitlesGeneric, iMaster)
if sFascistTitle: return sFascistTitle
if short(iMaster) == "Austria" and iPlayer == iPoland:
return "TXT_KEY_CIV_AUSTRIAN_POLAND"
if iMaster == iEngland and iPlayer == iMughals:
if not pIndia.isAlive():
return vassalTitle(iIndia, iEngland)
if iMaster == iSpain and short(iPlayer) == "Colombia":
return "TXT_KEY_CIV_SPANISH_COLOMBIA"
if iMaster not in lRebirths or not gc.getPlayer(iMaster).isReborn():
sSpecificTitle = getOrElse(getOrElse(dSpecificVassalTitles, iMaster, {}), iPlayer)
if sSpecificTitle: return sSpecificTitle
sMasterTitle = getOrElse(dMasterTitles, iMaster)
if sMasterTitle: return sMasterTitle
if iMaster not in lColonies and iMaster != iArgentina and iMaster != iBrazil and iPlayer in lColonies:
return "TXT_KEY_COLONY_OF"
return "TXT_KEY_PROTECTORATE_OF"
def communistTitle(iPlayer):
if iPlayer in lSocialistRepublicOf: return "TXT_KEY_SOCIALIST_REPUBLIC_OF"
if iPlayer in lSocialistRepublicAdj: return "TXT_KEY_SOCIALIST_REPUBLIC_ADJECTIVE"
if iPlayer in lPeoplesRepublicOf: return "TXT_KEY_PEOPLES_REPUBLIC_OF"
if iPlayer in lPeoplesRepublicAdj: return "TXT_KEY_PEOPLES_REPUBLIC_ADJECTIVE"
return key(iPlayer, "COMMUNIST")
def fascistTitle(iPlayer):
return key(iPlayer, "FASCIST")
def republicTitle(iPlayer):
if iPlayer == iHolyRome:
return "TXT_KEY_REPUBLIC_ADJECTIVE"
if iPlayer == iPoland:
if gc.getPlayer(iPlayer).getCurrentEra() <= iIndustrial:
return key(iPlayer, "COMMONWEALTH")
if iPlayer == iEngland:
iEra = gc.getPlayer(iPlayer).getCurrentEra()
if isEmpire(iEngland) and iEra == iIndustrial:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if iEra >= iGlobal:
return "TXT_KEY_CIV_ENGLAND_UNITED_REPUBLIC"
if iPlayer == iAmerica:
_, _, iCivicSociety, _, _, _ = getCivics(iPlayer)
if iCivicSociety in [iManorialism, iSlavery]:
return key(iPlayer, "CSA")
if iPlayer == iMaya:
if gc.getPlayer(iMaya).isReborn():
if isRegionControlled(iPlayer, rPeru) and isAreaControlled(iPlayer, tColombiaTL, tColombiaBR):
return "TXT_KEY_CIV_COLOMBIA_FEDERATION_ANDES"
if gc.getPlayer(iPlayer).getStateReligion() == iIslam:
if iPlayer in lIslamicRepublicOf: return "TXT_KEY_ISLAMIC_REPUBLIC_OF"
if iPlayer == iOttomans: return key(iPlayer, "ISLAMIC_REPUBLIC")
if iPlayer in lRepublicOf: return "TXT_KEY_REPUBLIC_OF"
if iPlayer in lRepublicAdj: return "TXT_KEY_REPUBLIC_ADJECTIVE"
return key(iPlayer, "REPUBLIC")
def defaultTitle(iPlayer):
return desc(iPlayer, key(iPlayer, "DEFAULT"))
def specificTitle(iPlayer, lPreviousOwners=[]):
iGameTurn = gc.getGame().getGameTurn()
pPlayer = gc.getPlayer(iPlayer)
tPlayer = gc.getTeam(pPlayer.getTeam())
iCivicGovernment, iCivicLegitimacy, iCivicSociety, iCivicEconomy, iCivicReligion, iCivicTerritory = getCivics(iPlayer)
iNumCities = pPlayer.getNumCities()
if iNumCities == 0: return defaultTitle(iPlayer)
bReborn = pPlayer.isReborn()
iReligion = pPlayer.getStateReligion()
capital = gc.getPlayer(iPlayer).getCapitalCity()
tCapitalCoords = capitalCoords(iPlayer)
bAnarchy = pPlayer.isAnarchy()
bEmpire = isEmpire(iPlayer)
bCityStates = isCityStates(iPlayer)
bTheocracy = (iCivicReligion == iTheocracy)
bResurrected = data.players[iPlayer].iResurrections > 0
bCapitulated = isCapitulated(iPlayer)
iAnarchyTurns = data.players[iPlayer].iAnarchyTurns
iEra = pPlayer.getCurrentEra()
iGameEra = gc.getGame().getCurrentEra()
bWar = isAtWar(iPlayer)
if iPlayer == iEgypt:
if bResurrected or utils.getScenario() >= i600AD:
if iReligion == iIslam:
if bTheocracy: return "TXT_KEY_CALIPHATE_ADJECTIVE"
return "TXT_KEY_SULTANATE_ADJECTIVE"
return "TXT_KEY_KINGDOM_ADJECTIVE"
if iGreece in lPreviousOwners:
return "TXT_KEY_CIV_EGYPT_PTOLEMAIC"
if bCityStates:
return "TXT_KEY_CITY_STATES_ADJECTIVE"
if iEra == iAncient:
if iAnarchyTurns == 0: return "TXT_KEY_CIV_EGYPT_OLD_KINGDOM"
if iAnarchyTurns == utils.getTurns(1): return "TXT_KEY_CIV_EGYPT_MIDDLE_KINGDOM"
return "TXT_KEY_CIV_EGYPT_NEW_KINGDOM"
if iEra == iClassical:
return "TXT_KEY_CIV_EGYPT_NEW_KINGDOM"
elif iPlayer == iIndia:
if iReligion == iIslam:
return "TXT_KEY_SULTANATE_OF"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if iEra >= iRenaissance:
return "TXT_KEY_CONFEDERACY_ADJECTIVE"
if bCityStates:
return "TXT_KEY_CIV_INDIA_MAHAJANAPADAS"
elif iPlayer == iChina:
if bEmpire:
if iEra >= iIndustrial or utils.getScenario() == i1700AD:
return "TXT_KEY_EMPIRE_OF"
if iEra == iRenaissance and iGameTurn >= getTurnForYear(1400):
return "TXT_KEY_EMPIRE_OF"
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iBabylonia:
if bCityStates and not bEmpire:
return "TXT_KEY_CITY_STATES_ADJECTIVE"
if bEmpire and iEra > iAncient:
return "TXT_KEY_CIV_BABYLONIA_NEO_EMPIRE"
elif iPlayer == iGreece:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if bCityStates:
if bWar:
return "TXT_KEY_CIV_GREECE_LEAGUE"
return "TXT_KEY_CITY_STATES_ADJECTIVE"
elif iPlayer == iPersia:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iPhoenicia:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if bCityStates:
return "TXT_KEY_CITY_STATES_ADJECTIVE"
elif iPlayer == iPolynesia:
if isCapital(iPlayer, ["Kaua'i", "O'ahu", "Maui"]):
return "TXT_KEY_KINGDOM_OF"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iRome:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if bCityStates:
return "TXT_KEY_REPUBLIC_ADJECTIVE"
elif iPlayer == iMaya:
if bReborn:
if bEmpire:
if isRegionControlled(iPlayer, rPeru) and isAreaControlled(iPlayer, tColombiaTL, tColombiaBR):
return "TXT_KEY_CIV_COLOMBIA_EMPIRE_ANDES"
return "TXT_KEY_CIV_COLOMBIA_EMPIRE"
elif iPlayer == iJapan:
if bEmpire:
return "TXT_KEY_EMPIRE_OF"
if iCivicLegitimacy == iCentralism:
return "TXT_KEY_EMPIRE_OF"
if iEra >= iIndustrial:
return "TXT_KEY_EMPIRE_OF"
elif iPlayer == iTamils:
if iReligion == iIslam:
return "TXT_KEY_SULTANATE_ADJECTIVE"
if iEra >= iMedieval:
return "TXT_KEY_KINGDOM_OF"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iEthiopia:
if bCityStates:
return "TXT_KEY_CITY_STATES_ADJECTIVE"
if iReligion == iIslam:
return "TXT_KEY_SULTANATE_ADJECTIVE"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iKorea:
if iEra >= iIndustrial:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if iEra == iClassical:
if bEmpire:
return "TXT_KEY_EMPIRE_OF"
if bCityStates:
return "TXT_KEY_CIV_KOREA_SAMHAN"
if iReligion >= 0:
return "TXT_KEY_KINGDOM_OF"
elif iPlayer == iByzantium:
if iReligion == iIslam:
return "TXT_KEY_SULTANATE_OF"
if tCapitalCoords != Areas.getCapital(iPlayer):
if capital.getRegionID() == rAnatolia:
return "TXT_KEY_EMPIRE_OF"
return "TXT_KEY_CIV_BYZANTIUM_DESPOTATE"
elif iPlayer == iVikings:
if bCityStates:
return "TXT_KEY_CIV_VIKINGS_ALTHINGS"
if isAreaControlled(iPlayer, tBritainTL, tBritainBR):
return "TXT_KEY_CIV_VIKINGS_NORTH_SEA_EMPIRE"
if iReligion < 0 and iEra < iRenaissance:
return "TXT_KEY_CIV_VIKINGS_NORSE_KINGDOMS"
if bEmpire:
if iEra <= iMedieval:
return "TXT_KEY_CIV_VIKINGS_KALMAR_UNION"
if iEra == iRenaissance or isCapital(iPlayer, ["Stockholm"]):
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iTurks:
if bCityStates or iCivicGovernment == iElective:
return "TXT_KEY_CIV_TURKS_KURULTAI"
if iReligion >= 0:
if bEmpire:
if isAreaControlled(iTurks, Areas.tCoreArea[iPersia][0], Areas.tCoreArea[iPersia][1]) and not bResurrected:
return "TXT_KEY_CIV_TURKS_GREAT_EMPIRE"
return "TXT_KEY_EMPIRE_ADJECTIVE"
if not isAreaControlled(iTurks, Areas.tCoreArea[iPersia][0], Areas.tCoreArea[iPersia][1]):
return "TXT_KEY_CIV_TURKS_KHANATE_OF"
if iReligion == iIslam:
if isAreaControlled(iTurks, Areas.tCoreArea[iPersia][0], Areas.tCoreArea[iPersia][1]):
return "TXT_KEY_SULTANATE_ADJECTIVE"
return "TXT_KEY_SULTANATE_OF"
return "TXT_KEY_KINGDOM_OF"
if bEmpire:
return "TXT_KEY_CIV_TURKS_KHAGANATE"
elif iPlayer == iArabia:
if bResurrected:
return "TXT_KEY_KINGDOM_OF"
if iReligion == iIslam and (bTheocracy or controlsHolyCity(iArabia, iIslam)):
return "TXT_KEY_CALIPHATE_ADJECTIVE"
elif iPlayer == iTibet:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iKhmer:
if iEra <= iRenaissance and isCapital(iPlayer, ["Angkor"]):
return "TXT_KEY_EMPIRE_ADJECTIVE"
if isCapital(iPlayer, ["Hanoi"]):
return "TXT_KEY_CIV_KHMER_DAI_VIET"
elif iPlayer == iIndonesia:
if iReligion == iIslam:
return "TXT_KEY_SULTANATE_OF"
elif iPlayer == iMoors:
if bCityStates:
return "TXT_KEY_CIV_MOORS_TAIFAS"
if iReligion == iIslam and utils.isPlotInArea(tCapitalCoords, vic.tIberiaTL, vic.tIberiaBR):
if bEmpire:
return "TXT_KEY_CALIPHATE_OF"
return "TXT_KEY_CIV_MOORS_EMIRATE_OF"
if bEmpire and iEra <= iRenaissance:
if iReligion == iIslam and bTheocracy:
return "TXT_KEY_CALIPHATE_ADJECTIVE"
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iSpain:
if iReligion == iIslam:
return "TXT_KEY_SULTANATE_OF"
if bEmpire and iEra > iMedieval:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if iEra == iMedieval and isCapital(iPlayer, ["Barcelona", "Valencia"]):
return "TXT_KEY_CIV_SPAIN_CROWN_OF"
elif iPlayer == iFrance:
if not tCapitalCoords in Areas.getNormalArea(iPlayer):
return "TXT_KEY_CIV_FRANCE_EXILE"
if iEra >= iIndustrial and bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if iCivicLegitimacy == iRevolutionism:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if not pHolyRome.isAlive() and iEra == iMedieval:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iEngland:
if not utils.isPlotInCore(iPlayer, tCapitalCoords):
return "TXT_KEY_CIV_ENGLAND_EXILE"
if iEra == iMedieval and getMaster(iFrance) == iEngland:
return "TXT_KEY_CIV_ENGLAND_ANGEVIN_EMPIRE"
if getColumn(iPlayer) >= 11:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if countPlayerAreaCities(iPlayer, utils.getPlotList(tBritainTL, tBritainBR)) >= 3:
return "TXT_KEY_CIV_ENGLAND_UNITED_KINGDOM_OF"
elif iPlayer == iHolyRome:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if isCapital(iPlayer, ["Buda"]):
return "TXT_KEY_KINGDOM_OF"
if pGermany.isAlive():
return "TXT_KEY_CIV_HOLY_ROME_ARCHDUCHY_OF"
elif iPlayer == iRussia:
if bEmpire and iEra >= iRenaissance:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if bCityStates and iEra <= iMedieval:
if isCapital(iPlayer, ["Kiev"]):
return "TXT_KEY_CIV_RUSSIA_KIEVAN_RUS"
return "TXT_KEY_CIV_RUSSIA_RUS"
if isAreaControlled(iPlayer, tEuropeanRussiaTL, tEuropeanRussiaBR, 5, tEuropeanRussiaExceptions):
return "TXT_KEY_CIV_RUSSIA_TSARDOM_OF"
elif iPlayer == iNetherlands:
if bCityStates:
return "TXT_KEY_CIV_NETHERLANDS_REPUBLIC"
if not utils.isPlotInCore(iPlayer, tCapitalCoords):
return "TXT_KEY_CIV_NETHERLANDS_EXILE"
if bEmpire:
if iEra >= iIndustrial:
return "TXT_KEY_EMPIRE_ADJECTIVE"
return "TXT_KEY_CIV_NETHERLANDS_UNITED_KINGDOM_OF"
# Nothing for Mali
elif iPlayer == iPoland:
if iEra >= iRenaissance and bEmpire:
return "TXT_KEY_CIV_POLAND_COMMONWEALTH"
if isCapital(iPlayer, ["Kowno", "Medvegalis", "Wilno", "Ryga"]):
return "TXT_KEY_CIV_POLAND_GRAND_DUCHY_OF"
elif iPlayer == iPortugal:
if utils.isPlotInCore(iBrazil, tCapitalCoords) and not pBrazil.isAlive():
return "TXT_KEY_CIV_PORTUGAL_BRAZIL"
if not utils.isPlotInArea(tCapitalCoords, vic.tIberiaTL, vic.tIberiaBR):
return "TXT_KEY_CIV_PORTUGAL_EXILE"
if bEmpire and iEra >= iRenaissance:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iInca:
if not bResurrected:
if bEmpire:
return "TXT_KEY_CIV_INCA_FOUR_REGIONS"
elif iPlayer == iItaly:
if bCityStates:
if bWar:
return "TXT_KEY_CIV_ITALY_LEAGUE"
return "TXT_KEY_CIV_ITALY_MARITIME_REPUBLICS"
if not bResurrected:
if iReligion == iCatholicism:
if bTheocracy:
return "TXT_KEY_CIV_ITALY_PAPAL_STATES"
if isCapital(iItaly, ["Roma"]):
return "TXT_KEY_CIV_ITALY_PAPAL_STATES"
if not bEmpire:
return "TXT_KEY_CIV_ITALY_DUCHY_OF"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iMongolia:
if capital.getRegionID() == rPersia:
return "TXT_KEY_CIV_MONGOLIA_ILKHANATE"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if iEra <= iRenaissance:
if iNumCities <= 3:
return "TXT_KEY_CIV_MONGOLIA_KHAMAG"
return "TXT_KEY_CIV_MONGOLIA_KHANATE"
elif iPlayer == iAztecs:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if bCityStates:
return "TXT_KEY_CIV_AZTECS_ALTEPETL"
elif iPlayer == iMughals:
if bResurrected:
if bEmpire:
return "TXT_KEY_EMPIRE_OF"
return "TXT_KEY_SULTANATE_OF"
if iEra == iMedieval and not bEmpire:
return "TXT_KEY_SULTANATE_OF"
elif iPlayer == iOttomans:
if iReligion == iIslam:
if bTheocracy and gc.getGame().getHolyCity(iIslam) and gc.getGame().getHolyCity(iIslam).getOwner() == iOttomans:
return "TXT_KEY_CALIPHATE_ADJECTIVE"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
return "TXT_KEY_SULTANATE_ADJECTIVE"
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iThailand:
if iEra >= iIndustrial and bEmpire:
return "TXT_KEY_EMPIRE_OF"
elif iPlayer == iGermany:
if iEra >= iIndustrial and bEmpire:
if getMaster(iHolyRome) == iGermany:
return "TXT_KEY_CIV_GERMANY_GREATER_EMPIRE"
return "TXT_KEY_EMPIRE_ADJECTIVE"
elif iPlayer == iAmerica:
if iCivicSociety in [iSlavery, iManorialism]:
if isRegionControlled(iAmerica, rMesoamerica) and isRegionControlled(iAmerica, rCaribbean):
return "TXT_KEY_CIV_AMERICA_GOLDEN_CIRCLE"
return "TXT_KEY_CIV_AMERICA_CSA"
elif iPlayer == iArgentina:
if bEmpire:
return "TXT_KEY_EMPIRE_ADJECTIVE"
if tCapitalCoords != Areas.getCapital(iPlayer):
return "TXT_KEY_CIV_ARGENTINA_CONFEDERATION"
elif iPlayer == iBrazil:
if bEmpire:
return "TXT_KEY_EMPIRE_OF"
return None
### Leader methods ###
def startingLeader(iPlayer):
if iPlayer in dStartingLeaders[utils.getScenario()]: return dStartingLeaders[utils.getScenario()][iPlayer]
return dStartingLeaders[i3000BC][iPlayer]
def leader(iPlayer):
if iPlayer >= iNumPlayers: return None
if not gc.getPlayer(iPlayer).isAlive(): return None
if gc.getPlayer(iPlayer).isHuman(): return None
pPlayer = gc.getPlayer(iPlayer)
tPlayer = gc.getTeam(pPlayer.getTeam())
bReborn = pPlayer.isReborn()
iReligion = pPlayer.getStateReligion()
capital = gc.getPlayer(iPlayer).getCapitalCity()
tCapitalCoords = (capital.getX(), capital.getY())
iCivicGovernment, iCivicLegitimacy, iCivicSociety, iCivicEconomy, iCivicReligion, iCivicTerritory = getCivics(iPlayer)
iGameTurn = gc.getGame().getGameTurn()
bEmpire = isEmpire(iPlayer)
bCityStates = isCityStates(iPlayer)
bTheocracy = (iCivicReligion == iTheocracy)
bResurrected = data.players[iPlayer].iResurrections > 0
bMonarchy = not (isCommunist(iPlayer) or isFascist(iPlayer) or isRepublic(iPlayer))
iAnarchyTurns = data.players[iPlayer].iAnarchyTurns
iEra = pPlayer.getCurrentEra()
iGameEra = gc.getGame().getCurrentEra()
if iPlayer == iEgypt:
if not bMonarchy and iEra >= iGlobal: return iNasser
if bResurrected or utils.getScenario() >= i600AD: return iBaibars
if getColumn(iPlayer) >= 4: return iCleopatra
elif iPlayer == iIndia:
if not bMonarchy and iEra >= iGlobal: return iGandhi
if iEra >= iRenaissance: return iShahuji
if getColumn(iPlayer) >= 5: return iChandragupta
elif iPlayer == iChina:
if isCommunist(iPlayer) or isRepublic(iPlayer) and iEra >= iIndustrial: return iMao
if iEra >= iRenaissance and iGameTurn >= getTurnForYear(1400): return iHongwu
if bResurrected: return iHongwu
if utils.getScenario() >= i1700AD: return iHongwu
if iEra >= iMedieval: return iTaizong
elif iPlayer == iBabylonia:
if iGameTurn >= getTurnForYear(-1600): return iHammurabi
elif iPlayer == iGreece:
if iEra >= iIndustrial: return iGeorge
if bResurrected and getColumn(iPlayer) >= 11: return iGeorge
if bEmpire: return iAlexanderTheGreat
if not bCityStates: return iAlexanderTheGreat
elif iPlayer == iPersia:
if bReborn:
if | |
freq_max=params_dict["freq_max"], unit_ids=unit_ids,
duration_in_frames=None, verbose=params_dict['verbose'])
md.compute_pca_scores(**kwargs)
d_prime = DPrime(metric_data=md)
d_primes = d_prime.compute_metric(num_channels_to_compare, max_spikes_per_cluster, **kwargs)
return d_primes
def compute_l_ratios(
sorting,
recording,
num_channels_to_compare=LRatio.params['num_channels_to_compare'],
max_spikes_per_cluster=LRatio.params['max_spikes_per_cluster'],
unit_ids=None,
**kwargs
):
"""
Computes and returns the l ratios in the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be evaluated
recording: RecordingExtractor
The given recording extractor from which to extract amplitudes
num_channels_to_compare: int
The number of channels to be used for the PC extraction and comparison
max_spikes_per_cluster: int
Max spikes to be used from each unit
unit_ids: list
List of unit ids to compute metric for. If not specified, all units are used
**kwargs: keyword arguments
Keyword arguments among the following:
method: str
If 'absolute' (default), amplitudes are absolute amplitudes in uV are returned.
If 'relative', amplitudes are returned as ratios between waveform amplitudes and template amplitudes
peak: str
If maximum channel has to be found among negative peaks ('neg'), positive ('pos') or
both ('both' - default)
frames_before: int
Frames before peak to compute amplitude
frames_after: int
Frames after peak to compute amplitude
apply_filter: bool
If True, recording is bandpass-filtered
freq_min: float
High-pass frequency for optional filter (default 300 Hz)
freq_max: float
Low-pass frequency for optional filter (default 6000 Hz)
grouping_property: str
Property to group channels. E.g. if the recording extractor has the 'group' property and
'grouping_property' is 'group', then waveforms are computed group-wise.
ms_before: float
Time period in ms to cut waveforms before the spike events
ms_after: float
Time period in ms to cut waveforms after the spike events
dtype: dtype
The numpy dtype of the waveforms
compute_property_from_recording: bool
If True and 'grouping_property' is given, the property of each unit is assigned as the corresponding
property of the recording extractor channel on which the average waveform is the largest
max_channels_per_waveforms: int or None
Maximum channels per waveforms to return. If None, all channels are returned
n_jobs: int
Number of parallel jobs (default 1)
memmap: bool
If True, waveforms are saved as memmap object (recommended for long recordings with many channels)
save_property_or_features: bool
If true, it will save features in the sorting extractor
recompute_info: bool
If True, waveforms are recomputed
max_spikes_per_unit: int
The maximum number of spikes to extract per unit
seed: int
Random seed for reproducibility
verbose: bool
If True, will be verbose in metric computation
Returns
----------
l_ratios: np.ndarray
The l ratios of the sorted units.
"""
params_dict = update_all_param_dicts_with_kwargs(kwargs)
if unit_ids is None:
unit_ids = sorting.get_unit_ids()
md = MetricData(sorting=sorting, sampling_frequency=recording.get_sampling_frequency(), recording=recording,
apply_filter=params_dict["apply_filter"], freq_min=params_dict["freq_min"],
freq_max=params_dict["freq_max"], unit_ids=unit_ids,
duration_in_frames=None, verbose=params_dict['verbose'])
md.compute_pca_scores(**kwargs)
l_ratio = LRatio(metric_data=md)
l_ratios = l_ratio.compute_metric(num_channels_to_compare, max_spikes_per_cluster, **kwargs)
return l_ratios
def compute_isolation_distances(
sorting,
recording,
num_channels_to_compare=IsolationDistance.params['num_channels_to_compare'],
max_spikes_per_cluster=IsolationDistance.params['max_spikes_per_cluster'],
unit_ids=None,
**kwargs
):
"""
Computes and returns the isolation distances in the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be evaluated.
recording: RecordingExtractor
The given recording extractor from which to extract amplitudes
num_channels_to_compare: int
The number of channels to be used for the PC extraction and comparison
max_spikes_per_cluster: int
Max spikes to be used from each unit
unit_ids: list
List of unit ids to compute metric for. If not specified, all units are used
**kwargs: keyword arguments
Keyword arguments among the following:
method: str
If 'absolute' (default), amplitudes are absolute amplitudes in uV are returned.
If 'relative', amplitudes are returned as ratios between waveform amplitudes and template amplitudes
peak: str
If maximum channel has to be found among negative peaks ('neg'), positive ('pos') or
both ('both' - default)
frames_before: int
Frames before peak to compute amplitude
frames_after: int
Frames after peak to compute amplitude
apply_filter: bool
If True, recording is bandpass-filtered
freq_min: float
High-pass frequency for optional filter (default 300 Hz)
freq_max: float
Low-pass frequency for optional filter (default 6000 Hz)
grouping_property: str
Property to group channels. E.g. if the recording extractor has the 'group' property and
'grouping_property' is 'group', then waveforms are computed group-wise.
ms_before: float
Time period in ms to cut waveforms before the spike events
ms_after: float
Time period in ms to cut waveforms after the spike events
dtype: dtype
The numpy dtype of the waveforms
compute_property_from_recording: bool
If True and 'grouping_property' is given, the property of each unit is assigned as the corresponding
property of the recording extractor channel on which the average waveform is the largest
max_channels_per_waveforms: int or None
Maximum channels per waveforms to return. If None, all channels are returned
n_jobs: int
Number of parallel jobs (default 1)
memmap: bool
If True, waveforms are saved as memmap object (recommended for long recordings with many channels)
save_property_or_features: bool
If true, it will save features in the sorting extractor
recompute_info: bool
If True, waveforms are recomputed
max_spikes_per_unit: int
The maximum number of spikes to extract per unit
seed: int
Random seed for reproducibility
verbose: bool
If True, will be verbose in metric computation
Returns
----------
isolation_distances: np.ndarray
The isolation distances of the sorted units.
"""
params_dict = update_all_param_dicts_with_kwargs(kwargs)
if unit_ids is None:
unit_ids = sorting.get_unit_ids()
md = MetricData(sorting=sorting, sampling_frequency=recording.get_sampling_frequency(), recording=recording,
apply_filter=params_dict["apply_filter"], freq_min=params_dict["freq_min"],
freq_max=params_dict["freq_max"], unit_ids=unit_ids,
duration_in_frames=None, verbose=params_dict['verbose'])
md.compute_pca_scores(**kwargs)
isolation_distance = IsolationDistance(metric_data=md)
isolation_distances = isolation_distance.compute_metric(num_channels_to_compare, max_spikes_per_cluster,
**kwargs)
return isolation_distances
def compute_nn_metrics(
sorting,
recording,
num_channels_to_compare=NearestNeighbor.params['num_channels_to_compare'],
max_spikes_per_cluster=NearestNeighbor.params['max_spikes_per_cluster'],
max_spikes_for_nn=NearestNeighbor.params['max_spikes_for_nn'],
n_neighbors=NearestNeighbor.params['n_neighbors'],
unit_ids=None,
**kwargs
):
"""
Computes and returns the nearest neighbor metrics in the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be evaluated.
recording: RecordingExtractor
The given recording extractor from which to extract amplitudes
num_channels_to_compare: int
The number of channels to be used for the PC extraction and comparison
max_spikes_per_cluster: int
Max spikes to be used from each unit
max_spikes_for_nn: int
Max spikes to be used for nearest-neighbors calculation
n_neighbors: int
Number of neighbors to compare
unit_ids: list
List of unit ids to compute metric for. If not specified, all units are used
**kwargs: keyword arguments
Keyword arguments among the following:
method: str
If 'absolute' (default), amplitudes are absolute amplitudes in uV are returned.
If 'relative', amplitudes are returned as ratios between waveform amplitudes and template amplitudes
peak: str
If maximum channel has to be found among negative peaks ('neg'), positive ('pos') or
both ('both' - default)
frames_before: int
Frames before peak to compute amplitude
frames_after: int
Frames after peak to compute amplitude
apply_filter: bool
If True, recording is bandpass-filtered
freq_min: float
High-pass frequency for optional filter (default 300 Hz)
freq_max: float
Low-pass frequency for optional filter (default 6000 Hz)
grouping_property: str
Property to group channels. E.g. if the recording extractor has the 'group' property and
'grouping_property' is 'group', then waveforms are computed group-wise.
ms_before: float
Time period in ms to cut waveforms before the spike events
ms_after: float
Time period in ms to cut waveforms after the spike events
dtype: dtype
The numpy dtype of the waveforms
compute_property_from_recording: bool
If True and 'grouping_property' is given, the property of each unit is assigned as the corresponding
property of the recording extractor channel on which the average waveform is the largest
max_channels_per_waveforms: int or None
Maximum channels per waveforms to return. If None, all channels are returned
n_jobs: int
Number of parallel jobs (default 1)
memmap: bool
If True, waveforms are saved as memmap object (recommended for long recordings with many channels)
save_property_or_features: bool
If true, it will save features in the sorting extractor
recompute_info: bool
If True, waveforms are recomputed
max_spikes_per_unit: int
The maximum number of spikes to extract per unit
seed: int
Random seed for reproducibility
verbose: bool
If True, will be verbose in metric computation
Returns
----------
nn_metrics: np.ndarray
The nearest neighbor metrics of the sorted units.
"""
params_dict = update_all_param_dicts_with_kwargs(kwargs)
if unit_ids is None:
unit_ids = sorting.get_unit_ids()
md = MetricData(sorting=sorting, sampling_frequency=recording.get_sampling_frequency(), recording=recording,
apply_filter=params_dict["apply_filter"], freq_min=params_dict["freq_min"],
freq_max=params_dict["freq_max"], unit_ids=unit_ids,
duration_in_frames=None, verbose=params_dict['verbose'])
md.compute_pca_scores(**kwargs)
nn = NearestNeighbor(metric_data=md)
nn_metrics = nn.compute_metric(num_channels_to_compare, max_spikes_per_cluster,
max_spikes_for_nn, n_neighbors, **kwargs)
return nn_metrics
def compute_drift_metrics(
sorting,
recording,
drift_metrics_interval_s=DriftMetric.params['drift_metrics_interval_s'],
drift_metrics_min_spikes_per_interval=DriftMetric.params['drift_metrics_min_spikes_per_interval'],
unit_ids=None,
**kwargs
):
"""
Computes and returns the drift metrics in the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be evaluated.
recording: RecordingExtractor
The given recording extractor from which to extract amplitudes
drift_metrics_interval_s: float
Time period for evaluating | |
str,
select: Optional[dict] = None,
) -> "ListservList":
"""
Args:
name: Name of the list of messages, e.g. '3GPP_TSG_SA_WG2_UPCON'.
directorypaths: List of directory paths where LISTSERV formatted
messages are.
filedsc: A description of the relevant files, e.g. *.LOG?????
select: Selection criteria that can filter messages by:
- content, i.e. header and/or body
- period, i.e. written in a certain year, month, week-of-month
"""
_filepaths = []
# run through directories and collect all filepaths
for directorypath in directorypaths:
_filepaths.append(
get_all_file_from_directory(directorypath, filedsc)
)
# flatten list of lists
filepaths = [fp for li in _filepaths for fp in li]
return cls.from_listserv_files(name, filepaths, select)
@classmethod
def from_listserv_files(
cls,
name: str,
filepaths: List[str],
select: Optional[dict] = None,
) -> "ListservList":
"""
Args:
name: Name of the list of messages, e.g. '3GPP_TSG_SA_WG2_UPCON'
filepaths: List of file paths where LISTSERV formatted messages are.
Such files can have a file extension of the form: *.LOG1405D
select: Selection criteria that can filter messages by:
- content, i.e. header and/or body
- period, i.e. written in a certain year, month, week-of-month
"""
if select is None:
select = {"fields": "total"}
msgs = []
for filepath in filepaths:
# TODO: implement selection filter
file = open(filepath, "r")
fcontent = file.readlines()
# get positions of all Emails in file
header_start_line_nrs = cls.get_line_numbers_of_header_starts(
fcontent
)
file.close()
# run through all messages in file
for msg_nr in header_start_line_nrs:
msgs.append(
ListservMessage.from_listserv_file(
name,
filepath,
msg_nr,
select["fields"],
)
)
return cls(name, filepaths, msgs)
@classmethod
def get_messages_from_url(
cls,
name: str,
url: str,
select: Optional[dict] = None,
session: Optional[dict] = None,
) -> List[ListservMessage]:
"""
Generator that yields all messages within a certain period
(e.g. January 2021, Week 5).
Args:
name: Name of the list of messages, e.g. '3GPP_TSG_SA_WG2_UPCON'
url: URL to the LISTSERV list.
select: Selection criteria that can filter messages by:
- content, i.e. header and/or body
- period, i.e. written in a certain year, month, week-of-month
session: AuthSession
"""
if select is None:
select = {"fields": "total"}
msgs = []
# run through periods
for period_url in ListservList.get_period_urls(url, select):
# run through messages within period
for msg_url in ListservList.get_messages_urls(name, period_url):
msgs.append(
ListservMessage.from_url(
name,
msg_url,
select["fields"],
session=session,
)
)
# wait between loading messages, for politeness
time.sleep(1)
return msgs
@classmethod
def get_period_urls(
cls, url: str, select: Optional[dict] = None
) -> List[str]:
"""
All messages within a certain period
(e.g. January 2021, Week 5).
"""
url_root = ("/").join(url.split("/")[:-2])
# create dictionary with key indicating period and values the url
periods, urls_of_periods = cls.get_all_periods_and_their_urls(
url_root, get_website_content(url)
)
if any(
period in list(select.keys())
for period in ["years", "months", "weeks"]
):
for key, value in select.items():
if key == "years":
cond = lambda x: int(re.findall(r"\d{4}", x)[0])
elif key == "months":
cond = lambda x: x.split(" ")[0]
elif key == "weeks":
cond = lambda x: int(x.split(" ")[-1])
else:
continue
periodquants = [cond(period) for period in periods]
indices = ListservList.get_index_of_elements_in_selection(
periodquants,
urls_of_periods,
value,
)
periods = [periods[idx] for idx in indices]
urls_of_periods = [urls_of_periods[idx] for idx in indices]
return urls_of_periods
@staticmethod
def get_all_periods_and_their_urls(
url_root: str,
soup: BeautifulSoup,
) -> Tuple[List[str], List[str]]:
periods = [list_tag.find("a").text for list_tag in soup.find_all("li")]
urls_of_periods = [
urllib.parse.urljoin(url_root, list_tag.find("a").get("href"))
for list_tag in soup.find_all("li")
]
return periods, urls_of_periods
@staticmethod
def get_index_of_elements_in_selection(
times: List[Union[int, str]],
urls: List[str],
filtr: Union[tuple, list, int, str],
) -> List[int]:
"""
Filter out messages that where in a specific period. Period here is a set
containing units of year, month, and week-of-month which can have the following
example elements:
- years: (1992, 2010), [2000, 2008], 2021
- months: ["January", "July"], "November"
- weeks: (1, 4), [1, 5], 2
Args:
times: A list containing information of the period for each
group of ListservMessage.
urls: Corresponding URLs of each group of ListservMessage of which the
period info is contained in `times`.
filtr: Containing info on what should be filtered.
Returns:
Indices of to the elements in `times`/`ursl`.
"""
if isinstance(filtr, tuple):
# filter year or week in range
cond = lambda x: (np.min(filtr) <= x <= np.max(filtr))
if isinstance(filtr, list):
# filter in year, week, or month in list
cond = lambda x: x in filtr
if isinstance(filtr, int):
# filter specific year or week
cond = lambda x: x == filtr
if isinstance(filtr, str):
# filter specific month
cond = lambda x: x == filtr
return [idx for idx, time in enumerate(times) if cond(time)]
@classmethod
def get_messages_urls(cls, name: str, url: str) -> List[str]:
"""
Args:
name: Name of the `ListservList`
url: URL to group of messages that are within the same period.
Returns:
List to URLs from which`ListservMessage` can be initialized.
"""
url_root = ("/").join(url.split("/")[:-2])
soup = get_website_content(url)
a_tags = soup.select(f'a[href*="A2="][href*="{name}"]')
if a_tags:
a_tags = [
urllib.parse.urljoin(url_root, url.get("href"))
for url in a_tags
]
return a_tags
@classmethod
def get_line_numbers_of_header_starts(
cls, content: List[str]
) -> List[int]:
"""
By definition LISTSERV logs seperate new messages by a row
of 73 equal signs.
Args:
content: The content of one LISTSERV-file.
Returns:
List of line numbers where header starts
"""
return [
line_nr for line_nr, line in enumerate(content) if "=" * 73 in line
]
def to_dict(self) -> Dict[str, List[str]]:
"""
Place all message into a dictionary of the form:
dic = {
"Subject": [messages[0], ... , messages[n]],
.
.
.
"ContentType": [messages[0], ... , messages[n]]
}
"""
# initialize dictionary
dic = {}
for key in list(self.messages[0].to_dict().keys()):
dic[key] = []
# run through messages
for msg in self.messages:
# run through message attributes
for key, value in msg.to_dict().items():
dic[key].append(value)
return dic
def to_pandas_dataframe(self) -> pd.DataFrame:
return pd.DataFrame.from_dict(self.to_dict())
def to_mbox(self, dir_out: str, filename: Optional[str] = None):
"""
Safe mail list to .mbox files.
Args:
"""
if filename is None:
filepath = f"{dir_out}/{self.name}.mbox"
else:
filepath = f"{dir_out}/{filename}.mbox"
first = True
for msg in self.messages:
if first:
msg.to_mbox(filepath, mode="w")
first = False
else:
msg.to_mbox(filepath, mode="a")
class ListservArchive(object):
"""
This class handles a public mailing list archive that uses the
LISTSERV 16.5 format.
An archive is a list of ListservList elements.
Parameters
----------
name
The of whom the archive is (e.g. 3GPP, IEEE, ...)
url
The URL where the archive lives
lists
A list containing the mailing lists as `ListservList` types
Methods
-------
from_url
from_mailing_lists
get_lists
get_sections
to_dict
to_pandas_dataframe
to_mbox
Example
-------
arch = ListservArchive.from_url(
"3GPP",
"https://list.etsi.org/scripts/wa.exe?",
"https://list.etsi.org/scripts/wa.exe?HOME",
select={
"years": (2020, 2021),
"months": "January",
"weeks": [1,5],
"fields": "header",
},
)
"""
def __init__(self, name: str, url: str, lists: List[ListservList]):
self.name = name
self.url = url
self.lists = lists
def __len__(self):
return len(self.lists)
def __iter__(self):
return iter(self.lists)
def __getitem__(self, index):
return self.lists[index]
@classmethod
def from_url(
cls,
name: str,
url_root: str,
url_home: str,
select: dict,
url_login: str = "https://list.etsi.org/scripts/wa.exe?LOGON",
login: Optional[Dict[str, str]] = {"username": None, "password": <PASSWORD>},
session: Optional[str] = None,
) -> "ListservArchive":
"""
Create ListservArchive from a given URL.
Args:
name:
url_root:
url_home:
select:
"""
session = get_auth_session(url_login, **login)
lists = cls.get_lists_from_url(url_root, url_home, select, session)
return cls.from_mailing_lists(name, url_root, lists, select)
@classmethod
def from_mailing_lists(
cls,
name: str,
url_root: str,
url_mailing_lists: Union[List[str], List[ListservList]],
select: dict,
url_login: str = "https://list.etsi.org/scripts/wa.exe?LOGON",
login: Optional[Dict[str, str]] = {"username": None, "password": <PASSWORD>},
session: Optional[str] = None,
) -> "ListservArchive":
"""
Create ListservArchive from a given list of 'ListservList'.
Args:
name:
url_root:
url_mailing_lists:
"""
if isinstance(url_mailing_lists[0], str):
if session is None:
session = get_auth_session(url_login, **login)
lists = []
for idx, url in enumerate(url_mailing_lists):
lists.append(
ListservList.from_url(
name=idx,
url=url,
select=select,
session=session,
)
)
else:
lists = url_mailing_lists
return cls(name, url_root, lists)
@staticmethod
def get_lists_from_url(
url_root: str,
url_home: str,
select: dict,
session: Optional[str] = None,
) -> List[ListservList]:
"""
Created dictionary of all lists in the archive.
Args:
Returns:
archive_dict: the keys are the names of the lists and the value their url
"""
archive = []
# run through archive sections
for url in list(
ListservArchive.get_sections(url_root, url_home).keys()
)[:1]:
soup = get_website_content(url)
a_tags_in_section = soup.select(
'a[href*="A0="][onmouseover*="showDesc"][onmouseout*="hideDesc"]',
)
# run through archive lists in section
for a_tag in a_tags_in_section:
value = urllib.parse.urljoin(url_root, a_tag.get("href"))
key = | |
<reponame>ColinKennedy/tk-config-default2-respawn
"""
Filesystem-related utilities.
"""
from threading import Lock
from tempfile import mkdtemp
from contextlib import contextmanager
import weakref
import atexit
import posixpath
import ntpath
import os.path
import shutil
import os
import re
import stat
class TempDirs(object):
"""Tempdir manager.
Makes tmpdirs and ensures they're cleaned up on program exit.
"""
instances_lock = Lock()
instances = []
def __init__(self, tmpdir, prefix="rez_"):
self.tmpdir = tmpdir
self.prefix = prefix
self.dirs = set()
self.lock = Lock()
with TempDirs.instances_lock:
TempDirs.instances.append(weakref.ref(self))
def mkdtemp(self, cleanup=True):
path = mkdtemp(dir=self.tmpdir, prefix=self.prefix)
if not cleanup:
return path
with self.lock:
self.dirs.add(path)
return path
def __del__(self):
self.clear()
def clear(self):
with self.lock:
if not self.dirs:
return
dirs = self.dirs
self.dirs = set()
for path in dirs:
if os.path.exists(path) and not os.getenv("REZ_KEEP_TMPDIRS"):
shutil.rmtree(path)
@classmethod
def clear_all(cls):
with TempDirs.instances_lock:
instances = cls.instances[:]
for ref in instances:
instance = ref()
if instance is not None:
instance.clear()
atexit.register(TempDirs.clear_all)
@contextmanager
def retain_cwd():
"""Context manager that keeps cwd unchanged afterwards.
"""
cwd = os.getcwd()
try:
yield
finally:
os.chdir(cwd)
def safe_makedirs(path):
# makedirs that takes into account that multiple threads may try to make
# the same dir at the same time
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError:
if not os.path.exists(path):
raise
def is_subdirectory(path_a, path_b):
"""Returns True if `path_a` is a subdirectory of `path_b`."""
path_a = os.path.realpath(path_a)
path_b = os.path.realpath(path_b)
relative = os.path.relpath(path_a, path_b)
return (not relative.startswith(os.pardir + os.sep))
def copy_or_replace(src, dst):
'''try to copy with mode, and if it fails, try replacing
'''
try:
shutil.copy(src, dst)
except (OSError, IOError), e:
# It's possible that the file existed, but was owned by someone
# else - in that situation, shutil.copy might then fail when it
# tries to copy perms.
# However, it's possible that we have write perms to the dir -
# in which case, we can just delete and replace
import errno
if e.errno == errno.EPERM:
import tempfile
# try copying into a temporary location beside the old
# file - if we have perms to do that, we should have perms
# to then delete the old file, and move the new one into
# place
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
dst_dir, dst_name = os.path.split(dst)
dst_temp = tempfile.mktemp(prefix=dst_name + '.', dir=dst_dir)
shutil.copy(src, dst_temp)
if not os.path.isfile(dst_temp):
raise RuntimeError(
"shutil.copy completed successfully, but path"
" '%s' still did not exist" % dst_temp)
os.remove(dst)
shutil.move(dst_temp, dst)
def copytree(src, dst, symlinks=False, ignore=None, hardlinks=False):
'''copytree that supports hard-linking
'''
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if hardlinks:
def copy(srcname, dstname):
try:
# try hard-linking first
os.link(srcname, dstname)
except OSError:
shutil.copy2(srcname, dstname)
else:
copy = shutil.copy2
if not os.path.isdir(dst):
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
copy(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error), why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except shutil.Error, err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except shutil.WindowsError:
# can't copy file access times on Windows
pass
except OSError, why:
errors.extend((src, dst, str(why)))
if errors:
raise shutil.Error(errors)
def movetree(src, dst):
"""Attempts a move, and falls back to a copy+delete if this fails
"""
try:
shutil.move(src, dst)
except:
copytree(src, dst, symlinks=True, hardlinks=True)
shutil.rmtree(src)
def safe_chmod(path, mode):
"""Set the permissions mode on path, but only if it differs from the current mode.
"""
if stat.S_IMODE(os.stat(path).st_mode) != mode:
os.chmod(path, mode)
def to_nativepath(path):
return os.path.join(path.split('/'))
def to_ntpath(path):
return ntpath.sep.join(path.split(posixpath.sep))
def to_posixpath(path):
return posixpath.sep.join(path.split(ntpath.sep))
def encode_filesystem_name(input_str):
"""Encodes an arbitrary unicode string to a generic filesystem-compatible
non-unicode filename.
The result after encoding will only contain the standard ascii lowercase
letters (a-z), the digits (0-9), or periods, underscores, or dashes
(".", "_", or "-"). No uppercase letters will be used, for
comaptibility with case-insensitive filesystems.
The rules for the encoding are:
1) Any lowercase letter, digit, period, or dash (a-z, 0-9, ., or -) is
encoded as-is.
2) Any underscore is encoded as a double-underscore ("__")
3) Any uppercase ascii letter (A-Z) is encoded as an underscore followed
by the corresponding lowercase letter (ie, "A" => "_a")
4) All other characters are encoded using their UTF-8 encoded unicode
representation, in the following format: "_NHH..., where:
a) N represents the number of bytes needed for the UTF-8 encoding,
except with N=0 for one-byte representation (the exception for N=1
is made both because it means that for "standard" ascii characters
in the range 0-127, their encoding will be _0xx, where xx is their
ascii hex code; and because it mirrors the ways UTF-8 encoding
itself works, where the number of bytes needed for the character can
be determined by counting the number of leading "1"s in the binary
representation of the character, except that if it is a 1-byte
sequence, there are 0 leading 1's).
b) HH represents the bytes of the corresponding UTF-8 encoding, in
hexadecimal (using lower-case letters)
As an example, the character "*", whose (hex) UTF-8 representation
of 2A, would be encoded as "_02a", while the "euro" symbol, which
has a UTF-8 representation of E2 82 AC, would be encoded as
"_3e282ac". (Note that, strictly speaking, the "N" part of the
encoding is redundant information, since it is essentially encoded
in the UTF-8 representation itself, but it makes the resulting
string more human-readable, and easier to decode).
As an example, the string "Foo_Bar (fun).txt" would get encoded as:
_foo___bar_020_028fun_029.txt
"""
if isinstance(input_str, str):
input_str = unicode(input_str)
elif not isinstance(input_str, unicode):
raise TypeError("input_str must be a basestring")
as_is = u'abcdefghijklmnopqrstuvwxyz0123456789.-'
uppercase = u'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = []
for char in input_str:
if char in as_is:
result.append(char)
elif char == u'_':
result.append('__')
elif char in uppercase:
result.append('_%s' % char.lower())
else:
utf8 = char.encode('utf8')
N = len(utf8)
if N == 1:
N = 0
HH = ''.join('%x' % ord(c) for c in utf8)
result.append('_%d%s' % (N, HH))
return ''.join(result)
_FILESYSTEM_TOKEN_RE = re.compile(r'(?P<as_is>[a-z0-9.-])|(?P<underscore>__)|_(?P<uppercase>[a-z])|_(?P<N>[0-9])')
_HEX_RE = re.compile('[0-9a-f]+$')
def decode_filesystem_name(filename):
"""Decodes a filename encoded using the rules given in encode_filesystem_name
to a unicode string.
"""
result = []
remain = filename
i = 0
while remain:
# use match, to ensure it matches from the start of the string...
match = _FILESYSTEM_TOKEN_RE.match(remain)
if not match:
raise ValueError("incorrectly encoded filesystem name %r"
" (bad index: %d - %r)" % (filename, i,
remain[:2]))
match_str = match.group(0)
match_len = len(match_str)
i += match_len
remain = remain[match_len:]
match_dict = match.groupdict()
if match_dict['as_is']:
result.append(unicode(match_str))
elif match_dict['underscore']:
result.append(u'_')
elif match_dict['uppercase']:
result.append(unicode(match_dict['uppercase'].upper()))
elif match_dict['N']:
N = int(match_dict['N'])
if N == 0:
N = 1
# hex-encoded, so need to grab 2*N chars
bytes_len = 2 * N
i += bytes_len
bytes = remain[:bytes_len]
remain = remain[bytes_len:]
# need this check to ensure that we don't end up eval'ing
# something nasty...
if not _HEX_RE.match(bytes):
raise ValueError("Bad utf8 encoding in name %r"
" (bad index: %d - %r)" % (filename, i, bytes))
bytes_repr = ''.join('\\x%s' % bytes[i:i + 2]
for i in xrange(0, bytes_len, 2))
bytes_repr = "'%s'" % bytes_repr
result.append(eval(bytes_repr).decode('utf8'))
else:
raise ValueError("Unrecognized match type in filesystem name %r"
" (bad index: %d - %r)" % (filename, i, remain[:2]))
return u''.join(result)
def test_encode_decode():
def do_test(orig, expected_encoded):
print '=' * 80
print orig
encoded = encode_filesystem_name(orig)
print encoded
assert encoded == expected_encoded
decoded = decode_filesystem_name(encoded)
print decoded
assert decoded == orig
do_test("Foo_Bar (fun).txt", '_foo___bar_020_028fun_029.txt')
# u'\u20ac' == Euro symbol
do_test(u"\u20ac3 ~= $4.06", '_3e282ac3_020_07e_03d_020_0244.06')
def walk_up_dirs(path):
"""Yields absolute directories starting with the given path, and iterating
up through all it's parents, until it reaches a root directory"""
prev_path = None
current_path = os.path.abspath(path)
while current_path != prev_path:
yield current_path
prev_path = current_path
current_path = os.path.dirname(prev_path)
# Copyright 2013-2016 <NAME>.
#
# This library is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
#
# This library is distributed | |
<reponame>eoinjordan/thefeck
import pytest
from io import BytesIO
from thefeck.types import Command
from thefeck.rules.docker_not_command import get_new_command, match
_DOCKER_SWARM_OUTPUT = '''
Usage: docker swarm COMMAND
Manage Swarm
Commands:
ca Display and rotate the root CA
init Initialize a swarm
join Join a swarm as a node and/or manager
join-token Manage join tokens
leave Leave the swarm
unlock Unlock swarm
unlock-key Manage the unlock key
update Update the swarm
Run 'docker swarm COMMAND --help' for more information on a command.
'''
_DOCKER_IMAGE_OUTPUT = '''
Usage: docker image COMMAND
Manage images
Commands:
build Build an image from a Dockerfile
history Show the history of an image
import Import the contents from a tarball to create a filesystem image
inspect Display detailed information on one or more images
load Load an image from a tar archive or STDIN
ls List images
prune Remove unused images
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rm Remove one or more images
save Save one or more images to a tar archive (streamed to STDOUT by default)
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
Run 'docker image COMMAND --help' for more information on a command.
'''
@pytest.fixture
def docker_help(mocker):
help = b'''Usage: docker [OPTIONS] COMMAND [arg...]
A self-sufficient runtime for linux containers.
Options:
--api-cors-header= Set CORS headers in the remote API
-b, --bridge= Attach containers to a network bridge
--bip= Specify network bridge IP
-D, --debug=false Enable debug mode
-d, --daemon=false Enable daemon mode
--default-gateway= Container default gateway IPv4 address
--default-gateway-v6= Container default gateway IPv6 address
--default-ulimit=[] Set default ulimits for containers
--dns=[] DNS server to use
--dns-search=[] DNS search domains to use
-e, --exec-driver=native Exec driver to use
--exec-opt=[] Set exec driver options
--exec-root=/var/run/docker Root of the Docker execdriver
--fixed-cidr= IPv4 subnet for fixed IPs
--fixed-cidr-v6= IPv6 subnet for fixed IPs
-G, --group=docker Group for the unix socket
-g, --graph=/var/lib/docker Root of the Docker runtime
-H, --host=[] Daemon socket(s) to connect to
-h, --help=false Print usage
--icc=true Enable inter-container communication
--insecure-registry=[] Enable insecure registry communication
--ip=0.0.0.0 Default IP when binding container ports
--ip-forward=true Enable net.ipv4.ip_forward
--ip-masq=true Enable IP masquerading
--iptables=true Enable addition of iptables rules
--ipv6=false Enable IPv6 networking
-l, --log-level=info Set the logging level
--label=[] Set key=value labels to the daemon
--log-driver=json-file Default driver for container logs
--log-opt=map[] Set log driver options
--mtu=0 Set the containers network MTU
-p, --pidfile=/var/run/docker.pid Path to use for daemon PID file
--registry-mirror=[] Preferred Docker registry mirror
-s, --storage-driver= Storage driver to use
--selinux-enabled=false Enable selinux support
--storage-opt=[] Set storage driver options
--tls=false Use TLS; implied by --tlsverify
--tlscacert=~/.docker/ca.pem Trust certs signed only by this CA
--tlscert=~/.docker/cert.pem Path to TLS certificate file
--tlskey=~/.docker/key.pem Path to TLS key file
--tlsverify=false Use TLS and verify the remote
--userland-proxy=true Use userland proxy for loopback traffic
-v, --version=false Print version information and quit
Commands:
attach Attach to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders from a container's filesystem to the host path
create Create a new container
diff Inspect changes on a container's filesystem
events Get real time events from the server
exec Run a command in a running container
export Stream the contents of a container as a tar archive
history Show the history of an image
images List images
import Create a new filesystem image from the contents of a tarball
info Display system-wide information
inspect Return low-level information on a container or image
kill Kill a running container
load Load an image from a tar archive
login Register or log in to a Docker registry server
logout Log out from a Docker registry server
logs Fetch the logs of a container
pause Pause all processes within a container
port Lookup the public-facing port that is NAT-ed to PRIVATE_PORT
ps List containers
pull Pull an image or a repository from a Docker registry server
push Push an image or a repository to a Docker registry server
rename Rename an existing container
restart Restart a running container
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save an image to a tar archive
search Search for an image on the Docker Hub
start Start a stopped container
stats Display a stream of a containers' resource usage statistics
stop Stop a running container
tag Tag an image into a repository
top Lookup the running processes of a container
unpause Unpause a paused container
version Show the Docker version information
wait Block until a container stops, then print its exit code
Run 'docker COMMAND --help' for more information on a command.
'''
mock = mocker.patch('subprocess.Popen')
mock.return_value.stdout = BytesIO(help)
return mock
@pytest.fixture
def docker_help_new(mocker):
helptext_new = b'''
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/Users/ik1ne/.docker")
-c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var
and default context set with "docker context use")
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "/Users/ik1ne/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/Users/ik1ne/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/Users/ik1ne/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
builder Manage builds
config Manage Docker configs
container Manage containers
context Manage contexts
image Manage images
network Manage networks
node Manage Swarm nodes
plugin Manage plugins
secret Manage Docker secrets
service Manage services
stack Manage Docker stacks
swarm Manage Swarm
system Manage Docker
trust Manage trust on Docker images
volume Manage volumes
Commands:
attach Attach local standard input, output, and error streams to a running container
build Build an image from a Dockerfile
commit Create a new image from a container's changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a container's filesystem
events Get real time events from the server
exec Run a command in a running container
export Export a container's filesystem as a tar archive
history Show the history of an image
images List images
import Import the contents from a tarball to create a filesystem image
info Display system-wide information
inspect Return low-level information on Docker objects
kill Kill one or more running containers
load Load an image from a tar archive or STDIN
login Log in to a Docker registry
logout Log out from a Docker registry
logs Fetch the logs of a container
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
ps List containers
pull Pull an image or a repository from a registry
push Push an image or a repository to a registry
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
rmi Remove one or more images
run Run a command in a new container
save Save one or more images to a tar archive (streamed to STDOUT by default)
search Search the Docker Hub for images
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
version Show the Docker version information
wait Block until one or more containers stop, then print their exit codes
Run 'docker COMMAND --help' for more information on a command.
'''
mock = mocker.patch('subprocess.Popen')
mock.return_value.stdout = BytesIO(b'')
mock.return_value.stderr = BytesIO(helptext_new)
return mock
def output(cmd):
return "docker: '{}' is not a | |
keyword argument '%s'"
" to method get_conversations_messaging_integrations_whatsapp_integration_id" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'integration_id' is set
if ('integration_id' not in params) or (params['integration_id'] is None):
raise ValueError("Missing the required parameter `integration_id` when calling `get_conversations_messaging_integrations_whatsapp_integration_id`")
resource_path = '/api/v2/conversations/messaging/integrations/whatsapp/{integrationId}'.replace('{format}', 'json')
path_params = {}
if 'integration_id' in params:
path_params['integrationId'] = params['integration_id']
query_params = {}
if 'expand' in params:
query_params['expand'] = params['expand']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['PureCloud OAuth']
response = self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='WhatsAppIntegration',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def get_conversations_messaging_sticker(self, messenger_type, **kwargs):
"""
Get a list of Messaging Stickers
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_conversations_messaging_sticker(messenger_type, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str messenger_type: Messenger Type (required)
:param int page_size: Page size
:param int page_number: Page number
:return: MessagingStickerEntityListing
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['messenger_type', 'page_size', 'page_number']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_conversations_messaging_sticker" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'messenger_type' is set
if ('messenger_type' not in params) or (params['messenger_type'] is None):
raise ValueError("Missing the required parameter `messenger_type` when calling `get_conversations_messaging_sticker`")
resource_path = '/api/v2/conversations/messaging/stickers/{messengerType}'.replace('{format}', 'json')
path_params = {}
if 'messenger_type' in params:
path_params['messengerType'] = params['messenger_type']
query_params = {}
if 'page_size' in params:
query_params['pageSize'] = params['page_size']
if 'page_number' in params:
query_params['pageNumber'] = params['page_number']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['PureCloud OAuth']
response = self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='MessagingStickerEntityListing',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def get_conversations_messaging_threadingtimeline(self, **kwargs):
"""
Get conversation threading window timeline for each messaging type
Conversation messaging threading timeline is a setting defined for each messenger type in your organization. This setting will dictate whether a new message is added to the most recent existing conversation, or creates a new Conversation. If the existing Conversation is still in a connected state the threading timeline setting will never play a role. After the conversation is disconnected, if an inbound message is received or an outbound message is sent after the setting for threading timeline expires, a new conversation is created.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_conversations_messaging_threadingtimeline(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: ConversationThreadingWindow
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_conversations_messaging_threadingtimeline" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v2/conversations/messaging/threadingtimeline'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['PureCloud OAuth']
response = self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ConversationThreadingWindow',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_conversation_participant(self, conversation_id, participant_id, body, **kwargs):
"""
Update a participant.
Update conversation participant.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_conversation_participant(conversation_id, participant_id, body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str conversation_id: conversation ID (required)
:param str participant_id: participant ID (required)
:param MediaParticipantRequest body: Update request (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['conversation_id', 'participant_id', 'body']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_conversation_participant" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'conversation_id' is set
if ('conversation_id' not in params) or (params['conversation_id'] is None):
raise ValueError("Missing the required parameter `conversation_id` when calling `patch_conversation_participant`")
# verify the required parameter 'participant_id' is set
if ('participant_id' not in params) or (params['participant_id'] is None):
raise ValueError("Missing the required parameter `participant_id` when calling `patch_conversation_participant`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_conversation_participant`")
resource_path = '/api/v2/conversations/{conversationId}/participants/{participantId}'.replace('{format}', 'json')
path_params = {}
if 'conversation_id' in params:
path_params['conversationId'] = params['conversation_id']
if 'participant_id' in params:
path_params['participantId'] = params['participant_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['PureCloud OAuth']
response = self.api_client.call_api(resource_path, 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_conversation_participant_attributes(self, conversation_id, participant_id, body, **kwargs):
"""
Update the attributes on a conversation participant.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_conversation_participant_attributes(conversation_id, participant_id, body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str conversation_id: conversation ID (required)
:param str participant_id: participant ID (required)
:param ParticipantAttributes body: Participant attributes (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['conversation_id', 'participant_id', 'body']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_conversation_participant_attributes" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'conversation_id' is set
if ('conversation_id' not in params) or (params['conversation_id'] is None):
raise ValueError("Missing the required parameter `conversation_id` when calling `patch_conversation_participant_attributes`")
# verify the required parameter 'participant_id' is set
if ('participant_id' not in params) or (params['participant_id'] is None):
raise ValueError("Missing the required parameter `participant_id` when calling `patch_conversation_participant_attributes`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_conversation_participant_attributes`")
resource_path = '/api/v2/conversations/{conversationId}/participants/{participantId}/attributes'.replace('{format}', 'json')
path_params = {}
if 'conversation_id' in params:
path_params['conversationId'] = params['conversation_id']
if 'participant_id' in params:
path_params['participantId'] = params['participant_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['PureCloud OAuth']
response = self.api_client.call_api(resource_path, 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_conversations_call(self, conversation_id, body, **kwargs):
"""
Update a conversation by setting it's recording state, merging in other conversations to create a conference, or disconnecting all of the participants
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = | |
<reponame>aguilerapy/kingfisher-process
import datetime
import os
import sqlalchemy as sa
from ocdskingfisherprocess.store import Store
from tests.base import BaseDataBaseTest
from ocdskingfisherprocess.checks import Checks
class TestDefaultsOff(BaseDataBaseTest):
def alter_config(self):
self.config.default_value_collection_check_data = False
self.config.default_value_collection_check_older_data_with_schema_version_1_1 = False
def test_records(self):
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_record.json'
)
store.store_file_from_local("test.json", "http://example.com", "record", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
def test_releases(self):
self.config.default_value_collection_check_data = False
self.config.default_value_collection_check_older_data_with_schema_version_1_1 = False
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_release.json'
)
store.store_file_from_local("test.json", "http://example.com", "release_package", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
class TestCheckOn(BaseDataBaseTest):
def alter_config(self):
self.config.default_value_collection_check_data = True
self.config.default_value_collection_check_older_data_with_schema_version_1_1 = False
def test_records(self):
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_record.json'
)
store.store_file_from_local("test.json", "http://example.com", "record", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert not data.override_schema_version
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks Again - that should be fine
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert not data.override_schema_version
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
def test_release(self):
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_release.json'
)
store.store_file_from_local("test.json", "http://example.com", "release_package", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert not data.override_schema_version
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks Again - that should be fine
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert not data.override_schema_version
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
class TestCheckOlderThan11On(BaseDataBaseTest):
def alter_config(self):
self.config.default_value_collection_check_data = False
self.config.default_value_collection_check_older_data_with_schema_version_1_1 = True
def test_records(self):
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_record.json'
)
store.store_file_from_local("test.json", "http://example.com", "record", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert '1.1' == data.override_schema_version
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks Again - that should be fine
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert '1.1' == data.override_schema_version
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
def test_release(self):
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_release.json'
)
store.store_file_from_local("test.json", "http://example.com", "release_package", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert '1.1' == data.override_schema_version
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks Again - that should be fine
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 1 == result.rowcount
data = result.fetchone()
assert '1.1' == data.override_schema_version
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
class TestCheckAllOn(BaseDataBaseTest):
def alter_config(self):
self.config.default_value_collection_check_data = True
self.config.default_value_collection_check_older_data_with_schema_version_1_1 = True
def test_records(self):
collection_id = self.database.get_or_create_collection_id("test", datetime.datetime.now(), False)
collection = self.database.get_collection(collection_id)
store = Store(self.config, self.database)
store.set_collection(collection)
json_filename = os.path.join(os.path.dirname(
os.path.realpath(__file__)), 'data', 'sample_1_0_record.json'
)
store.store_file_from_local("test.json", "http://example.com", "record", "utf-8", json_filename)
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.record_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
s = sa.sql.select([self.database.release_check_error_table])
result = connection.execute(s)
assert 0 == result.rowcount
# Call Checks
checks = Checks(self.database, collection)
checks.process_all_files()
# Check Number of check results
with self.database.get_engine().begin() as connection:
s = sa.sql.select([self.database.record_check_table])
result = connection.execute(s)
assert 2 == result.rowcount
| |
# Copyright 2016 <NAME>
# Governed by the license described in LICENSE.txt
import libtcodpy as libtcod
import cProfile
import scipy.spatial.kdtree
import config
import algebra
import map
import log
from components import *
import miscellany
import bestiary
import ai
import actions
import spells
import quest
import compound_cartographer
import mine_cartographer
import ca_cartographer
import dungeon_cartographer
ROOM_MAX_SIZE = 10
ROOM_MIN_SIZE = 6
MAX_ROOMS = 30
QUARRY_ELEVATION = 3
GHUL_COUNT_GOAL = 2
MINE_ENTRANCE_COUNT = 3
def _random_position_in_region(new_map, region):
"""
Given a region of a map, return an algebra.Location in the region
"""
center = new_map.region_seeds[region]
while True:
candidate = algebra.Location(
libtcod.random_get_int(0, center[0]-5, center[0]+5),
libtcod.random_get_int(0, center[1]-5, center[1]+5))
if (candidate.x < 0 or candidate.y < 0 or
candidate.x >= new_map.width or
candidate.y >= new_map.height):
continue
if new_map.region[candidate.x][candidate.y] == region:
return candidate
def _random_choice_index(chances):
"""
choose one option from list of chances, returning its index
"""
dice = libtcod.random_get_int(0, 1, sum(chances))
running_sum = 0
choice = 0
for w in chances:
running_sum += w
if dice <= running_sum:
return choice
choice += 1
def _random_choice(chances_dict):
"""
choose one option from dictionary of chances, returning its key
"""
chances = chances_dict.values()
strings = chances_dict.keys()
return strings[_random_choice_index(chances)]
def _place_random_creatures(new_map, player):
start_region = new_map.region[player.pos.x][player.pos.y]
terrain_chances = {
'lake' : { None : 10 },
'marsh' : { None : 10, bestiary.swamp_goblin : 10 },
'desert' : { None : 20, bestiary.hyena_pair : 5, bestiary.gazelle : 10 },
'scrub' : { None : 20, bestiary.hyena : 2, bestiary.gazelle : 4,
bestiary.deer : 4, bestiary.wolf : 2 },
'forest' : { None : 20, bestiary.deer : 10, bestiary.wolf_pair : 5,
bestiary.bear : 3 },
'rock' : { None : 10, bestiary.snow_leopard : 1 },
'ice' : { None : 10, bestiary.snow_leopard : 1 }
}
for r in range(len(new_map.region_seeds)):
if (r == start_region or
(new_map.quarry_regions and r in new_map.quarry_regions)):
continue
fn = _random_choice(terrain_chances[new_map.region_terrain[r]])
if fn is not None:
pos = algebra.Location(new_map.region_seeds[r][0], new_map.region_seeds[r][1])
while new_map.is_blocked_at(pos):
pos += actions.random_direction()
pos.bound(algebra.Rect(0, 0, new_map.width-1, new_map.height-1))
if new_map.caravanserai and new_map.caravanserai.bounds.contains(pos):
continue
# print('Creature in region ' + str(r) + ' at ' + str(pos.x) + ' ' + str(pos.y))
fn(new_map, pos, player)
def _inhabit_rotunda(new_map, peak):
goddess = Object(algebra.Location(peak[0], peak[1]), '@', 'The White Goddess', libtcod.white, blocks=True,
interactable=Interactable(use_function=quest.goddess_charge))
new_map.objects.append(goddess)
def _inhabit_quarry(new_map, player):
for i in range(GHUL_COUNT_GOAL):
rgn = new_map.quarry_regions[_random_choice_index([1 for ii in range(len(new_map.quarry_regions))])]
ghul = bestiary.ghul(new_map, _random_position_in_region(new_map, rgn), player)
def _interpolate_heights(new_map, peak):
print('Climbing the shoulders of the mountain')
for p in range(len(new_map.region_elevations)):
if new_map.region_elevations[p] > -1:
continue
dx = new_map.region_seeds[p][0] - peak[0]
dy = new_map.region_seeds[p][1] - peak[1]
p_distance = math.sqrt(dx*dx+dy*dy)
# Hack - conical mountain, but not horrible.
if dx < 0:
cand_x = peak[0]
elif dx == 0:
cand_x = new_map.width
else:
cand_x = new_map.width - peak[0]
if dy < 0:
cand_y = peak[1]
elif dy == 0:
cand_y = new_map.height
else:
cand_y = new_map.height - peak[1]
edge_distance = min(cand_x, cand_y)
elevation = int(9 * ((edge_distance - p_distance) / edge_distance))
new_map.region_elevations[p] = max(elevation, 0)
def _ensure_penultimate_height(new_map, peak, region_tree):
"""
Worldgen will frequently generate a map with a peak at elevation 9,
and nothing else above elevation 7, which prevents easy access to
the summit.
"""
for r in new_map.region_elevations:
if r == 8:
print('Found height 8 at index ' + str(r))
return
(d, i) = region_tree.query(peak, 8)
for r in i:
if new_map.region_elevations[r] == 9:
continue
if new_map.region_elevations[r] == 8:
print('Error? There was no 8, and now there is.')
return
if new_map.region_elevations[r] == 7:
new_map.region_elevations[r] = 8
print('Changed height 7 to 8 at index ' + str(r))
return
print("Couldn't find elevation 8 near the peak.")
def _extend_hills(new_map, peak):
print('Raising the southern hills')
dy = new_map.height - peak[1]
x_intercept = peak[0] + dy / 2
for r in range(len(new_map.region_seeds)):
seed = new_map.region_seeds[r]
if new_map.region_elevations[r] > 4:
continue
if seed[1] < peak[1]:
continue
local_dy = seed[1] - peak[1]
midline = peak[0] + local_dy / 2
dx = abs(midline - seed[0])
if (dx > 40):
continue
e = int(4 - dx / 10)
if new_map.region_elevations[r] < e:
new_map.region_elevations[r] = e
def _place_seaside_height(new_map):
"""
Guarantee that there's at least one elevated spot along the seaside
"""
for r in range(20, 80):
if (new_map.region_elevations[r] >= 2 and
new_map.region_terrain[r-20] == 'lake'):
new_map.grotto_region = r
return
# Rather than looking for a "best" location,
# place it as soon as possible.
for r in range(20, 80):
print(r, new_map.region_terrain[r], new_map.region_elevations[r])
if (new_map.region_terrain[r] == 'lake' or
new_map.region_terrain[r] == 'marsh'):
continue
if new_map.region_terrain[r-20] != 'lake':
print('Not lakeside...')
continue
new_map.region_elevations[r] = 1
new_map.region_terrain[r] = 'scrub'
new_map.grotto_region = r
if (r+1)/20 == r/20:
new_map.region_elevations[r+1] = 2
new_map.region_terrain[r+1] = 'forest'
new_map.grotto_region = r
if (r+2)/20 == r/20:
new_map.region_elevations[r+2] = 1
new_map.region_terrain[r+2] = 'scrub'
return
print("Whoops! Can't find anywhere to place a seaside grotto.")
new_map.grotto_region = None
def _should_slope(new_map, x, y):
"""
True if any adjacent tile is higher than this one.
"""
el = new_map.region_elevations[new_map.region[x][y]]
return (new_map.elevation(x-1, y-1) == el+1 or
new_map.elevation(x, y-1) == el+1 or
new_map.elevation(x+1, y-1) == el+1 or
new_map.elevation(x-1, y) == el+1 or
new_map.elevation(x+1, y) == el+1 or
new_map.elevation(x-1, y+1) == el+1 or
new_map.elevation(x, y+1) == el+1 or
new_map.elevation(x+1, y+1) == el+1)
def _find_terrain_types(new_map):
strata = { x : [] for x in map.region_colors_seen.keys() }
for r in range(len(new_map.region_terrain)):
type = strata.get(new_map.region_terrain[r])
type.append(r)
return strata
def _mark_slopes(new_map):
print('Finding the slopes')
for x in range(1, config.OUTDOOR_MAP_WIDTH - 1):
for y in range(1, config.OUTDOOR_MAP_HEIGHT - 1):
if _should_slope(new_map, x, y):
new_map.terrain[x][y] = map.TERRAIN_SLOPE
def _clump_terrain(new_map):
print('Determining terrain clumps')
for r in range(len(new_map.region_seeds)):
el = new_map.region_elevations[r]
seed = new_map.region_seeds[r]
if el == 0:
# Fill in the upper-left-hand-corner so that the mountain
# tends to be flush against the marsh & lake.
in_corner = seed[0] + seed[1] < new_map.width * 0.75
if seed[0] < 20 or (in_corner and seed[0] <= seed[1]):
new_map.region_terrain[r] = 'lake'
elif seed[1] < 20 or (in_corner and seed[1] < seed[0]):
new_map.region_terrain[r] = 'marsh'
else:
new_map.region_terrain[r] = 'desert'
elif el < 3:
new_map.region_terrain[r] = 'scrub'
elif el < 6:
new_map.region_terrain[r] = 'forest'
elif el < 7:
new_map.region_terrain[r] = 'rock'
else:
new_map.region_terrain[r] = 'ice'
def _assign_terrain(new_map):
terrain_lookup = { map.terrain_types[i].name : i
for i in range(len(map.terrain_types)) }
marsh_chances = { 'water' : 10, 'ground' : 40, 'reeds' : 10, 'saxaul' : 10 }
desert_chances = { 'ground' : 80, 'nitraria' : 5, 'ephedra' : 5, 'boulder' : 5 }
scrub_chances = { 'ground' : 40, 'nitraria' : 10, 'ephedra' : 10, 'boulder' : 5 }
forest_chances = { 'ground' : 45, 'poplar' : 15, 'boulder' : 5 }
terrain_chances = {
'lake' : { 'water' : 10 },
'marsh' : marsh_chances,
'desert' : desert_chances,
'scrub' : scrub_chances,
'forest' : forest_chances,
'rock' : { 'ground' : 45, 'boulder' : 5 },
'ice' : { 'ground' : 75, 'boulder' : 5 }
}
print('Assigning narrow terrain')
for x in range(config.OUTDOOR_MAP_WIDTH):
for y in range(config.OUTDOOR_MAP_HEIGHT):
t = new_map.region_terrain[new_map.region[x][y]]
if new_map.terrain[x][y] != map.TERRAIN_GROUND and t != 'lake':
# For now don't overwrite slopes, except underwater
continue
new_map.terrain[x][y] = terrain_lookup[_random_choice(terrain_chances[t])]
def _make_rotunda(new_map, peak):
"""
Create a rotunda on top of the mountain.
This is always at the peak.
"""
for x in range(peak[0]-3, peak[0]+4):
for y in range(peak[1]-3, peak[1]+4):
if new_map.elevation(x, y) != 9:
# in theory would be better to glom onto a closer region
# if one exists
new_map.region[x][y] = new_map.region[peak[0]][peak[1]]
# interior of rotunda is floor, edges are bare ground
if (x > peak[0]-3 and x < peak[0]+3 and
y > peak[1]-3 and y < peak[1]+3):
new_map.terrain[x][y] = map.TERRAIN_FLOOR
elif new_map.terrain[x][y] != map.TERRAIN_SLOPE:
new_map.terrain[x][y] = map.TERRAIN_GROUND
if (x == peak[0]-2 or x == peak[0]+2 or
y == peak[1]-2 or y == peak[1]+2):
# borders have alternating pillars
if ((x - peak[0]) % 2 == 0 and
(y - peak[1]) % 2 == 0):
new_map.terrain[x][y] = map.TERRAIN_WALL
def _test_quarry_placement(new_map, region_span):
"""
Look for a site of a given elevation in a particular consecutive range of regions.
"""
for r in range(region_span[0], region_span[1]):
if new_map.region_elevations[r] == QUARRY_ELEVATION:
return r
return None
def _mark_quarry_slopes(new_map, region):
# BUG still not quite right?
center = new_map.region_seeds[region]
print('Centering quarry at ' + str(center[0]) + ' ' + str(center[1]))
for x in range(max(center[0] - 10, 0), min(center[0] + 10, new_map.width - | |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle
import numpy as np
import paddle.nn as nn
from ...modules.init import kaiming_normal_, constant_, constant_init
from ...modules.dcn import DeformableConv_dygraph
# from paddle.vision.ops import DeformConv2D #to be compiled
from .builder import GENERATORS
@paddle.no_grad()
def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
"""Initialize network weights.
Args:
module_list (list[nn.Module] | nn.Module): Modules to be initialized.
scale (float): Scale initialized weights, especially for residual
blocks. Default: 1.
bias_fill (float): The value to fill bias. Default: 0
kwargs (dict): Other arguments for initialization function.
"""
if not isinstance(module_list, list):
module_list = [module_list]
for m in module_list:
if isinstance(m, nn.Conv2D):
kaiming_normal_(m.weight, **kwargs)
scale_weight = scale * m.weight
m.weight.set_value(scale_weight)
if m.bias is not None:
constant_(m.bias, bias_fill)
elif isinstance(m, nn.Linear):
kaiming_normal_(m.weight, **kwargs)
scale_weight = scale * m.weight
m.weight.set_value(scale_weight)
if m.bias is not None:
constant_(m.bias, bias_fill)
class ResidualBlockNoBN(nn.Layer):
"""Residual block without BN.
It has a style of:
---Conv-ReLU-Conv-+-
|________________|
Args:
nf (int): Channel number of intermediate features.
Default: 64.
"""
def __init__(self, nf=64):
super(ResidualBlockNoBN, self).__init__()
self.nf = nf
self.conv1 = nn.Conv2D(self.nf, self.nf, 3, 1, 1)
self.conv2 = nn.Conv2D(self.nf, self.nf, 3, 1, 1)
self.relu = nn.ReLU()
default_init_weights([self.conv1, self.conv2], 0.1)
def forward(self, x):
identity = x
out = self.conv2(self.relu(self.conv1(x)))
return identity + out
def MakeMultiBlocks(func, num_layers, nf=64):
"""Make layers by stacking the same blocks.
Args:
func (nn.Layer): nn.Layer class for basic block.
num_layers (int): number of blocks.
Returns:
nn.Sequential: Stacked blocks in nn.Sequential.
"""
Blocks = nn.Sequential()
for i in range(num_layers):
Blocks.add_sublayer('block%d' % i, func(nf))
return Blocks
class PredeblurResNetPyramid(nn.Layer):
"""Pre-dublur module.
Args:
in_nf (int): Channel number of input image. Default: 3.
nf (int): Channel number of intermediate features. Default: 64.
HR_in (bool): Whether the input has high resolution. Default: False.
"""
def __init__(self, in_nf=3, nf=64, HR_in=False):
super(PredeblurResNetPyramid, self).__init__()
self.in_nf = in_nf
self.nf = nf
self.HR_in = True if HR_in else False
self.Leaky_relu = nn.LeakyReLU(negative_slope=0.1)
if self.HR_in:
self.conv_first_1 = nn.Conv2D(in_channels=self.in_nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.conv_first_2 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=2,
padding=1)
self.conv_first_3 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=2,
padding=1)
else:
self.conv_first = nn.Conv2D(in_channels=self.in_nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.RB_L1_1 = ResidualBlockNoBN(nf=self.nf)
self.RB_L1_2 = ResidualBlockNoBN(nf=self.nf)
self.RB_L1_3 = ResidualBlockNoBN(nf=self.nf)
self.RB_L1_4 = ResidualBlockNoBN(nf=self.nf)
self.RB_L1_5 = ResidualBlockNoBN(nf=self.nf)
self.RB_L2_1 = ResidualBlockNoBN(nf=self.nf)
self.RB_L2_2 = ResidualBlockNoBN(nf=self.nf)
self.RB_L3_1 = ResidualBlockNoBN(nf=self.nf)
self.deblur_L2_conv = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=2,
padding=1)
self.deblur_L3_conv = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=2,
padding=1)
self.upsample = nn.Upsample(scale_factor=2,
mode="bilinear",
align_corners=False,
align_mode=0)
def forward(self, x):
if self.HR_in:
L1_fea = self.Leaky_relu(self.conv_first_1(x))
L1_fea = self.Leaky_relu(self.conv_first_2(L1_fea))
L1_fea = self.Leaky_relu(self.conv_first_3(L1_fea))
else:
L1_fea = self.Leaky_relu(self.conv_first(x))
L2_fea = self.deblur_L2_conv(L1_fea)
L2_fea = self.Leaky_relu(L2_fea)
L3_fea = self.deblur_L3_conv(L2_fea)
L3_fea = self.Leaky_relu(L3_fea)
L3_fea = self.RB_L3_1(L3_fea)
L3_fea = self.upsample(L3_fea)
L2_fea = self.RB_L2_1(L2_fea) + L3_fea
L2_fea = self.RB_L2_2(L2_fea)
L2_fea = self.upsample(L2_fea)
L1_fea = self.RB_L1_1(L1_fea)
L1_fea = self.RB_L1_2(L1_fea) + L2_fea
out = self.RB_L1_3(L1_fea)
out = self.RB_L1_4(out)
out = self.RB_L1_5(out)
return out
class TSAFusion(nn.Layer):
"""Temporal Spatial Attention (TSA) fusion module.
Temporal: Calculate the correlation between center frame and
neighboring frames;
Spatial: It has 3 pyramid levels, the attention is similar to SFT.
(SFT: Recovering realistic texture in image super-resolution by deep
spatial feature transform.)
Args:
nf (int): Channel number of middle features. Default: 64.
nframes (int): Number of frames. Default: 5.
center (int): The index of center frame. Default: 2.
"""
def __init__(self, nf=64, nframes=5, center=2):
super(TSAFusion, self).__init__()
self.nf = nf
self.nframes = nframes
self.center = center
self.sigmoid = nn.Sigmoid()
self.Leaky_relu = nn.LeakyReLU(negative_slope=0.1)
self.tAtt_2 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.tAtt_1 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.fea_fusion = nn.Conv2D(in_channels=self.nf * self.nframes,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0)
self.sAtt_1 = nn.Conv2D(in_channels=self.nf * self.nframes,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0)
self.max_pool = nn.MaxPool2D(3, stride=2, padding=1)
self.avg_pool = nn.AvgPool2D(3, stride=2, padding=1, exclusive=False)
self.sAtt_2 = nn.Conv2D(in_channels=2 * self.nf,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0)
self.sAtt_3 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.sAtt_4 = nn.Conv2D(
in_channels=self.nf,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0,
)
self.sAtt_5 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.sAtt_add_1 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0)
self.sAtt_add_2 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0)
self.sAtt_L1 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=1,
stride=1,
padding=0)
self.sAtt_L2 = nn.Conv2D(
in_channels=2 * self.nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1,
)
self.sAtt_L3 = nn.Conv2D(in_channels=self.nf,
out_channels=self.nf,
kernel_size=3,
stride=1,
padding=1)
self.upsample = nn.Upsample(scale_factor=2,
mode="bilinear",
align_corners=False,
align_mode=0)
def forward(self, aligned_fea):
"""
Args:
aligned_feat (Tensor): Aligned features with shape (b, n, c, h, w).
Returns:
Tensor: Features after TSA with the shape (b, c, h, w).
"""
B, N, C, H, W = aligned_fea.shape
x_center = aligned_fea[:, self.center, :, :, :]
emb_rf = self.tAtt_2(x_center)
emb = aligned_fea.reshape([-1, C, H, W])
emb = self.tAtt_1(emb)
emb = emb.reshape([-1, N, self.nf, H, W])
cor_l = []
for i in range(N):
emb_nbr = emb[:, i, :, :, :] #[B,C,W,H]
cor_tmp = paddle.sum(emb_nbr * emb_rf, axis=1)
cor_tmp = paddle.unsqueeze(cor_tmp, axis=1)
cor_l.append(cor_tmp)
cor_prob = paddle.concat(cor_l, axis=1) #[B,N,H,W]
cor_prob = self.sigmoid(cor_prob)
cor_prob = paddle.unsqueeze(cor_prob, axis=2) #[B,N,1,H,W]
cor_prob = paddle.expand(cor_prob, [B, N, self.nf, H, W]) #[B,N,C,H,W]
cor_prob = cor_prob.reshape([B, -1, H, W])
aligned_fea = aligned_fea.reshape([B, -1, H, W])
aligned_fea = aligned_fea * cor_prob
fea = self.fea_fusion(aligned_fea)
fea = self.Leaky_relu(fea)
#spatial fusion
att = self.sAtt_1(aligned_fea)
att = self.Leaky_relu(att)
att_max = self.max_pool(att)
att_avg = self.avg_pool(att)
att_pool = paddle.concat([att_max, att_avg], axis=1)
att = self.sAtt_2(att_pool)
att = self.Leaky_relu(att)
#pyramid
att_L = self.sAtt_L1(att)
att_L = self.Leaky_relu(att_L)
att_max = self.max_pool(att_L)
att_avg = self.avg_pool(att_L)
att_pool = paddle.concat([att_max, att_avg], axis=1)
att_L = self.sAtt_L2(att_pool)
att_L = self.Leaky_relu(att_L)
att_L = self.sAtt_L3(att_L)
att_L = self.Leaky_relu(att_L)
att_L = self.upsample(att_L)
att = self.sAtt_3(att)
att = self.Leaky_relu(att)
att = att + att_L
att = self.sAtt_4(att)
att = self.Leaky_relu(att)
att = self.upsample(att)
att = self.sAtt_5(att)
att_add = self.sAtt_add_1(att)
att_add = self.Leaky_relu(att_add)
att_add = self.sAtt_add_2(att_add)
att = self.sigmoid(att)
fea = fea * att * 2 + att_add
return fea
class DCNPack(nn.Layer):
"""Modulated deformable conv for deformable alignment.
Ref:
Delving Deep into Deformable Alignment in Video Super-Resolution.
"""
def __init__(self,
num_filters=64,
kernel_size=3,
stride=1,
padding=1,
dilation=1,
deformable_groups=8,
extra_offset_mask=True):
super(DCNPack, self).__init__()
self.extra_offset_mask = extra_offset_mask
self.deformable_groups = deformable_groups
self.num_filters = num_filters
if isinstance(kernel_size, int):
self.kernel_size = [kernel_size, kernel_size]
self.conv_offset_mask = nn.Conv2D(in_channels=self.num_filters,
out_channels=self.deformable_groups *
3 * self.kernel_size[0] *
self.kernel_size[1],
kernel_size=self.kernel_size,
stride=stride,
padding=padding)
self.total_channels = self.deformable_groups * 3 * self.kernel_size[
0] * self.kernel_size[1]
self.split_channels = self.total_channels // 3
self.dcn = DeformableConv_dygraph(
num_filters=self.num_filters,
filter_size=self.kernel_size,
dilation=dilation,
stride=stride,
padding=padding,
deformable_groups=self.deformable_groups)
# self.dcn = DeformConv2D(in_channels=self.num_filters,out_channels=self.num_filters,kernel_size=self.kernel_size,stride=stride,padding=padding,dilation=dilation,deformable_groups=self.deformable_groups,groups=1) # to be compiled
self.sigmoid = nn.Sigmoid()
# init conv offset
constant_init(self.conv_offset_mask, 0., 0.)
def forward(self, fea_and_offset):
out = None
x = None
if self.extra_offset_mask:
out = self.conv_offset_mask(fea_and_offset[1])
x = fea_and_offset[0]
o1 = out[:, 0:self.split_channels, :, :]
o2 = out[:, self.split_channels:2 * self.split_channels, :, :]
mask = out[:, 2 * self.split_channels:, :, :]
offset = paddle.concat([o1, o2], axis=1)
mask = self.sigmoid(mask)
y = self.dcn(x, offset, mask)
return y
class PCDAlign(nn.Layer):
"""Alignment module using Pyramid, Cascading and Deformable convolution
(PCD). It is used in EDVR.
Ref:
EDVR: Video Restoration with Enhanced Deformable Convolutional Networks
Args:
nf (int): Channel number of middle features. Default: 64.
groups (int): Deformable groups. Defaults: 8.
"""
def __init__(self, nf=64, groups=8):
super(PCDAlign, self).__init__()
self.nf = nf
self.groups = groups
self.Leaky_relu = nn.LeakyReLU(negative_slope=0.1)
self.upsample = nn.Upsample(scale_factor=2,
mode="bilinear",
align_corners=False,
align_mode=0)
# Pyramid has three levels:
# L3: level 3, 1/4 spatial size
# L2: level 2, 1/2 spatial size
# L1: level 1, original spatial size
# L3
self.PCD_Align_L3_offset_conv1 = nn.Conv2D(in_channels=nf * 2,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
self.PCD_Align_L3_offset_conv2 = nn.Conv2D(in_channels=nf,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
self.PCD_Align_L3_dcn = DCNPack(num_filters=nf,
kernel_size=3,
stride=1,
padding=1,
deformable_groups=groups)
#L2
self.PCD_Align_L2_offset_conv1 = nn.Conv2D(in_channels=nf * 2,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
self.PCD_Align_L2_offset_conv2 = nn.Conv2D(in_channels=nf * 2,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
self.PCD_Align_L2_offset_conv3 = nn.Conv2D(in_channels=nf,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
self.PCD_Align_L2_dcn = DCNPack(num_filters=nf,
kernel_size=3,
stride=1,
padding=1,
deformable_groups=groups)
self.PCD_Align_L2_fea_conv = nn.Conv2D(in_channels=nf * 2,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
#L1
self.PCD_Align_L1_offset_conv1 = nn.Conv2D(in_channels=nf * 2,
out_channels=nf,
kernel_size=3,
stride=1,
padding=1)
self.PCD_Align_L1_offset_conv2 = nn.Conv2D(in_channels=nf * 2,
out_channels=nf,
kernel_size=3,
stride=1,
| |
import numpy as np
from extra_data.components import AGIPD1M
import dask.array as da
import xarray as xr
from dask.distributed import Client, progress
import warnings
import h5py as h5
import bottleneck as bn
import pdb
class Calibrator:
"""Calibrate AGIPD dataset"""
adu_per_photon = 66
mask = np.ones((16, 512, 128), "bool")
def __init__(
self,
run,
cell_ids,
train_ids,
flatfield_run_number=None,
dark_run_number=None,
mask=None,
is_dark=False,
is_flatfield=False,
apply_internal_mask=False,
dropletize=False,
stripes=None,
baseline=False,
asic_commonmode=False,
subshape=(64, 64),
cell_commonmode=False,
cellCM_window=2,
):
#: DataCollection: e.g., returned from extra_data.RunDirectory
self.run = run
#: bool: True if data is a dark run
self.is_dark = is_dark
#: bool: True if data is a flatfield run
self.is_flatfield = is_flatfield
#: tuple: asic (or subasic) shape for asic commonmode. Default (64, 64)
self.subshape = subshape
self.cell_ids = cell_ids
self.train_ids = train_ids
# corrections applied on Dask lazy array
self.corrections = {
"dark_subtraction": False,
"baseline": baseline, # baseline has to be applied
# before any masking
"masking": False, # Switch of masking with DataArray.where and mask on workers.
"internal_masking": apply_internal_mask,
# 'dropletize': dropletize,
}
# corrections applied on each worker
self.worker_corrections = {
"asic_commonmode": asic_commonmode,
"cell_commonmode": cell_commonmode,
"dropletize": dropletize,
}
self.mask = mask
self.xmask = self.mask
self.is_proc = None
#: (np.ndarray): average dark over trains
self.avr_dark = None
#: (np.ndarray): mask calculated from darks
self.dark_mask = None
#: str: file with dark data.
self.darkfile = None
# setting the dark run also sets the previous dark attributes
self.dark_run_number = dark_run_number
#: (np.ndarray): flatfield data
self.flatfield = None
#: (np.ndarray): mask calculated from flatfields
self.flatfield_mask = None
#: str: file with flatfield data.
self.flatfieldfile = None
# setting the flatfield run also sets the previous attributes
self.flatfield_run_number = flatfield_run_number
self.stripes = stripes
# Darks will not be calibrated (overwrite configfile)
if self.is_dark or self.is_flatfield:
for correction in ["corrections", "worker_corrections"]:
correction_dict = getattr(self, correction)
for key in correction_dict:
correction_dict[key] = False
#: DataArray: the run AGIPD data
self.data = None
def __getstate__(self):
"""needed for apply dask.apply_along_axis
We return only those attributes needed by the worker functions
"""
attrs = ["adu_per_photon", "worker_corrections", "subshape", "mask"]
return {attr: getattr(self, attr) for attr in attrs}
@property
def xmask(self):
"""DataArray: pixel mask as xarray.DataArray"""
return self.__xmask
@xmask.setter
def xmask(self, mask):
if isinstance(mask, xr.DataArray):
mask = mask.values
elif isinstance(mask, np.ndarray):
pass
else:
raise ValueError(f"{type(mask)} cannot be used as mask.")
self.__xmask = xr.DataArray(
mask,
dims=("module", "dim_0", "dim_1"),
coords={
"module": np.arange(16),
"dim_0": np.arange(512),
"dim_1": np.arange(128),
},
)
@property
def dark_run_number(self):
"""The run number and the file index to load the average dark"""
return self.__dark_run_number
@dark_run_number.setter
def dark_run_number(self, number):
if number is None:
pass
elif len(number) == 2:
self.darkfile = f"r{number[0]:04}-dark_{number[1]:03}.h5"
with h5.File(self.darkfile, "r") as f:
avr_dark = f["dark/intensity"][:]
pulse_ids = f["identifiers/pulse_ids"][:].flatten()
self.dark_mask = self.xmask.copy(data=f["dark/mask"][:])
xdark = xr.DataArray(
avr_dark,
dims=("pulseId", "module", "dim_0", "dim_1"),
coords={
"pulseId": pulse_ids,
"module": np.arange(16),
"dim_0": np.arange(512),
"dim_1": np.arange(128),
},
)
xdark = xdark.transpose("module", "dim_0", "dim_1", "pulseId")
self.avr_dark = xdark
self.is_proc = False
self.corrections["dark_subtraction"] = True
# internal mask available only in processed data
self.corrections["internal_masking"] = False
else:
raise ValueError(
"Dark input parameter could not be processed:\n" f"{number}"
)
self.__dark_run_number = number
@property
def flatfield_run_number(self):
"""The run number and the file index to load the flatfield"""
return self.__flatfield_run_number
@flatfield_run_number.setter
def flatfield_run_number(self, number):
if number is None:
pass
elif len(number) == 2:
self.flatfieldfile = f"r{number[0]:04}-flatfield_{number[1]:03}.h5"
with h5.File(self.flatfieldfile, "r") as f:
flatfield = f["flatfield/intensity"][:]
pulse_ids = f["identifiers/pulse_ids"][:].flatten()
self.flatfield_mask = self.xmask.copy(data=f["flatfield/mask"][:])
xflatfield = xr.DataArray(
flatfield,
dims=("pulseId", "module", "dim_0", "dim_1"),
coords={
"pulseId": pulse_ids,
"module": np.arange(16),
"dim_0": np.arange(512),
"dim_1": np.arange(128),
},
)
xflatfield = xflatfield.transpose("module", "dim_0", "dim_1", "pulseId")
self.flatfield = xflatfield
else:
raise ValueError(
"Flatfield input parameter could not be processed:\n" f"{number}"
)
self.__flatfield_run_number = number
@property
def stripes(self):
"""Pixels behind the Ta stripes for baseline correction."""
return self.__stripes
@stripes.setter
def stripes(self, stripes):
if isinstance(stripes, str):
stripes = np.load(stripes).astype("bool")
if stripes.shape != (16, 512, 128):
raise ValueError(
"Stripe mask has wrong shape: " f"shape is {stripe.shape}"
)
self.corrections["baseline"] = True
if self.dark_mask is not None:
print("Combining dark-mask and stripe-mask")
stripes &= self.dark_mask.values
elif stripes is None:
pass
else:
raise TypeError(f"Invalid dark run number type {type(number)}.")
self.__stripes = stripes
def _get_data(self):
"""Read data and apply corrections
Args:
train_step (int): step between trains for slicing.
last_train (int): last train index to process.
Return:
DataArray: of the run data.
"""
print("Requesting data...", flush=True)
self._agp = AGIPD1M(self.run, min_modules=16)
arr = self._agp.get_dask_array("image.data")
print("Loaded dask array.", flush=True)
# coords are module, dim_0, dim_1, trainId, pulseId after unstack
arr = arr.unstack()
self.is_proc = True if len(arr.dims) == 5 else False
print(f"Is processed: {self.is_proc}")
arr = self._slice(arr)
arr = arr.stack(train_pulse=("trainId", "pulseId"))
arr = arr.transpose("train_pulse", ...)
for correction, options in self.corrections.items():
if bool(options):
print(f"Apply {correction}")
arr = getattr(self, "_" + correction)(arr)
for correction, flag in self.worker_corrections.items():
if bool(flag):
print(f"Apply {correction} on workers.")
arr = arr.stack(pixels=("module", "dim_0", "dim_1"))
arr = arr.transpose("train_pulse", "pixels")
self.data = arr
def _slice(self, arr):
"""Select trains and pulses."""
arr = arr.sel(trainId=self.train_ids).sel(pulseId=self.cell_ids)
if not self.is_proc:
arr = arr.isel(dim_0=0)
arr = arr.rename({"dim_1": "dim_0", "dim_2": "dim_1"})
# slicing dark should not be neccessary as xarrays
# broadcasting takes coords into account
# if self.avr_dark is not None:
# # first cell has been cut when averaging dark
# dark_slice = slice(
# self.first_cell - 1,
# (self.first_cell - 1 +
# self.pulses_per_train * self.pulse_step),
# self.pulse_step)
# self.avr_dark = self.avr_dark[..., dark_slice]
return arr
def _dark_subtraction(self, arr):
"""Subtract average darks from train data."""
arr = arr.unstack()
arr = arr - self.avr_dark
arr = arr.stack(train_pulse=("trainId", "pulseId"))
arr = arr.transpose("train_pulse", ...)
return arr
def _masking(self, arr):
"""Mask bad pixels with provided use mask."""
if self.dark_mask is not None:
print("using dark mask")
arr = arr.where(self.xmask & self.dark_mask)
if self.flatfield_mask is not None:
print("using flatfield mask")
arr = arr.where(self.flatfield_mask)
return arr
else:
return arr.where(self.xmask)
def _dropletize(self, arr):
"""Convert adus to photon counts."""
arr = np.floor((arr + 0.5 * self.adu_per_photon) / self.adu_per_photon)
arr = arr.where(arr >= 0, other=-1).fillna(-1).astype("int16")
return arr
def _internal_masking(self, arr):
"""Exclude pixels based on calibration pipeline."""
mask_int = self._agp.get_dask_array("image.mask")
mask_int = mask_int.unstack()
mask_int = self._slice(mask_int)
mask_int = mask_int.stack(train_pulse=("trainId", "pulseId"))
arr = arr.where((mask_int <= 0) | (mask_int >= 8))
return arr
def _baseline(self, arr):
"""Baseline correction based on Ta stripes"""
pix = arr.where(self.stripes[None, ...])
module_median = pix.median(["dim_0", "dim_1"], skipna=True)
# if np.sum(np.isfinite(module_median)).compute() == 0:
# warnings.warn("All module medians are nan. Check masks")
module_median = module_median.where(
(np.isfinite(module_median) & (module_median < 0.5 * self.adu_per_photon)),
0,
)
arr = arr - module_median
return arr
def _asic_commonmode(self, arr):
return self._asic_commonmode_xarray(arr)
@classmethod
def _calib_worker(cls, frames):
"""Apply corrections on workers."""
if cls.worker_corrections["asic_commonmode"]:
frames = cls._asic_commonmode_worker(frames)
return frames
def _asic_commonmode_ufunc(self, arr):
"""Apply commonmode on asic level"""
# arr = arr.unstack()
# arr = arr.stack(frame_data=('module', 'dim_0', 'dim_1'))
# npulses = np.unique(arr.pulseId.values).size
arr = arr.chunk({"pixels": -1})
arr = xr.apply_ufunc(
self._asic_commonmode_worker,
arr,
vectorize=True,
input_core_dims=[["pixels"]],
output_core_dims=[["pixels"]],
output_dtypes=[np.int],
dask="parallelized",
)
# dim = arr.get_axis_num("train_data")
# arr.data = da.apply_along_axis(worker, dim, arr.data, dtype='float32')
# # shape=(npulses*16*512*128))
# arr = arr.persist()
# progress(arr)
# arr = arr.unstack()
# arr = arr.stack(train_pulse=('trainId', 'pulseId'),
# pixels=('module', 'dim_0', 'dim_1'))
return arr
def _asic_commonmode_xarray(self, arr):
"""Apply commonmode on asic level using xarray."""
nrows, ncols = self.subshape
nv = 512 // nrows
nh = 128 // ncols // 2
nhl = sorted(set([x * y for x in [-1, 1] for y in range(1, 1 + nh)]))
arr = arr.unstack()
arr = arr.stack(train_pulse_module=["trainId", "pulseId", "module"])
arr = arr.chunk({"train_pulse_module": 1024})
arr = arr.assign_coords(
asc_0=("dim_0", np.repeat(np.arange(1, nv + 1), nrows)),
asc_1=("dim_1", np.repeat(nhl, ncols)),
)
arr = arr.assign_coords(asc=arr.asc_0 * arr.asc_1)
asics = arr.groupby("asc")
asic_median = asics.median(skipna=True)
asic_median = asic_median.where(asic_median < self.adu_per_photon / 2, other=0)
asics -= asic_median
arr = asics.drop(("asc", "asc_0", "asc_1"))
arr = arr.unstack()
arr = arr.stack(train_pulse=("trainId", "pulseId"))
return arr
def _create_asic_mask():
"""Mask asic borders."""
asic_mask = np.ones((512, 128))
asic_mask[:3, :] = 0
asic_mask[-3:, :] = 0
asic_mask[:, -3:] = 0
asic_mask[:, :3] = 0
asic_mask[:, 62:66] = 0
for i in range(1, 9):
c = 64 * i
asic_mask[c - 2 : c + 2, :] = 0
asic_mask = np.rollaxis(np.dstack([asic_mask] * 16), axis=-1)
return asic_mask.astype("bool")
def _create_ta_mask():
"""Mask Ta stripes."""
ta_mask = [np.zeros((512, 128)) for _ in range(4)]
| |
from datetime import datetime
from calendar import monthrange
import logging
from flask import Flask, Response, request
from entites.BaseEntity import BaseApiResponse
from validation.http_api_validation import isValidationError, validateIsNumber, validateIsmatchDateFormat, validationErrMessage
from usecases.CovidTestUseCase import CovidTestUseCase
import time
class CovidTestApiHandler():
def __init__(self, flaskApp: Flask, covidTestUseCase: CovidTestUseCase):
self.http = flaskApp
# init usecase deps
self.useCase = covidTestUseCase
# get root logger
self.logger = logging.getLogger('root')
def serverErrorResponse(self):
"""
Returns:
return api response serverity error
"""
return Response(
BaseApiResponse(ok=False, data={}, message='something wrong with server').to_json(),
status=500,
content_type='application/json'
)
def notFoundResponse(self):
"""
Returns:
return api response serverity error
"""
return Response(
BaseApiResponse(ok=False, data={}, message='data not found').to_json(),
status=404,
content_type='application/json'
)
def getGeneralInformation(self):
"""handle request general information
Returns:
[json]: [response json]
"""
# process use case
result, err = self.useCase.getGeneralInformation()
# TODO: handle loging
if err is not None:
self.logger.error(err)
# return server error json
return self.serverErrorResponse()
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getYearlyData(self):
"""handle request get data yearly
return json yearly data if empty query param return all yearly data
Returns:
[json]: [response json]
"""
# get query param since, upto
since = request.args.get('since', 2020)
upto = request.args.get('upto', datetime.now().year)
# validate request
valErr = [
validateIsNumber(since, "since"),
validateIsNumber(upto, "upto")
]
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getYearlyDatasList(int(since), int(upto))
if err is not None:
self.logger.error(err)
# return server error json
return self.serverErrorResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getDataByYear(self, year):
"""handle request get data by year
Returns:
[json]: [response json]
"""
# validate request
valErr = [validateIsNumber(year, "year")]
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getDataByYear(year)
if err is not None:
self.logger.error(err)
# return server error json
return self.serverErrorResponse()
# if data not found return epmty object
if result is None:
# return not found
return self.notFoundResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getMonthlyData(self):
"""handle request get data monthly
return json monthly data if empty query param return all monthly data
Returns:
[json]: [response json]
"""
# get query param since, upto
since = request.args.get('since', '2020.01')
upto = request.args.get('upto', datetime.utcfromtimestamp(time.time()).strftime("%Y.%m"))
# validate request
valErr = [
validateIsmatchDateFormat(since, '%Y.%m', 'since', '<year>.<month> eg. 2020.01 and cant be empty'),
validateIsmatchDateFormat(upto, '%Y.%m', 'upto', '<year>.<month> eg. 2020.01 and cant be empty')
]
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getMonthlyData(since, upto)
if err is not None:
self.logger.error(err)
# return not found
return self.notFoundResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getMonthlyDataByYear(self, year):
"""handle request get data monthly in a year
returning json data per month in spesific year
return all month in year if query param empty
Returns:
[json]: [response json]
"""
since = request.args.get('since', '{}.01'.format(year))
upto = request.args.get('upto', '{}.12'.format(year))
# validate request query param
valErr = [
validateIsNumber(year, "year"),
validateIsmatchDateFormat(since, '%Y.%m', 'since', '<year>.<month> eg. 2020.01 and cant be empty'),
validateIsmatchDateFormat(upto, '%Y.%m', 'upto', '<year>.<month> eg. 2020.01 and cant be empty')
]
# cek if month requested is in year param
try:
if datetime.strptime(since, "%Y.%m").timetuple().tm_year != int(year) or datetime.strptime(upto, "%Y.%m").timetuple().tm_year != int(year):
valErr.append('month format request is not in year, make sure <year> in ?since=<year>.<month> and ?upto=<year>.<month> /monthly/<year> is same year, (eg. monthly/2021?since=2021.05&upto=2021.09)')
except ValueError:
pass
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getMonthlyData(since, upto)
if err is not None:
self.logger.error(err)
# return server error
return self.serverErrorResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getMonthlyDataByYearMonth(self, year, month):
"""handle request get data monthly by year and month
return single json monthly data
Returns:
[json]: [response json]
"""
# validate request
valErr = [
validateIsmatchDateFormat(year, '%Y', 'since', '<year>.<month> eg. 2020 and cant be empty'),
validateIsmatchDateFormat(month, '%m', 'upto', '<year>.<month> eg. 09 and cant be empty')
]
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getMonthlyData('{}.{}'.format(year, month), '{}.{}'.format(year, month))
if err is not None:
self.logger.error(err)
return Response(
BaseApiResponse(ok=False, data={}, message='something wrong with server').to_json(),
status=500,
content_type='application/json'
)
if len(result) == 0:
# return not found
return self.notFoundResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result[0], message='success').to_json(),
status=200,
content_type='application/json'
)
def getDailyData(self):
"""handle request get data daily
return json daily data if empty query param return all daily data
Returns:
[json]: [response json]
"""
# get query param since, upto
since = request.args.get('since', '2020.01.01')
upto = request.args.get('upto', datetime.utcfromtimestamp(time.time()).strftime("%Y.%m.%d"))
# validate request
valErr = [
validateIsmatchDateFormat(since, '%Y.%m.%d', 'since', '<year>.<month> eg. 2020.01.01 and cant be empty'),
validateIsmatchDateFormat(upto, '%Y.%m.%d', 'upto', '<year>.<month> eg. 2020.01.01 and cant be empty')
]
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getDailyData(since, upto)
if err is not None:
self.logger.error(err)
return self.serverErrorResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getDailyDataByYear(self, year):
"""handle request get data daily in a year
returning json data per day in spesific year
return all day in year if query param empty
Returns:
[json]: [response json]
"""
since = request.args.get('since', '{}.01.01'.format(year))
upto = request.args.get('upto', '{}.12.31'.format(year))
# validate request query param
valErr = [
validateIsNumber(year, 'year'),
validateIsmatchDateFormat(since, '%Y.%m.%d', 'since', '<year>.<month> eg. 2020.01.01 and cant be empty'),
validateIsmatchDateFormat(upto, '%Y.%m.%d', 'upto', '<year>.<month> eg. 2020.01.01 and cant be empty')
]
# cek if day requested is in year param
try:
if datetime.strptime(since, "%Y.%m.%d").timetuple().tm_year != int(year) or datetime.strptime(upto, "%Y.%m.%d").timetuple().tm_year != int(year):
valErr.append('date format request is not in year, make sure <year> in ?since=<year>.<month>.<day> and ?upto=<year>.<month>.<day> /daily/<year> is same year, (eg. daily/2021?since=2021.05.01&upto=2021.09.01)')
except ValueError:
pass
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getDailyData(since, upto)
if err is not None:
self.logger.error(err)
# retuen server error
return self.serverErrorResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getDailyDataInYearMonth(self, year, month):
"""handle request get data daily in year and month
return single json daily data
Returns:
[json]: [response json]
"""
# validate request query param
valErr = [
validateIsNumber(year, "year"),
validateIsNumber(month, "month")
]
# validation month year valid
try:
monthrange(int(year), int(month))[1]
except ValueError:
valErr.append('make sure year month and date in 2021.01.01 date format')
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# calculate total day of month
totalDayOfMonth = monthrange(int(year), int(month))[1]
since = request.args.get('since', '{}.{}.01'.format(year, month))
upto = request.args.get('upto', '{}.{}.{}'.format(year, month, totalDayOfMonth))
# validate request query param
valErr.append(validateIsmatchDateFormat(since, '%Y.%m.%d', 'since', '<year>.<month>.<date> eg. 2020.01.01 and cant be empty'))
valErr.append(validateIsmatchDateFormat(upto, '%Y.%m.%d', 'upto', '<year>.<month>.<date> eg. 2020.01.01 and cant be empty'))
# cek if month requested is in year param
try:
dateSince = datetime.strptime(since, "%Y.%m.%d").timetuple()
dateUpto = datetime.strptime(upto, "%Y.%m.%d").timetuple()
if dateSince.tm_year != int(year) or dateUpto.tm_year != int(year) or dateSince.tm_mon != int(month.strip("0")) or dateUpto.tm_mon != int(month.strip("0")):
valErr.append('month format request is not in year, make sure <year> in ?since=<year>.<month>.<date> and ?upto=<year>.<month>.<date> /daily/<year>/<month> is same year, (eg. daily/2021/05?since=2021.05.01&upto=2021.05.10)')
except ValueError:
pass
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getDailyData(since, upto)
if err is not None:
self.logger.error(err)
# return server error
return self.serverErrorResponse()
# return success response
return Response(
BaseApiResponse(ok=True, data=result, message='success').to_json(),
status=200,
content_type='application/json'
)
def getDailyDataByDate(self, year, month, date):
"""handle request get data monthly by year and month
return single json monthly data
Returns:
[json]: [response json]
"""
# validate request
valErr = [
validateIsmatchDateFormat(year, '%Y', 'year', '<year>.<month>.<date> eg. 2020 and cant be empty'),
validateIsmatchDateFormat(month, '%m', 'month', '<year>.<month>.<date> eg. 09 and cant be empty'),
validateIsmatchDateFormat(date, '%d', 'date', '<year>.<month>.<date> eg. 09 and cant be empty')
]
if isValidationError(valErr):
return Response(
BaseApiResponse(ok=False, data={}, message='Validation error, {}'.format(validationErrMessage(valErr))).to_json(),
status=422,
content_type='application/json'
)
# process use case
result, err = self.useCase.getDailyData('{}.{}.{}'.format(year, month, date), '{}.{}.{}'.format(year, month, date))
if err is not None:
self.logger.error(err)
# return server error
return self.serverErrorResponse()
if len(result) == 0:
# return | |
1
nfreq = 100
freq = np.linspace(1, 10.0, nfreq)
rng = np.random.RandomState(100) # set the seed for the random number generator
noise = rng.exponential(size=nfreq)
cls.model = models.Lorentz1D() + models.Const1D()
cls.x_0_0 = 2.0
cls.fwhm_0 = 0.05
cls.amplitude_0 = 1000.0
cls.amplitude_1 = 2.0
cls.model.x_0_0 = cls.x_0_0
cls.model.fwhm_0 = cls.fwhm_0
cls.model.amplitude_0 = cls.amplitude_0
cls.model.amplitude_1 = cls.amplitude_1
p = cls.model(freq)
np.random.seed(400)
power = noise*p
ps = Powerspectrum()
ps.freq = freq
ps.power = power
ps.m = m
ps.df = freq[1]-freq[0]
ps.norm = "leahy"
cls.ps = ps
cls.a_mean, cls.a_var = 2.0, 1.0
cls.a2_mean, cls.a2_var = 100.0, 10.0
p_amplitude_1 = lambda amplitude: \
scipy.stats.norm(loc=cls.a_mean, scale=cls.a_var).pdf(amplitude)
p_x_0_0 = lambda alpha: \
scipy.stats.uniform(0.0, 5.0).pdf(alpha)
p_fwhm_0 = lambda alpha: \
scipy.stats.uniform(0.0, 0.5).pdf(alpha)
p_amplitude_0 = lambda amplitude: \
scipy.stats.norm(loc=cls.a2_mean, scale=cls.a2_var).pdf(amplitude)
cls.priors = {"amplitude_1": p_amplitude_1,
"amplitude_0": p_amplitude_0,
"x_0_0": p_x_0_0,
"fwhm_0": p_fwhm_0}
cls.lpost = PSDPosterior(cls.ps.freq, cls.ps.power,
cls.model, m=cls.ps.m)
cls.lpost.logprior = set_logprior(cls.lpost, cls.priors)
cls.fitmethod = "powell"
cls.max_post = True
cls.t0 = [cls.x_0_0, cls.fwhm_0, cls.amplitude_0, cls.amplitude_1]
cls.neg = True
def test_fitting_with_ties_and_bounds(self, capsys):
double_f = lambda model : model.x_0_0 * 2
model = self.model.copy()
model += models.Lorentz1D(amplitude=model.amplitude_0,
x_0 = model.x_0_0 * 2,
fwhm = model.fwhm_0)
model.x_0_0 = self.model.x_0_0
model.amplitude_0 = self.model.amplitude_0
model.amplitude_1 = self.model.amplitude_1
model.fwhm_0 = self.model.fwhm_0
model.x_0_2.tied = double_f
model.fwhm_0.bounds = [0, 10]
model.amplitude_0.fixed = True
p = model(self.ps.freq)
noise = np.random.exponential(size=len(p))
power = noise*p
ps = Powerspectrum()
ps.freq = self.ps.freq
ps.power = power
ps.m = self.ps.m
ps.df = self.ps.df
ps.norm = "leahy"
pe = PSDParEst(ps, fitmethod="TNC")
llike = PSDLogLikelihood(ps.freq, ps.power, model)
true_pars = [self.x_0_0, self.fwhm_0,
self.amplitude_1,
model.amplitude_2.value,
model.fwhm_2.value]
res = pe.fit(llike, true_pars, neg=True)
compare_pars = [self.x_0_0, self.fwhm_0,
self.amplitude_1,
model.amplitude_2.value,
model.fwhm_2.value]
assert np.allclose(compare_pars, res.p_opt, rtol=0.5)
def test_par_est_initializes(self):
pe = PSDParEst(self.ps)
assert pe.max_post is True, "max_post should be set to True as a default."
def test_fit_fails_when_object_is_not_posterior_or_likelihood(self):
x = np.ones(10)
y = np.ones(10)
pe = PSDParEst(self.ps)
with pytest.raises(TypeError):
res = pe.fit(x, y)
def test_fit_fails_without_lpost_or_t0(self):
pe = PSDParEst(self.ps)
with pytest.raises(TypeError):
res = pe.fit()
def test_fit_fails_without_t0(self):
pe = PSDParEst(self.ps)
with pytest.raises(TypeError):
res = pe.fit(np.ones(10))
def test_fit_fails_with_incorrect_number_of_parameters(self):
pe = PSDParEst(self.ps)
t0 = [1,2]
with pytest.raises(ValueError):
res = pe.fit(self.lpost, t0)
@pytest.mark.skipif("not can_plot")
def test_fit_method_works_with_correct_parameter(self):
pe = PSDParEst(self.ps)
lpost = PSDPosterior(self.ps.freq, self.ps.power,
self.model, self.priors, m=self.ps.m)
t0 = [2.0, 1, 1, 1]
res = pe.fit(lpost, t0)
assert isinstance(res, OptimizationResults), "res must be of type " \
"OptimizationResults"
pe.plotfits(res, save_plot=True)
assert os.path.exists("test_ps_fit.png")
os.unlink("test_ps_fit.png")
pe.plotfits(res, save_plot=True, log=True)
assert os.path.exists("test_ps_fit.png")
os.unlink("test_ps_fit.png")
pe.plotfits(res, res2=res, save_plot=True)
assert os.path.exists("test_ps_fit.png")
os.unlink("test_ps_fit.png")
def test_compute_lrt_fails_when_garbage_goes_in(self):
pe = PSDParEst(self.ps)
t0 = [2.0, 1, 1, 1]
with pytest.raises(TypeError):
pe.compute_lrt(self.lpost, t0, None, t0)
with pytest.raises(ValueError):
pe.compute_lrt(self.lpost, t0[:-1], self.lpost, t0)
def test_compute_lrt_works(self):
t0 = [2.0, 1, 1, 1]
pe = PSDParEst(self.ps, max_post=True)
assert pe.max_post is True
delta_deviance, _, _ = pe.compute_lrt(self.lpost, t0, self.lpost, t0)
assert pe.max_post is False
assert np.absolute(delta_deviance) < 1.5e-4
def test_simulate_lrts_works(self):
m = 1
nfreq = 100
freq = np.linspace(1, 10, nfreq)
rng = np.random.RandomState(100)
noise = rng.exponential(size=nfreq)
model = models.Const1D()
model.amplitude = 2.0
p = model(freq)
power = noise * p
ps = Powerspectrum()
ps.freq = freq
ps.power = power
ps.m = m
ps.df = freq[1] - freq[0]
ps.norm = "leahy"
loglike = PSDLogLikelihood(ps.freq, ps.power, model, m=1)
s_all = np.atleast_2d(np.ones(5) * 2.0).T
model2 = models.PowerLaw1D() + models.Const1D()
model2.x_0_0.fixed = True
loglike2 = PSDLogLikelihood(ps.freq, ps.power, model2, 1)
pe = PSDParEst(ps)
lrt_obs, res1, res2 = pe.compute_lrt(loglike, [2.0], loglike2,
[2.0, 1.0, 2.0], neg=True)
lrt_sim = pe.simulate_lrts(s_all, loglike, [2.0], loglike2,
[2.0, 1.0, 2.0],
seed=100)
assert (lrt_obs > 0.4) and (lrt_obs < 0.6)
assert np.all(lrt_sim < 10.0) and np.all(lrt_sim > 0.01)
def test_compute_lrt_fails_with_wrong_input(self):
pe = PSDParEst(self.ps)
with pytest.raises(AssertionError):
lrt_sim = pe.simulate_lrts(np.arange(5), self.lpost, [1, 2, 3, 4],
[1, 2, 3, 4], [1, 2, 3, 4])
def test_generate_model_data(self):
pe = PSDParEst(self.ps)
m = self.model
_fitter_to_model_params(m, self.t0)
model = m(self.ps.freq)
pe_model = pe._generate_model(self.lpost, [self.x_0_0, self.fwhm_0,
self.amplitude_0,
self.amplitude_1])
assert np.allclose(model, pe_model)
def generate_data_rng_object_works(self):
pe = PSDParEst(self.ps)
sim_data1 = pe._generate_data(self.lpost,
[self.x_0_0, self.fwhm_0,
self.amplitude_0,
self.amplitude_1],
seed=1)
sim_data2 = pe._generate_data(self.lpost,
[self.x_0_0, self.fwhm_0,
self.amplitude_0,
self.amplitude_1],
seed=1)
assert np.allclose(sim_data1.power, sim_data2.power)
def test_generate_data_produces_correct_distribution(self):
model = models.Const1D()
model.amplitude = 2.0
p = model(self.ps.freq)
seed = 100
rng = np.random.RandomState(seed)
noise = rng.exponential(size=len(p))
power = noise*p
ps = Powerspectrum()
ps.freq = self.ps.freq
ps.power = power
ps.m = 1
ps.df = self.ps.freq[1]-self.ps.freq[0]
ps.norm = "leahy"
lpost = PSDLogLikelihood(ps.freq, ps.power, model, m=1)
pe = PSDParEst(ps)
rng2 = np.random.RandomState(seed)
sim_data = pe._generate_data(lpost, [2.0], rng2)
assert np.allclose(ps.power, sim_data.power)
def test_generate_model_breaks_with_wrong_input(self):
pe = PSDParEst(self.ps)
with pytest.raises(AssertionError):
pe_model = pe._generate_model([1, 2, 3, 4], [1, 2, 3, 4])
def test_generate_model_breaks_for_wrong_number_of_parameters(self):
pe = PSDParEst(self.ps)
with pytest.raises(AssertionError):
pe_model = pe._generate_model(self.lpost, [1, 2, 3])
def test_pvalue_calculated_correctly(self):
a = [1, 1, 1, 2]
obs_val = 1.5
pe = PSDParEst(self.ps)
pval = pe._compute_pvalue(obs_val, a)
assert np.isclose(pval, 1./len(a))
def test_calibrate_lrt_fails_without_lpost_objects(self):
pe = PSDParEst(self.ps)
with pytest.raises(TypeError):
pval = pe.calibrate_lrt(self.lpost, [1, 2, 3, 4],
np.arange(10), np.arange(4))
def test_calibrate_lrt_fails_with_wrong_parameters(self):
pe = PSDParEst(self.ps)
with pytest.raises(ValueError):
pval = pe.calibrate_lrt(self.lpost, [1, 2, 3, 4],
self.lpost, [1, 2, 3])
def test_calibrate_lrt_works_as_expected(self):
m = 1
nfreq = 100
freq = np.linspace(1, 10, nfreq)
rng = np.random.RandomState(100)
noise = rng.exponential(size=nfreq)
model = models.Const1D()
model.amplitude = 2.0
p = model(freq)
power = noise * p
ps = Powerspectrum()
ps.freq = freq
ps.power = power
ps.m = m
ps.df = freq[1] - freq[0]
ps.norm = "leahy"
loglike = PSDLogLikelihood(ps.freq, ps.power, model, m=1)
s_all = np.atleast_2d(np.ones(10) * 2.0).T
model2 = models.PowerLaw1D() + models.Const1D()
model2.x_0_0.fixed = True
loglike2 = PSDLogLikelihood(ps.freq, ps.power, model2, 1)
pe = PSDParEst(ps)
pval = pe.calibrate_lrt(loglike, [2.0], loglike2,
[2.0, 1.0, 2.0], sample=s_all,
max_post=False, nsim=5,
seed=100)
assert pval > 0.001
@pytest.mark.skipif("not can_sample")
def test_calibrate_lrt_works_with_sampling(self):
m = 1
nfreq = 100
freq = np.linspace(1, 10, nfreq)
rng = np.random.RandomState(100)
noise = rng.exponential(size=nfreq)
model = models.Const1D()
model.amplitude = 2.0
p = model(freq)
power = noise * p
ps = Powerspectrum()
ps.freq = freq
ps.power = power
ps.m = m
ps.df = freq[1] - freq[0]
ps.norm = "leahy"
lpost = PSDPosterior(ps.freq, ps.power, model, m=1)
p_amplitude_1 = lambda amplitude: \
scipy.stats.norm(loc=2.0, scale=1.0).pdf(amplitude)
p_alpha_0 = lambda alpha: \
scipy.stats.uniform(0.0, 5.0).pdf(alpha)
p_amplitude_0 = lambda amplitude: \
scipy.stats.norm(loc=self.a2_mean, scale=self.a2_var).pdf(
amplitude)
priors = {"amplitude": p_amplitude_1}
priors2 = {"amplitude_1": p_amplitude_1,
"amplitude_0": p_amplitude_0,
"alpha_0": p_alpha_0}
lpost.logprior = set_logprior(lpost, priors)
model2 = models.PowerLaw1D() + models.Const1D()
model2.x_0_0.fixed = True
lpost2 = PSDPosterior(ps.freq, ps.power, model2, 1)
lpost2.logprior = set_logprior(lpost2, priors2)
pe = PSDParEst(ps)
with catch_warnings(RuntimeWarning):
pval = pe.calibrate_lrt(lpost, [2.0], lpost2,
[2.0, 1.0, 2.0], sample=None,
max_post=True, nsim=10, nwalkers=10,
burnin=10, niter=10,
seed=100)
assert pval > 0.001
def test_find_highest_outlier_works_as_expected(self):
mp_ind = 5
max_power = 1000.0
ps = Powerspectrum()
ps.freq = np.arange(10)
ps.power = np.ones_like(ps.freq)
ps.power[mp_ind] = max_power
ps.m = 1
ps.df = ps.freq[1]-ps.freq[0]
ps.norm = "leahy"
pe = PSDParEst(ps)
max_x, max_ind = pe._find_outlier(ps.freq, ps.power, max_power)
assert np.isclose(max_x, ps.freq[mp_ind])
assert max_ind == mp_ind
def test_compute_highest_outlier_works(self):
mp_ind = 5
max_power = 1000.0
ps = Powerspectrum()
ps.freq = np.arange(10)
ps.power = np.ones_like(ps.freq)
ps.power[mp_ind] = max_power
ps.m = 1
ps.df = ps.freq[1]-ps.freq[0]
ps.norm = "leahy"
model = models.Const1D()
p_amplitude = lambda amplitude: \
scipy.stats.norm(loc=1.0, scale=1.0).pdf(
amplitude)
priors = {"amplitude": p_amplitude}
lpost = PSDPosterior(ps.freq, ps.power, model, 1)
lpost.logprior = set_logprior(lpost, priors)
pe = PSDParEst(ps)
res = pe.fit(lpost, [1.0])
res.mfit = np.ones_like(ps.freq)
max_y, max_x, max_ind = pe._compute_highest_outlier(lpost, res)
assert np.isclose(max_y[0], 2*max_power)
assert np.isclose(max_x[0], ps.freq[mp_ind])
assert max_ind == mp_ind
def test_simulate_highest_outlier_works(self):
m = 1
nfreq = 100
seed = 100
freq = np.linspace(1, 10, nfreq)
rng = np.random.RandomState(seed)
noise = rng.exponential(size=nfreq)
model = models.Const1D()
model.amplitude = 2.0
p = model(freq)
power = noise * p
ps = Powerspectrum()
ps.freq = freq
ps.power = power
ps.m = m
ps.df = freq[1] - freq[0]
ps.norm = "leahy"
nsim = 5
loglike = PSDLogLikelihood(ps.freq, ps.power, model, m=1)
s_all = np.atleast_2d(np.ones(nsim) * 2.0).T
pe = PSDParEst(ps)
maxpow_sim = pe.simulate_highest_outlier(s_all, loglike, [2.0],
max_post=False, seed=seed)
assert maxpow_sim.shape[0] == nsim
assert np.all(maxpow_sim > 9.00) and np.all(maxpow_sim < 31.0)
def test_calibrate_highest_outlier_works(self):
m = 1
nfreq = 100
seed = 100
freq = np.linspace(1, 10, nfreq)
rng = np.random.RandomState(seed)
noise = rng.exponential(size=nfreq)
model = models.Const1D()
model.amplitude = 2.0
p = model(freq)
power = noise * p
ps = Powerspectrum()
ps.freq = freq
ps.power = power
ps.m = m
ps.df = freq[1] - freq[0]
ps.norm = | |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import *
import hashlib
from edb import errors
from edb.common import struct
from edb.edgeql import ast as qlast
from . import delta as sd
from . import inheriting
from . import objects as so
from . import schema as s_schema
from . import name as sn
from . import utils
ReferencedT = TypeVar('ReferencedT', bound='ReferencedObject')
ReferencedInheritingObjectT = TypeVar('ReferencedInheritingObjectT',
bound='ReferencedInheritingObject')
class ReferencedObject(so.DerivableObject):
#: True if the object has an explicit definition and is not
#: purely inherited.
is_local = so.SchemaField(
bool,
default=False,
inheritable=False,
compcoef=0.909,
reflection_method=so.ReflectionMethod.AS_LINK,
)
def get_subject(self, schema: s_schema.Schema) -> Optional[so.Object]:
# NB: classes that inherit ReferencedObject define a `get_subject`
# method dynamically, with `subject = SchemaField`
raise NotImplementedError
def get_referrer(self, schema: s_schema.Schema) -> Optional[so.Object]:
return self.get_subject(schema)
def delete(self, schema: s_schema.Schema) -> s_schema.Schema:
cmdcls = sd.ObjectCommandMeta.get_command_class_or_die(
sd.DeleteObject, type(self))
cmd = cmdcls(classname=self.get_name(schema))
context = sd.CommandContext(
modaliases={},
schema=schema,
disable_dep_verification=True,
)
delta, parent_cmd = cmd._build_alter_cmd_stack(
schema, context, self)
parent_cmd.add(cmd)
with context(sd.DeltaRootContext(schema=schema, op=delta)):
schema = delta.apply(schema, context)
return schema
def derive_ref(
self: ReferencedT,
schema: s_schema.Schema,
referrer: so.QualifiedObject,
*qualifiers: str,
mark_derived: bool = False,
attrs: Optional[Dict[str, Any]] = None,
dctx: Optional[sd.CommandContext] = None,
derived_name_base: Optional[str] = None,
inheritance_merge: bool = True,
preserve_path_id: Optional[bool] = None,
refdict_whitelist: Optional[AbstractSet[str]] = None,
transient: bool = False,
name: Optional[str] = None,
**kwargs: Any,
) -> Tuple[s_schema.Schema, ReferencedT]:
if name is None:
derived_name: str = self.get_derived_name(
schema, referrer, *qualifiers,
mark_derived=mark_derived,
derived_name_base=derived_name_base)
else:
derived_name = name
if self.get_name(schema) == derived_name:
raise errors.SchemaError(
f'cannot derive {self!r}({derived_name}) from itself')
derived_attrs: Dict[str, object] = {}
if attrs is not None:
derived_attrs.update(attrs)
derived_attrs['name'] = derived_name
derived_attrs['bases'] = so.ObjectList.create(
schema, [self])
mcls = type(self)
referrer_class = type(referrer)
refdict = referrer_class.get_refdict_for_class(mcls)
reftype = referrer_class.get_field(refdict.attr).type
refname = reftype.get_key_for_name(schema, derived_name)
refcoll = referrer.get_field_value(schema, refdict.attr)
existing = refcoll.get(schema, refname, default=None)
if existing is not None:
cmdcls: Type[sd.Command] = \
sd.ObjectCommandMeta.get_command_class_or_die(sd.AlterObject,
type(self))
else:
cmdcls = sd.ObjectCommandMeta.get_command_class_or_die(
sd.CreateObject, type(self))
cmd = cmdcls(classname=derived_name)
for k, v in derived_attrs.items():
cmd.set_attribute_value(k, v)
if existing is not None:
new_bases = derived_attrs['bases']
old_bases = existing.get_bases(schema)
if new_bases != old_bases:
assert isinstance(new_bases, so.ObjectList)
removed_bases, added_bases = inheriting.delta_bases(
[b.get_name(schema) for b in old_bases.objects(schema)],
[b.get_name(schema) for b in new_bases.objects(schema)],
)
rebase_cmdcls = sd.ObjectCommandMeta.get_command_class_or_die(
inheriting.RebaseInheritingObject, type(self))
rebase_cmd = rebase_cmdcls(
classname=derived_name,
added_bases=added_bases,
removed_bases=removed_bases,
)
cmd.add(rebase_cmd)
context = sd.CommandContext(
modaliases={},
schema=schema,
)
assert isinstance(cmd, sd.ObjectCommand)
delta, parent_cmd = cmd._build_alter_cmd_stack(
schema, context, self, referrer=referrer)
with context(sd.DeltaRootContext(schema=schema, op=delta)):
if not inheritance_merge:
context.current().inheritance_merge = False
if refdict_whitelist is not None:
context.current().inheritance_refdicts = refdict_whitelist
if mark_derived:
context.current().mark_derived = True
if transient:
context.current().transient_derivation = True
if preserve_path_id:
context.current().preserve_path_id = True
parent_cmd.add(cmd)
schema = delta.apply(schema, context)
derived: ReferencedT = schema.get(derived_name)
return schema, derived
def get_verbosename(
self,
schema: s_schema.Schema,
*,
with_parent: bool = False,
) -> str:
vn = super().get_verbosename(schema)
if with_parent:
subject = self.get_subject(schema)
if subject is not None:
pn = subject.get_verbosename(schema, with_parent=True)
return f'{vn} of {pn}'
return vn
class ReferencedInheritingObject(
so.DerivableInheritingObject,
ReferencedObject,
):
# Indicates that the object has been declared as
# explicitly inherited.
declared_overloaded = so.SchemaField(
bool,
default=False,
compcoef=None,
introspectable=False,
inheritable=False,
ephemeral=True,
)
def get_implicit_bases(
self: ReferencedInheritingObjectT,
schema: s_schema.Schema,
) -> List[ReferencedInheritingObjectT]:
return [
b for b in self.get_bases(schema).objects(schema)
if not b.generic(schema)
]
class ReferencedObjectCommandMeta(sd.ObjectCommandMeta):
_transparent_adapter_subclass: ClassVar[bool] = True
_referrer_context_class: Optional[
Type[sd.ObjectCommandContext[so.Object]]
] = None
def __new__(mcls,
name: str,
bases: Tuple[type, ...],
clsdct: Dict[str, Any],
*,
referrer_context_class: Optional[
Type[sd.ObjectCommandContext[so.Object]]
] = None,
**kwargs: Any
) -> ReferencedObjectCommandMeta:
cls = super().__new__(mcls, name, bases, clsdct, **kwargs)
assert isinstance(cls, ReferencedObjectCommandMeta)
if referrer_context_class is not None:
cls._referrer_context_class = referrer_context_class
return cls
class ReferencedObjectCommandBase(
sd.QualifiedObjectCommand[ReferencedT],
metaclass=ReferencedObjectCommandMeta,
):
@classmethod
def get_referrer_context_class(
cls,
) -> Type[sd.ObjectCommandContext[so.Object]]:
if cls._referrer_context_class is None:
raise TypeError(
f'referrer_context_class is not defined for {cls}')
return cls._referrer_context_class
@classmethod
def get_referrer_context(
cls,
context: sd.CommandContext,
) -> Optional[sd.ObjectCommandContext[so.Object]]:
"""Get the context of the command for the referring object, if any.
E.g. for a `create/alter/etc concrete link` command this would
be the context of the `create/alter/etc type` command.
"""
ctxcls = cls.get_referrer_context_class()
ctx = context.get(ctxcls) # type: ignore
return cast(Optional[sd.ObjectCommandContext[so.Object]], ctx)
@classmethod
def get_referrer_context_or_die(
cls,
context: sd.CommandContext,
) -> sd.ObjectCommandContext[so.Object]:
ctx = cls.get_referrer_context(context)
if ctx is None:
raise RuntimeError(f'no referrer context for {cls}')
return ctx
class StronglyReferencedObjectCommand(
ReferencedObjectCommandBase[ReferencedT]
):
pass
class ReferencedObjectCommand(ReferencedObjectCommandBase[ReferencedT]):
@classmethod
def _classname_from_ast(cls,
schema: s_schema.Schema,
astnode: qlast.NamedDDL,
context: sd.CommandContext
) -> sn.Name:
name = super()._classname_from_ast(schema, astnode, context)
parent_ctx = cls.get_referrer_context(context)
if parent_ctx is not None:
assert isinstance(parent_ctx.op, sd.QualifiedObjectCommand)
referrer_name = parent_ctx.op.classname
base_name: str
try:
base_ref = utils.ast_to_object(
astnode.name,
modaliases=context.modaliases,
schema=schema,
)
except errors.InvalidReferenceError:
base_name = sn.Name(name)
else:
base_name = base_ref.get_name(schema)
quals = cls._classname_quals_from_ast(
schema, astnode, base_name, referrer_name, context)
pnn = sn.get_specialized_name(base_name, referrer_name, *quals)
name = sn.Name(name=pnn, module=referrer_name.module)
assert isinstance(name, sn.Name)
return name
@classmethod
def _classname_from_name(
cls,
name: sn.SchemaName,
referrer_name: sn.SchemaName,
) -> sn.Name:
base_name = sn.shortname_from_fullname(name)
quals = cls._classname_quals_from_name(name)
pnn = sn.get_specialized_name(base_name, referrer_name, *quals)
return sn.Name(name=pnn, module=referrer_name.module)
@classmethod
def _classname_quals_from_ast(
cls,
schema: s_schema.Schema,
astnode: qlast.NamedDDL,
base_name: str,
referrer_name: str,
context: sd.CommandContext,
) -> Tuple[str, ...]:
return ()
@classmethod
def _classname_quals_from_name(
cls,
name: sn.SchemaName,
) -> Tuple[str, ...]:
return ()
@classmethod
def _name_qual_from_exprs(cls,
schema: s_schema.Schema,
exprs: Iterable[str]) -> str:
m = hashlib.sha1()
for expr in exprs:
m.update(expr.encode())
return m.hexdigest()
def _get_ast_node(self,
schema: s_schema.Schema,
context: sd.CommandContext
) -> Type[qlast.DDLOperation]:
subject_ctx = self.get_referrer_context(context)
ref_astnode: Type[qlast.DDLOperation] = getattr(self,
'referenced_astnode',
None)
if subject_ctx is not None and ref_astnode is not None:
return ref_astnode
else:
if isinstance(self.astnode, (list, tuple)):
return self.astnode[1]
else:
return self.astnode
def _build_alter_cmd_stack(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
scls: so.Object,
*,
referrer: Optional[so.Object] = None
) -> Tuple[sd.DeltaRoot, sd.Command]:
delta = sd.DeltaRoot()
if referrer is None:
assert isinstance(scls, ReferencedObject)
referrer = scls.get_referrer(schema)
obj = referrer
object_stack = []
if type(self) != type(referrer):
object_stack.append(referrer)
while obj is not None:
if isinstance(obj, ReferencedObject):
obj = obj.get_referrer(schema)
object_stack.append(obj)
else:
obj = None
cmd: sd.Command = delta
for obj in reversed(object_stack):
assert obj is not None
alter_cmd_cls = sd.ObjectCommandMeta.get_command_class_or_die(
sd.AlterObject, type(obj))
alter_cmd = alter_cmd_cls(classname=obj.get_name(schema))
cmd.add(alter_cmd)
cmd = alter_cmd
return delta, cmd
class CreateReferencedObject(
ReferencedObjectCommand[ReferencedT],
sd.CreateObject[ReferencedT],
):
referenced_astnode: ClassVar[Type[qlast.ObjectDDL]]
@classmethod
def _cmd_tree_from_ast(
cls,
schema: s_schema.Schema,
astnode: qlast.DDLOperation,
context: sd.CommandContext,
) -> sd.Command:
cmd = super()._cmd_tree_from_ast(schema, astnode, context)
if isinstance(astnode, cls.referenced_astnode):
objcls = cls.get_schema_metaclass()
referrer_ctx = cls.get_referrer_context_or_die(context)
referrer_class = referrer_ctx.op.get_schema_metaclass()
referrer_name = referrer_ctx.op.classname
refdict = referrer_class.get_refdict_for_class(objcls)
cmd.set_attribute_value(
refdict.backref_attr,
so.ObjectShell(
name=referrer_name,
schemaclass=referrer_class,
),
)
cmd.set_attribute_value('is_local', True)
if getattr(astnode, 'is_abstract', None):
cmd.set_attribute_value('is_abstract', True)
return cmd
def _get_ast_node(self,
schema: s_schema.Schema,
context: sd.CommandContext
) -> Type[qlast.DDLOperation]:
scls = self.get_object(schema, context)
assert isinstance(scls, ReferencedInheritingObject)
implicit_bases = scls.get_implicit_bases(schema)
if implicit_bases and not context.declarative:
mcls = self.get_schema_metaclass()
Alter = sd.ObjectCommandMeta.get_command_class_or_die(
sd.AlterObject, mcls)
alter = Alter(classname=self.classname)
return alter._get_ast_node(schema, context)
else:
return super()._get_ast_node(schema, context)
@classmethod
def as_inherited_ref_cmd(cls,
schema: s_schema.Schema,
context: sd.CommandContext,
astnode: qlast.ObjectDDL,
parents: Any) -> sd.Command:
cmd = cls(classname=cls._classname_from_ast(schema, astnode, context))
cmd.set_attribute_value('name', cmd.classname)
return cmd
@classmethod
def as_inherited_ref_ast(cls,
schema: s_schema.Schema,
context: sd.CommandContext,
name: str,
parent: ReferencedObject) -> qlast.ObjectDDL:
nref = cls.get_inherited_ref_name(schema, context, parent, name)
astnode_cls = cls.referenced_astnode
astnode = astnode_cls(name=nref)
assert isinstance(astnode, qlast.ObjectDDL)
return astnode
@classmethod
def get_inherited_ref_name(cls,
schema: s_schema.Schema,
context: sd.CommandContext,
parent: ReferencedObject,
name: str
) -> qlast.ObjectRef:
# reduce name to shortname
if sn.Name.is_qualified(name):
shortname: str = sn.shortname_from_fullname(sn.Name(name))
else:
shortname = name
nref = qlast.ObjectRef(
name=shortname,
module=parent.get_shortname(schema).module,
)
return nref
def _create_innards(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
) -> s_schema.Schema:
referrer_ctx = self.get_referrer_context(context)
if referrer_ctx is None:
return super()._create_innards(schema, context)
else:
referrer = referrer_ctx.scls
schema = self._create_ref(schema, context, referrer)
return super()._create_innards(schema, context)
def _create_ref(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
referrer: so.Object,
) -> s_schema.Schema:
referrer_cls = type(referrer)
mcls = type(self.scls)
refdict = referrer_cls.get_refdict_for_class(mcls)
schema = referrer.add_classref(schema, refdict.attr, self.scls)
return schema
class DeleteReferencedObjectCommand(
ReferencedObjectCommand[ReferencedT],
sd.DeleteObject[ReferencedT],
):
def _delete_innards(
self,
schema: s_schema.Schema,
context: sd.CommandContext,
) -> s_schema.Schema:
schema = super()._delete_innards(schema, context)
referrer_ctx | |
# Databricks notebook source
slides_html="""
<iframe src="https://docs.google.com/presentation/d/1yR3oBKg8vvwKjvj4WWezf5ygJweo8rWuklD7IF4uVX0/embed?start=true&loop=true&delayms=4000" frameborder="0" width="900" height="560" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
"""
displayHTML(slides_html)
# COMMAND ----------
# MAGIC %md
# MAGIC # Spark OCR in Healthcare
# MAGIC
# MAGIC Spark OCR is a commercial extension of Spark NLP for optical character recognition from images, scanned PDF documents, Microsoft DOCX and DICOM files.
# MAGIC
# MAGIC In this notebook we will:
# MAGIC - Parsing the Files through OCR.
# MAGIC - Extract PHI entites from extracted texts.
# MAGIC - Hide PHI entites and get an obfucated versions of pdf files.
# MAGIC - Hide PHI entities on original image.
# MAGIC - Extract text from some Dicom images.
# MAGIC - Hide PHI entities on Dicom images.
# COMMAND ----------
import os
import json
import string
#import sys
#import base64
import numpy as np
import pandas as pd
import sparknlp
import sparknlp_jsl
from sparknlp.base import *
from sparknlp.util import *
from sparknlp.annotator import *
from sparknlp_jsl.base import *
from sparknlp_jsl.annotator import *
from sparknlp.pretrained import ResourceDownloader
import sparkocr
from sparkocr.transformers import *
from sparkocr.utils import *
from sparkocr.enums import *
from pyspark.sql import functions as F
from pyspark.ml import Pipeline, PipelineModel
from sparknlp.training import CoNLL
import matplotlib.pyplot as plt
pd.set_option('max_colwidth', 100)
pd.set_option('display.max_columns', 100)
pd.set_option('display.expand_frame_repr', False)
spark.sql("set spark.sql.legacy.allowUntypedScalaUDF=true")
print('sparknlp.version : ',sparknlp.version())
print('sparknlp_jsl.version : ',sparknlp_jsl.version())
print('sparkocr : ',sparkocr.version())
spark
# COMMAND ----------
# MAGIC %md
# MAGIC **Reading PDF files **
# MAGIC
# MAGIC If you have large datasets, you can take your data into delta table and read from there to create a dataframe by using this script:
# MAGIC
# MAGIC ```
# MAGIC pdfs = spark.read.format("delta").load("/mnt/delta/ocr_samples")
# MAGIC
# MAGIC print("Number of files in the folder : ", pdfs.count())
# MAGIC
# MAGIC ```
# COMMAND ----------
# MAGIC %sh
# MAGIC for i in {0..3}
# MAGIC do
# MAGIC wget -q https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/data/ocr/MT_OCR_0$i.pdf -P /dbfs/FileStore/HLS/nlp/
# MAGIC done
# COMMAND ----------
file_path='dbfs:/FileStore/HLS/nlp/'
pdfs = spark.read.format("binaryFile").load(f'{file_path}MT_OCR*.pdf').sort('path')
print("Number of files in the folder : ", pdfs.count())
# COMMAND ----------
display(pdfs)
# COMMAND ----------
# MAGIC %md
# MAGIC ## 1. Parsing the Files through OCR
# COMMAND ----------
# MAGIC %md
# MAGIC - The pdf files can have more than one page. We will transform the document in to images per page. Than we can run OCR to get text.
# MAGIC - We are using `PdfToImage()` to render PDF to images and `ImageToText()` to runs OCR for each images.
# COMMAND ----------
# Transform PDF document to images per page
pdf_to_image = PdfToImage()\
.setInputCol("content")\
.setOutputCol("image")
# Run OCR
ocr = ImageToText()\
.setInputCol("image")\
.setOutputCol("text")\
.setConfidenceThreshold(65)\
.setIgnoreResolution(False)
ocr_pipeline = PipelineModel(stages=[
pdf_to_image,
ocr
])
# COMMAND ----------
# MAGIC %md
# MAGIC - Now, we can transform the `pdfs` with our pipeline.
# COMMAND ----------
ocr_result = ocr_pipeline.transform(pdfs)
# COMMAND ----------
# MAGIC %md
# MAGIC - After transforming we get following columns :
# MAGIC
# MAGIC - path
# MAGIC - modificationTime
# MAGIC - length
# MAGIC - image
# MAGIC - total_pages
# MAGIC - pagenum
# MAGIC - documentnum
# MAGIC - confidence
# MAGIC - exception
# MAGIC - text
# MAGIC - positions
# COMMAND ----------
display(
ocr_result.select('modificationTime', 'length', 'total_pages', 'pagenum', 'documentnum', 'confidence', 'exception')
)
# COMMAND ----------
display(ocr_result.select('path', 'image', 'text', 'positions'))
# COMMAND ----------
# MAGIC %md
# MAGIC - Now, we have our pdf files in text format and as image.
# MAGIC
# MAGIC - Let's see the images and the text.
# COMMAND ----------
import matplotlib.pyplot as plt
img = ocr_result.collect()[0].image
img_pil = to_pil_image(img, img.mode)
plt.figure(figsize=(24,16))
plt.imshow(img_pil, cmap='gray')
plt.show()
# COMMAND ----------
# MAGIC %md
# MAGIC - Let's see extracted text which is stored in `'text'` column as a list. Each line is is an item in this list, so we can join them and see the whole page.
# COMMAND ----------
print("\n".join([row.text for row in ocr_result.select("text").collect()[0:1]]))
# COMMAND ----------
# MAGIC %md
# MAGIC ### 1.1. Skew Correction
# MAGIC
# MAGIC In some images, there may be some skewness and this reduces acuracy of the extracted text. Spark OCR has `ImageSkewCorrector` which detects skew of the image and rotates it.
# COMMAND ----------
# Image skew corrector
pdf_to_image = PdfToImage()\
.setInputCol("content")\
.setOutputCol("image")
skew_corrector = ImageSkewCorrector()\
.setInputCol("image")\
.setOutputCol("corrected_image")\
.setAutomaticSkewCorrection(True)
ocr = ImageToText()\
.setInputCol("corrected_image")\
.setOutputCol("text")\
.setConfidenceThreshold(65)\
.setIgnoreResolution(False)
ocr_skew_corrected = PipelineModel(stages=[
pdf_to_image,
skew_corrector,
ocr
])
# COMMAND ----------
ocr_skew_corrected_result = ocr_skew_corrected.transform(pdfs).cache()
# COMMAND ----------
# MAGIC %md
# MAGIC Let's see the results after the skew correction.
# COMMAND ----------
# DBTITLE 1,Original Images
display(ocr_result.filter(ocr_result.path==f"{file_path}MT_OCR_01.pdf").select('path', 'confidence'))
# COMMAND ----------
# DBTITLE 1,Skew Corrected Images
display(ocr_skew_corrected_result.filter(ocr_skew_corrected_result.path==f"{file_path}MT_OCR_01.pdf").select('path', 'confidence'))
# COMMAND ----------
# MAGIC %md
# MAGIC After skew correction, confidence is increased from %48.3 to % %66.5. Let's display the corrected image and the original image side by side.
# COMMAND ----------
img_orig = ocr_skew_corrected_result.select("image").collect()[1].image
img_corrected = ocr_skew_corrected_result.select("corrected_image").collect()[1].corrected_image
img_pil_orig = to_pil_image(img_orig, img_orig.mode)
img_pil_corrected = to_pil_image(img_corrected, img_corrected.mode)
plt.figure(figsize=(24,16))
plt.subplot(1, 2, 1)
plt.imshow(img_pil_orig, cmap='gray')
plt.title('Original')
plt.subplot(1, 2, 2)
plt.imshow(img_pil_corrected, cmap='gray')
plt.title("Skew Corrected")
plt.show()
# COMMAND ----------
# MAGIC %md
# MAGIC ### 1.2. Image Processing
# MAGIC
# MAGIC * After reading pdf files, we can process on images to increase the confidency.
# MAGIC
# MAGIC * By **`ImageAdaptiveThresholding`**, we can compute a threshold mask image based on local pixel neighborhood and apply it to image.
# MAGIC
# MAGIC * Another method which we can add to pipeline is applying morphological operations. We can use **`ImageMorphologyOperation`** which support:
# MAGIC - Erosion
# MAGIC - Dilation
# MAGIC - Opening
# MAGIC - Closing
# MAGIC
# MAGIC * To remove remove background objects **`ImageRemoveObjects`** can be used.
# MAGIC
# MAGIC * We will add **`ImageLayoutAnalyzer`** to pipeline, to analyze the image and determine the regions of text.
# COMMAND ----------
from sparkocr.enums import *
# Read binary as image
pdf_to_image = PdfToImage()\
.setInputCol("content")\
.setOutputCol("image")\
.setResolution(400)
# Correcting the skewness
skew_corrector = ImageSkewCorrector()\
.setInputCol("image")\
.setOutputCol("skew_corrected_image")\
.setAutomaticSkewCorrection(True)
# Binarize using adaptive tresholding
binarizer = ImageAdaptiveThresholding()\
.setInputCol("skew_corrected_image")\
.setOutputCol("binarized_image")\
.setBlockSize(91)\
.setOffset(50)
# Apply morphology opening
opening = ImageMorphologyOperation()\
.setKernelShape(KernelShape.SQUARE)\
.setOperation(MorphologyOperationType.OPENING)\
.setKernelSize(3)\
.setInputCol("binarized_image")\
.setOutputCol("opening_image")
# Remove small objects
remove_objects = ImageRemoveObjects()\
.setInputCol("opening_image")\
.setOutputCol("corrected_image")\
.setMinSizeObject(130)
ocr_corrected = ImageToText()\
.setInputCol("corrected_image")\
.setOutputCol("corrected_text")\
.setPageIteratorLevel(PageIteratorLevel.SYMBOL) \
.setPageSegMode(PageSegmentationMode.SPARSE_TEXT) \
.setConfidenceThreshold(65)
# OCR pipeline
image_pipeline = PipelineModel(stages=[
pdf_to_image,
skew_corrector,
binarizer,
opening,
remove_objects,
ocr_corrected
])
# COMMAND ----------
result_processed = image_pipeline.transform(pdfs).cache()
# COMMAND ----------
# MAGIC %md
# MAGIC Let's see the original image and corrected image.
# COMMAND ----------
img_orig = result_processed.select("image").collect()[1].image
img_corrected = result_processed.select("corrected_image").collect()[1].corrected_image
img_pil_orig = to_pil_image(img_orig, img_orig.mode)
img_pil_corrected = to_pil_image(img_corrected, img_corrected.mode)
plt.figure(figsize=(24,16))
plt.subplot(1, 2, 1)
plt.imshow(img_pil_orig, cmap='gray')
plt.title('Original')
plt.subplot(1, 2, 2)
plt.imshow(img_pil_corrected, cmap='gray')
plt.title("Skew Corrected")
plt.show()
# COMMAND ----------
# MAGIC %md
# MAGIC After processing, we have cleaner image. And confidence is increased to %97
# COMMAND ----------
print("Original Images")
display(ocr_result.filter(ocr_result.path==f"{file_path}MT_OCR_01.pdf").select('confidence'))
print("Skew Corrected Images")
display(ocr_skew_corrected_result.filter(ocr_skew_corrected_result.path==f"{file_path}MT_OCR_01.pdf").select('confidence'))
print("Corrected Images")
display(result_processed.filter(result_processed.path==f"{file_path}MT_OCR_01.pdf").select('confidence'))
# COMMAND ----------
# MAGIC %md
# MAGIC ## 2. Extracting the Clinical Entites
# MAGIC
# MAGIC Now Let's create a clinical NER pipeline and see which entities we have. We will use `sentence_detector_dl_healthcare` to detect sentences and get entities by using [`ner_jsl`](https://nlp.johnsnowlabs.com/2021/06/24/ner_jsl_en.html) in `MedicalNerModel`.
# COMMAND ----------
documentAssembler = DocumentAssembler()\
.setInputCol("text")\
.setOutputCol("document")
sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl_healthcare","en","clinical/models")\
.setInputCols(["document"]) \
.setOutputCol("sentence")
tokenizer = Tokenizer()\
.setInputCols(["sentence"])\
.setOutputCol("token")\
word_embeddings = WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models")\
.setInputCols(["sentence", "token"])\
.setOutputCol("embeddings")
clinical_ner = MedicalNerModel.pretrained("ner_jsl", "en", "clinical/models") \
.setInputCols(["sentence", "token", "embeddings"]) \
.setOutputCol("ner")
ner_converter = NerConverter() \
.setInputCols(["sentence", "token", "ner"]) \
.setOutputCol("ner_chunk")
# COMMAND ----------
ner_pipeline = Pipeline(
stages = [
documentAssembler,
sentenceDetector,
tokenizer,
word_embeddings,
clinical_ner,
ner_converter])
empty_data = spark.createDataFrame([['']]).toDF("text")
ner_model = ner_pipeline.fit(empty_data)
# COMMAND ----------
ner_results = ner_model.transform(ocr_result)
# COMMAND ----------
# MAGIC %md
# MAGIC Now we will visualize a sample text with `NerVisualizer`.
# MAGIC
# MAGIC `NerVisualizer` woks with Lightpipeline, so we will create a `light_model` with our ner_model.
# COMMAND ----------
sample_text = ocr_result.limit(2).select("text").collect()[0].text
# COMMAND ----------
print(sample_text)
# COMMAND ----------
light_model = LightPipeline(ner_model)
ann_text = light_model.fullAnnotate(sample_text)[0]
# COMMAND ----------
# MAGIC %md
# MAGIC `fullAnnotate` method returns the results as a dictionary. But the dictionary stored in a list. So we can reach to the dict by adding `[0]` to the end of the annotated text.
# MAGIC
# MAGIC We can get some columns and transform them to a Pandas dataframe.
# COMMAND ----------
chunks = []
entities = []
sentence= []
begin = []
end = []
for n in ann_text['ner_chunk']:
begin.append(n.begin)
end.append(n.end)
chunks.append(n.result)
entities.append(n.metadata['entity'])
sentence.append(n.metadata['sentence'])
import pandas as pd
df = pd.DataFrame({'chunks':chunks, 'begin': begin, 'end':end,
'sentence_id':sentence, 'entities':entities})
df.head(20)
# COMMAND ----------
# MAGIC %md
# MAGIC We can visualise the annotated text by `display` method of `NerVisualizer()`
# COMMAND ----------
from sparknlp_display import NerVisualizer
visualiser = NerVisualizer()
ner_vis = visualiser.display(ann_text, label_col='ner_chunk',return_html=True)
displayHTML(ner_vis)
# COMMAND ----------
# MAGIC %md
# MAGIC ## 3. Extracting and Hiding the PHI Entities
# MAGIC
# MAGIC In our documents we have some fields which we want to hide. To do it, we will use deidentification model. It identifies instances of protected health information in text documents, and it can either obfuscate them (e.g., replacing names with different, fake names) or mask them.
# COMMAND ----------
documentAssembler = DocumentAssembler()\
.setInputCol("corrected_text")\
.setOutputCol("document")
sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl_healthcare","en","clinical/models")\
.setInputCols(["document"]) \
.setOutputCol("sentence")
tokenizer = Tokenizer()\
.setInputCols(["sentence"])\
.setOutputCol("token")\
word_embeddings = WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models")\
.setInputCols(["sentence", "token"])\
.setOutputCol("embeddings")
deid_ner = MedicalNerModel.pretrained("ner_deid_generic_augmented", "en", "clinical/models") \
.setInputCols(["sentence", "token", "embeddings"]) \
.setOutputCol("ner")
deid_ner_converter = NerConverter() \
| |
"""This module contains the classes used for constructing and conducting an Experiment (most notably,
:class:`CrossValidationExperiment`). Any class contained herein whose name starts with 'Base' should not be used directly.
:class:`CrossValidationExperiment` is the preferred means of conducting one-off experimentation
Related
-------
:mod:`hyperparameter_hunter.experiment_core`
Defines :class:`ExperimentMeta`, an understanding of which is critical to being able to understand :mod:`experiments`
:mod:`hyperparameter_hunter.metrics`
Defines :class:`ScoringMixIn`, a parent of :class:`experiments.BaseExperiment` that enables scoring and evaluating models
:mod:`hyperparameter_hunter.models`
Used to instantiate the actual learning models, which are a single part of the entire experimentation workflow, albeit the
most significant part
Notes
-----
As mentioned above, the inner workings of :mod:`experiments` will be very confusing without a grasp on whats going on in
:mod:`experiment_core`, and its related modules"""
##################################################
# Import Own Assets
##################################################
from hyperparameter_hunter.algorithm_handlers import identify_algorithm, identify_algorithm_hyperparameters
from hyperparameter_hunter.exception_handler import EnvironmentInactiveError, EnvironmentInvalidError, RepeatedExperimentError
from hyperparameter_hunter.experiment_core import ExperimentMeta
from hyperparameter_hunter.key_handler import HyperparameterKeyMaker
from hyperparameter_hunter.metrics import ScoringMixIn, get_formatted_target_metric
from hyperparameter_hunter.models import model_selector
from hyperparameter_hunter.recorders import RecorderList
from hyperparameter_hunter.settings import G
##################################################
# Import Miscellaneous Assets
##################################################
from abc import abstractmethod
from copy import copy, deepcopy
from inspect import isclass, signature
import numpy as np
import os
import pandas as pd
import random
import shutil
from sys import exc_info
from uuid import uuid4 as uuid
import warnings
##################################################
# Import Learning Assets
##################################################
from sklearn.model_selection import KFold, StratifiedKFold, RepeatedKFold, RepeatedStratifiedKFold
import sklearn.utils as sklearn_utils
pd.set_option('display.expand_frame_repr', False)
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=DeprecationWarning)
warnings.simplefilter(action='ignore', category=sklearn_utils.DataConversionWarning)
np.random.seed(32)
class BaseExperiment(ScoringMixIn):
def __init__(
# TODO: Make `model_init_params` an optional kwarg - If not given, algorithm defaults used
self, model_initializer, model_init_params, model_extra_params=None, feature_selector=None,
preprocessing_pipeline=None, preprocessing_params=None, notes=None, do_raise_repeated=False, auto_start=True,
target_metric=None,
):
"""Base class for :class:`BaseCVExperiment`
Parameters
----------
model_initializer: Class, or functools.partial, or class instance
The algorithm class being used to initialize a model
model_init_params: Dict, or object
The dictionary of arguments given when creating a model instance with `model_initializer` via the `__init__` method
of :class:`models.Model`. Any kwargs that are considered valid by the `__init__` method of `model_initializer` are
valid in `model_init_params`
model_extra_params: Dict, or None, default=None
A dictionary of extra parameters passed to :class:`models.Model`. This is used to provide parameters to models'
non-initialization methods (like `fit`, `predict`, `predict_proba`, etc.), and for neural networks
feature_selector: List of str, callable, list of booleans, default=None
The value provided when splitting apart the input data for all provided DataFrames. `feature_selector` is provided as
the second argument for calls to `pandas.DataFrame.loc` in :meth:`BaseExperiment._initial_preprocessing`. If None,
`feature_selector` is set to all columns in :attr:`train_dataset`, less :attr:`target_column`, and :attr:`id_column`
preprocessing_pipeline: ...
... Experimental...
preprocessing_params: ...
... Experimental...
notes: String, or None, default=None
Additional information about the Experiment that will be saved with the Experiment's description result file. This
serves no purpose other than to facilitate saving Experiment details in a more readable format
do_raise_repeated: Boolean, default=False
If True and this Experiment locates a previous Experiment's results with matching Environment and Hyperparameter Keys,
a RepeatedExperimentError will be raised. Else, a warning will be logged
auto_start: Boolean, default=True
If True, after the Experiment is initialized, it will automatically call :meth:`BaseExperiment.preparation_workflow`,
followed by :meth:`BaseExperiment.experiment_workflow`, effectively completing all essential tasks without requiring
additional method calls
target_metric: Tuple, or str, default=('oof', <first key in :attr:`environment.Environment.metrics_map`>)
A path denoting the metric to be used to compare completed Experiments or to use for certain early stopping
procedures in some model classes. The first value should be one of ['oof', 'holdout', 'in_fold']. The second value
should be the name of a metric being recorded according to the values supplied in
:attr:`environment.Environment.metrics_params`. See the documentation for :func:`metrics.get_formatted_target_metric`
for more info. Any values returned by, or used as the `target_metric` input to this function are acceptable values
for :attr:`BaseExperiment.target_metric`"""
self.model_initializer = model_initializer
self.model_init_params = identify_algorithm_hyperparameters(self.model_initializer) # FLAG: Play nice with Keras
try:
self.model_init_params.update(model_init_params)
except TypeError:
self.model_init_params.update(dict(build_fn=model_init_params))
self.model_extra_params = model_extra_params
self.feature_selector = feature_selector
self.preprocessing_pipeline = preprocessing_pipeline
self.preprocessing_params = preprocessing_params
self.notes = notes
self.do_raise_repeated = do_raise_repeated
self.auto_start = auto_start
self.target_metric = target_metric
#################### Attributes From Active Environment ####################
G.Env.initialize_reporting()
self._validate_environment()
self.train_dataset = G.Env.train_dataset.copy()
try:
self.holdout_dataset = G.Env.holdout_dataset.copy()
except AttributeError:
self.holdout_dataset = G.Env.holdout_dataset
try:
self.test_dataset = G.Env.test_dataset.copy()
except AttributeError:
self.test_dataset = G.Env.test_dataset
self.target_column = G.Env.target_column
self.id_column = G.Env.id_column
self.do_predict_proba = G.Env.do_predict_proba
self.prediction_formatter = G.Env.prediction_formatter
self.metrics_params = G.Env.metrics_params
self.experiment_params = G.Env.cross_experiment_params
self.cross_validation_params = G.Env.cross_validation_params
self.result_paths = G.Env.result_paths
self.cross_experiment_key = G.Env.cross_experiment_key
#################### Instantiate Other Attributes ####################
self.train_input_data = None
self.train_target_data = None
self.holdout_input_data = None
self.holdout_target_data = None
self.test_input_data = None
self.model = None
self.metrics_map = None # Set by :class:`metrics.ScoringMixIn`
self.stat_aggregates = dict()
self.result_description = None
#################### Experiment Identification Attributes ####################
self.experiment_id = None
self.hyperparameter_key = None
self.algorithm_name, self.module_name = identify_algorithm(self.model_initializer)
ScoringMixIn.__init__(self, **self.metrics_params if self.metrics_params else {})
if self.auto_start is True:
self.preparation_workflow()
self.experiment_workflow()
def __repr__(self):
return '{}("{}", cross_experiment_key="{}", hyperparameter_key="{}")'.format(
type(self).__name__, self.experiment_id, self.cross_experiment_key, self.hyperparameter_key
)
def __getattr__(self, attr):
"""If AttributeError thrown, resort to checking :attr:`settings.G.Env` for target attribute"""
try:
return getattr(G.Env, attr)
except AttributeError:
raise AttributeError("Could not find '{}' in 'G.Env', or any of the following locations: {}".format(
attr, [_.__name__ for _ in type(self).__mro__]
)).with_traceback(exc_info()[2]) from None
def experiment_workflow(self):
"""Define the actual experiment process, including execution, result saving, and cleanup"""
if self.hyperparameter_key.exists is True:
_ex = F'{self!r} has already been run'
if self.do_raise_repeated is True:
self._clean_up()
raise RepeatedExperimentError(_ex)
G.warn(_ex)
self._initialize_random_seeds()
self._initial_preprocessing()
self.execute()
recorders = RecorderList(file_blacklist=G.Env.file_blacklist)
recorders.format_result()
G.log(F'Saving results for Experiment: "{self.experiment_id}"')
recorders.save_result()
self._clean_up()
def preparation_workflow(self):
"""Execute all tasks that must take place before the experiment is actually started. Such tasks include (but are not
limited to): Creating experiment IDs and hyperparameter keys, creating script backups, and validating parameters"""
G.debug('Starting preparation_workflow...')
self._generate_experiment_id()
self._create_script_backup()
self._validate_parameters()
self._generate_hyperparameter_key()
self._additional_preparation_steps()
G.debug('Completed preparation_workflow')
@abstractmethod
def _additional_preparation_steps(self):
"""Perform additional preparation tasks prior to initializing random seeds and beginning initial preprocessing"""
raise NotImplementedError()
@abstractmethod
def execute(self):
"""Execute the fitting protocol for the Experiment, comprising the following: instantiation of learners for each run,
preprocessing of data as appropriate, training learners, making predictions, and evaluating and aggregating those
predictions and other stats/metrics for later use"""
raise NotImplementedError()
##################################################
# Data Preprocessing Methods:
##################################################
def _initial_preprocessing(self):
"""Perform preprocessing steps prior to executing fitting protocol (usually cross-validation), consisting of: 1) Split
train/holdout data into respective train/holdout input and target data attributes, 2) Feature selection on input data
sets, 3) Set target datasets to target_column contents, 4) Initialize PreprocessingPipeline to perform core preprocessing,
5) Set datasets to their (modified) counterparts in PreprocessingPipeline, 6) Log whether datasets changed"""
#################### Preprocessing ####################
# preprocessor = PreprocessingPipelineMixIn(
# pipeline=[], preprocessing_params=dict(apply_standard_scale=True), features=self.features,
# target_column=self.target_column, train_input_data=self.train_input_data,
# train_target_data=self.train_target_data, holdout_input_data=self.holdout_input_data,
# holdout_target_data=self.holdout_target_data, test_input_data=self.test_input_data,
# fitting_guide=None, fail_gracefully=False, preprocessing_stage='infer'
# )
#
# # TODO: Switch from below direct calls to preprocessor.execute_pipeline() call
# # TODO: After calling execute_pipeline(), set data attributes to their counterparts in preprocessor class
# preprocessor.data_imputation()
# preprocessor.target_data_transformation()
# preprocessor.data_scaling()
#
# for dataset_name in preprocessor.all_input_sets + preprocessor.all_target_sets:
# old_val, new_val = getattr(self, dataset_name), getattr(preprocessor, dataset_name)
# G.log('Dataset: "{}" {} updated'.format(dataset_name, 'was not' if old_val.equals(new_val) else 'was'))
# setattr(self, dataset_name, new_val)
self.train_input_data = self.train_dataset.copy().loc[:, self.feature_selector]
self.train_target_data = self.train_dataset.copy()[[self.target_column]]
if isinstance(self.holdout_dataset, pd.DataFrame):
self.holdout_input_data = self.holdout_dataset.copy().loc[:, self.feature_selector]
self.holdout_target_data = self.holdout_dataset.copy()[[self.target_column]]
if isinstance(self.test_dataset, pd.DataFrame):
self.test_input_data = self.test_dataset.copy().loc[:, self.feature_selector]
G.log('Initial preprocessing stage complete')
##################################################
# Supporting Methods:
##################################################
def _validate_parameters(self):
"""Ensure provided input parameters are properly formatted"""
#################### target_metric ####################
self.target_metric = get_formatted_target_metric(self.target_metric, self.metrics_map)
#################### feature_selector ####################
if self.feature_selector is None:
restricted_cols = [_ for _ in [self.target_column, self.id_column] if _ is not None]
self.feature_selector = [_ for _ in self.train_dataset.columns.values if _ not in restricted_cols]
G.debug('Experiment parameters have been validated')
def _validate_environment(self):
"""Check that there is a currently active Environment instance that is not already occupied"""
if G.Env is None:
raise EnvironmentInactiveError('')
if G.Env.current_task is None:
G.Env.current_task = self
G.log(F'Validated Environment with key: "{self.cross_experiment_key}"')
else:
raise EnvironmentInvalidError('An experiment is in progress. It must finish before a new one can be started')
@staticmethod
def _clean_up():
"""Clean up after experiment to prepare for next experiment"""
G.Env.current_task = None
##################################################
# Key/ID Methods:
##################################################
def _generate_experiment_id(self):
"""Set :attr:`experiment_id` to a UUID"""
self.experiment_id = str(uuid())
G.log('')
G.log('Initialized new Experiment with ID: {}'.format(self.experiment_id))
def _generate_hyperparameter_key(self):
"""Set :attr:`hyperparameter_key` to a key to describe the experiment's hyperparameters"""
parameters = dict(
model_initializer=self.model_initializer,
model_init_params=self.model_init_params,
model_extra_params=self.model_extra_params,
preprocessing_pipeline=self.preprocessing_pipeline,
preprocessing_params=self.preprocessing_params,
feature_selector=self.feature_selector,
# FLAG: Should probably add :attr:`target_metric` to key - With option to ignore it?
)
self.hyperparameter_key = HyperparameterKeyMaker(parameters, self.cross_experiment_key)
| |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import json
import os
import re
import configparser
import pytest
from assertpy import assert_that
import tests.pcluster.config.utils as utils
from pcluster.config.cfn_param_types import CfnParam, CfnSection
from pcluster.config.mappings import ALLOWED_VALUES, FSX
from pcluster.config.validators import (
DCV_MESSAGES,
EBS_VOLUME_TYPE_TO_VOLUME_SIZE_BOUNDS,
FSX_MESSAGES,
FSX_SUPPORTED_ARCHITECTURES_OSES,
LOGFILE_LOGGER,
architecture_os_validator,
check_usage_class,
cluster_type_validator,
compute_resource_validator,
disable_hyperthreading_architecture_validator,
efa_gdr_validator,
efa_os_arch_validator,
fsx_ignored_parameters_validator,
instances_architecture_compatibility_validator,
intel_hpc_architecture_validator,
queue_compute_type_validator,
queue_validator,
region_validator,
s3_bucket_region_validator,
settings_validator,
)
from pcluster.constants import FSX_HDD_THROUGHPUT, FSX_SSD_THROUGHPUT
from tests.common import MockedBoto3Request
from tests.pcluster.config.defaults import DefaultDict
@pytest.fixture()
def boto3_stubber_path():
return "pcluster.config.validators.boto3"
@pytest.mark.parametrize(
"section_dict, expected_message, expected_warning",
[
# traditional scheduler
({"scheduler": "sge", "initial_queue_size": 1, "max_queue_size": 2, "maintain_initial_size": True}, None, None),
(
{"scheduler": "sge", "initial_queue_size": 3, "max_queue_size": 2, "maintain_initial_size": True},
"initial_queue_size must be fewer than or equal to max_queue_size",
None,
),
(
{"scheduler": "sge", "initial_queue_size": 3, "max_queue_size": 2, "maintain_initial_size": False},
"initial_queue_size must be fewer than or equal to max_queue_size",
None,
),
# awsbatch
({"scheduler": "awsbatch", "min_vcpus": 1, "desired_vcpus": 2, "max_vcpus": 3}, None, None),
(
{"scheduler": "awsbatch", "min_vcpus": 3, "desired_vcpus": 2, "max_vcpus": 3},
"desired_vcpus must be greater than or equal to min_vcpus",
None,
),
(
{"scheduler": "awsbatch", "min_vcpus": 1, "desired_vcpus": 4, "max_vcpus": 3},
"desired_vcpus must be fewer than or equal to max_vcpus",
None,
),
(
{"scheduler": "awsbatch", "min_vcpus": 4, "desired_vcpus": 4, "max_vcpus": 3},
"max_vcpus must be greater than or equal to min_vcpus",
None,
),
# key pair not provided
({"scheduler": "awsbatch"}, None, "If you do not specify a key pair"),
],
)
def test_cluster_validator(mocker, capsys, section_dict, expected_message, expected_warning):
config_parser_dict = {"cluster default": section_dict}
utils.assert_param_validator(
mocker, config_parser_dict, expected_message, capsys, expected_warning=expected_warning
)
@pytest.mark.parametrize(
"instance_type, expected_message", [("t2.micro", None), ("c4.xlarge", None), ("c5.xlarge", "is not supported")]
)
def test_ec2_instance_type_validator(mocker, instance_type, expected_message):
config_parser_dict = {"cluster default": {"compute_instance_type": instance_type}}
utils.assert_param_validator(mocker, config_parser_dict, expected_message)
@pytest.mark.parametrize("instance_type, expected_message", [("t2.micro", None), ("c4.xlarge", None)])
def test_head_node_instance_type_validator(mocker, instance_type, expected_message):
config_parser_dict = {"cluster default": {"master_instance_type": instance_type}}
utils.assert_param_validator(mocker, config_parser_dict, expected_message)
@pytest.mark.parametrize(
"scheduler, instance_type, expected_message, expected_warnings",
[
("sge", "t2.micro", None, None),
("sge", "c4.xlarge", None, None),
("sge", "c5.xlarge", "is not supported", None),
# NOTE: compute_instance_type_validator calls ec2_instance_type_validator only if the scheduler is not awsbatch
("awsbatch", "t2.micro", None, None),
("awsbatch", "c4.xlarge", "is not supported", None),
("awsbatch", "t2", None, None), # t2 family
("awsbatch", "optimal", None, None),
("sge", "p4d.24xlarge", None, "has 4 Network Interfaces."),
("slurm", "p4d.24xlarge", None, None),
],
)
def test_compute_instance_type_validator(mocker, scheduler, instance_type, expected_message, expected_warnings):
config_parser_dict = {"cluster default": {"scheduler": scheduler, "compute_instance_type": instance_type}}
extra_patches = {
"pcluster.config.validators.InstanceTypeInfo.max_network_interface_count": 4
if instance_type == "p4d.24xlarge"
else 1,
}
utils.assert_param_validator(
mocker, config_parser_dict, expected_message, expected_warnings, extra_patches=extra_patches
)
def test_ec2_key_pair_validator(mocker, boto3_stubber):
describe_key_pairs_response = {
"KeyPairs": [
{"KeyFingerprint": "12:bf:7c:56:6c:dd:4f:8c:24:45:75:f1:1b:16:54:89:82:09:a4:26", "KeyName": "key1"}
]
}
mocked_requests = [
MockedBoto3Request(
method="describe_key_pairs", response=describe_key_pairs_response, expected_params={"KeyNames": ["key1"]}
)
]
boto3_stubber("ec2", mocked_requests)
# TODO test with invalid key
config_parser_dict = {"cluster default": {"key_name": "key1"}}
utils.assert_param_validator(mocker, config_parser_dict)
@pytest.mark.parametrize(
"image_architecture, bad_ami_message, bad_architecture_message",
[
("x86_64", None, None),
(
"arm64",
None,
"incompatible with the architecture supported by the instance type chosen for the head node",
),
(
"arm64",
"Unable to get information for AMI",
"incompatible with the architecture supported by the instance type chosen for the head node",
),
],
)
def test_ec2_ami_validator(mocker, boto3_stubber, image_architecture, bad_ami_message, bad_architecture_message):
describe_images_response = {
"Images": [
{
"VirtualizationType": "paravirtual",
"Name": "My server",
"Hypervisor": "xen",
"ImageId": "ami-12345678",
"RootDeviceType": "ebs",
"State": "available",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"DeleteOnTermination": True,
"SnapshotId": "snap-1234567890abcdef0",
"VolumeSize": 8,
"VolumeType": "standard",
},
}
],
"Architecture": image_architecture,
"ImageLocation": "123456789012/My server",
"KernelId": "aki-88aa75e1",
"OwnerId": "123456789012",
"RootDeviceName": "/dev/sda1",
"Public": False,
"ImageType": "machine",
"Description": "An AMI for my server",
}
]
}
mocked_requests = [
MockedBoto3Request(
method="describe_images",
response=describe_images_response,
expected_params={"ImageIds": ["ami-12345678"]},
generate_error=bad_ami_message,
)
]
boto3_stubber("ec2", mocked_requests)
# TODO test with invalid key
config_parser_dict = {"cluster default": {"custom_ami": "ami-12345678"}}
expected_message = bad_ami_message or bad_architecture_message
utils.assert_param_validator(mocker, config_parser_dict, expected_message)
@pytest.mark.parametrize(
"section_dict, expected_message",
[
({"tags": {"key": "value", "key2": "value2"}}, None),
(
{"tags": {"key": "value", "Version": "value2"}},
r"Version.*reserved",
),
],
)
def test_tags_validator(mocker, capsys, section_dict, expected_message):
config_parser_dict = {"cluster default": section_dict}
utils.assert_param_validator(mocker, config_parser_dict, expected_error=expected_message)
def test_ec2_volume_validator(mocker, boto3_stubber):
describe_volumes_response = {
"Volumes": [
{
"AvailabilityZone": "us-east-1a",
"Attachments": [
{
"AttachTime": "2013-12-18T22:35:00.000Z",
"InstanceId": "i-1234567890abcdef0",
"VolumeId": "vol-12345678",
"State": "attached",
"DeleteOnTermination": True,
"Device": "/dev/sda1",
}
],
"Encrypted": False,
"VolumeType": "gp2",
"VolumeId": "vol-049df61146c4d7901",
"State": "available", # TODO add test with "in-use"
"SnapshotId": "snap-1234567890abcdef0",
"CreateTime": "2013-12-18T22:35:00.084Z",
"Size": 8,
}
]
}
mocked_requests = [
MockedBoto3Request(
method="describe_volumes",
response=describe_volumes_response,
expected_params={"VolumeIds": ["vol-12345678"]},
)
]
boto3_stubber("ec2", mocked_requests)
# TODO test with invalid key
config_parser_dict = {
"cluster default": {"ebs_settings": "default"},
"ebs default": {"shared_dir": "test", "ebs_volume_id": "vol-12345678"},
}
utils.assert_param_validator(mocker, config_parser_dict)
@pytest.mark.parametrize(
"region, base_os, scheduler, expected_message",
[
# verify awsbatch supported regions
(
"ap-northeast-3",
"alinux2",
"awsbatch",
"Region 'ap-northeast-3' is not yet officially supported by ParallelCluster",
),
("us-gov-east-1", "alinux2", "awsbatch", None),
("us-gov-west-1", "alinux2", "awsbatch", None),
("eu-west-1", "alinux2", "awsbatch", None),
("us-east-1", "alinux2", "awsbatch", None),
("eu-north-1", "alinux2", "awsbatch", None),
("cn-north-1", "alinux2", "awsbatch", None),
("cn-northwest-1", "alinux2", "awsbatch", None),
# verify traditional schedulers are supported in all the regions but ap-northeast-3
("cn-northwest-1", "alinux2", "sge", None),
("us-gov-east-1", "alinux2", "sge", None),
("cn-northwest-1", "alinux2", "slurm", None),
("us-gov-east-1", "alinux2", "slurm", None),
("cn-northwest-1", "alinux2", "torque", None),
("us-gov-east-1", "alinux2", "torque", None),
(
"ap-northeast-3",
"alinux2",
"sge",
"Region 'ap-northeast-3' is not yet officially supported by ParallelCluster",
),
# verify awsbatch supported OSes
("eu-west-1", "centos7", "awsbatch", "scheduler supports the following Operating Systems"),
("eu-west-1", "centos8", "awsbatch", "scheduler supports the following Operating Systems"),
("eu-west-1", "ubuntu1804", "awsbatch", "scheduler supports the following Operating Systems"),
("eu-west-1", "alinux2", "awsbatch", None),
# verify sge supports all the OSes
("eu-west-1", "centos7", "sge", None),
("eu-west-1", "centos8", "sge", None),
("eu-west-1", "ubuntu1804", "sge", None),
("eu-west-1", "alinux2", "sge", None),
# verify slurm supports all the OSes
("eu-west-1", "centos7", "slurm", None),
("eu-west-1", "centos8", "slurm", None),
("eu-west-1", "ubuntu1804", "slurm", None),
("eu-west-1", "alinux2", "slurm", None),
# verify torque supports all the OSes
("eu-west-1", "centos7", "torque", None),
("eu-west-1", "centos8", "torque", None),
("eu-west-1", "ubuntu1804", "torque", None),
("eu-west-1", "alinux2", "torque", None),
],
)
def test_scheduler_validator(mocker, capsys, region, base_os, scheduler, expected_message):
# we need to set the region in the environment because it takes precedence respect of the config file
os.environ["AWS_DEFAULT_REGION"] = region
config_parser_dict = {"cluster default": {"base_os": base_os, "scheduler": scheduler}}
# Deprecation warning should be printed for sge and torque
expected_warning = None
wiki_url = "https://github.com/aws/aws-parallelcluster/wiki/Deprecation-of-SGE-and-Torque-in-ParallelCluster"
if scheduler in ["sge", "torque"]:
expected_warning = ".{0}. is scheduled to be deprecated.*{1}".format(scheduler, wiki_url)
utils.assert_param_validator(mocker, config_parser_dict, expected_message, capsys, expected_warning)
def test_placement_group_validator(mocker, boto3_stubber):
describe_placement_groups_response = {
"PlacementGroups": [{"GroupName": "my-cluster", "State": "available", "Strategy": "cluster"}]
}
mocked_requests = [
MockedBoto3Request(
method="describe_placement_groups",
response=describe_placement_groups_response,
expected_params={"GroupNames": ["my-cluster"]},
)
]
boto3_stubber("ec2", mocked_requests)
# TODO test with invalid group name
config_parser_dict = {"cluster default": {"placement_group": "my-cluster"}}
utils.assert_param_validator(mocker, config_parser_dict)
def test_url_validator(mocker, boto3_stubber, capsys):
head_object_response = {
"AcceptRanges": "bytes",
"ContentType": "text/html",
"LastModified": "Thu, 16 Apr 2015 18:19:14 GMT",
"ContentLength": 77,
"VersionId": "null",
"ETag": '"30a6ec7e1a9ad79c203d05a589c8b400"',
"Metadata": {},
}
mocked_requests = [
MockedBoto3Request(
method="head_object", response=head_object_response, expected_params={"Bucket": "test", "Key": "test.json"}
)
]
boto3_stubber("s3", mocked_requests)
mocker.patch("pcluster.config.validators.urllib.request.urlopen")
tests = [("s3://test/test.json", None), ("http://test/test.json", None)]
for template_url, expected_message in tests:
config_parser_dict = {"cluster default": {"template_url": template_url}}
utils.assert_param_validator(mocker, config_parser_dict, expected_message)
# Test S3 URI in custom_chef_cookbook.
tests = [
(
"s3://test/cookbook.tgz",
None,
MockedBoto3Request(
method="head_object",
response=head_object_response,
expected_params={"Bucket": "test", "Key": "cookbook.tgz"},
),
),
(
"s3://failure/cookbook.tgz",
(
"WARNING: The configuration parameter 'custom_chef_cookbook' generated the following warnings:\n"
"The S3 object does not exist or you do not have access to it.\n"
"Please make sure the cluster nodes have access to it."
),
MockedBoto3Request(
method="head_object",
response=head_object_response,
expected_params={"Bucket": "failure", "Key": "cookbook.tgz"},
generate_error=True,
error_code=404,
),
),
]
for custom_chef_cookbook_url, expected_message, mocked_request in tests:
boto3_stubber("s3", mocked_request)
mocker.patch("pcluster.config.validators.urllib.request.urlopen")
config_parser_dict = {
"cluster default": {
"scheduler": "slurm",
"s3_read_resource": "arn:aws:s3:::test*",
"custom_chef_cookbook": custom_chef_cookbook_url,
}
}
utils.assert_param_validator(mocker, config_parser_dict, capsys=capsys, expected_warning=expected_message)
@pytest.mark.parametrize(
"config, num_calls, error_code, bucket, expected_message",
[
(
{
"cluster default": {"fsx_settings": "fsx"},
"fsx fsx": {
"storage_capacity": 1200,
"import_path": "s3://test/test1/test2",
"export_path": "s3://test/test1/test2",
"auto_import_policy": "NEW",
},
},
2,
None,
{"Bucket": "test"},
"AutoImport is not supported for cross-region buckets.",
),
(
{
"cluster default": {"fsx_settings": "fsx"},
"fsx fsx": {
"storage_capacity": 1200,
"import_path": "s3://test/test1/test2",
"export_path": "s3://test/test1/test2",
"auto_import_policy": "NEW",
},
},
2,
"NoSuchBucket",
{"Bucket": "test"},
"The S3 bucket 'test' does not | |
"""Finite-dimensional linear operators."""
from typing import Callable, Optional, Tuple, Union
import numpy as np
import scipy.linalg
import scipy.sparse.linalg
import probnum.utils
from probnum import config
from probnum.typing import DTypeArgType, ScalarArgType, ShapeArgType
BinaryOperandType = Union[
"LinearOperator", ScalarArgType, np.ndarray, scipy.sparse.spmatrix
]
# pylint: disable="too-many-lines"
class LinearOperator:
r"""Composite base class for finite-dimensional linear operators.
This class provides a way to define finite-dimensional linear operators without
explicitly constructing a matrix representation. Instead it suffices to define a
matrix-vector product and a shape attribute. This avoids unnecessary memory usage
and can often be more convenient to derive.
:class:`LinearOperator` instances can be multiplied, added and exponentiated. This
happens lazily: the result of these operations is a new, composite
:class:`LinearOperator`, that defers linear operations to the original operators and
combines the results.
To construct a concrete :class:`LinearOperator`, either pass appropriate callables to
the constructor of this class, or subclass it.
A subclass must implement either one of the methods ``_matvec`` and ``_matmat``, and
the attributes/properties ``shape`` (pair of integers) and ``dtype`` (may be
``None``). It may call the ``__init__`` on this class to have these attributes
validated. Implementing ``_matvec`` automatically implements ``_matmat`` (using a
naive algorithm) and vice-versa.
Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint`` to implement the
Hermitian adjoint (conjugate transpose). As with ``_matvec`` and ``_matmat``,
implementing either ``_rmatvec`` or ``_adjoint`` implements the other automatically.
Implementing ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for backwards
compatibility.
Parameters
----------
shape :
Matrix dimensions `(M, N)`.
dtype :
Data type of the operator.
matmul :
Callable which computes the matrix-matrix product :math:`y = A V`, where
:math:`A` is the linear operator and :math:`V` is an :math:`N \times K` matrix.
The callable must support broadcasted matrix products, i.e. the argument
:math:`V` might also be a stack of matrices in which case the broadcasting rules
of :func:`np.matmul` must apply.
Note that the argument to this callable is guaranteed to have at least two
dimensions.
rmatmul :
Callable which implements the matrix-matrix product, i.e. :math:`A @ V`, where
:math:`A` is the linear operator and :math:`V` is a matrix of shape `(N, K)`.
todense :
Callable which returns a dense matrix representation of the linear operator as a
:class:`np.ndarray`. The output of this function must be equivalent to the
output of :code:`A.matmat(np.eye(N, dtype=A.dtype))`.
rmatvec :
Callable which implements the matrix-vector product with the adjoint of the
operator, i.e. :math:`A^H v`, where :math:`A^H` is the conjugate transpose of
the linear operator :math:`A` and :math:`v` is a vector of shape `(N,)`.
This argument will be ignored if `adjoint` is given.
rmatmat :
Returns :math:`A^H V`, where :math:`V` is a dense matrix with dimensions (M, K).
See Also
--------
aslinop : Transform into a LinearOperator.
Examples
--------
>>> import numpy as np
>>> from probnum.linops import LinearOperator
>>> @LinearOperator.broadcast_matvec
... def mv(v):
... return np.array([2 * v[0] - v[1], 3 * v[1]])
>>> A = LinearOperator(shape=(2, 2), dtype=np.float_, matmul=mv)
>>> A
<LinearOperator with shape=(2, 2) and dtype=float64>
>>> A @ np.array([1., 2.])
array([0., 6.])
>>> A @ np.ones(2)
array([1., 3.])
"""
# pylint: disable=too-many-public-methods
def __init__(
self,
shape: ShapeArgType,
dtype: DTypeArgType,
*,
matmul: Callable[[np.ndarray], np.ndarray],
rmatmul: Optional[Callable[[np.ndarray], np.ndarray]] = None,
apply: Callable[[np.ndarray, int], np.ndarray] = None,
todense: Optional[Callable[[], np.ndarray]] = None,
transpose: Optional[Callable[[np.ndarray], "LinearOperator"]] = None,
inverse: Optional[Callable[[], "LinearOperator"]] = None,
rank: Optional[Callable[[], np.intp]] = None,
eigvals: Optional[Callable[[], np.ndarray]] = None,
cond: Optional[
Callable[[Optional[Union[None, int, str, np.floating]]], np.number]
] = None,
det: Optional[Callable[[], np.number]] = None,
logabsdet: Optional[Callable[[], np.flexible]] = None,
trace: Optional[Callable[[], np.number]] = None,
):
self.__shape = probnum.utils.as_shape(shape, ndim=2)
# DType
self.__dtype = np.dtype(dtype)
if not np.issubdtype(self.__dtype, np.number):
raise TypeError("The dtype of a linear operator must be numeric.")
if np.issubdtype(self.__dtype, np.complexfloating):
raise TypeError("Linear operators do not support complex dtypes.")
self.__matmul = matmul # (self @ x)
self.__rmatmul = rmatmul # (x @ self)
self.__apply = apply # __call__
self.__todense = todense
self.__transpose = transpose
self.__inverse = inverse
# Matrix properties
self.__rank = rank
self.__eigvals = eigvals
self.__cond = cond
self.__det = det
self.__logabsdet = logabsdet
self.__trace = trace
# Caches
self.__todense_cache = None
self.__rank_cache = None
self.__eigvals_cache = None
self.__cond_cache = {}
self.__det_cache = None
self.__logabsdet_cache = None
self.__trace_cache = None
@property
def shape(self) -> Tuple[int, int]:
"""Shape of the linear operator.
Defined as a tuple of the output and input dimension of
operator.
"""
return self.__shape
@property
def ndim(self) -> int:
"""Number of linear operator dimensions.
Defined analogously to :attr:`numpy.ndarray.ndim`.
"""
return 2
@property
def size(self) -> int:
return np.prod(self.__shape)
@property
def dtype(self) -> np.dtype:
"""Data type of the linear operator."""
return self.__dtype
@property
def is_square(self) -> bool:
"""Whether input dimension matches output dimension."""
return self.shape[0] == self.shape[1]
def __repr__(self) -> str:
return (
f"<{self.__class__.__name__} with "
f"shape={self.shape} and "
f"dtype={str(self.dtype)}>"
)
def __call__(self, x: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
if axis is not None and (axis < -x.ndim or axis >= x.ndim):
raise ValueError(
f"Axis {axis} is out-of-bounds for operand of shape {np.shape(x)}."
)
if x.ndim == 1:
return self @ x
elif x.ndim > 1:
if axis is None:
axis = -1
if axis < 0:
axis += x.ndim
if axis == (x.ndim - 1):
return (self @ x[..., np.newaxis])[..., 0]
elif axis == (x.ndim - 2):
return self @ x
else:
if self.__apply is None:
return np.moveaxis(self @ np.moveaxis(x, axis, -2), -2, axis)
return self.__apply(x, axis)
else:
raise ValueError("The operand must be at least one dimensional.")
def astype(
self,
dtype: DTypeArgType,
order: str = "K",
casting: str = "unsafe",
subok: bool = True,
copy: bool = True,
) -> "LinearOperator":
"""Cast a linear operator to a different ``dtype``.
Parameters
----------
dtype:
Data type to which the linear operator is cast.
order:
Memory layout order of the result.
casting:
Controls what kind of data casting may occur.
subok:
If True, then sub-classes will be passed-through (default). False is currently not supported for linear operators.
copy:
Whether to return a new linear operator, even if ``dtype`` is the same.
"""
dtype = np.dtype(dtype)
if not np.can_cast(self.dtype, dtype, casting=casting):
raise TypeError(
f"Cannot cast linear operator from {self.dtype} to {dtype} "
f"according to the rule {casting}"
)
if not subok:
raise NotImplementedError(
"Setting `subok` to `False` is not supported for linear operators"
)
return self._astype(dtype, order, casting, copy)
def _astype(
self, dtype: np.dtype, order: str, casting: str, copy: bool
) -> "LinearOperator":
if self.dtype == dtype and not copy:
return self
else:
return _TypeCastLinearOperator(self, dtype, order, casting, copy)
def todense(self, cache: bool = True) -> np.ndarray:
"""Dense matrix representation of the linear operator.
This method can be computationally very costly depending on the shape of the
linear operator. Use with caution.
Returns
-------
matrix : np.ndarray
Matrix representation of the linear operator.
"""
if self.__todense_cache is None:
if self.__todense is not None:
dense = self.__todense()
else:
dense = self @ np.eye(self.shape[1], dtype=self.__dtype, order="F")
if not cache:
return dense
self.__todense_cache = dense
return self.__todense_cache
####################################################################################
# Derived Quantities
####################################################################################
def rank(self) -> np.intp:
"""Rank of the linear operator."""
if self.__rank_cache is None:
if self.__rank is not None:
self.__rank_cache = self.__rank()
else:
self.__rank_cache = np.linalg.matrix_rank(self.todense(cache=False))
return self.__rank_cache
def eigvals(self) -> np.ndarray:
"""Eigenvalue spectrum of the linear operator."""
if self.__eigvals_cache is None:
if not self.is_square:
raise np.linalg.LinAlgError(
"Eigenvalues are only defined for square operators"
)
if self.__eigvals is not None:
self.__eigvals_cache = self.__eigvals()
else:
self.__eigvals_cache = np.linalg.eigvals(self.todense(cache=False))
self.__eigvals_cache.setflags(write=False)
return self.__eigvals_cache
def cond(self, p=None) -> np.inexact:
"""Compute the condition number of the linear operator.
The condition number of the linear operator with respect to the ``p`` norm. It
measures how much the solution :math:`x` of the linear system :math:`Ax=b`
changes with respect to small changes in :math:`b`.
Parameters
----------
p : {None, 1, , 2, , inf, 'fro'}, optional
Order of the norm:
======= ============================
p norm for matrices
======= ============================
None 2-norm, computed directly via singular value decomposition
'fro' Frobenius norm
np.inf max(sum(abs(x), axis=1))
1 max(sum(abs(x), axis=0))
2 2-norm (largest sing. value)
======= ============================
Returns
| |
"""
Class for processing FITS files processed by DECam Community Pipelines.
These pipelines will bundle entire focal planes into a single file, which can
be successfully processed by the MultiExtensionFits class, but for which we can
create better visualisations.
Note that the focusing and guiding chips are not processed, but are usually
present in Community Pipelines products.
"""
import os
from PIL import Image, ImageOps
import matplotlib.pyplot as plt
import numpy as np
from .multi_extension_fits import MultiExtensionFits
from upload.models import Thumbnails
__all__ = ["DecamFits", ]
row_layout = {
1: {"indices": ( (2, 0), (3, 0), (4, 0)),
"names": ( "S29", "S30", "S31"), "rtype": "even"},
2: {"indices": ( (1, 1), (2, 1), (3, 1), (4, 1)),
"names": ( "S25", "S26", "S27", "S28"), "rtype": "odd"},
3: {"indices": ( (1, 2), (2, 2), (3, 2), (4, 2), (5, 2)),
"names": ( "S20", "S21", "S22", "S23", "S24"), "rtype": "even"},
4: {"indices": ( (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3)),
"names": ( "S14", "S15", "S16", "S17", "S18", "S19"), "rtype": "odd"},
5: {"indices": ( (0, 4), (1, 4), (2, 4), (3, 4), (4, 4), (5, 4)),
"names": ( "S8", "S9", "S10", "S11", "S12", "S13"), "rtype": "odd"},
6: {"indices": ( (0, 5), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5)),
"names": ( "S1", "S2", "S3", "S4", "S5", "S6", "S7"), "rtype":"even"},
7: {"indices": ( (0, 6), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6)),
"names": ( "N1", "N2", "N3", "N4", "N5", "N6", "N7"), "rtype":"even"},
8: {"indices": ( (0, 7), (1, 7), (2, 7), (3, 7), (4, 7), (5, 7)),
"names": ( "N8", "N9", "N10", "N11", "N12", "N13"),"rtype": "odd"},
9: {"indices": ( (0, 8), (1, 8), (2, 8), (3, 8), (4, 8), (5, 8)),
"names": ( "N14", "N15", "N16", "N17", "N18", "N19"),"rtype": "odd"},
10: {"indices": ( (1, 9), (2, 9), (3, 9), (4, 9), (5, 9)),
"names": ( "N20", "N21", "N22", "N23", "N24"), "rtype": "even"},
11: {"indices": ((1, 10), (2, 10), (3, 10), (4, 10)),
"names": ( "N25", "N26", "N27", "N28"), "rtype": "odd"},
12: {"indices": ((2, 11), (3, 11), (4, 11)),
"names": ( "N29", "N30", "N31"), "rtype": "even"},
}
"""A row-based layour of the DECam focal plane science detectors."""
class Detector:
"""A single DECam science CCD detector.""""""
Attributes
----------
scaling : `float`
Detector size scaling factor. Detector's scaled size is the detector's
physical size divided by the scaling factor.
idx : `tuple`, optional
Detector zero-based index (row, col), as counted from the center of a
detector.
label : `str`, optional
Detector label, for example S1, S3 etc.
xdim : `int`, optional
Detector's physical width, in pixels. Defaults to 4096.
ydim : `int`, optional
Detector's physical height, in pixels. Defaults to 2048
"""
index_detector_map = {name:index for row in row_layout.values()
for name, index in zip(row["names"], row["indices"])}
"""Map between detector index and detector label."""
detector_index_map = {name:index for row in row_layout.values()
for name, index in zip(row["names"], row["indices"])}
"""Map between detector labels and their positional indices."""
detector_type_map = {name:row["rtype"] for row in row_layout.values()
for name in row["names"]}
"""Map between detector labels and their row type."""
dimX = 4096
"""Default, assumed, width, in pixels, of a detector."""
dimY = 2048
"""Default, assumed, height, in pixels, of a detector."""
def __init__(self, scaling, idx=None, label=None, xdim=None, ydim=None):
if idx is not None:
self.row, self.col = idx
self.label = self.index_detector_map[idx]
self.rowType = self.detector_type_map[self.label]
elif label is not None:
self.row, self.col = self.detector_index_map[label]
self.label = label
self.rowType = self.detector_type_map[label]
self.scale = scaling
self.setDimensions(xdim, ydim)
def setDimensions(self, xdim=None, ydim=None):
"""Updates the detector dimensions using the default or provided values
and recalculates relavant detector's scaled dimensions.
Parameters
----------
xdim : `int`
New detector width.
ydim : `int`
New detector height.
"""
self.xdim = xdim if xdim is not None else self.dimX
self.ydim = ydim if ydim is not None else self.dimY
self.scaledX = int(self.xdim/self.scale)
self.scaledY = int(self.ydim/self.scale)
class DecamFocalPlane:
"""Represents the science only CCDs of the DECam focal plane.
All CCDs are assumed to have the same size and the same scaling factor.
Parameters
----------
scaling : `float`
Scaling factor for which the focal plane size in pixels will be reduced
by in order to be displayed.
detectorSize : `tuple`, optional
Physical detector size in pixels as a tuple (width, height). Defaults
to (4096, 2048) as set in `Detector`.
ccdGap : `int`, optional
Physical size of the gap between detectors, in pixels. Defaults to 208.
rowOffset : `int`, optional
Physical offset, in pixels, between 'even' and 'odd' rows.
"""
detector_labels = [name for row in row_layout.values() for name in row["names"]]
"""A list of all detector labels."""
nRows = 7
"""Number of detector rows in the focal plane."""
nCols = 12
"""Number of columns in the focal plane."""
ccd_gap = 208
"""Default, assumed, gap size in pixels, between two detectors."""
row_offset = Detector.dimX/2
"""Default, assumed, offset between even and odd rows."""
def __init__(self, scaling, detectorSize=None, ccdGap=None, rowOffset=None):
self.scale = scaling
self.gap = self.ccd_gap if ccdGap is None else ccdGap
self.rowOffset = self.row_offset if rowOffset is None else rowOffset
self.__initAssumedDetectorDimensions(detectorSize)
self.detectors = {}
for label in self.detector_labels:
self.detectors[label] = Detector(scaling, label=label)
self.planeImage = None
def __initAssumedDetectorDimensions(self, detectorSize=None):
"""In general there is no reason to assume all detectors have the same
sizes, gaps or offsets. But for DECam they do and this lets us perform
an easy and quick generation of in-focal-plane-image-array coordinate
calculations.
Unfortunately it also requires pre-calculating and storing a lot of
not-very-clear quantities.
"""
if detectorSize is None:
xdim, ydim = Detector.dimX, Detector.dimY
else:
xdim, ydim = detectorSize
self.xdim = xdim
self.ydim = ydim
self.scaledX = int(self.xdim/self.scale)
self.scaledY = int(self.ydim/self.scale)
self.scaledGap = int(self.gap/self.scale)
self.scaledRowOffset = int(self.scaledX/2)
self.scaledGappedX = self.scaledX + self.scaledGap
self.scaledGappedY = self.scaledY + self.scaledGap
self.scaledGappedOffsetX = self.scaledGappedX*1.5 + self.scaledGap
def _even_row_coords(self, i, j):
return (i*self.scaledGappedX), int(j*self.scaledGappedY)
def _odd_row_coords(self, i, j):
return (self.scaledRowOffset + i*self.scaledGappedX), j*self.scaledGappedY
def get_coords(self, detectorLabel):
"""Get start and end coordinates of the scaled detector.
Parameters
----------
detectorLabel : `str`
Label of the detector in the focal plane.
Returns
-------
xCoordinates : `tuple`
Tuple of start and end coordinates in the x axis.
yCoordinates : `tuple`
Tuple of start and end coordinates in the y axis.
"""
detector = self.detectors[detectorLabel]
if detector.rowType == "even":
coords = self._even_row_coords(detector.row, detector.col)
elif detector.rowType == "odd":
coords = self._odd_row_coords(detector.row, detector.col)
else:
raise ValueError("Unrecognized row type. Expected 'odd' or 'even' "
"got {detector.rowType} instead.")
return (coords[0], coords[0]+self.scaledX), (coords[1], coords[1]+self.scaledY)
def get_slice(self, detectorLabel):
"""Get array slice that covers the area of the detector.
Parameters
----------
detectorLabel : `str`
Label of the detector in the focal plane.
Returns
-------
xSlice : `slice`
An edge-to-edge slice of the detector, i.e. [start:end], in x axis.
ySlice : `tuple`
An edge-to-edge slice of the detector, i.e. [start:end], in y axis.
"""
coords = self.get_coords(detectorLabel)
return slice(*coords[0]), slice(*coords[1])
def add_image(self, image, detectorLabel):
"""Will place the given image at the location of the given detector
label.
Parameters
----------
image : `np.array`
A 2D array representing the image that will be placed at the
location of the detector
detectorLabel : `str`
The label of the detector.
Note
----
Depending on the scaling factor used, materializing the full focal
plane can require a lot of memory. The plane image will not be
materialized until the firt image is placed in it.
"""
if self.planeImage is None:
self.planeImage = np.zeros((self.nRows*self.scaledGappedX,
self.nCols*self.scaledGappedY),
dtype=np.uint8)
start, end = self.get_slice(detectorLabel)
self.planeImage[start, end] = image
class DecamFits(MultiExtensionFits):
name = "DECamCommunityFits"
priority = 2
def __init__(self, uploadInfo, uploadedFile):
super().__init__(uploadInfo, uploadedFile)
# Override the default processed exts to filter only science images
# from all image-like exts, ignoring focus and guider chips.
self.exts = self._getScienceImages(self.exts)
@classmethod
def _getScienceImages(cls, hdulist):
exts = []
for hdu in hdulist:
exttype = hdu.header.get("DETPOS", False)
if exttype:
if "G" not in exttype and "F" not in exttype:
exts.append(hdu)
return exts
@classmethod
def canProcess(cls, uploadedFile, returnHdulist=False):
canProcess, hdulist = super().canProcess(uploadedFile, returnHdulist=True)
# Data examples I have seen Community Pipeines exclusively utilize the
# CompImageHDU headers and at any time in | |
flag set to 0, sigma clipped,
timegroups selected based on `mingap` day gaps, then fit vs time by a
legendre polynomial of lowish degree".
Args:
lcd (dict): the lightcurvedictionary returned by
astrokep.read_kepler_fitslc.
detrend (str): method by which to detrend the LC. 'legendre' is the
only thing implemented.
sigclip (float or list): to pass to astrobase.lcmath.sigclip_magseries
mingap (float): number of days by which to define "timegroups" (for
individual fitting each of timegroup, and to eliminate "burn-in" of
Kepler spacecraft. For long cadence data, 0.5 days is typical.
Returns:
tuple of (lcd, errflag), where
lcd (dict): lcd, with the new key lcd['centroids'], containing the
detrended times, (centroid_x, centroid_y) values, and their errors.
errflag (bool): boolean error flag, could be raised at various points.
'''
qnum = npunique(lcd['quarter'])
try:
assert qnum.size == 1, 'lcd should be for a unique quarter'
assert detrend == 'legendre'
qnum = int(qnum)
except:
errflag = True
# Get finite, QUALITY_FLAG != 0 times, centroids, and their errors.
# Fraquelli & Thompson (2012), or perhaps also newer papers, give the list
# of exclusions for quality flags.
nbefore = lcd['time'].size
# "ctd" for centroid.
times = lcd['time'][lcd['sap_quality'] == 0]
# Kepler Archive Manual KDMC-10008-006, pg 18. MOM_CENTR1 is the *column*
# value for the flux-weighted centroid, MOM_CENTR2 is the row value.
ctd_x = lcd['mom_centr2'][lcd['sap_quality'] == 0]
ctd_y = lcd['mom_centr1'][lcd['sap_quality'] == 0]
ctd_x_err = lcd['mom_centr2_err'][lcd['sap_quality'] == 0]
ctd_y_err = lcd['mom_centr1_err'][lcd['sap_quality'] == 0]
find = npisfinite(times) & npisfinite(ctd_x) & npisfinite(ctd_y)
find &= (npisfinite(ctd_x_err)) & (npisfinite(ctd_y_err))
f_times, f_ctd_x, f_ctd_y = times[find], ctd_x[find], ctd_y[find]
f_ctd_x_err, f_ctd_y_err = ctd_x_err[find], ctd_y_err[find]
# Sigma clip whopping outliers. It'd be better to have a general purpose
# function for this, but sigclip_magseries works.
stimes_x, s_ctd_x, s_ctd_x_err = sigclip_magseries(f_times, f_ctd_x,
f_ctd_x_err, magsarefluxes=True, sigclip=30.)
stimes_y, s_ctd_y, s_ctd_y_err = sigclip_magseries(f_times, f_ctd_y,
f_ctd_y_err, magsarefluxes=True, sigclip=30.)
# Get times and centroids where everything is finite and sigma clipped.
mask_x = npin1d(stimes_x, stimes_y)
s_times, s_ctd_x, s_ctd_x_err = (stimes_x[mask_x],
s_ctd_x[mask_x],
s_ctd_x_err[mask_x])
mask_y = npin1d(stimes_y, stimes_x)
tmp, s_ctd_y, s_ctd_y_err = (stimes_y[mask_y],
s_ctd_y[mask_y],
s_ctd_y_err[mask_y])
try:
np.testing.assert_array_equal(s_times, tmp)
assert len(s_ctd_y) == len(s_times)
assert len(s_ctd_y_err) == len(s_times)
assert len(s_ctd_x) == len(s_times)
assert len(s_ctd_x_err) == len(s_times)
except AssertionError:
errflag = True
nqflag = s_times.size
# Drop intra-quarter and interquarter gaps in the timeseries. These are the
# same limits set by Armstrong et al (2014): split each quarter's
# timegroups by whether points are within 0.5 day limits. Then drop points
# within 0.5 days of any boundary. Finally, since the interquarter burn-in
# time is more like 1 day, drop a further 0.5 days from the edges of each
# quarter. A nicer way to implement this would be with numpy masks, but
# this approach just constructs the full arrays for any given quarter.
ngroups, groups = find_lc_timegroups(s_times, mingap=mingap)
tmp_times, tmp_ctd_x, tmp_ctd_y = [], [], []
tmp_ctd_x_err, tmp_ctd_y_err = [], []
for group in groups:
tg_times = s_times[group]
tg_ctd_x = s_ctd_x[group]
tg_ctd_y = s_ctd_y[group]
tg_ctd_x_err = s_ctd_x_err[group]
tg_ctd_y_err = s_ctd_y_err[group]
try:
sel = ((tg_times > npmin(tg_times)+mingap) &
(tg_times < npmax(tg_times)-mingap))
except ValueError:
# If tgtimes is empty, continue to next timegroup.
continue
tmp_times.append(tg_times[sel])
tmp_ctd_x.append(tg_ctd_x[sel])
tmp_ctd_y.append(tg_ctd_y[sel])
tmp_ctd_x_err.append(tg_ctd_x_err[sel])
tmp_ctd_y_err.append(tg_ctd_y_err[sel])
s_times,s_ctd_x,s_ctd_y,s_ctd_x_err,s_ctd_y_err = (
nparray([]),nparray([]),nparray([]),nparray([]),nparray([])
)
# N.b.: works fine with empty arrays.
for ix, _ in enumerate(tmp_times):
s_times = npappend(s_times, tmp_times[ix])
s_ctd_x = npappend(s_ctd_x, tmp_ctd_x[ix])
s_ctd_y = npappend(s_ctd_y, tmp_ctd_y[ix])
s_ctd_x_err = npappend(s_ctd_x_err, tmp_ctd_x_err[ix])
s_ctd_y_err = npappend(s_ctd_y_err, tmp_ctd_y_err[ix])
# Extra inter-quarter burn-in of 0.5 days.
try:
s_ctd_x = s_ctd_x[(s_times>(npmin(s_times)+mingap)) &
(s_times<(npmax(s_times)-mingap))]
except:
# Case: s_times is wonky, all across this quarter. (Implemented because
# of a rare bug with a singleton s_times array).
LOGERROR('DETREND FAILED, qnum {:d}'.format(qnum))
return npnan, True
s_ctd_y = s_ctd_y[(s_times>(npmin(s_times)+mingap)) &
(s_times<(npmax(s_times)-mingap))]
s_ctd_x_err = s_ctd_x_err[(s_times>(npmin(s_times)+mingap)) &
(s_times<(npmax(s_times)-mingap))]
s_ctd_y_err = s_ctd_y_err[(s_times>(npmin(s_times)+mingap)) &
(s_times<(npmax(s_times)-mingap))]
# Careful to do this last...
s_times = s_times[(s_times>(npmin(s_times)+mingap)) &
(s_times<(npmax(s_times)-mingap))]
nafter = s_times.size
LOGINFO(
'CLIPPING (SAP), qnum: {:d}'.format(qnum) +
'\nndet before qflag & sigclip: {:d} ({:.3g}),'.format(
nbefore, 1.
) +
'\nndet after qflag & finite & sigclip: {:d} ({:.3g})'.format(
nqflag, nqflag/float(nbefore)
) +
'\nndet after dropping pts near gaps: {:d} ({:.3g})'.format(
nafter, nafter/float(nbefore)
)
)
# DETREND: fit a "low" order legendre series (see
# "legendredeg_vs_npts_per_timegroup_ctd.pdf"), and save it to the output
# dictionary. Save the fit (residuals to be computed after).
ctd_dtr = {}
if detrend == 'legendre':
mingap = 0.5 # days
ngroups, groups = find_lc_timegroups(s_times, mingap=mingap)
tmpctdxlegfit, tmpctdylegfit, legdegs = [], [], []
for group in groups:
tg_times = s_times[group]
tg_ctd_x = s_ctd_x[group]
tg_ctd_x_err = s_ctd_x_err[group]
tg_ctd_y = s_ctd_y[group]
tg_ctd_y_err = s_ctd_y_err[group]
legdeg = _get_legendre_deg_ctd(len(tg_times))
tg_ctd_x_fit, _, _ = _legendre_dtr(tg_times,tg_ctd_x,tg_ctd_x_err,
legendredeg=legdeg)
tg_ctd_y_fit, _, _ = _legendre_dtr(tg_times,tg_ctd_y,tg_ctd_y_err,
legendredeg=legdeg)
tmpctdxlegfit.append(tg_ctd_x_fit)
tmpctdylegfit.append(tg_ctd_y_fit)
legdegs.append(legdeg)
fit_ctd_x, fit_ctd_y = nparray([]), nparray([])
for ix, _ in enumerate(tmpctdxlegfit):
fit_ctd_x = npappend(fit_ctd_x, tmpctdxlegfit[ix])
fit_ctd_y = npappend(fit_ctd_y, tmpctdylegfit[ix])
ctd_dtr = {'times':s_times,
'ctd_x':s_ctd_x,
'ctd_x_err':s_ctd_x_err,
'fit_ctd_x':fit_ctd_x,
'ctd_y':s_ctd_y,
'ctd_y_err':s_ctd_y_err,
'fit_ctd_y':fit_ctd_y
}
lcd['ctd_dtr'] = ctd_dtr
return lcd, False
def get_centroid_offsets(lcd, t_ing_egr, oot_buffer_time=0.1, sample_factor=3):
'''
After running detrend_centroid, get positions of centroids during transits,
and outside of transits. These positions can then be used in a false
positive analysis.
This routine requires knowing the ingress and egress times for every
transit of interest within the quarter this routine is being called for.
There is currently no astrobase routine that automates this for periodic
transits (it must be done in a calling routine).
To get out of transit centroids, this routine takes points outside of the
"buffer" set by `oot_buffer_time`, sampling 3x as many points on either
side of the transit as are in the transit (or however many are specified by
`sample_factor`).
args:
lcd (dict): "lightcurvedict", the dictionary output by
astrokep.read_kepler_fitslc (data from a single Kepler quarter).
Assumes astrokep.detrend_centroid has been run.
t_ing_egr (list of tuples): [(ingress time of i^th transit, egress time
of i^th transit)] for i the transit number index in this quarter
(starts at zero at the beginning of every quarter). Assumes units of
BJD.
oot_buffer_time (float): number of days away from ingress and egress
times to begin sampling "out of transit" centroid points. The number of
out of transit points to take per transit is 3x the number of points in
transit.
sample_factor (float): size of out of transit window from which to
sample.
returns:
cd (dict): dictionary keyed by transit number (i.e. the same index as
t_ing_egr), where each key contains:
{'ctd_x_in_tra':ctd_x_in_tra,
'ctd_y_in_tra':ctd_y_in_tra,
'ctd_x_oot':ctd_x_oot,
'ctd_y_oot':ctd_y_oot,
'npts_in_tra':len(ctd_x_in_tra),
'npts_oot':len(ctd_x_oot),
'in_tra_times':in_tra_times,
'oot_times':oot_times
}
'''
# NOTE:
# Bryson+ (2013) gives a more complicated and more correct approach to this
# problem, computing offsets relative to positions defined on the SKY. This
# requires using a Kepler focal plane geometry model. I don't have that
# model, or know how to get it. So I use a simpler approach.
qnum = int(np.unique(lcd['quarter']))
LOGINFO('Getting centroid offsets (qnum: {:d})...'.format(qnum))
# Kepler pixel scale, cf.
# https://keplerscience.arc.nasa.gov/the-kepler-space-telescope.html
arcsec_per_px = 3.98
# Get the residuals (units: pixel offset).
times = lcd['ctd_dtr']['times']
ctd_resid_x = lcd['ctd_dtr']['ctd_x'] - lcd['ctd_dtr']['fit_ctd_x']
ctd_resid_y = lcd['ctd_dtr']['ctd_y'] - lcd['ctd_dtr']['fit_ctd_y']
# Return results in "centroid dictionary" (has keys of transit number).
cd = {}
for ix,(t_ing,t_egr) in enumerate(t_ing_egr):
# We have in-transit times as input.
in_tra_times = times[(times > t_ing) & (times < t_egr)]
# Compute out of transit times on either side of the in-transit times.
transit_dur = t_egr - t_ing
oot_window_len = sample_factor * transit_dur
oot_before = times[
(times < (t_ing-oot_buffer_time)) &
(times > (t_ing-oot_buffer_time-oot_window_len))]
oot_after = times[
(times > (t_egr+oot_buffer_time)) &
(times < (t_egr+oot_buffer_time+oot_window_len))]
oot_times = npconcatenate([oot_before, oot_after])
mask_tra = npin1d(times, in_tra_times)
mask_oot = npin1d(times, oot_times)
# Convert to units of arcseconds.
ctd_x_in_tra = ctd_resid_x[mask_tra]*arcsec_per_px
ctd_y_in_tra = ctd_resid_y[mask_tra]*arcsec_per_px
ctd_x_oot = ctd_resid_x[mask_oot]*arcsec_per_px
ctd_y_oot = ctd_resid_y[mask_oot]*arcsec_per_px
cd[ix] = {'ctd_x_in_tra':ctd_x_in_tra,
'ctd_y_in_tra':ctd_y_in_tra,
'ctd_x_oot':ctd_x_oot,
'ctd_y_oot':ctd_y_oot,
'npts_in_tra':len(ctd_x_in_tra),
'npts_oot':len(ctd_x_oot),
'in_tra_times':in_tra_times,
'oot_times':oot_times
}
LOGINFO('Got centroid offsets (qnum: {:d}).'.format(qnum))
return cd
############################################
# UTILITY FUNCTION FOR CENTROID DETRENDING #
############################################
def _get_legendre_deg_ctd(npts):
from scipy.interpolate import interp1d
degs = nparray([4,5,6,10,15])
pts = nparray([1e2,3e2,5e2,1e3,3e3])
fn = interp1d(pts, degs, kind='linear',
bounds_error=False,
fill_value=(min(degs), max(degs)))
legendredeg = int(npfloor(fn(npts)))
return legendredeg
#######################################
# UTILITY FUNCTION FOR ANY DETRENDING | |
<reponame>BenWiederhake/hangchat<gh_stars>0
#!/usr/bin/env python3
from datetime import datetime
# from telegram import ParseMode
from telegram.ext import CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram.ext.dispatcher import run_async
# from shared_vars import gm, updater, dispatcher
#from start_bot import start_bot
# from utils import send_async, answer_async, error, TIMEOUT, user_is_creator_or_admin, user_is_creator, game_is_running
def new_game(bot, update):
"""Handler for the /new command"""
chat_id = update.message.chat_id
if update.message.chat.type == 'private':
help_handler(bot, update)
else:
if update.message.chat_id in gm.remind_dict:
for user in gm.remind_dict[update.message.chat_id]:
send_async(bot,
user,
text=_("A new game has been started in {title}").format(
title=update.message.chat.title))
del gm.remind_dict[update.message.chat_id]
game = gm.new_game(update.message.chat)
game.starter = update.message.from_user
game.owner.append(update.message.from_user.id)
game.mode = DEFAULT_GAMEMODE
send_async(bot, chat_id,
text=_("Created a new game! Join the game with /join "
"and start the game with /start"))
def kill_game(bot, update):
"""Handler for the /kill command"""
chat = update.message.chat
user = update.message.from_user
games = gm.chatid_games.get(chat.id)
if update.message.chat.type == 'private':
help_handler(bot, update)
return
if not games:
send_async(bot, chat.id,
text=_("There is no running game in this chat."))
return
game = games[-1]
if user_is_creator_or_admin(user, game, bot, chat):
try:
gm.end_game(chat, user)
send_async(bot, chat.id, text=__("Game ended!", multi=game.translate))
except NoGameInChatError:
send_async(bot, chat.id,
text=_("The game is not started yet. "
"Join the game with /join and start the game with /start"),
reply_to_message_id=update.message.message_id)
else:
send_async(bot, chat.id,
text=_("Only the game creator ({name}) and admin can do that.")
.format(name=game.starter.first_name),
reply_to_message_id=update.message.message_id)
def join_game(bot, update):
"""Handler for the /join command"""
chat = update.message.chat
if update.message.chat.type == 'private':
help_handler(bot, update)
return
try:
gm.join_game(update.message.from_user, chat)
except LobbyClosedError:
send_async(bot, chat.id, text=_("The lobby is closed"))
except NoGameInChatError:
send_async(bot, chat.id,
text=_("No game is running at the moment. "
"Create a new game with /new"),
reply_to_message_id=update.message.message_id)
except AlreadyJoinedError:
send_async(bot, chat.id,
text=_("You already joined the game. Start the game "
"with /start"),
reply_to_message_id=update.message.message_id)
except DeckEmptyError:
send_async(bot, chat.id,
text=_("There are not enough cards left in the deck for "
"new players to join."),
reply_to_message_id=update.message.message_id)
else:
send_async(bot, chat.id,
text=_("Joined the game"),
reply_to_message_id=update.message.message_id)
def leave_game(bot, update):
"""Handler for the /leave command"""
chat = update.message.chat
user = update.message.from_user
player = gm.player_for_user_in_chat(user, chat)
if player is None:
send_async(bot, chat.id, text=_("You are not playing in a game in "
"this group."),
reply_to_message_id=update.message.message_id)
return
game = player.game
user = update.message.from_user
try:
gm.leave_game(user, chat)
except NoGameInChatError:
send_async(bot, chat.id, text=_("You are not playing in a game in "
"this group."),
reply_to_message_id=update.message.message_id)
except NotEnoughPlayersError:
gm.end_game(chat, user)
send_async(bot, chat.id, text=__("Game ended!", multi=game.translate))
else:
if game.started:
send_async(bot, chat.id,
text=__("Okay. Next Player: {name}",
multi=game.translate).format(
name=display_name(game.current_player.user)),
reply_to_message_id=update.message.message_id)
else:
send_async(bot, chat.id,
text=__("{name} left the game before it started.",
multi=game.translate).format(
name=display_name(user)),
reply_to_message_id=update.message.message_id)
def kick_player(bot, update):
"""Handler for the /kick command"""
if update.message.chat.type == 'private':
help_handler(bot, update)
return
chat = update.message.chat
user = update.message.from_user
try:
game = gm.chatid_games[chat.id][-1]
except (KeyError, IndexError):
send_async(bot, chat.id,
text=_("No game is running at the moment. "
"Create a new game with /new"),
reply_to_message_id=update.message.message_id)
return
if not game.started:
send_async(bot, chat.id,
text=_("The game is not started yet. "
"Join the game with /join and start the game with /start"),
reply_to_message_id=update.message.message_id)
return
if user_is_creator_or_admin(user, game, bot, chat):
if update.message.reply_to_message:
kicked = update.message.reply_to_message.from_user
try:
gm.leave_game(kicked, chat)
except NoGameInChatError:
send_async(bot, chat.id, text=_("Player {name} is not found in the current game.".format(name=display_name(kicked))),
reply_to_message_id=update.message.message_id)
return
except NotEnoughPlayersError:
gm.end_game(chat, user)
send_async(bot, chat.id,
text=_("{0} was kicked by {1}".format(display_name(kicked), display_name(user))))
send_async(bot, chat.id, text=__("Game ended!", multi=game.translate))
return
send_async(bot, chat.id,
text=_("{0} was kicked by {1}".format(display_name(kicked), display_name(user))))
else:
send_async(bot, chat.id,
text=_("Please reply to the person you want to kick and type /kick again."),
reply_to_message_id=update.message.message_id)
return
send_async(bot, chat.id,
text=__("Okay. Next Player: {name}",
multi=game.translate).format(
name=display_name(game.current_player.user)),
reply_to_message_id=update.message.message_id)
else:
send_async(bot, chat.id,
text=_("Only the game creator ({name}) and admin can do that.")
.format(name=game.starter.first_name),
reply_to_message_id=update.message.message_id)
def status_update(bot, update):
"""Remove player from game if user leaves the group"""
chat = update.message.chat
if update.message.left_chat_member:
user = update.message.left_chat_member
try:
gm.leave_game(user, chat)
game = gm.player_for_user_in_chat(user, chat).game
except NoGameInChatError:
pass
except NotEnoughPlayersError:
gm.end_game(chat, user)
send_async(bot, chat.id, text=__("Game ended!",
multi=game.translate))
else:
send_async(bot, chat.id, text=__("Removing {name} from the game",
multi=game.translate)
.format(name=display_name(user)))
def start_game(bot, update, args, job_queue):
"""Handler for the /start command"""
if update.message.chat.type != 'private':
chat = update.message.chat
try:
game = gm.chatid_games[chat.id][-1]
except (KeyError, IndexError):
send_async(bot, chat.id,
text=_("There is no game running in this chat. Create "
"a new one with /new"))
return
if game.started:
send_async(bot, chat.id, text=_("The game has already started"))
elif len(game.players) < MIN_PLAYERS:
send_async(bot, chat.id,
text=__("At least {minplayers} players must /join the game "
"before you can start it").format(minplayers=MIN_PLAYERS))
else:
# Starting a game
game.start()
for player in game.players:
player.draw_first_hand()
choice = [[InlineKeyboardButton(text=_("Make your choice!"), switch_inline_query_current_chat='')]]
first_message = (
__("First player: {name}\n"
"Use /close to stop people from joining the game.\n"
"Enable multi-translations with /enable_translations",
multi=game.translate)
.format(name=display_name(game.current_player.user)))
@run_async
def send_first():
"""Send the first card and player"""
bot.sendSticker(chat.id,
sticker=c.STICKERS[str(game.last_card)],
timeout=TIMEOUT)
bot.sendMessage(chat.id,
text=first_message,
reply_markup=InlineKeyboardMarkup(choice),
timeout=TIMEOUT)
send_first()
start_player_countdown(bot, game, job_queue)
elif len(args) and args[0] == 'select':
players = gm.userid_players[update.message.from_user.id]
groups = list()
for player in players:
title = player.game.chat.title
if player is gm.userid_current[update.message.from_user.id]:
title = '- %s -' % player.game.chat.title
groups.append(
[InlineKeyboardButton(text=title,
callback_data=str(player.game.chat.id))]
)
send_async(bot, update.message.chat_id,
text=_('Please select the group you want to play in.'),
reply_markup=InlineKeyboardMarkup(groups))
else:
help_handler(bot, update)
def close_game(bot, update):
"""Handler for the /close command"""
chat = update.message.chat
user = update.message.from_user
games = gm.chatid_games.get(chat.id)
if not games:
send_async(bot, chat.id,
text=_("There is no running game in this chat."))
return
game = games[-1]
if user.id in game.owner:
game.open = False
send_async(bot, chat.id, text=_("Closed the lobby. "
"No more players can join this game."))
return
else:
send_async(bot, chat.id,
text=_("Only the game creator ({name}) and admin can do that.")
.format(name=game.starter.first_name),
reply_to_message_id=update.message.message_id)
return
def open_game(bot, update):
"""Handler for the /open command"""
chat = update.message.chat
user = update.message.from_user
games = gm.chatid_games.get(chat.id)
if not games:
send_async(bot, chat.id,
text=_("There is no running game in this chat."))
return
game = games[-1]
if user.id in game.owner:
game.open = True
send_async(bot, chat.id, text=_("Opened the lobby. "
"New players may /join the game."))
return
else:
send_async(bot, chat.id,
text=_("Only the game creator ({name}) and admin can do that.")
.format(name=game.starter.first_name),
reply_to_message_id=update.message.message_id)
return
def reply_to_query(bot, update):
"""
Handler for inline queries.
Builds the result list for inline queries and answers to the client.
"""
results = list()
switch = None
try:
user = update.inline_query.from_user
user_id = user.id
players = gm.userid_players[user_id]
player = gm.userid_current[user_id]
game = player.game
except KeyError:
add_no_game(results)
else:
# The game has not started.
# The creator may change the game mode, other users just get a "game has not started" message.
if not game.started:
if user_is_creator(user, game):
add_mode_classic(results)
add_mode_fast(results)
add_mode_wild(results)
add_mode_text(results)
else:
add_not_started(results)
elif user_id == game.current_player.user.id:
if game.choosing_color:
add_choose_color(results, game)
add_other_cards(player, results, game)
else:
if not player.drew:
add_draw(player, results)
else:
add_pass(results, game)
if game.last_card.special == c.DRAW_FOUR and game.draw_counter:
add_call_bluff(results, game)
playable = player.playable_cards()
added_ids = list() # Duplicates are not allowed
for card in sorted(player.cards):
add_card(game, card, results,
can_play=(card in playable and
str(card) not in added_ids))
added_ids.append(str(card))
add_gameinfo(game, results)
elif user_id != game.current_player.user.id or not game.started:
for card in sorted(player.cards):
add_card(game, card, results, can_play=False)
else:
add_gameinfo(game, results)
for result in results:
result.id += ':%d' % player.anti_cheat
if players and game and len(players) > 1:
switch = _('Current game: {game}').format(game=game.chat.title)
answer_async(bot, update.inline_query.id, results, cache_time=0,
switch_pm_text=switch, switch_pm_parameter='select')
def process_result(bot, update, job_queue):
"""
Handler for chosen inline results.
Checks the players actions and acts accordingly.
"""
try:
user = update.chosen_inline_result.from_user
player = gm.userid_current[user.id]
game = player.game
result_id = update.chosen_inline_result.result_id
chat = game.chat
except (KeyError, AttributeError):
return
logger.debug("Selected result: " + result_id)
result_id, anti_cheat = result_id.split(':')
last_anti_cheat = player.anti_cheat
player.anti_cheat += 1
if result_id in ('hand', 'gameinfo', 'nogame'):
return
elif result_id.startswith('mode_'):
# First 5 characters are 'mode_', the rest is the gamemode.
mode = result_id[5:]
game.set_mode(mode)
logger.info("Gamemode changed to {mode}".format(mode = mode))
send_async(bot, chat.id, text=__("Gamemode changed to {mode}".format(mode = mode)))
return
elif len(result_id) == 36: # UUID result
return
elif int(anti_cheat) != last_anti_cheat:
send_async(bot, chat.id,
text=__("Cheat attempt by {name}", multi=game.translate)
.format(name=display_name(player.user)))
return
elif result_id == 'call_bluff':
reset_waiting_time(bot, player)
do_call_bluff(bot, player)
elif result_id == 'draw':
reset_waiting_time(bot, player)
do_draw(bot, player)
elif result_id == 'pass':
game.turn()
elif result_id in c.COLORS:
game.choose_color(result_id)
else:
reset_waiting_time(bot, player)
do_play_card(bot, player, result_id)
if game_is_running(game):
nextplayer_message = (
__("Next player: {name}", multi=game.translate)
.format(name=display_name(game.current_player.user)))
choice = [[InlineKeyboardButton(text=_("Make your choice!"), switch_inline_query_current_chat='')]]
send_async(bot, chat.id,
text=nextplayer_message,
reply_markup=InlineKeyboardMarkup(choice))
start_player_countdown(bot, game, job_queue)
# Add all handlers to the dispatcher and run the bot
#dispatcher.add_handler(CallbackQueryHandler(select_game))
dispatcher.add_handler(CommandHandler('start', start_game, pass_args=True, pass_job_queue=True))
dispatcher.add_handler(CommandHandler('new', new_game))
dispatcher.add_handler(CommandHandler('kill', kill_game))
dispatcher.add_handler(CommandHandler('join', join_game))
dispatcher.add_handler(CommandHandler('leave', leave_game))
dispatcher.add_handler(CommandHandler('kick', kick_player))
dispatcher.add_handler(CommandHandler('open', open_game))
#dispatcher.add_handler(CommandHandler('close', | |
# -*- coding: utf-8 -*-
import re
import copy
import os
import string
import xlrd
import pickle
from .get_tokens import *
keywords_0 = ('auto', 'typedf', 'const', 'extern', 'register', 'static', 'volatile', 'continue', 'break',
'default', 'return', 'goto', 'else', 'case')
keywords_1 = ('catch', 'sizeof', 'if', 'switch', 'while', 'for')
keywords_2 = ('memcpy', 'wmemcpy', '_memccpy', 'memmove', 'wmemmove', 'memset', 'wmemset', 'memcmp', 'wmemcmp', 'memchr',
'wmemchr', 'strncpy', 'lstrcpyn', 'wcsncpy', 'strncat', 'bcopy', 'cin', 'strcpy', 'lstrcpy', 'wcscpy', '_tcscpy',
'_mbscpy', 'CopyMemory', 'strcat', 'lstrcat', 'fgets', 'main', '_main', '_tmain', 'Winmain', 'AfxWinMain', 'getchar',
'getc', 'getch', 'getche', 'kbhit', 'stdin', 'm_lpCmdLine', 'getdlgtext', 'getpass', 'istream.get', 'istream.getline',
'istream.peek', 'istream.putback', 'streambuf.sbumpc', 'streambuf.sgetc', 'streambuf.sgetn', 'streambuf.snextc', 'streambuf.sputbackc',
'SendMessage', 'SendMessageCallback', 'SendNotifyMessage', 'PostMessage', 'PostThreadMessage', 'recv', 'recvfrom', 'Receive',
'ReceiveFrom', 'ReceiveFromEx', 'CEdit.GetLine', 'CHtmlEditCtrl.GetDHtmlDocument', 'CListBox.GetText', 'CListCtrl.GetItemText',
'CRichEditCtrl.GetLine', 'GetDlgItemText', 'CCheckListBox.GetCheck', 'DISP_FUNCTION', 'DISP_PROPERTY_EX', 'getenv', 'getenv_s', '_wgetenv',
'_wgetenv_s', 'snprintf', 'vsnprintf', 'scanf', 'sscanf', 'catgets', 'gets', 'fscanf', 'vscanf', 'vfscanf', 'printf', 'vprintf', 'CString.Format',
'CString.FormatV', 'CString.FormatMessage', 'CStringT.Format', 'CStringT.FormatV', 'CStringT.FormatMessage', 'CStringT.FormatMessageV',
'vsprintf', 'asprintf', 'vasprintf', 'fprintf', 'sprintf', 'syslog', 'swscanf', 'sscanf_s', 'swscanf_s', 'swprintf', 'malloc',
'readlink', 'lstrlen', 'strchr', 'strcmp', 'strcoll', 'strcspn', 'strerror', 'strlen', 'strpbrk', 'strrchr', 'strspn', 'strstr',
'strtok', 'strxfrm', 'kfree', '_alloca')
keywords_3 = ('_strncpy*', '_tcsncpy*', '_mbsnbcpy*', '_wcsncpy*', '_strncat*', '_mbsncat*', 'wcsncat*', 'CEdit.Get*', 'CRichEditCtrl.Get*',
'CComboBox.Get*', 'GetWindowText*', 'istream.read*', 'Socket.Receive*', 'DDX_*', '_snprintf*', '_snwprintf*')
keywords_5 = ('*malloc',)
xread = xlrd.open_workbook('./sysevr/ml_models/function.xls')
keywords_4 = []
for sheet in xread.sheets():
col = sheet.col_values(0)[1:]
keywords_4 += col
#print keywords_4
typewords_0 = ('short', 'int', 'long', 'float', 'doubule', 'char', 'unsigned', 'signed', 'void' ,'wchar_t', 'size_t', 'bool')
typewords_1 = ('struct', 'union', 'enum')
typewords_2 = ('new', 'delete')
operators = ('+', '-', '*', '/', '=', '%', '?', ':', '!=', '==', '<<', '&&', '||', '+=', '-=', '++', '--', '>>', '|=')
function = '^[_a-zA-Z][_a-zA-Z0-9]*$'
variable = '^[_a-zA-Z][_a-zA-Z0-9(->)?(\.)?]*$'
number = '[0-9]+'
stringConst = '(^\'[\s|\S]*\'$)|(^"[\s|\S]*"$)'
constValue = ['NULL', 'false', 'true']
phla = '[^a-zA-Z0-9_]'
space = '\s'
spa = ''
def isinKeyword_3(token):
for key in keywords_3:
if len(token) < len(key)-1:
return False
if key[:-1] == token[:len(key)-1]:
return True
else:
return False
def isinKeyword_5(token):
for key in keywords_5:
if len(token) < len(key)-1:
return False
if token.find(key[1:]) != -1:
if "_" in token:
return False
else:
return True
else:
return False
def isphor(s, liter):
m = re.search(liter, s)
if m is not None:
return True
else:
return False
def var(s):
m = re.match(function, s)
if m is not None:
return True
else:
return False
def CreateVariable(string, token):
length = len(string)
stack1 = []
s = ''
i = 0
while (i < length):
if var(string[i]):
#if i + 1 < length and (string[i + 1] == '->' or string[i + 1] == '.'):
# stack1.append(string[i])
# stack1.append(string[i + 1])
# i = i + 2
#else:
while stack1 != []:
s = stack1.pop() + s
s = s + string[i]
token.append(s)
s = ''
i = i + 1
else:
token.append(string[i])
i = i + 1
def mapping(list_sentence):
list_code = []
list_func = []
for code in list_sentence:
#print code
_string = ''
for c in code:
_string = _string + ' ' + c
_string = _string[1:]
list_code.append(_string)
#print list_code
_func_dict = {}
_variable_dict = {}
index = 0
while index < len(list_code):
string = []
token = []
j = 0
str1 = copy.copy(list_code[index])
i = 0
tag = 0
strtemp = ''
while i < len(str1):
if tag == 0:
if isphor(str1[i], space):
if i > 0:
string.append(str1[j:i])
j = i + 1
else:
j = i + 1
i = i + 1
elif i + 1 == len(str1):
string.append(str1[j:i + 1])
break
elif isphor(str1[i], phla):
if i + 1 < len(str1) and str1[i] == '-' and str1[i + 1] == '>':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '<' and str1[i + 1] == '<':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '>' and str1[i + 1] == '>':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '&' and str1[i + 1] == '&':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '|' and str1[i + 1] == '|':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '|' and str1[i + 1] == '=':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '=' and str1[i + 1] == '=':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '!' and str1[i + 1] == '=':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '+' and str1[i + 1] == '+':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '-' and str1[i + 1] == '-':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '+' and str1[i + 1] == '=':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif i + 1 < len(str1) and str1[i] == '-' and str1[i + 1] == '=':
string.append(str1[i] + str1[i + 1])
j = i + 2
i = i + 2
elif str1[i] == '"':
strtemp = strtemp + str1[i]
i = i + 1
tag = 1
elif str1[i] == '\'':
strtemp = strtemp + str1[i]
i = i + 1
tag = 2
else:
string.append(str1[i])
j = i + 1
i += 1
else:
i += 1
elif tag == 1:
if str1[i] != '"':
strtemp = strtemp + str1[i]
i = i + 1
else:
strtemp = strtemp + str1[i]
string.append(strtemp)
strtemp = ''
tag = 0
j = i + 1
i += 1
elif tag == 2:
if str1[i] != '\'':
strtemp = strtemp + str1[i]
i = i + 1
else:
strtemp = strtemp + str1[i]
string.append(strtemp)
strtemp = ''
tag = 0
j = i + 1
i += 1
count = 0
for sub in string:
if sub == spa:
count += 1
for i in range(count):
string.remove('')
CreateVariable(string, token)
j = 0
while j < len(token):
if token[j] in constValue:
token[j] = token[j]
j += 1
elif j < len(token) and isphor(token[j], variable):
if (token[j] in keywords_0) or (token[j] in typewords_0) or (token[j] in typewords_1 or token[j] in typewords_2):
j += 1
elif j - 1 >= 0 and j + 1 < len(token) and token[j-1] == 'new' and token[j + 1] == '[':
j = j + 2
elif j + 1 < len(token) and token[j + 1] == '(':
#print(token[j])
if token[j] in keywords_1:
j = j + 2
elif token[j] in keywords_2:
#print('3', token[j])
j = j + 2
elif isinKeyword_3(token[j]):
#print('4', token[j])
j = j + 2
elif token[j] in keywords_4:
#print('5', token[j])
j = j + 2
elif isinKeyword_5(token[j]):
#print('6', token[j])
j = j + 2
else:
#print('7',token[j])
if "good" in token[j] or "bad" in token[j]:
list_func.append(str(token[j]))
if token[j] in _func_dict.keys():
token[j] = _func_dict[token[j]]
else:
list_values = _func_dict.values()
if len(list_values) == 0:
_func_dict[token[j]] = 'func_0'
token[j] = _func_dict[token[j]]
else:
if token[j] in _func_dict.keys():
token[j] = _func_dict[token[j]]
else:
list_num = []
for value in list_values:
list_num.append(int(value.split('_')[-1]))
_max = max(list_num)
_func_dict[token[j]] = 'func_' + str(_max+1)
token[j] = _func_dict[token[j]]
j = j + 2
elif j + 1 < len(token) and (not isphor(token[j + 1], variable)):
if token[j + 1] == '*':
if j + 2 < len(token) and token[j + 2] == 'const':
| |
.align_to(pos, RIGHT)
self.play(Write(text1), run_time=2)
self.wait()
self.play(Write(text2), run_time=2)
self.wait()
self.play(ShowCreation(line1))
self.wait()
multi = TexMobject("\\times").scale(1.5).next_to(text2, LEFT).align_to(text2, DOWN).shift(LEFT*0.5)
self.play(DrawBorderThenFill(multi))
self.play(ScaleInPlace(multi, 3, rate_func = wiggle))
text3 = VGroup(
sub(), num(3), num(0), VGroup(eks(), dgt(3)), sub(), num(3), num(5), VGroup(eks(), dgt(2)), add(), num(5), num(0), eks(), sub(), num(4), num(5),
).arrange(RIGHT/2)
for i in [4,8]:
text3[i-1][1].next_to(text3[i-1][0], (RIGHT+UP)/2).shift(DOWN*0.15)
pos.shift(DOWN)
text3[0].move_to(pos[12].get_center()).shift(UP*0.1)
text3[1:4].move_to(pos[13:16].get_center()).align_to(pos, DOWN)
text3[4].move_to(pos[16].get_center()).shift(UP*0.1)
text3[5:8].move_to(pos[17:20].get_center()).align_to(pos, DOWN)
text3[8].move_to(pos[20].get_center()).shift(UP*0.1)
text3[9:12].move_to(pos[21:24].get_center()).align_to(pos, DOWN)
text3[12].move_to(pos[24].get_center()).shift(UP*0.1)
text3[13:15].move_to(pos[25:27].get_center()).align_to(pos, DOWN)
self.play(
ShowCreationThenDestructionAround(text1),
ShowCreationThenDestructionAround(text2[6:8])
)
self.play(Write(text3), run_time=2)
self.wait()
text4 = VGroup(
num(2), num(4), VGroup(eks(), dgt(4)), add(), num(2), num(8), VGroup(eks(), dgt(3)), sub(), num(4), num(0), VGroup(eks(), dgt(2)), add(), num(3), num(6), eks(),
).arrange(RIGHT/2)
for i in [3,7,11]:
text4[i-1][1].next_to(text4[i-1][0], (RIGHT+UP)/2).shift(DOWN*0.15)
pos.shift(DOWN)
text4[0:3].move_to(pos[9:12].get_center()).align_to(pos, DOWN)
text4[3].move_to(pos[12].get_center()).shift(UP*0.1)
text4[4:7].move_to(pos[13:16].get_center()).align_to(pos, DOWN)
text4[7].move_to(pos[16].get_center()).shift(UP*0.1)
text4[8:11].move_to(pos[17:20].get_center()).align_to(pos, DOWN)
text4[11].move_to(pos[20].get_center()).shift(UP*0.1)
text4[12:15].move_to(pos[21:24].get_center()).align_to(pos, DOWN)
self.play(
ShowCreationThenDestructionAround(text1),
ShowCreationThenDestructionAround(text2[3:6])
)
self.play(Write(text4), run_time=2)
self.wait()
text5 = VGroup(
sub(), num(1), num(2), VGroup(eks(), dgt(6)), sub(), num(1), num(4), VGroup(eks(), dgt(5)), add(), num(2), num(0), VGroup(eks(), dgt(4)), sub(), num(1), num(8), VGroup(eks(), dgt(3)),
).arrange(RIGHT/2)
for i in [4,8,12,16]:
text5[i-1][1].next_to(text5[i-1][0], (RIGHT+UP)/2).shift(DOWN*0.15)
pos.shift(DOWN)
for i in range(4):
text5[4*i].move_to(pos[4*i].get_center()).shift(UP*0.1)
text5[1+4*i:4+4*i].move_to(pos[1+4*i:4+4*i].get_center()).align_to(pos, DOWN)
self.play(
ShowCreationThenDestructionAround(text1),
ShowCreationThenDestructionAround(text2[0:3])
)
self.play(Write(text5), run_time=2)
self.wait()
line2 = Line(ORIGIN, RIGHT*12.7).next_to(text5, DOWN, buff=0.34)\
.set_stroke(width=5, color=WHITE, opacity=0.5)\
.align_to(pos, RIGHT)
self.play(ShowCreation(line2))
self.wait()
text6 = VGroup(
sub(), num(1), num(2), VGroup(eks(), dgt(6)), sub(), num(1), num(4), VGroup(eks(), dgt(5)), add(), num(4), num(4), VGroup(eks(), dgt(4)),
sub(), num(2), num(0), VGroup(eks(), dgt(3)), sub(), num(7), num(5), VGroup(eks(), dgt(2)), add(), num(8), num(6), eks(), sub(), num(4), num(5),
).arrange(RIGHT/2)
for i in [4,8,12,16,20]:
text6[i-1][1].next_to(text6[i-1][0], (RIGHT+UP)/2).shift(DOWN*0.15)
pos.shift(DOWN)
for i in range(6):
text6[4*i].move_to(pos[4*i].get_center()).shift(UP*0.1)
text6[1+4*i:4+4*i].move_to(pos[1+4*i:4+4*i].get_center()).align_to(pos, DOWN)
text6[24].move_to(pos[24].get_center()).shift(UP*0.1)
text6[25:27].move_to(pos[25:27].get_center()).align_to(pos, DOWN)
text6_bg = VGroup(
SurroundingRectangle(VGroup(text3[12:15]), color=YELLOW, fill_opacity=0),
SurroundingRectangle(VGroup(text3[8:12], text4[11:15]), color=YELLOW, fill_opacity=0),
SurroundingRectangle(VGroup(text3[4:8], text4[7:11]), color=YELLOW, fill_opacity=0),
SurroundingRectangle(VGroup(text3[0:4], text4[3:7], text5[12:16]), color=YELLOW, fill_opacity=0),
SurroundingRectangle(VGroup(text4[0:3], text5[8:12]), color=YELLOW, fill_opacity=0),
SurroundingRectangle(VGroup(text5[4:8]), color=YELLOW, fill_opacity=0),
SurroundingRectangle(VGroup(text5[0:4]), color=YELLOW, fill_opacity=0),
)
self.play(ScaleInPlace(text6_bg[0], 3, rate_func = wiggle))
self.play(ReplacementTransform(text6_bg[0], text6[24:27]))
self.wait()
for i in range(6):
self.play(ScaleInPlace(text6_bg[i+1], 3, rate_func = wiggle))
self.play(ReplacementTransform(text6_bg[i+1], text6[20-4*i:24-4*i]))
self.wait()
self.wait()
class Polynomial_part3_3(Scene):
def construct(self):
title = Title2("多项式", font="Source Han Sans CN").set_color(BLUE)
title_mul = SubTopic("多项式乘法").scale(0.8).move_to([-4, title.get_bottom()[1] - 0.5, 0])
self.add(title, title_mul)
self.wait()
t2c2 = {
"A" : ORANGE,
"B" : ORANGE,
"C" : ORANGE,
"x" : RED,
"a" : GREEN,
"b" : GREEN,
"c" : GREEN,
"_i": BLUE_D,
"^i": BLUE_E,
}
A = TexMobject("A", "(", "x", ")", "=", "\\sum\\nolimits", "_{i", "=", "0}", "^n", "a", "_i", "x", "^i").set_color_by_tex_to_color_map(t2c2)
B = TexMobject("B", "(", "x", ")", "=", "\\sum\\nolimits", "_{i", "=", "0}", "^n", "b", "_i", "x", "^i").set_color_by_tex_to_color_map(t2c2)
formula_C = TexMobject("C", "(", "x", ")", "=", "A", "(", "x", ")", "B", "(", "x", ")").set_color_by_tex_to_color_map(t2c2)
C = TexMobject("C", "(", "x", ")", "=", "\\sum\\nolimits", "_{i", "=", "0}", "^{2n}", "c", "_i", "x", "^i").set_color_by_tex_to_color_map(t2c2)
A[6].set_color(GOLD)
B[6].set_color(GOLD)
C[6:8].set_color(GOLD)
A[7].set_color(BLUE)
B[7].set_color(BLUE)
C[8].set_color(BLUE)
A.next_to(title_mul, DOWN, aligned_edge=LEFT)
B.next_to(A, RIGHT, buff=2)
C.next_to(A[4].get_center(), DOWN, index_of_submobject_to_align=4, buff=1.3)
deg = TextMobject("degree(", "$C$", ")=degree(", "$A$", ")+degree(", "$B$", ")").scale(0.8)
deg.next_to(C, RIGHT, buff=1)
deg[1].set_color(ORANGE)
deg[3].set_color(ORANGE)
deg[5].set_color(ORANGE)
ci = TexMobject("c", "_i", "=", "\\sum\\nolimits", "_{j", "=", "0}", "^i", "a", "_j", "b", "_{i-j}")
ci.next_to(C, DOWN, aligned_edge=LEFT, buff=0.85)
ci[0].set_color(GREEN)
ci[8].set_color(GREEN)
ci[10].set_color(GREEN)
ci[1].set_color(BLUE_D)
ci[9].set_color(BLUE_D)
ci[11].set_color(BLUE_D)
ci[4].set_color(GOLD)
ci[5].set_color(BLUE)
c = TexMobject("c", "=", "a", "\\otimes", "b").next_to(ci, RIGHT, buff=1)
c[0].set_color(GREEN)
c[2].set_color(GREEN)
c[4].set_color(GREEN)
self.play(Write(A))
self.play(Write(B))
self.wait(2)
self.play(FadeInFromDown(deg))
self.wait(2)
self.play(Write(C))
self.wait(2)
self.play(Write(ci))
self.wait(2)
self.play(FadeInFrom(c, LEFT))
self.wait(3)
class Polynomial_part4(Scene):
def construct(self):
mid_line = DashedLine([0, 5, 0], [0, -5, 0])
self.play(ShowCreation(mid_line))
self.wait()
self.left()
self.wait()
self.right()
def left(self):
title1 = Text("系数表示", font="Source Han Sans CN").set_color(BLUE).scale(0.57).move_to([-5.2, 3.3, 0])
self.play(Write(title1))
coef = TexMobject("\\boldsymbol{a}", "=", "[", "a", "_0", ",", "a", "_1", ",", "a", "_2", ",", "\\cdots", ",", "a", "_n", "]^\\top")\
.set_color_by_tex_to_color_map({"a":GREEN, "\\boldsymbol{a}":RED, "_0":BLUE, "_1":BLUE, "_2":BLUE, "_n":BLUE})
coef.next_to(title1, DOWN, aligned_edge=LEFT).shift(RIGHT*0.5)
self.play(Write(coef))
self.wait()
t2c = {
"{c}" : GREEN,
"{_i}": BLUE,
"{a}" : GREEN,
"{b}" : GREEN,
}
sub1_1 = SubTopic("加法").scale(0.8).next_to(title1, DOWN, buff=1, aligned_edge=LEFT)
plus1 = TexMobject("{c}{_i}={a}{_i}+{b}{_i}", tex_to_color_map=t2c).move_to([-3.5, sub1_1.get_center()[1]-0.7, 0])
O1_1 = TexMobject("O(n)").scale(0.85).next_to(sub1_1, RIGHT)
self.play(Write(sub1_1))
self.wait()
self.play(Write(plus1))
self.wait(2)
self.play(FadeInFrom(O1_1, RIGHT))
self.wait(2)
sub1_2 = SubTopic("乘法").scale(0.8).next_to(sub1_1, DOWN, buff=1)
mul1 = TexMobject("\\boldsymbol{c}", "=", "\\boldsymbol{a}", "\\otimes", "\\boldsymbol{b}").move_to([-3.5, sub1_2.get_center()[1]-0.7, 0])
O1_2 = TexMobject("O(n^2)").scale(0.85).next_to(sub1_2, RIGHT)
mul1[0].set_color(GREEN)
mul1[2].set_color(GREEN)
mul1[4].set_color(GREEN)
self.play(Write(sub1_2))
self.wait()
self.play(Write(mul1))
self.wait(2)
self.play(FadeInFrom(O1_2, RIGHT))
self.wait(2)
sub1_3 = SubTopic("求值").scale(0.8).next_to(sub1_2, DOWN, buff=1)
t2c2 = {
"{A}": ORANGE,
"{a}": GREEN,
"{x}": RED,
"{_n}": BLUE,
"{_{n-1}}": BLUE,
"{_{n-2}}": BLUE,
"{_1}": BLUE,
"{_0}": BLUE,
}
eva = TexMobject("{A}({x})=&(\\cdots(({a}{_n}{x}+{a}{_{n-1}}){x}+\\\\&{a}{_{n-2}}){x}+\\cdots+{a}{_1}){x}+{a}{_0}", tex_to_color_map=t2c2)
eva.scale(0.8).move_to([-3.5, sub1_3.get_center()[1]-0.85, 0])
O1_3 = TexMobject("O(n)").scale(0.85).next_to(sub1_3, RIGHT)
self.play(Write(sub1_3))
self.wait()
self.play(Write(eva))
self.wait(2)
self.play(FadeInFrom(O1_3, RIGHT))
self.wait(2)
def right(self):
title2 = Text("点值表示", font="Source Han Sans CN").set_color(BLUE).scale(0.57).move_to([1.5, 3.3, 0])
self.play(Write(title2))
t2c = {
"{x}": RED,
"{A}": ORANGE,
"{B}": ORANGE,
"{C}": ORANGE,
"{_0}": BLUE,
"{_1}": BLUE,
"{_n}": BLUE,
"{_i}": BLUE,
}
point = TexMobject("\\{", "({x}{_0}, {A}({x}{_0})), ({x}{_1}, {A}({x}{_1})),\\cdots ,({x}{_n}, {A}({x}{_n}))", "\\}", \
tex_to_color_map=t2c).scale(0.7).next_to(title2, DOWN, aligned_edge=LEFT).shift(LEFT*0.2)
self.play(Write(point))
self.wait()
sub2_1 = SubTopic("加法").scale(0.8).next_to(title2, DOWN, buff=1, aligned_edge=LEFT)
plus2 = TexMobject("{C}({x}{_i})={A}({x}{_i})+{B}({x}{_i})", tex_to_color_map=t2c).move_to([3.5, sub2_1.get_center()[1]-0.7, 0])
O2_1 = TexMobject("O(n)").scale(0.85).next_to(sub2_1, RIGHT)
self.play(Write(sub2_1))
self.wait()
self.play(Write(plus2))
self.wait(2)
self.play(FadeInFrom(O2_1, RIGHT))
self.wait(2)
sub2_2 = SubTopic("乘法").scale(0.8).next_to(sub2_1, DOWN, buff=1)
mul2 = TexMobject("{C}({x}{_i})={A}({x}{_i}){B}({x}{_i})", tex_to_color_map=t2c).move_to([3.5, sub2_2.get_center()[1]-0.7, 0])
O2_2 = TexMobject("O(n)").scale(0.85).next_to(sub2_2, RIGHT)
self.play(Write(sub2_2))
self.wait()
self.play(Write(mul2))
self.wait(2)
self.play(FadeInFrom(O2_2, RIGHT))
self.wait(2)
sub2_3 = SubTopic("插值").scale(0.8).next_to(sub2_2, DOWN, buff=1)
t2c2 = {
"{A}" : ORANGE,
"{x}" : RED,
"{_i}": BLUE
}
inter = TexMobject("{A}({x})=\\sum_{i=0}^n{A}({x}{_i})\\frac{\\prod_{j\\neq i}(x_{}-x_j)}{\\prod_{j\\neq i}(x_i-x_j)}", \
tex_to_color_map=t2c2)
inter.scale(0.8).move_to([3.5, sub2_3.get_center()[1]-0.87, 0])
O2_3 = TexMobject("O(n^2)").scale(0.85).next_to(sub2_3, RIGHT)
self.play(Write(sub2_3))
self.wait()
self.play(Write(inter))
self.wait(2)
self.play(FadeInFrom(O2_3, RIGHT))
self.wait(2)
class DFT(Scene):
def construct(self):
title = Text("离散傅里叶变换", font="Source Han Sans CN", t2c={"离散" : YELLOW,"傅里叶变换" : BLUE,})
title.scale(0.6).move_to([-4.5, 3.3, 0])
en_title = TextMobject("D", "iscrete ", "F", "ourier ", "T", "ransform").next_to(title, RIGHT)
en_title[0].set_color(YELLOW)
en_title[2].set_color(BLUE)
en_title[4].set_color(BLUE)
self.play(Write(title))
self.wait()
self.play(DrawBorderThenFill(en_title))
self.wait()
defi = VGroup(
TexMobject("A", "(", "x", ")", "=", "\\sum", "^{n-1}", "_{i", "=", "0}", "a", "_i", "x", "^i"),
TextMobject("在$\\omega_n^0, \\omega_n^1, \\cdots, \\omega_n^{n-1}$处的值$y_0, y_1, \\cdots, y_{n-1}$").scale(0.9)
).arrange_submobjects(RIGHT)
defi[0][0].set_color(ORANGE)
defi[0][2].set_color(RED)
defi[0][7].set_color(BLUE)
defi[0][10].set_color(GREEN)
defi[0][11].set_color(BLUE)
defi[0][12].set_color(RED)
defi[0][13].set_color(BLUE)
defi.move_to([0, title.get_center()[1]-1.2, 0])
pos = defi[0].get_center()
defi[0].move_to(ORIGIN)
self.play(Write(defi[0]))
self.wait()
self.play(defi[0].move_to, pos, run_time=1.5)
self.wait(0.2)
self.play(Write(defi[1]))
self.wait(2)
dft = TexMobject("y_i=", "A", "(", "\\omega", "_n", "^i", ")", "=\\sum", "^{n-1}", "_{j", "=", "0}", "\\omega", "_n", "^{i", "j}", "a", "_j")
dft[1].set_color(ORANGE)
dft[3].set_color(RED)
dft[12].set_color(RED)
dft[4:6].set_color(GOLD)
dft[13].set_color(GOLD)
dft[15].set_color(GOLD)
dft[9].set_color(BLUE)
dft[14].set_color(BLUE)
dft[17].set_color(BLUE)
dft[16].set_color(GREEN)
dft.next_to(defi, DOWN)
pos2 = dft[:7].get_center()
dft[:7].move_to([0, pos2[1], 0])
self.play(Write(dft[:7]))
self.wait()
self.play(dft[:7].move_to, pos2, run_time=1.5)
self.wait()
self.play(Write(dft[7:]))
self.wait(2)
dft2 = VGroup(
TexMobject("\\boldsymbol{y}=\\text{DFT}", "_n", "(", "\\boldsymbol{a}", ")"),
TexMobject("\\boldsymbol{y}=", "\\mathcal{F}", "\\boldsymbol{a}")
).arrange_submobjects(RIGHT, buff=1).next_to(dft, DOWN, buff=0.8)
dft2[0][1].set_color(GOLD)
dft2[0][3].set_color(GREEN)
dft2[1][1].set_color(YELLOW)
dft2[1][2].set_color(GREEN)
pos3 = dft2[0].get_center()
dft2[0].move_to([0, pos3[1], 0])
self.play(Write(dft2[0]))
self.wait()
self.play(dft2[0].move_to, pos3, run_time=1.5)
self.wait()
self.play(Write(dft2[1]))
self.wait(3)
self.play(
dft.move_to, [-3.5, pos2[1], 0],
dft2.move_to, [3.5, pos2[1], 0],
run_time=2
)
O1 = TexMobject("O(n^2)").next_to(en_title, RIGHT).set_color(GOLD)
self.wait()
self.play(FadeInFrom(O1, RIGHT))
self.wait()
title2 = Text("快速傅里叶变换", font="Source Han Sans CN", t2c={"快速" : YELLOW,"傅里叶变换" : BLUE,})
title2.scale(0.6).move_to([-4.5, -1.5, 0])
en_title2 = TextMobject("F", "ast ", "{\\tiny discrete} ", "F", "ourier ", "T", "ransform").next_to(title2, RIGHT)
en_title2[0].set_color(YELLOW)
en_title2[2].set_color(YELLOW)
en_title2[3].set_color(BLUE)
en_title2[5].set_color(BLUE)
pos4 = en_title2[3:].get_center()
en_title2[3:].next_to(en_title2[1], RIGHT, aligned_edge=DOWN)
self.play(Write(title2))
self.wait()
self.play(DrawBorderThenFill(en_title2[:2]), DrawBorderThenFill(en_title2[3:]))
self.wait()
self.play(en_title2[3:].move_to, pos4)
self.wait()
self.play(TransformFromCopy(en_title[:2], en_title2[2]), run_time=1.5)
self.wait(3)
O2 = TexMobject("O(n\\log n)").next_to(en_title2, RIGHT).set_color(GOLD)
self.play(TransformFromCopy(O1, O2), run_time=1.5)
self.wait(3)
class FFT_part1(Scene):
def construct(self):
title2 = Text("快速傅里叶变换", font="Source Han Sans CN", t2c={"快速" : YELLOW,"傅里叶变换" : BLUE,})
title2.scale(0.6).move_to([-4.5, -1.5, 0])
old_title = Text("离散傅里叶变换", font="Source Han Sans CN", t2c={"离散" : YELLOW,"傅里叶变换" : BLUE,})
old_title.scale(0.6).move_to([-4.5, 3.3, 0])
en_title2 = TextMobject("F", "ast ", "{\\tiny discrete} ", "F", "ourier ", "T", "ransform").next_to(title2, RIGHT)
en_title2[0].set_color(YELLOW)
en_title2[2].set_color(YELLOW)
en_title2[3].set_color(BLUE)
en_title2[5].set_color(BLUE)
O2 = TexMobject("O(n\\log n)").next_to(en_title2, RIGHT).set_color(GOLD)
self.add(title2, en_title2, O2)
self.play(FadeOut(VGroup(O2, en_title2[2])))
en_title = TextMobject("F", "ast ", "F", "ourier ", "T", "ransform").next_to(old_title, RIGHT)
en_title[0].set_color(YELLOW)
en_title[2].set_color(BLUE)
en_title[4].set_color(BLUE)
self.play(
title2.move_to, [-4.5, 3.3, 0],
Transform(en_title2[0:2], en_title[0:2]),
Transform(en_title2[3:], en_title[2:])
)
self.wait(2)
title = title2
t2c = {
"A": ORANGE,
"x": RED,
"\\boldsymbol{a}": GREEN,
"a": GREEN,
"_0": BLUE,
"_1": BLUE,
"_2": BLUE,
"_3": BLUE,
"_4": BLUE,
"_5": BLUE,
"_{n-1}": BLUE,
"_{n-2}": BLUE,
"\\rightarrow": WHITE,
"^{[0]}": GOLD,
"^{[1]}": GOLD,
"^2": BLUE_A,
"^{n-1}": BLUE_A,
"^{\\frac{n}{2}-1}": BLUE_A
}
A = TexMobject("A", "(", "x", ")", "\\rightarrow", "\\boldsymbol{a}", "=[", "a", "_0", ",", "a", "_1", ",",\
"a", "_2", ",", "\\cdots", ",", "a", "_{n-1}", "]^\\top")
A.set_color_by_tex_to_color_map(t2c)
A.move_to([0, title.get_center()[1]-0.8, 0])
comment = Text("FFT的n应保证为2的幂", font="Source Han Serif CN").scale(0.2).set_color(GRAY).next_to(A, RIGHT, aligned_edge=DOWN)
a0 = TexMobject("\\boldsymbol{a}", "^{[0]}", "=[", "a", "_0", ",", "a", "_2", ",", "\\cdots", ",", "a", "_{n-2}", "]^\\top")
a0.set_color_by_tex_to_color_map(t2c)
a0.next_to(A[5], DOWN, aligned_edge=LEFT)
a1 = TexMobject("\\boldsymbol{a}", "^{[1]}", "=[", "a", "_1", ",", "a", "_3", ",", "\\cdots", ",", "a", "_{n-1}", "]^\\top")
a1.set_color_by_tex_to_color_map(t2c)
a1.next_to(a0, DOWN, aligned_edge=LEFT)
eve = Text("偶", font="Source Han Serif CN").scale(0.5).set_color(GOLD).next_to(a0, LEFT)
odd = Text("奇", font="Source Han Serif CN").scale(0.5).set_color(GOLD).next_to(a1, LEFT)
arrow0 = ArcBetweenPoints(A[0:4].get_bottom()+DOWN*0.1, eve.get_left()+LEFT*0.1).add_tip(0.2)
arrow1 = ArcBetweenPoints(A[0:4].get_bottom()+DOWN*0.1, odd.get_left()+LEFT*0.1).add_tip(0.2)
A0 = TexMobject("\\rightarrow", "A", "^{[0]}", "(", "x", ")").set_color_by_tex_to_color_map(t2c).next_to(a0, RIGHT).set_opacity(0.8)
A1 = TexMobject("\\rightarrow", "A", "^{[1]}", "(", "x", ")").set_color_by_tex_to_color_map(t2c).next_to(a1, RIGHT).set_opacity(0.8)
self.play(Write(A[:5]))
self.wait()
self.play(Write(A[5:]))
self.play(FadeInFromDown(comment))
self.wait(2)
self.play(
ShowCreation(arrow0),
| |
coverage = 1
try:
xs = re.sequni()
except self.mod.RE.InfiniteError:
print('Infinitely long args example for %s' % self.srcfullname)
print(
'Limiting by expanding each Cleene closure 0 up to %d times.' % coverage)
re = re.limited(coverage)
xs = re.sequni()
examples = [ArgsExample(self, tuple(
x), mapname, top_kind) for x in xs]
except CoverageError:
return []
else:
return examples
def get_args_for_args(self, args, match):
arglist = []
for a in self.find_arg_aspects():
t = a.d_tag
if t == 'arg':
name = a.get_name()
if name in match:
v = args.get_arg_value(match[name])
else:
ex = a.get_examples()
if not ex:
# I have been able to cause this to happen in test67.
self.error(
'Test coverage error: Can not create precondition for %r\n -- no examples specified for the argument above.' % args.mapping.tgtfullname,
a.src.node
)
v = ex[0]
arglist.append(v)
else:
assert 0
# raise ConditionError, 'Can not match this precondition'
return ArgsExample(self, tuple(arglist), args.mapname, args.top_kind)
def get_args_re(self, opt):
re = self.mod.RE.Epsilon
for a in self.find_arg_aspects():
re += a.get_re(opt)
return re
def get_arguments(self):
# Get the arguments subjects, for doc description purposes
return self.find_arg_aspects()
def get_return_kind(self):
return self.make_and_kind([x.get_kind() for x in self.find_aspects('returns')])
def get_return_test_kind(self):
return self.make_and_test_kind([x.get_test_kind() for x in self.find_aspects('returns')])
class ArgsExample:
def __init__(self, mapping, egs, mapname, top_kind):
self.mapping = mapping
self.egs = egs
self.mapname = mapname
self.top_kind = top_kind
self.negs = [mapname(x) for x in egs]
def __str__(self):
return ', '.join(self.negs)
def get_arg_value(self, name):
i = 0
for a in self.mapping.find_arg_aspects():
t = a.d_tag
if t == 'arg':
if a.get_name() == name:
return self.egs[i]
else:
raise ConditionError('No argument matches: %r' % name)
i += 1
def get_preconditions(self):
return self.mapping.find_aspects('precondition')
def get_postconditions(self):
return self.mapping.find_aspects('postcondition')
def get_setups_for_preconditions(self):
pres = self.get_preconditions()
if not pres:
return []
kind = self.top_kind
map = self.mapping
pres = map.find_aspects('precondition')
if pres:
for a in kind.find_aspects('attribute'):
for m in a.find_aspects('mapping'):
mpre = m.find_aspects('precondition')
if mpre:
continue
match = self.match_to(m.find_aspects('postcondition'))
if match is not None:
# found one
args = m.get_args_for_args(self, match)
return [SetUp(a.get_attr_name(), args)]
break
else:
continue
break
else:
# Caller will do error reporting
return None
return []
def match_to_kind(self, kind):
pass
def match_to(self, posts):
match = {}
for pre in self.get_preconditions():
for pos in posts:
if pos.cond_id == pre.cond_id:
if len(pos.arg_names) != len(pre.arg_names):
continue
upd = {}
for a, b in zip(pos.arg_names, pre.arg_names):
if a in match:
break
upd[a] = b
else:
match.update(upd)
break
else:
return None
assert ',' not in match
return match
class SetUp:
def __init__(self, name, args):
self.name = name
self.args = args
def get_name(self):
return self.name
def get_args(self):
return self.args
class Operator(Mapping):
d_is_def = 1
d_type = 'operator'
d_sub = ('arg', 'comment', 'description', 'description_with_header',
'equation',
'postcondition', 'precondition',
'self', 'returns', )
def get_op_name(self):
return self.src.node.arg.strip()
def resolve_special(self):
self.chk_num_args(1, 1)
class ReverseOperator(Operator):
pass
class FunctionOperator(Operator):
def resolve_special(self):
self.chk_num_args(0, 0)
class InplaceOperator(Operator):
pass
class SetItem(Mapping):
d_type = 'other'
d_sub = ('arg', 'comment', 'description', 'description_with_header',
'equation',
'postcondition', 'precondition',
'self')
def get_op_name(self):
return '[]'
def resolve_special(self):
self.chk_num_args(2, None)
class DelItem(SetItem):
def resolve_special(self):
self.chk_num_args(1, None)
class GetItem(SetItem):
d_sub = SetItem.d_sub + ('returns', )
def resolve_special(self):
self.chk_num_args(1, None)
class Condition(Description):
d_is_def = 1
d_sub = ('self', 'arg', 'comment', 'description', 'python_code')
def get_arg_names(self):
an = []
for a in self.find_aspects('*'):
if a.d_tag in ('self', 'arg'):
an.append(a.src.node.arg.strip())
return an
def get_def_name(self):
dn = self.src.lastname
return dn
def_name = property(get_def_name)
class PythonCode(Description):
d_sub = ('comment', 'description', 'in_context')
class ConditionRef(Description):
d_sub = ('comment', 'description',)
def __repr__(self):
try:
return self.cond_expr
except AttributeError:
return Description.__repr__(self)
def get_cond_id(self):
cond_id = self.cond_definition.tgtfullname
if self.is_not:
cond_id = 'not ' + cond_id
self.cond_id = cond_id
return cond_id
cond_id = property_nondata(get_cond_id)
def get_definition(self):
return self.cond_definition
def resolve_special(self):
cond_def = self.src.cond_definition
self.cond_definition = self.env.get_descr_by_subject(cond_def)
self.cond_doc_name = cond_def.parent.lastname + '.' + cond_def.lastname
self.cond_expr = self.src.node.arg.strip() # Mostly for information
self.arg_names = self.src.arg_names
self.is_not = self.src.is_not
class Precondition(ConditionRef):
#doc_name = 'Before'
doc_name = 'Precondition'
class Postcondition(ConditionRef):
#doc_name = 'After'
doc_name = 'Postcondition'
class PostcondCase:
# Postcondition with specific variables
def __init__(postcond, variables):
self.postcond = postcond
self.variables = variables
class Constructor(Description):
d_type = 'with_args'
d_sub = ('comment', 'description',)
class Equation(Description):
d_sub = ('comment', 'description', 'precondition', 'postcondition')
class Args(Description):
d_type = 'with_args'
d_sub = ('comment', 'description', 'optionals', )
def get_re(self, opt):
re = self.mod.RE.Epsilon
for a in self.find_arg_aspects():
re += a.get_re(opt)
return re
class NoArg(Description):
def get_re(self, opt):
return self.mod.RE.Epsilon
class Arg(Description):
d_sub = ('comment', 'default', 'description', 'superkind_of', 'name', )
def get_kind(self):
return self.make_or_kind(self.find_kind_aspects())
def get_name(self):
try:
return self.get_arg_name()
except AttributeError:
return '?'
def get_arg_name(self):
return self.src.specified_name
def get_examples(self, get_all=False):
examples = []
exs = self.find_aspects('example')
for ex in exs:
examples.extend(ex.get_examples())
if not exs or get_all:
k = self.get_kind()
examples.extend(k.get_examples())
return examples
class KeyArgEG:
def __init__(self, name, eg):
self.name = name
self.eg = eg
def get_ex_text(self):
return self.eg.get_ex_text()
def get_ctx_text(self):
return self.eg.get_ctx_text()
def get_use_text(self, x):
return '%s=%s' % (self.name, x)
class KeyArg(Arg):
# Spec with keyarg means it is:
# NOT to be used as positional argument
# ONLY as keyword argument
def get_examples(self, get_all=False):
name = self.get_arg_name()
return [KeyArgEG(name, eg) for eg in Arg.get_examples(self, get_all)]
class Draw(Description):
d_sub = ('comment', 'description', 'key_arg', 'seq', )
def get_re(self, opt):
re = self.mod.RE.Epsilon
for a in self.find_arg_aspects():
re += a.get_re(opt)('?')
return re
class Optionals(Description):
d_sub = ('arg', 'args', 'key_arg', 'comment', 'seq', )
d_type = 'with_args'
def get_re(self, opt):
def opt_ra(aspects):
if not aspects:
return self.mod.RE.Epsilon
return (aspects[0].get_re(opt) + opt_ra(aspects[1:]))('?')
return opt_ra(self.find_arg_aspects())
class Repeat(Description):
d_sub = ('alt', 'arg', 'args', 'comment', 'description')
def get_arg(self):
return self.src.node.arg.strip()
def get_re(self, opt):
asp = self.find_arg_aspects()
if not asp:
self.error('No argument aspects.', self.src.node)
re = asp[0].get_re(opt)
for a in asp[1:]:
re += a.get_re(opt)
arg = self.get_arg()
sep = '..'
if sep in arg:
args = arg.split(sep)
if len(args) != 2:
self.error('More than one %r in argument.' %
sep, self.src.node)
lo, hi = [x.strip() for x in args]
try:
lo = int(lo)
except ValueError:
self.error('Expected int in lower bound.', self.src.node)
if hi != '*':
try:
hi = int(hi)
except ValueError:
self.error('Expected int or * in upper bound.',
self.src.node)
else:
try:
lo = int(arg)
except ValueError:
self.error(
'Expected int, int..int or int..* in argument.', self.src.node)
hi = lo
if lo < 0 or (hi != '*' and hi < 0):
self.error('Expected non-negative repetition count.',
self.src.node)
if hi == '*':
res = re('*')
for i in range(lo):
res = re + res
else:
if hi < lo:
self.error('Expected upper bound >= lower bound.',
self.src.node)
a = self.mod.RE.Epsilon
for i in range(lo):
a += re
b = self.mod.RE.Epsilon
for i in range(lo, hi):
b = (re + b)('?')
res = a + b
return res
class Seq(Description):
d_sub = ('arg', 'comment', 'description', 'optionals',)
d_sub += ('key_arg', ) # May perhaps be optionally disabled
d_type = 'with_args'
def get_re(self, opt):
re = self.mod.RE.Epsilon
for a in self.find_arg_aspects():
re += a.get_re(opt)
return re
class Alt(Description):
d_sub = ('arg', 'comment', 'descripton', 'key_arg', 'no_arg', 'seq', )
d_type = 'with_args'
def get_re(self, opt):
asp = self.find_arg_aspects()
if not asp:
self.error('No alternatives.', self.src.node)
re = asp[0].get_re(opt)
for a in asp[1:]:
re |= a.get_re(opt)
return re
class Returns(Description):
d_sub = ('attribute', 'comment', 'description', 'description_with_header',
'either', 'mapping', 'method')
d_type = 'with_opt_args'
def get_kind(self):
return self.make_and_kind(self.find_kind_aspects())
def get_test_kind(self):
return self.make_and_test_kind(self.find_kind_aspects())
# help functions
def find_aspects_inseq(seq, tag):
as_ = []
for o in seq:
as_.extend(o.find_aspects(tag))
return as_
# Beam base class
class Beam:
def __init__(self, k_tag, *objects):
self.src = objects[0]
self.tgt = objects[-1]
self.k_tag = k_tag
self.objects = objects
def __add__(self, other):
return compose(self, other)
class KindBeam(Beam):
pass
class AtomKindBeam(Beam):
pass
class KindMappingBeam(Beam):
pass
class KindOpBeam(Beam):
op_index = 1
op_name_index = 1
def find_equations(self):
return find_aspects_inseq(self.get_op_seq(), 'equation')
def find_postconditions(self):
return find_aspects_inseq(self.get_op_seq(), 'postcondition')
def find_preconditions(self):
return find_aspects_inseq(self.get_op_seq(), 'precondition')
def get_args_examples(self, mapname):
top_kind = self.objects[0]
return self.get_the_op().get_args_examples(mapname, top_kind)
def get_op_id_name(self):
return self.objects[self.op_name_index].get_id_name()
def get_op_name(self):
return self.objects[self.op_name_index].get_op_name()
def get_op_seq(self):
return self.objects[self.op_index:]
def get_self_name(self):
return self.get_the_op().get_self_name()
def get_the_op(self):
return self.objects[self.op_index]
def get_return_test_kind(self):
return self.get_the_op().get_return_test_kind()
class KindAttributeBeam(KindOpBeam):
def get_the_op(self):
assert 0
class KindAttributeMappingBeam(KindOpBeam):
op_index = 2
class KindMappingBeam(KindOpBeam):
def get_op_name(self):
return '()'
class KOKOpBeam(KindOpBeam):
op_index = 2
op_name_index = 2
def subkind_of_kind(*objects):
return beam(*objects[2:])
def compose(a, b):
if a.tgt is not b.src:
raise "Composition error, tgt %r is not src %r" % (a.tgt, b.src)
objects = a.objects + b.objects[1:]
return beam(*objects)
def remove_1_2(k_tag, *objects):
return beam(objects[0], *objects[3:])
def remove_0(k_tag, *objects):
return beam(*objects[1:])
beam_table = {
('attribute', 'attribute'): Beam,
| |
update(self, emitted):
round_dec = 6
# drawing the individual signals
if not pause:
x_index = emitted[-1]
# round is crucial here since int will make 199.99 as 199. Want to remove round off errors by rounding
# to the nearest
x_index_wrapped = wrap_around(x_index, round(self.max_t / self.dt))
if debug:
print('****** emitted ', emitted)
print('x_index ', x_index)
print('x wrapped ', x_index_wrapped)
if x_index == self.frame_size - 1:
self.frame_count += 1
if self.debug is True:
write_csv_array = [emitted[0].real, emitted[0].imag, x_index, x_index_wrapped]
write_csv_dict = {'real val': write_csv_array[0],
'imag val': write_csv_array[1],
'x index': write_csv_array[2],
'x wrapped index': write_csv_array[3],
'plot name': self.plot_name,
'frame': self.frame_count}
print('csv array', write_csv_array)
exists = os.path.exists(results_file_path)
if exists:
with open(results_file_path, 'a', newline="") as f:
w = csv.DictWriter(f, write_csv_dict.keys())
w.writerow(write_csv_dict)
else:
with open(results_file_path, 'w', newline="") as f:
w = csv.DictWriter(f, write_csv_dict.keys())
w.writeheader()
w.writerow(write_csv_dict)
# strip off index since it's been saved
emitted = emitted[:-1]
# round is necessary to insure round off errors don't impact the synced updates between rect plots
if self.t_data.size == 0:
last_t = 0
else:
last_t = round(self.t_data[-1], round_dec)
if continuous:
# this is not used at all, probably delete
if self.t_data.size == 0:
if last_t > self.max_t:
self.ax_r.set_xlim(last_t - self.max_t, last_t)
else:
if last_t > self.t_data[0] + self.max_t:
self.ax_r.set_xlim(last_t - self.max_t, last_t)
else:
# frozen frame but keeps drawing on the same frame
# round is necessary to insure round off errors don't impact the synced updates between rect plots
round_nearest_max_t = round(self.max_t - self.dt, round_dec)
if debug:
print('self dt is', self.dt)
print('last_t is ', last_t)
print('max_t is ', self.max_t)
print('round_nearest_max_t is ', round_nearest_max_t)
if last_t >= round_nearest_max_t:
if debug:
print('End of x axis. Zeroing x and y axis data')
# print('last_t is ', last_t)
# print('round_nearest_max_t is ', round_nearest_max_t)
self.t_data = np.empty(0)
self.y_data_cmbd = [[], []]
self.y_data_curr_pt = [0, 0]
if debug:
print('t_data ', self.t_data)
print('y_data_cmbd_0', self.y_data_cmbd[0])
if x_index_wrapped == 0:
# reset t_data once one cycle (2pi rotation) is completed
self.t_data = np.empty(0)
# reinitialize y_data_cmbd to start clean slate if x_index is zero
self.y_data_cmbd[0] = []
self.y_data_cmbd[1] = []
# reinitialize y_data_cmbd to start clean slate if x_index is zero
self.y_data = []
for _ in range(self.num_sigs):
self.y_data.append([[], []])
self.t_data = (np.append(self.t_data, x_index_wrapped * self.dt))
for emitted_sig, sig_line_r, y_data_1 in zip(emitted, self.sig_lines_r, self.y_data):
y_data_1[0].append(emitted_sig.real)
y_data_1[1].append(emitted_sig.imag)
# these will show the individual line imag and real parts of each signal in rotating_phasors
# these are usually commented out to avoid clutter
# sig_line_r[0].set_data(self.t_data, y_data_1[0])
# sig_line_r[1].set_data(self.t_data, y_data_1[1])
# combined output drawing
curr_pt_real = sum(emitted).real
curr_pt_imag = sum(emitted).imag
self.y_data_cmbd[0].append(curr_pt_real)
self.y_data_cmbd[1].append(curr_pt_imag)
self.y_data_curr_pt[0] = curr_pt_real
self.y_data_curr_pt[1] = curr_pt_imag
y_low, y_high = self.ax_r.get_ylim()
if len(self.legend_list) == 1:
max_pt = self.y_data_cmbd[0][-1]
min_pt = self.y_data_cmbd[0][-1]
else:
max_pt = max(self.y_data_cmbd[0][-1], self.y_data_cmbd[1][-1])
min_pt = min(self.y_data_cmbd[0][-1], self.y_data_cmbd[1][-1])
if max_pt >= y_high:
self.ax_r.set_ylim(y_low, max_pt + 10)
if min_pt <= y_low:
self.ax_r.set_ylim(min_pt - 10, y_high)
# this will draw the final combined output of the signals in rotating_phasors
if len(self.legend_list) == 1:
# only 1 line will be drawn, it'll be either mag or phase
self.sig_lines_r_cmbd[0].set_data(self.t_data / 1, self.y_data_cmbd[0])
else:
# two lines will be drawn, it's real projection and imag projection
self.sig_lines_r_cmbd[0].set_data(self.t_data / 1, self.y_data_cmbd[0])
self.sig_lines_r_cmbd[1].set_data(self.t_data / 1, self.y_data_cmbd[1])
# print('t_data')
# print(self.t_data)
# print('data0')
# print(self.y_data_cmbd[0])
# print('data1')
# print(self.y_data_cmbd[1])
# this will draw the current point of final combined output of the signals in rotating_phasors
if len(self.legend_list) == 1:
self.sig_lines_r_curr_pt[0].set_data(self.t_data[-1], self.y_data_curr_pt[0])
else:
self.sig_lines_r_curr_pt[0].set_data(self.t_data[-1], self.y_data_curr_pt[0])
self.sig_lines_r_curr_pt[1].set_data(self.t_data[-1], self.y_data_curr_pt[1])
self.time_text.set_text(int(x_index_wrapped))
# print(list(list_acs.list_acs.flatten_list_list(self.sig_lines_r)))
return list(
list_acs.flatten_list(
self.sig_lines_r + self.sig_lines_r_cmbd + self.sig_lines_r_curr_pt + [self.time_text]))
class ScopePolarCmbd:
def __init__(self, ax, num_sigs):
self.ax_p = ax
if self.ax_p.name == 'polar':
self.polar_plot = True
else:
self.polar_plot = False
self.ax_p.grid(True)
self.ax_p.set_aspect('equal', adjustable='box')
self.mag_accu = []
self.theta_accu = []
self.sig_lines_p = []
self.mag_accu_cmbd = []
self.theta_accu_cmbd = []
# data lines for drawing the phasor, edge tracing, real and image projection for each item in rotating_phasors
for _ in range(num_sigs):
self.sig_lines_p.append(
[self.ax_p.plot([], [], fstr, linewidth=lw)[0] for _, fstr, lw in
zip(range(4), ['-', '-', '-', '-'], [3, 1.5, 1.5, 1.5])])
self.mag_accu.append([0])
self.theta_accu.append([0])
# data lines for drawing the combined phasor, edge tracing, real and image projection
# or each item in rotating_phasors
self.sig_lines_p_cmbd = [self.ax_p.plot([], [], fstr, linewidth=lw)[0] for _, fstr, lw in
zip(range(4), ['g-', '-', 'r-', 'b-'], [3, 1.5, 1.5, 1.5])]
self.prev_end_pts = 0 + 0j
# adding legend
self.sig_lines_p_cmbd[0].set_label('Mag')
self.sig_lines_p_cmbd[2].set_label('I')
self.sig_lines_p_cmbd[3].set_label('Q')
if self.polar_plot:
self.ax_p.legend(bbox_to_anchor=(1.3, 1.3), loc="upper right")
else:
# self.ax_p.legend()
self.ax_p.legend(bbox_to_anchor=(2.3, 1), loc="upper right")
# self.ax_p.set_title('Rotating Phasors in Polar Plot')
if self.polar_plot:
self.ax_p.set_rmax(max_mag + 2)
else:
min_xy = round(-max_mag - 1)
max_xy = round(max_mag + 1)
self.ax_p.set_xlim(min_xy, max_xy)
self.ax_p.set_ylim(min_xy, max_xy)
#
# self.ax_p.set_xticks(np.arange(min_xy, max_xy, step=round((max_xy-min_xy)/5)))
# self.ax_p.set_yticks(np.arange(min_xy, max_xy, step=round((max_xy-min_xy)/5)))
pass
self.one_cycle_index = Fs / f1
def update(self, emitted):
# drawing the individual signals
self.prev_end_pts = 0 + 0j
emitted_list = []
if not pause:
x_index = emitted[-1]
x_index_wrapped = wrap_around(x_index, self.one_cycle_index)
# strip off index, don't need it here
emitted = emitted[:-1]
for emitted_sig, sig_line_p, mag_accu, theta_accu in zip(emitted, self.sig_lines_p, self.mag_accu,
self.theta_accu):
emitted_list.append(emitted_sig)
if spin_orig_center:
mag, theta = cm.polar(emitted_sig)
else:
mag, theta = cm.polar(sum(emitted_list))
# print(theta)
if x_index_wrapped == 0:
mag_accu = []
theta_accu = []
mag_accu.append(mag)
theta_accu.append(theta)
cmplx = cm.rect(mag, theta)
x = cmplx.real
y = cmplx.imag
mag_x, theta_x = cm.polar(complex(x, 0))
mag_y, theta_y = cm.polar(complex(0, y))
mag_pep, theta_pep = cm.polar(self.prev_end_pts)
# rotating phasor
if self.polar_plot:
sig_line_p[0].set_data([theta_pep, theta], [mag_pep, mag])
else:
rect_pep = cm.rect(mag_pep, theta_pep)
rect = cm.rect(mag, theta)
sig_line_p[0].set_data([rect_pep.real, rect.real], [rect_pep.imag, rect.imag])
# phasor edge tracing
# usually commented out to avoid clutter
# sig_line_p[1].set_data(theta_accu, mag_accu)
# these will draw the real and imag component of each signal in rotating_phasors on the polar plot
# usually commented out to avoid clutter
# # projection to real tracing
# sig_line_p[2].set_data([theta_x, theta_x], [0, mag_x])
# # projection to imag tracing
# sig_line_p[3].set_data([theta_y, theta_y], [0, mag_y])
if not spin_orig_center:
self.prev_end_pts = cm.rect(mag, theta)
# drawing of combined output
mag, theta = cm.polar(sum(emitted))
if x_index_wrapped == 0:
self.mag_accu_cmbd = []
self.theta_accu_cmbd = []
self.mag_accu_cmbd.append(mag)
self.theta_accu_cmbd.append(theta)
# adjust polar r limit
if self.polar_plot:
if mag >= self.ax_p.get_rmax():
self.ax_p.set_rmax(mag + 1)
else:
if mag >= self.ax_p.get_xlim()[1] or mag >= self.ax_p.get_ylim()[1]:
self.ax_p.set_xlim(round(-mag - 2), round(mag + 2))
self.ax_p.set_ylim(round(-mag - 2), round(mag + 2))
cmplx = cm.rect(mag, theta)
x = cmplx.real
y = cmplx.imag
# print(cmplx)
mag_x, theta_x = cm.polar(complex(x, 0))
mag_y, theta_y = cm.polar(complex(0, y))
if self.polar_plot:
# rotating phasor
self.sig_lines_p_cmbd[0].set_data([theta, theta], [0, mag])
# # phasor edge tracing
self.sig_lines_p_cmbd[1].set_data(self.theta_accu_cmbd, self.mag_accu_cmbd)
#
# # # projection to real tracing
self.sig_lines_p_cmbd[2].set_data([theta_x, theta_x], [0, mag_x])
# # # projection to imag tracing
self.sig_lines_p_cmbd[3].set_data([theta_y, theta_y], [0, mag_y])
else:
# rect_pep = cm.rect(mag, theta)
rect = cm.rect(mag, theta)
self.sig_lines_p_cmbd[0].set_data([0, rect.real], [0, rect.imag])
theta_accu_cmbd = np.array(self.theta_accu_cmbd)
mag_accu_cmbd = np.array(self.mag_accu_cmbd)
x1 = mag_accu_cmbd * np.cos(theta_accu_cmbd)
y1 = mag_accu_cmbd * np.sin(theta_accu_cmbd)
self.sig_lines_p_cmbd[1].set_data(x1, y1)
self.sig_lines_p_cmbd[2].set_data([0, x], [0, 0])
self.sig_lines_p_cmbd[3].set_data([0, 0], [0, y])
# plt.draw()
return list(list_acs.flatten_list(self.sig_lines_p + self.sig_lines_p_cmbd))
class Scope:
def __init__(self, num_sigs, max_t=1 * fund_period, dt=Ts):
self.rect_time = ScopeRectCmbd(ax_rect_cmbd, num_sigs, ['Real', 'Imag'],
['Time [xE{} sec]'.format(round(Ts_pow10)), 'Amp [V]'],
max_t / 10 ** Ts_pow10,
dt / 10 ** Ts_pow10, plot_name='IQ_rect')
self.pol1 = ScopePolarCmbd(ax_polar_cmbd, num_sigs)
self.rect_mag = ScopeRectCmbd(ax_rect_mag, num_sigs, ['Magnitude'], ['Freq', 'Amp [dB]'], max_t * w0,
dt * w0, plot_name='Mag_rect')
self.rect_phase = ScopeRectCmbd(ax_rect_phase, num_sigs, ['Phase'], ['Freq', 'Phase [Deg]'], max_t * w0,
dt * w0, plot_name='Phase_rect')
def update(self, emitted):
if not pause:
x_index = emitted[-1]
else:
x_index = 1
lines_time = self.rect_time.update(emitted)
polars = self.pol1.update(emitted)
mag, phase = cm.polar(sum(emitted[:-1]))
phase = np.rad2deg(phase)
if mag < 0.001:
lines_mag = self.rect_mag.update([20 * np.log10(0.001), x_index])
lines_phase = self.rect_phase.update([phase, x_index])
else:
lines_mag = self.rect_mag.update([20 * np.log10(mag), x_index])
lines_phase = self.rect_phase.update([phase, x_index])
# lines_mag = self.rect_mag.update(emitted)
# lines_phase = self.rect_phase.update(emitted)
# return list(list_acs.flatten_list(polars + lines_mag + lines_phase))
return list(list_acs.flatten_list(lines_time + polars + lines_mag + lines_phase))
# return list(list_acs.flatten_list(lines_time + polars))
def sig_emitter():
i = 0
curr_phasor_values = []
while i < x_t.size:
# print('i is ', i)
if not pause:
curr_phasor_values.clear()
for phasor in rotating_phasors:
curr_phasor_values.append(phasor[i])
curr_phasor_values.append(i)
i = i + 1
yield curr_phasor_values
def onClick(event):
global pause
pause | |
r"""
Base class for polyhedra
"""
# ****************************************************************************
# Copyright (C) 2008 <NAME> <<EMAIL>>
# Copyright (C) 2011 <NAME> <<EMAIL>>
# Copyright (C) 2015 <NAME> <labbe at math.huji.ac.il>
# Copyright (C) 2020 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import division, print_function, absolute_import
import itertools
from sage.structure.element import Element, coerce_binop, is_Vector, is_Matrix
from sage.structure.richcmp import rich_to_bool, op_NE
from sage.cpython.string import bytes_to_str
from sage.misc.all import cached_method, prod
from sage.misc.randstate import current_randstate
from sage.misc.superseded import deprecated_function_alias
from sage.rings.all import QQ, ZZ, AA
from sage.rings.real_double import RDF
from sage.modules.free_module_element import vector
from sage.modules.vector_space_morphism import linear_transformation
from sage.matrix.constructor import matrix
from sage.functions.other import sqrt, floor, ceil
from sage.groups.matrix_gps.finitely_generated import MatrixGroup
from sage.graphs.graph import Graph
from .constructor import Polyhedron
from sage.categories.sets_cat import EmptySetError
#########################################################################
# Notes if you want to implement your own backend:
#
# * derive from Polyhedron_base
#
# * you must implement _init_from_Vrepresentation and
# _init_from_Hrepresentation
#
# * You might want to override _init_empty_polyhedron
#
# * You may implement _init_from_Vrepresentation_and_Hrepresentation
#
# * You can of course also override any other method for which you
# have a faster implementation.
#########################################################################
#########################################################################
def is_Polyhedron(X):
"""
Test whether ``X`` is a Polyhedron.
INPUT:
- ``X`` -- anything.
OUTPUT:
Boolean.
EXAMPLES::
sage: p = polytopes.hypercube(2)
sage: from sage.geometry.polyhedron.base import is_Polyhedron
sage: is_Polyhedron(p)
True
sage: is_Polyhedron(123456)
False
"""
return isinstance(X, Polyhedron_base)
#########################################################################
class Polyhedron_base(Element):
"""
Base class for Polyhedron objects
INPUT:
- ``parent`` -- the parent, an instance of
:class:`~sage.geometry.polyhedron.parent.Polyhedra`.
- ``Vrep`` -- a list ``[vertices, rays, lines]`` or ``None``. The
V-representation of the polyhedron. If ``None``, the polyhedron
is determined by the H-representation.
- ``Hrep`` -- a list ``[ieqs, eqns]`` or ``None``. The
H-representation of the polyhedron. If ``None``, the polyhedron
is determined by the V-representation.
- ``Vrep_minimal`` (optional) -- see below
- ``Hrep_minimal`` (optional) -- see below
- ``pref_rep`` -- string (default: ``None``);
one of``Vrep`` or ``Hrep`` to pick this in case the backend
cannot initialize from complete double description
If both ``Vrep`` and ``Hrep`` are provided, then
``Vrep_minimal`` and ``Hrep_minimal`` must be set to ``True``.
TESTS::
sage: p = Polyhedron()
sage: TestSuite(p).run()
::
sage: p = Polyhedron(vertices=[(1,0), (0,1)], rays=[(1,1)], base_ring=ZZ)
sage: TestSuite(p).run()
::
sage: p=polytopes.flow_polytope(digraphs.DeBruijn(3,2))
sage: TestSuite(p).run()
::
sage: TestSuite(Polyhedron([[]])).run()
sage: TestSuite(Polyhedron([[0]])).run()
::
sage: P = polytopes.permutahedron(3) * Polyhedron(rays=[[0,0,1],[0,1,1],[1,2,3]])
sage: TestSuite(P).run()
::
sage: P = polytopes.permutahedron(3)*Polyhedron(rays=[[0,0,1],[0,1,1]], lines=[[1,0,0]])
sage: TestSuite(P).run()
"""
def __init__(self, parent, Vrep, Hrep, Vrep_minimal=None, Hrep_minimal=None, pref_rep=None, **kwds):
"""
Initializes the polyhedron.
See :class:`Polyhedron_base` for a description of the input
data.
TESTS::
sage: p = Polyhedron() # indirect doctests
sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field
sage: from sage.geometry.polyhedron.parent import Polyhedra_field
sage: parent = Polyhedra_field(AA, 1, 'field')
sage: Vrep = [[[0], [1/2], [1]], [], []]
sage: Hrep = [[[0, 1], [1, -1]], []]
sage: p = Polyhedron_field(parent, Vrep, Hrep,
....: Vrep_minimal=False, Hrep_minimal=True)
Traceback (most recent call last):
...
ValueError: if both Vrep and Hrep are provided, they must be minimal...
Illustration of ``pref_rep``.
Note that ``ppl`` doesn't support precomputed data::
sage: from sage.geometry.polyhedron.backend_ppl import Polyhedron_QQ_ppl
sage: from sage.geometry.polyhedron.parent import Polyhedra_QQ_ppl
sage: parent = Polyhedra_QQ_ppl(QQ, 1, 'ppl')
sage: p = Polyhedron_QQ_ppl(parent, Vrep, 'nonsense',
....: Vrep_minimal=True, Hrep_minimal=True, pref_rep='Vrep')
sage: p = Polyhedron_QQ_ppl(parent, 'nonsense', Hrep,
....: Vrep_minimal=True, Hrep_minimal=True, pref_rep='Hrep')
sage: p = Polyhedron_QQ_ppl(parent, 'nonsense', Hrep,
....: Vrep_minimal=True, Hrep_minimal=True, pref_rep='Vrepresentation')
Traceback (most recent call last):
...
ValueError: ``pref_rep`` must be one of ``(None, 'Vrep', 'Hrep')``
If the backend supports precomputed data, ``pref_rep`` is ignored::
sage: p = Polyhedron_field(parent, Vrep, 'nonsense', # py3
....: Vrep_minimal=True, Hrep_minimal=True, pref_rep='Vrep')
Traceback (most recent call last):
...
TypeError: _init_Hrepresentation() takes 3 positional arguments but 9 were given
sage: p = Polyhedron_field(parent, Vrep, 'nonsense', # py2
....: Vrep_minimal=True, Hrep_minimal=True, pref_rep='Vrep')
Traceback (most recent call last):
...
TypeError: _init_Hrepresentation() takes exactly 3 arguments (9 given)
The empty polyhedron is detected when the Vrepresentation is given with generator;
see :trac:`29899`::
sage: from sage.geometry.polyhedron.backend_cdd import Polyhedron_QQ_cdd
sage: from sage.geometry.polyhedron.parent import Polyhedra_QQ_cdd
sage: parent = Polyhedra_QQ_cdd(QQ, 0, 'cdd')
sage: p = Polyhedron_QQ_cdd(parent, [iter([]), iter([]), iter([])], None)
"""
Element.__init__(self, parent=parent)
if Vrep is not None and Hrep is not None:
if not (Vrep_minimal is True and Hrep_minimal is True):
raise ValueError("if both Vrep and Hrep are provided, they must be minimal"
" and Vrep_minimal and Hrep_minimal must both be True")
if hasattr(self, "_init_from_Vrepresentation_and_Hrepresentation"):
self._init_from_Vrepresentation_and_Hrepresentation(Vrep, Hrep)
return
else:
if pref_rep is None:
# Initialize from Hrepresentation if this seems simpler.
Vrep = [tuple(Vrep[0]), tuple(Vrep[1]), Vrep[2]]
Hrep = [tuple(Hrep[0]), Hrep[1]]
if len(Hrep[0]) < len(Vrep[0]) + len(Vrep[1]):
pref_rep = 'Hrep'
else:
pref_rep = 'Vrep'
if pref_rep == 'Vrep':
Hrep = None
elif pref_rep == 'Hrep':
Vrep = None
else:
raise ValueError("``pref_rep`` must be one of ``(None, 'Vrep', 'Hrep')``")
if Vrep is not None:
vertices, rays, lines = Vrep
# We build tuples out of generators now to detect the empty polyhedron.
# The damage is limited:
# The backend will have to obtain all elements from the generator anyway.
# The generators are mainly for saving time with initializing from
# Vrepresentation and Hrepresentation.
# If we dispose of one of them (see above), it is wasteful to have generated it.
# E.g. the dilate will be set up with new Vrepresentation and Hrepresentation
# regardless of the backend along with the argument ``pref_rep``.
# As we only use generators, there is no penalty to this approach
# (and the method ``dilation`` does not have to distinguish by backend).
if not isinstance(vertices, (tuple, list)):
vertices = tuple(vertices)
if not isinstance(rays, (tuple, list)):
rays = tuple(rays)
if not isinstance(lines, (tuple, list)):
lines = tuple(lines)
if vertices or rays or lines:
self._init_from_Vrepresentation(vertices, rays, lines, **kwds)
else:
self._init_empty_polyhedron()
elif Hrep is not None:
ieqs, eqns = Hrep
self._init_from_Hrepresentation(ieqs, eqns, **kwds)
else:
self._init_empty_polyhedron()
def __hash__(self):
r"""
TESTS::
sage: K.<a> = QuadraticField(2)
sage: p = Polyhedron(vertices=[(0,1,a),(3,a,5)],
....: rays=[(a,2,3), (0,0,1)],
....: base_ring=K)
sage: q = Polyhedron(vertices=[(3,a,5),(0,1,a)],
....: rays=[(0,0,1), (a,2,3)],
....: base_ring=K)
sage: hash(p) == hash(q)
True
"""
# TODO: find something better *but* fast
return hash((self.dim(),
self.ambient_dim(),
self.n_Hrepresentation(),
self.n_Vrepresentation(),
self.n_equations(),
self.n_facets(),
self.n_inequalities(),
self.n_lines(),
self.n_rays(),
self.n_vertices()))
def _sage_input_(self, sib, coerced):
"""
Return Sage command to reconstruct ``self``.
See :mod:`sage.misc.sage_input` for details.
.. TODO::
Add the option ``preparse`` to the method.
EXAMPLES::
sage: P = Polyhedron(vertices = [[1, 0], [0, 1]], rays = [[1, 1]], backend='ppl')
sage: sage_input(P)
Polyhedron(backend='ppl', base_ring=QQ, rays=[(QQ(1), QQ(1))], vertices=[(QQ(0), QQ(1)), (QQ(1), QQ(0))])
sage: P = Polyhedron(vertices = [[1, 0], [0, 1]], rays = [[1, 1]], backend='normaliz') # optional - pynormaliz
sage: sage_input(P) # optional - pynormaliz
Polyhedron(backend='normaliz', base_ring=QQ, rays=[(QQ(1), QQ(1))], vertices=[(QQ(0), QQ(1)), (QQ(1), QQ(0))])
sage: P = Polyhedron(vertices = [[1, 0], [0, 1]], rays = [[1, 1]], backend='polymake') # optional - polymake
sage: sage_input(P) # optional - polymake
Polyhedron(backend='polymake', base_ring=QQ, rays=[(QQ(1), QQ(1))], vertices=[(QQ(1), QQ(0)), (QQ(0), QQ(1))])
"""
kwds = dict()
kwds['base_ring'] = sib(self.base_ring())
kwds['backend'] = sib(self.backend())
if self.n_vertices() > 0:
kwds['vertices'] = [sib(tuple(v)) for v in self.vertices()]
if self.n_rays() > 0:
kwds['rays'] = [sib(tuple(r)) for r in self.rays()]
if self.n_lines() > 0:
kwds['lines'] = [sib(tuple(l)) for l in self.lines()]
return sib.name('Polyhedron')(**kwds)
def _init_from_Vrepresentation(self, vertices, rays, lines, **kwds):
"""
Construct polyhedron from V-representation data.
INPUT:
- ``vertices`` -- list of point. Each point can be specified
as any iterable container of
:meth:`~sage.geometry.polyhedron.base.base_ring` elements.
- ``rays`` -- list of rays. Each ray can be specified as any
iterable container of
:meth:`~sage.geometry.polyhedron.base.base_ring` elements.
- ``lines`` -- list of lines. Each line can be specified as
any iterable container of
:meth:`~sage.geometry.polyhedron.base.base_ring` elements.
EXAMPLES::
sage: p = Polyhedron()
sage: from sage.geometry.polyhedron.base import Polyhedron_base
sage: Polyhedron_base._init_from_Vrepresentation(p, [], [], [])
Traceback (most recent call last):
...
NotImplementedError: a derived class must implement this method
"""
raise NotImplementedError('a derived class must implement this method')
def _init_from_Hrepresentation(self, ieqs, eqns, **kwds):
"""
Construct polyhedron from H-representation data.
INPUT:
- ``ieqs`` -- list of inequalities. Each line can be specified
as any iterable container of
:meth:`~sage.geometry.polyhedron.base.base_ring` elements.
- ``eqns`` -- list of equalities. Each line can be specified
as any iterable container of
:meth:`~sage.geometry.polyhedron.base.base_ring` elements.
EXAMPLES::
sage: | |
# -*- coding: utf-8 -*-
# (C) 2016 <NAME>
#
data = {
u"\u0b83": 11172,
u"\u0b85": 73738,
u"\u0b86": 32690,
u"\u0b87": 61948,
u"\u0b88": 4622,
u"\u0b89": 35756,
u"\u0b8a": 4101,
u"\u0b8e": 35429,
u"\u0b8f": 9073,
u"\u0b90": 4730,
u"\u0b92": 14445,
u"\u0b93": 5639,
u"\u0b94": 171,
u"\u0b95": 369818,
u"\u0b95\u0bbe": 74087,
u"\u0b95\u0bbf": 77496,
u"\u0b95\u0bc0": 0,
u"\u0b95\u0bc1": 141950,
u"\u0b95\u0bc2": 14867,
u"\u0b95\u0bc6": 6282,
u"\u0b95\u0bc7": 11570,
u"\u0b95\u0bc8": 21961,
u"\u0b95\u0bca": 23528,
u"\u0b95\u0bcb": 0,
u"\u0b95\u0bcc": 0,
u"\u0b95\u0bcd": 261963,
u"\u0b95\u0bcd\u0bb7": 0,
u"\u0b95\u0bcd\u0bb7\u0bbe": 0,
u"\u0b95\u0bcd\u0bb7\u0bbf": 0,
u"\u0b95\u0bcd\u0bb7\u0bc0": 0,
u"\u0b95\u0bcd\u0bb7\u0bc1": 0,
u"\u0b95\u0bcd\u0bb7\u0bc2": 0,
u"\u0b95\u0bcd\u0bb7\u0bc6": 0,
u"\u0b95\u0bcd\u0bb7\u0bc7": 0,
u"\u0b95\u0bcd\u0bb7\u0bc8": 0,
u"\u0b95\u0bcd\u0bb7\u0bca": 0,
u"\u0b95\u0bcd\u0bb7\u0bcb": 0,
u"\u0b95\u0bcd\u0bb7\u0bcc": 0,
u"\u0b99": 221,
u"\u0b99\u0bbe": 18,
u"\u0b99\u0bbf": 13,
u"\u0b99\u0bc0": 0,
u"\u0b99\u0bc1": 14,
u"\u0b99\u0bc2": 6,
u"\u0b99\u0bc6": 2,
u"\u0b99\u0bc7": 4,
u"\u0b99\u0bc8": 7,
u"\u0b99\u0bca": 1,
u"\u0b99\u0bcb": 0,
u"\u0b99\u0bcc": 0,
u"\u0b99\u0bcd": 72299,
u"\u0b9a": 58580,
u"\u0b9a\u0bbe": 23988,
u"\u0b9a\u0bbf": 62287,
u"\u0b9a\u0bc0": 0,
u"\u0b9a\u0bc1": 32862,
u"\u0b9a\u0bc2": 5440,
u"\u0b9a\u0bc6": 27364,
u"\u0b9a\u0bc7": 9304,
u"\u0b9a\u0bc8": 11126,
u"\u0b9a\u0bca": 4868,
u"\u0b9a\u0bcb": 0,
u"\u0b9a\u0bcc": 0,
u"\u0b9a\u0bcd": 48084,
u"\u0b9c": 6567,
u"\u0b9c\u0bbe": 3480,
u"\u0b9c\u0bbf": 5601,
u"\u0b9c\u0bc0": 0,
u"\u0b9c\u0bc1": 719,
u"\u0b9c\u0bc2": 747,
u"\u0b9c\u0bc6": 3668,
u"\u0b9c\u0bc7": 1376,
u"\u0b9c\u0bc8": 296,
u"\u0b9c\u0bca": 178,
u"\u0b9c\u0bcb": 0,
u"\u0b9c\u0bcc": 0,
u"\u0b9c\u0bcd": 2922,
u"\u0b9e": 1285,
u"\u0b9e\u0bbe": 1284,
u"\u0b9e\u0bbf": 53,
u"\u0b9e\u0bc0": 0,
u"\u0b9e\u0bc1": 14,
u"\u0b9e\u0bc2": 6,
u"\u0b9e\u0bc6": 39,
u"\u0b9e\u0bc7": 8,
u"\u0b9e\u0bc8": 126,
u"\u0b9e\u0bca": 2,
u"\u0b9e\u0bcb": 0,
u"\u0b9e\u0bcc": 0,
u"\u0b9e\u0bcd": 8467,
u"\u0b9f": 126479,
u"\u0b9f\u0bbe": 25026,
u"\u0b9f\u0bbf": 90136,
u"\u0b9f\u0bc0": 0,
u"\u0b9f\u0bc1": 89012,
u"\u0b9f\u0bc2": 1061,
u"\u0b9f\u0bc6": 7263,
u"\u0b9f\u0bc7": 5577,
u"\u0b9f\u0bc8": 32974,
u"\u0b9f\u0bca": 1229,
u"\u0b9f\u0bcb": 0,
u"\u0b9f\u0bcc": 0,
u"\u0b9f\u0bcd": 144780,
u"\u0ba3": 23644,
u"\u0ba3\u0bbe": 2909,
u"\u0ba3\u0bbf": 17869,
u"\u0ba3\u0bc0": 0,
u"\u0ba3\u0bc1": 4744,
u"\u0ba3\u0bc2": 132,
u"\u0ba3\u0bc6": 306,
u"\u0ba3\u0bc7": 492,
u"\u0ba3\u0bc8": 8734,
u"\u0ba3\u0bca": 88,
u"\u0ba3\u0bcb": 0,
u"\u0ba3\u0bcc": 0,
u"\u0ba3\u0bcd": 56607,
u"\u0ba4": 148306,
u"\u0ba4\u0bbe": 53989,
u"\u0ba4\u0bbf": 131491,
u"\u0ba4\u0bc0": 0,
u"\u0ba4\u0bc1": 114897,
u"\u0ba4\u0bc2": 4685,
u"\u0ba4\u0bc6": 8345,
u"\u0ba4\u0bc7": 13961,
u"\u0ba4\u0bc8": 25058,
u"\u0ba4\u0bca": 15555,
u"\u0ba4\u0bcb": 0,
u"\u0ba4\u0bcc": 0,
u"\u0ba4\u0bcd": 177918,
u"\u0ba8": 22199,
u"\u0ba8\u0bbe": 17759,
u"\u0ba8\u0bbf": 26333,
u"\u0ba8\u0bc0": 0,
u"\u0ba8\u0bc1": 3653,
u"\u0ba8\u0bc2": 2785,
u"\u0ba8\u0bc6": 5127,
u"\u0ba8\u0bc7": 3585,
u"\u0ba8\u0bc8": 714,
u"\u0ba8\u0bca": 893,
u"\u0ba8\u0bcb": 0,
u"\u0ba8\u0bcc": 0,
u"\u0ba8\u0bcd": 69426,
u"\u0ba9": 87837,
u"\u0ba9\u0bbe": 24886,
u"\u0ba9\u0bbf": 34021,
u"\u0ba9\u0bc0": 0,
u"\u0ba9\u0bc1": 13741,
u"\u0ba9\u0bc2": 1786,
u"\u0ba9\u0bc6": 2056,
u"\u0ba9\u0bc7": 4053,
u"\u0ba9\u0bc8": 19373,
u"\u0ba9\u0bca": 853,
u"\u0ba9\u0bcb": 0,
u"\u0ba9\u0bcc": 0,
u"\u0ba9\u0bcd": 191726,
u"\u0baa": 193417,
u"\u0baa\u0bbe": 53631,
u"\u0baa\u0bbf": 64256,
u"\u0baa\u0bc0": 0,
u"\u0baa\u0bc1": 59814,
u"\u0baa\u0bc2": 8539,
u"\u0baa\u0bc6": 25947,
u"\u0baa\u0bc7": 11571,
u"\u0baa\u0bc8": 7055,
u"\u0baa\u0bca": 14764,
u"\u0baa\u0bcb": 0,
u"\u0baa\u0bcc": 0,
u"\u0baa\u0bcd": 200894,
u"\u0bae": 79283,
u"\u0bae\u0bbe": 54296,
u"\u0bae\u0bbf": 30566,
u"\u0bae\u0bc0": 0,
u"\u0bae\u0bc1": 40304,
u"\u0bae\u0bc2": 7280,
u"\u0bae\u0bc6": 10129,
u"\u0bae\u0bc7": 13882,
u"\u0bae\u0bc8": 27282,
u"\u0bae\u0bca": 6844,
u"\u0bae\u0bcb": 0,
u"\u0bae\u0bcc": 0,
u"\u0bae\u0bcd": 203395,
u"\u0baf": 129005,
u"\u0baf\u0bbe": 56530,
u"\u0baf\u0bbf": 51980,
u"\u0baf\u0bc0": 0,
u"\u0baf\u0bc1": 31188,
u"\u0baf\u0bc2": 8079,
u"\u0baf\u0bc6": 3330,
u"\u0baf\u0bc7": 11538,
u"\u0baf\u0bc8": 14673,
u"\u0baf\u0bca": 1486,
u"\u0baf\u0bcb": 0,
u"\u0baf\u0bcc": 0,
u"\u0baf\u0bcd": 29530,
u"\u0bb0": 92430,
u"\u0bb0\u0bbe": 45415,
u"\u0bb0\u0bbf": 70560,
u"\u0bb0\u0bc0": 0,
u"\u0bb0\u0bc1": 98118,
u"\u0bb0\u0bc2": 2977,
u"\u0bb0\u0bc6": 5509,
u"\u0bb0\u0bc7": 7829,
u"\u0bb0\u0bc8": 21812,
u"\u0bb0\u0bca": 1712,
u"\u0bb0\u0bcb": 0,
u"\u0bb0\u0bcc": 0,
u"\u0bb0\u0bcd": 175635,
u"\u0bb1": 49741,
u"\u0bb1\u0bbe": 11283,
u"\u0bb1\u0bbf": 31242,
u"\u0bb1\u0bc0": 0,
u"\u0bb1\u0bc1": 37319,
u"\u0bb1\u0bc2": 263,
u"\u0bb1\u0bc6": 446,
u"\u0bb1\u0bc7": 1645,
u"\u0bb1\u0bc8": 20246,
u"\u0bb1\u0bca": 548,
u"\u0bb1\u0bcb": 0,
u"\u0bb1\u0bcc": 0,
u"\u0bb1\u0bcd": 76113,
u"\u0bb2": 55756,
u"\u0bb2\u0bbe": 32729,
u"\u0bb2\u0bbf": 43564,
u"\u0bb2\u0bc0": 0,
u"\u0bb2\u0bc1": 27144,
u"\u0bb2\u0bc2": 3107,
u"\u0bb2\u0bc6": 3909,
u"\u0bb2\u0bc7": 8819,
u"\u0bb2\u0bc8": 37759,
u"\u0bb2\u0bca": 821,
u"\u0bb2\u0bcb": 0,
u"\u0bb2\u0bcc": 0,
u"\u0bb2\u0bcd": 159337,
u"\u0bb3": 46365,
u"\u0bb3\u0bbe": 22285,
u"\u0bb3\u0bbf": 50298,
u"\u0bb3\u0bc0": 0,
u"\u0bb3\u0bc1": 31195,
u"\u0bb3\u0bc2": 1089,
u"\u0bb3\u0bc6": 818,
u"\u0bb3\u0bc7": 3013,
u"\u0bb3\u0bc8": 34813,
u"\u0bb3\u0bca": 131,
u"\u0bb3\u0bcb": 0,
u"\u0bb3\u0bcc": 0,
u"\u0bb3\u0bcd": 86313,
u"\u0bb4": 16265,
u"\u0bb4\u0bbe": 2028,
u"\u0bb4\u0bbf": 17650,
u"\u0bb4\u0bc0": 0,
u"\u0bb4\u0bc1": 14681,
u"\u0bb4\u0bc2": 93,
u"\u0bb4\u0bc6": 34,
u"\u0bb4\u0bc7": 94,
u"\u0bb4\u0bc8": 5165,
u"\u0bb4\u0bca": 29,
u"\u0bb4\u0bcb": 0,
u"\u0bb4\u0bcc": 0,
u"\u0bb4\u0bcd": 11956,
u"\u0bb5": 137503,
u"\u0bb5\u0bbe": 44179,
u"\u0bb5\u0bbf": 85472,
u"\u0bb5\u0bc0": 0,
u"\u0bb5\u0bc1": 37564,
u"\u0bb5\u0bc2": 1311,
u"\u0bb5\u0bc6": 17187,
u"\u0bb5\u0bc7": 19076,
u"\u0bb5\u0bc8": 21270,
u"\u0bb5\u0bca": 1294,
u"\u0bb5\u0bcb": 0,
u"\u0bb5\u0bcc": 0,
u"\u0bb5\u0bcd": 8886,
u"\u0bb6": 0,
u"\u0bb6\u0bbe": 0,
u"\u0bb6\u0bbf": 0,
u"\u0bb6\u0bc0": 0,
u"\u0bb6\u0bc1": 0,
u"\u0bb6\u0bc2": 0,
u"\u0bb6\u0bc6": 0,
u"\u0bb6\u0bc7": 0,
u"\u0bb6\u0bc8": 0,
u"\u0bb6\u0bca": 0,
u"\u0bb6\u0bcb": 0,
u"\u0bb6\u0bcc": 0,
u"\u0bb7": 4099,
u"\u0bb7\u0bbe": 1635,
u"\u0bb7\u0bbf": 2078,
u"\u0bb7\u0bc0": 0,
u"\u0bb7\u0bc1": 215,
u"\u0bb7\u0bc2": 170,
u"\u0bb7\u0bc6": 563,
u"\u0bb7\u0bc7": 521,
u"\u0bb7\u0bc8": 209,
u"\u0bb7\u0bca": 24,
u"\u0bb7\u0bcb": 0,
u"\u0bb7\u0bcc": 0,
u"\u0bb7\u0bcd": 5396,
u"\u0bb8": 2233,
u"\u0bb8\u0bbe": 1462,
u"\u0bb8\u0bbf": 4642,
u"\u0bb8\u0bc0": 0,
u"\u0bb8\u0bc1": 847,
u"\u0bb8\u0bc2": 179,
u"\u0bb8\u0bc6": 509,
u"\u0bb8\u0bc7": 239,
u"\u0bb8\u0bc8": 926,
u"\u0bb8\u0bca": 42,
u"\u0bb8\u0bcb": 0,
u"\u0bb8\u0bcc": 0,
u"\u0bb8\u0bcd": 54977,
u"\u0bb9": 3929,
u"\u0bb9\u0bbe": 3995,
u"\u0bb9\u0bbf": 1918,
u"\u0bb9\u0bc0": 0,
u"\u0bb9\u0bc1": 456,
u"\u0bb9\u0bc2": 441,
u"\u0bb9\u0bc6": 2410,
u"\u0bb9\u0bc7": 945,
u"\u0bb9\u0bc8": 832,
u"\u0bb9\u0bca": 520,
u"\u0bb9\u0bcb": 0,
u"\u0bb9\u0bcc": 0,
u"\u0bb9\u0bcd": 1275,
}
# unique words = 323
# sorted in Frequency order
freqsort_data = [
[u"க", 0.053238],
[u"க்", 0.0377115],
[u"ம்", 0.0292802],
[u"ப்", 0.0289202],
[u"ப", 0.0278438],
[u"ன்", 0.0276004],
[u"த்", 0.0256126],
[u"ர்", 0.025284],
[u"ல்", 0.0229377],
[u"த", 0.0213497],
[u"ட்", 0.0208422],
[u"கு", 0.0204348],
[u"வ", 0.0197946],
[u"தி", 0.0189291],
[u"ய", 0.0185712],
[u"ட", 0.0182076],
[u"து", 0.0165403],
[u"ரு", 0.0141248],
[u"ர", 0.013306],
[u"டி", 0.0129757],
[u"டு", 0.0128139],
[u"ன", 0.0126448],
[u"ள்", 0.0124254],
[u"வி", 0.0123043],
[u"ம", 0.0114134],
[u"கி", 0.0111561],
[u"ற்", 0.010957],
[u"கா", 0.0106654],
[u"அ", 0.0106151],
[u"ங்", 0.010408],
[u"ரி", 0.0101576],
[u"ந்", 0.00999439],
[u"பி", 0.00925013],
[u"சி", 0.00896667],
[u"இ", 0.00891787],
[u"பு", 0.00861067],
[u"ச", 0.00843302],
[u"ண்", 0.008149],
[u"யா", 0.00813791],
[u"ல", 0.00802649],
[u"ஸ்", 0.00791435],
[u"மா", 0.00781631],
[u"தா", 0.00777212],
[u"பா", 0.00772058],
[u"யி", 0.00748291],
[u"ளி", 0.00724077],
[u"ற", 0.00716058],
[u"ச்", 0.00692205],
[u"ள", 0.00667458],
[u"ரா", 0.00653782],
[u"வா", 0.00635989],
[u"லி", 0.00627136],
[u"மு", 0.00580206],
[u"லை", 0.00543569],
[u"வு", 0.00540762],
[u"று", 0.00537235],
[u"உ", 0.00514734],
[u"எ", 0.00510027],
[u"ளை", 0.00501159],
[u"னி", 0.00489757],
[u"டை", 0.00474685],
[u"சு", 0.00473073],
[u"லா", 0.00471158],
[u"ஆ", 0.00470597],
[u"றி", 0.00449752],
[u"ளு", 0.00449075],
[u"யு", 0.00448974],
[u"மி", 0.0044002],
[u"ய்", 0.00425106],
[u"செ", 0.00393925],
[u"மை", 0.00392745],
[u"லு", 0.00390758],
[u"நி", 0.00379083],
[u"பெ", 0.00373526],
[u"தை", 0.00360728],
[u"டா", 0.00360268],
[u"னா", 0.00358252],
[u"சா", 0.00345325],
[u"ண", 0.00340373],
[u"கொ", 0.00338703],
[u"ளா", 0.00320809],
[u"ந", 0.00319571],
[u"கை", 0.00316145],
[u"ரை", 0.00314],
[u"வை", 0.00306197],
[u"றை", 0.00291456],
[u"னை", 0.00278889],
[u"வே", 0.00274613],
[u"ணி", 0.00257237],
[u"நா", 0.00255654],
[u"ழி", 0.00254085],
[u"வெ", 0.0024742],
[u"ழ", 0.00234147],
[u"தொ", 0.00223926],
[u"கூ", 0.00214021],
[u"பொ", 0.00212539],
[u"ழு", 0.00211344],
[u"யை", 0.00211229],
[u"ஒ", 0.00207946],
[u"தே", 0.00200979],
[u"மே", 0.00199842],
[u"னு", 0.00197812],
[u"ழ்", 0.00172115],
[u"பே", 0.00166573],
[u"கே", 0.00166559],
[u"யே", 0.00166098],
[u"றா", 0.00162427],
[u"ஃ", 0.00160829],
[u"சை", 0.00160167],
[u"மெ", 0.00145814],
[u"சே", 0.00133938],
[u"ஏ", 0.00130613],
[u"வ்", 0.00127921],
[u"லே", 0.00126956],
[u"ணை", 0.00125732],
[u"பூ", 0.00122925],
[u"ஞ்", 0.00121889],
[u"தெ", 0.00120132],
[u"யூ", 0.00116303],
[u"ரே", 0.00112704],
[u"மூ", 0.00104801],
[u"டெ", 0.00104556],
[u"பை", 0.00101562],
[u"மொ", 0.000985244],
[u"ஜ", 0.000945368],
[u"கெ", 0.00090434],
[u"ஓ", 0.000811776],
[u"ஜி", 0.000806305],
[u"டே", 0.00080285],
[u"ரெ", 0.000793061],
[u"சூ", 0.000783128],
[u"ஷ்", 0.000776794],
[u"ழை", 0.00074354],
[u"நெ", 0.00073807],
[u"சொ", 0.000700785],
[u"ணு", 0.000682934],
[u"ஐ", 0.000680918],
[u"தூ", 0.00067444],
[u"ஸி", 0.00066825],
[u"ஈ", 0.000665371],
[u"ஊ", 0.000590369],
[u"ஷ", 0.000590081],
[u"னே", 0.000583459],
[u"ஹா", 0.00057511],
[u"ஹ", 0.000565609],
[u"லெ", 0.000562729],
[u"ஜெ", 0.000528036],
[u"நு", 0.000525876],
[u"நே", 0.000516087],
[u"ஜா", 0.000500972],
[u"யெ", 0.000479378],
[u"லூ", 0.000447276],
[u"ளே", 0.000433744],
[u"ரூ", 0.000428561],
[u"ஜ்", 0.000420643],
[u"ணா", 0.000418772],
[u"நூ", 0.000400921],
[u"ஹெ", 0.000346937],
[u"ஸ", 0.000321457],
[u"ஷி", 0.000299143],
[u"னெ", 0.000295976],
[u"ழா", 0.000291946],
[u"ஹி", 0.00027611],
[u"னூ", 0.000257108],
[u"ரொ", 0.000246455],
[u"றே", 0.00023681],
[u"ஷா", 0.00023537],
[u"யொ", 0.000213921],
[u"ஸா", 0.000210466],
[u"ஜே", 0.000198085],
[u"வூ", 0.000188728],
[u"வொ", 0.000186281],
[u"ஞ", 0.000184985],
[u"ஞா", 0.000184841],
[u"ஹ்", 0.000183546],
[u"டொ", 0.000176924],
[u"ளூ", 0.00015677],
[u"டூ", 0.000152739],
[u"ஹே", 0.00013604],
[u"ஸை", 0.000133305],
[u"நொ", 0.000128554],
[u"னொ", 0.000122796],
[u"ஸு", 0.000121932],
[u"ஹை", 0.000119773],
[u"லொ", 0.000118189],
[u"ளெ", 0.000117757],
[u"ஜூ", 0.000107536],
[u"ஜு", 0.000103505],
[u"நை", 0.000102786],
[u"ஷெ", 8.1048e-05],
[u"றொ", 7.88886e-05],
[u"ஷே", 7.50018e-05],
[u"ஹொ", 7.48578e-05],
[u"ஸெ", 7.32743e-05],
[u"ணே", 7.0827e-05],
[u"ஹு", 6.56446e-05],
[u"றெ", 6.4205e-05],
[u"ஹூ", 6.34852e-05],
[u"ணெ", 4.4051e-05],
[u"ஜை", 4.26114e-05],
[u"றூ", 3.78608e-05],
[u"ஸே", 3.44058e-05],
[u"ங", 3.18146e-05],
[u"ஷு", 3.09508e-05],
[u"ஷை", 3.00871e-05],
[u"ஸூ", 2.57684e-05],
[u"ஜொ", 2.56244e-05],
[u"ஔ", 2.46167e-05],
[u"ஷூ", 2.44728e-05],
[u"ணூ", 1.90024e-05],
[u"ளொ", 1.88584e-05],
[u"ஞை", 1.81386e-05],
[u"ழே", 1.3532e-05],
[u"ழூ", 1.3388e-05],
[u"ணொ", 1.26683e-05],
[u"ஞி", 7.62974e-06],
[u"ஸொ", 6.04621e-06],
[u"ஞெ", 5.61434e-06],
[u"ழெ", 4.89455e-06],
[u"ழொ", 4.17476e-06],
[u"ஷொ", 3.45498e-06],
[u"ஙா", 2.59123e-06],
[u"ஞு", 2.0154e-06],
[u"ஙு", 2.0154e-06],
[u"ஙி", 1.87145e-06],
[u"ஞே", 1.15166e-06],
[u"ஙை", 1.0077e-06],
[u"ஞூ", 8.63744e-07],
[u"ஙூ", 8.63744e-07],
[u"ஙே", 5.7583e-07],
[u"ஞொ", 2.87915e-07],
[u"ஙெ", 2.87915e-07],
[u"ஙொ", 1.43957e-07],
[u"ஜீ", 7.19787e-08],
[u"ஜௌ", 7.19787e-08],
[u"ஜோ", 7.19787e-08],
[u"மோ", 7.19787e-08],
[u"மௌ", 7.19787e-08],
[u"மீ", 7.19787e-08],
[u"வௌ", 7.19787e-08],
[u"வோ", 7.19787e-08],
[u"ஞௌ", 7.19787e-08],
[u"ஞீ", 7.19787e-08],
[u"ஷீ", 7.19787e-08],
[u"ஷௌ", 7.19787e-08],
[u"ஷோ", 7.19787e-08],
[u"வீ", 7.19787e-08],
[u"கௌ", 7.19787e-08],
[u"கோ", 7.19787e-08],
[u"கீ", 7.19787e-08],
[u"ரீ", 7.19787e-08],
[u"ரௌ", 7.19787e-08],
[u"ஶெ", 7.19787e-08],
[u"ரோ", 7.19787e-08],
[u"க்ஷ", 7.19787e-08],
[u"ஹௌ", 7.19787e-08],
[u"ஹீ", 7.19787e-08],
[u"ஶே", 7.19787e-08],
[u"ஙோ", 7.19787e-08],
[u"ஙௌ", 7.19787e-08],
[u"ஙீ", 7.19787e-08],
[u"லீ", 7.19787e-08],
[u"லௌ", 7.19787e-08],
[u"லோ", 7.19787e-08],
[u"னோ", 7.19787e-08],
[u"னௌ", 7.19787e-08],
[u"னீ", 7.19787e-08],
[u"ஶோ", 7.19787e-08],
[u"ஶௌ", 7.19787e-08],
[u"ழௌ", 7.19787e-08],
[u"ழோ", 7.19787e-08],
[u"ழீ", 7.19787e-08],
[u"க்ஷி", 7.19787e-08],
[u"க்ஷா", 7.19787e-08],
[u"ஶா", 7.19787e-08],
[u"ஶி", 7.19787e-08],
[u"தௌ", 7.19787e-08],
[u"தோ", 7.19787e-08],
[u"தீ", 7.19787e-08],
[u"க்ஷே", 7.19787e-08],
[u"க்ஷெ", 7.19787e-08],
[u"ஶீ", 7.19787e-08],
[u"ஶு", 7.19787e-08],
[u"ஶூ", 7.19787e-08],
[u"க்ஷூ", 7.19787e-08],
[u"க்ஷு", 7.19787e-08],
[u"க்ஷீ", 7.19787e-08],
[u"ஶை", 7.19787e-08],
[u"ஶொ", 7.19787e-08],
[u"க்ஷௌ", 7.19787e-08],
[u"க்ஷோ", 7.19787e-08],
[u"க்ஷொ", 7.19787e-08],
[u"க்ஷை", 7.19787e-08],
[u"யௌ", 7.19787e-08],
[u"யோ", 7.19787e-08],
[u"ஶ", 7.19787e-08],
[u"ஹோ", 7.19787e-08],
[u"டௌ", 7.19787e-08],
[u"டோ", 7.19787e-08],
[u"டீ", 7.19787e-08],
[u"ஸோ", 7.19787e-08],
[u"ஸௌ", 7.19787e-08],
[u"ஸீ", 7.19787e-08],
[u"றீ", 7.19787e-08],
[u"றோ", 7.19787e-08],
[u"றௌ", 7.19787e-08],
[u"நோ", 7.19787e-08],
| |
<reponame>GyChou/ray_elegant_carla
from ray_elegantrl.interaction import make_env
from ray_elegantrl.net import *
import torch
import numpy as np
import os
import time
# os.environ["DISPLAY"] = "localhost:13.0"
os.environ["SDL_VIDEODRIVER"] = "dummy"
RENDER = False
ENV_ID = "carla-v2"
STATE_DIM = 50
ACTION_DIM = 2
REWARD_DIM = 1
TARGET_RETURN = 700
def demo(policy, args):
from gym_carla_feature.start_env.config import params
params['port'] = (args.port[0] if len(args.port) == 1 else args.port) if hasattr(args, 'port') else 2280
params['max_waypt'] = args.max_waypt if hasattr(args, 'max_waypt') else 12
params['max_step'] = args.max_step if hasattr(args, 'max_step') else 1000
params['dt'] = args.dt if hasattr(args, 'dt') else 1 / 20
params['if_noise_dt'] = args.if_noise_dt if hasattr(args, 'if_noise_dt') else False
params['noise_std'] = args.noise_std if hasattr(args, 'noise_std') else 0.01
params['noise_interval'] = args.noise_interval if hasattr(args, 'noise_interval') else 10
params['render'] = RENDER
params['autopilot'] = args.autopilot if hasattr(args, 'autopilot') else False
params['desired_speed'] = args.desired_speed if hasattr(args, 'desired_speed') else 20
params['out_lane_thres'] = args.out_lane_thres if hasattr(args, 'out_lane_thres') else 5
params['sampling_radius'] = args.sampling_radius if hasattr(args, 'sampling_radius') else 3
# params['obs_space_type'] = args.obs_space_type if hasattr(args,'obs_space_type') else ['orgin_state', 'waypoint']
params['town'] = args.town if hasattr(args, 'town') else 'Town07'
params['task_mode'] = args.task_mode if hasattr(args, 'task_mode') else 'mountainroad'
params['reward_type'] = args.reward_type if hasattr(args, 'reward_type') else 1
params['if_dest_end'] = args.if_dest_end if hasattr(args, 'if_dest_end') else False
test_num = args.test_num if hasattr(args, 'test_num') else 1000
env = {
'id': ENV_ID,
'state_dim': STATE_DIM,
'action_dim': ACTION_DIM,
'action_type': params['action_type'],
'reward_dim': REWARD_DIM,
'target_reward': TARGET_RETURN,
'max_step': params['max_step'],
'params_name': {'params': params}
}
total_result = []
dir, subdirs, subfiles = os.walk(args.path).__next__()
if len(subdirs) == 0: # one policy eval
policy_path = dir + "/actor.pth"
policy.load_state_dict(torch.load(policy_path))
policy.eval()
result = eval_policy(policy, env, test_num, seed=0, net=args.net, action_space=args.action_space)
total_result.append(result)
else: # multi policy eval
for subdir in subdirs:
policy_path = dir + "/" + subdir + "/actor.pth"
policy.load_state_dict(torch.load(policy_path))
policy.eval()
result = eval_policy(policy, env, test_num, seed=0, net=args.net, action_space=args.action_space,
if_point=True)
total_result.append(result)
print(f"path:{args.path}")
safe_data = []
comfort_data = []
for k, vl in total_result[0].items():
data = []
for result in total_result:
data.append(np.array(result[k]).mean())
print(f'{k}: <mean>{np.array(data).mean()} | <std>{np.array(data).std()}')
#
if k in ['outroute', 'collision']:
safe_data.append(np.array(data))
if k in ['delta_a_lon', 'delta_a_lat', 'delta_jerk_lon', 'delta_jerk_lat']:
comfort_data.append(np.array(data))
safe = []
for outlane, collsion in zip(safe_data[0], safe_data[1]):
safe.append((outlane or collsion))
comfort = []
for delta_a_lon, delta_a_lat, delta_jerk_lon, delta_jerk_lat in zip(comfort_data[0], comfort_data[1],
comfort_data[2], comfort_data[3]):
comfort.append((1 / (1 + (delta_a_lon + delta_a_lat + delta_jerk_lon + delta_jerk_lat))))
print(f'safe: <mean>{1 - np.array(safe).mean()} | <std>{np.array(safe).std()}')
print(f'comfort: <mean>{np.array(comfort).mean()} | <std>{np.array(comfort).std()}')
# for cpu policy
def eval_policy(policy, env_dict, test_num=100, net=None, action_space=None, seed=0, if_point=True):
result = {}
result['return'] = []
result['avg_v'] = []
result['velocity_lon'] = []
result['velocity_lat'] = []
result['distance'] = []
result['step_num'] = []
result['delta_yaw'] = []
result['delta_steer'] = []
result['lat_distance'] = []
result['yaw_angle'] = []
result['delta_a_lon'] = []
result['delta_a_lat'] = []
result['delta_jerk_lon'] = []
result['delta_jerk_lat'] = []
result['outroute'] = []
result['collision'] = []
result['time'] = []
env = make_env(env_dict, seed)
for ep_i in range(test_num):
ss_time = time.time()
state = env.reset()
return_ = 0
delta_yaw = 0
delta_steer = 0
a_lon = 0
a_lat = 0
jerk_lon = 0
jerk_lat = 0
lat_distance = 0
yaw_angle = 0
avg_v = 0
velocity_lon = 0
velocity_lat = 0
distance = 0
outroute = 0
collision = 0
time_info = 0
ep_info = {
'position':[],
'reward': [],
'velocity': [],
'velocity_lon': [],
'velocity_lat': [],
'delta_steer': [],
'lon_action': [],
'steer': [],
'a0': [],
'a1': [],
'lat_distance': [],
'yaw_angle': [],
'delta_yaw': [],
'delta_a_lon': [],
'delta_a_lat': [],
'delta_jerk_lon': [],
'delta_jerk_lat': [],
}
if hasattr(policy, 'hidden_state_dim'):
hidden_state = torch.zeros([1, policy.hidden_state_dim], dtype=torch.float32)
cell_state = torch.zeros([1, policy.hidden_state_dim], dtype=torch.float32)
for i in range(1, env_dict['max_step'] + 1):
state = torch.as_tensor((state,), dtype=torch.float32).detach_()
if net in ["d3qn", "discreteppo"]:
action_idx = policy(state)
action = np.array(action_space[action_idx])
elif net in ["rnnppo"]:
action, hidden_state, cell_state = policy.actor_forward(state, hidden_state, cell_state)
action = action.detach().numpy()[0]
elif net in ["hybridppo-3", "hybridppo-2"]:
action = policy(state)
action = action.detach().numpy()[0]
if net in ["hybridppo-3"]:
def modify_action(action):
def mapping(da_dim, x):
if da_dim == 0:
return -abs(x)
elif da_dim == 2:
return abs(x)
else:
return x * 0.
da_idx = int(action[-1])
mod_a = np.zeros(action[:-1].shape)
mod_a[0] = mapping(da_idx // 3, action[0])
mod_a[1] = mapping(da_idx % 3, action[1])
return mod_a
elif net in ["hybridppo-2"]:
def modify_action(action):
def mapping(da_dim, x):
if da_dim == 1:
return x
else:
return x * 0.
da_idx = int(action[-1])
mod_a = np.zeros(action[:-1].shape)
mod_a[0] = mapping(da_idx // 2, action[0])
mod_a[1] = mapping(da_idx % 2, action[1])
return mod_a
else:
def modify_action(action):
pass
action = modify_action(action)
else:
action = policy(state)
action = action.detach().numpy()[0]
next_s, reward, done, info = env.step(action)
delta_yaw += abs(info['delta_yaw'])
delta_steer += abs(info['delta_steer'])
lat_distance += abs(info['lat_distance'])
yaw_angle += abs(info['yaw_angle'])
a_lon += abs(info['acc_lon'])
a_lat += abs(info['acc_lat'])
jerk_lon += abs(info['jerk_lon'])
jerk_lat += abs(info['jerk_lat'])
distance = info['distance']
outroute += info['outroute']
collision += info['collision']
return_ += reward
avg_v += info['velocity']
velocity_lon += info['velocity_lon']
velocity_lat += abs(info['velocity_lat'])
time_info += info['time']
# 'velocity': [],
# 'delta_steer': [],
# 'lat_distance': [],
# 'yaw_angle': [],
# 'delta_yaw': [],
# 'delta_a_lon': [],
# 'delta_a_lat': [],
# 'delta_jerk_lon': [],
# 'delta_jerk_lat': [],
ego_location = env.ego.get_transform().location
ep_info['position'].append([ego_location.x,ego_location.y])
ep_info['reward'].append(reward)
ep_info['velocity'].append(info['velocity'])
ep_info['velocity_lon'].append(info['velocity_lon'])
ep_info['velocity_lat'].append(info['velocity_lat'])
ep_info['delta_steer'].append(info['delta_steer'])
ep_info['lon_action'].append(info['lon_action'])
ep_info['steer'].append(info['steer'])
ep_info['a0'].append(info['a0'])
ep_info['a1'].append(info['a1'])
ep_info['yaw_angle'].append(info['yaw_angle'])
ep_info['delta_yaw'].append(info['delta_yaw'])
ep_info['lat_distance'].append(info['lat_distance'])
ep_info['delta_a_lon'].append(info['acc_lon'])
ep_info['delta_a_lat'].append(info['acc_lat'])
ep_info['delta_jerk_lon'].append(info['jerk_lon'])
ep_info['delta_jerk_lat'].append(info['jerk_lat'])
if done:
break
state = next_s
# print("*" * 60)
# print(f"ep{ep_i} used time:{time.time() - ss_time}s")
# print("step num:", i,
# "\n return:", return_,
# "\n avg_v:", avg_v / i,
# "\n distance:", distance,
# "\n outroute:", outroute,
# "\n collision:", collision,
# "\n delta_yaw(per step):", delta_yaw / i,
# "\n delta_steer(per step):", delta_steer / i,
# "\n lat_distance(per step):", lat_distance / i,
# "\n yaw_angle(per step):", yaw_angle / i,
# "\n delta_a_lon(per step):", a_lon / i,
# "\n delta_a_lat(per step):", a_lat / i,
# "\n delta_jerk_lon(per step):", jerk_lon / i,
# "\n delta_jerk_lat(per step):", jerk_lat / i,
# )
result['step_num'].append(i)
result['return'].append(return_)
result['avg_v'].append(avg_v / i)
result['distance'].append(distance)
result['collision'].append(collision)
result['outroute'].append(outroute)
result['delta_yaw'].append(delta_yaw / i)
result['delta_steer'].append(delta_steer / i)
result['lat_distance'].append(lat_distance / i)
result['yaw_angle'].append(yaw_angle / i)
result['velocity_lon'].append(velocity_lon / i)
result['velocity_lat'].append(velocity_lat / i)
result['delta_a_lon'].append(a_lon / i)
result['delta_a_lat'].append(a_lat / i)
result['delta_jerk_lon'].append(jerk_lon / i)
result['delta_jerk_lat'].append(jerk_lat / i)
result['time'].append(time_info)
# print(f'test {test_num} episode finished !!!')
# print('-' * 60)
save_path = f'/home/zgy/repos/ray_elegantrl/veh_control_logs/eval/{net}'
if not os.path.exists(save_path):
os.mkdir(save_path)
if if_point:
for k, vl in ep_info.items():
np.save(f'{save_path}/ep-{k}', np.array(vl))
safe_data = []
comfort_data = []
for k, vl in result.items():
print(f'{k}: <mean>{np.array(vl).mean()} | <std>{np.array(vl).std()}')
if k in ['outroute', 'collision']:
safe_data.append(np.array(vl))
if k in ['delta_a_lon', 'delta_a_lat', 'delta_jerk_lon', 'delta_jerk_lat']:
comfort_data.append(np.array(vl))
safe = []
for outlane, collsion in zip(safe_data[0], safe_data[1]):
safe.append((outlane or collsion))
comfort = []
for delta_a_lon, delta_a_lat, delta_jerk_lon, delta_jerk_lat in zip(comfort_data[0], comfort_data[1],
comfort_data[2], comfort_data[3]):
comfort.append((1 / (1 + (delta_a_lon + delta_a_lat + delta_jerk_lon + delta_jerk_lat))))
print(f'safe: <mean>{1 - np.array(safe).mean()} | <std>{np.array(safe).std()}')
print(f'comfort: <mean>{np.array(comfort).mean()} | <std>{np.array(comfort).std()}')
print('-' * 60)
return result
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Carla RL')
parser.add_argument('--reward_type', type=int, default=12)
parser.add_argument('--port', nargs='+', type=int, default=[2050])
parser.add_argument('--desired_speed', type=float, default=12)
parser.add_argument('--max_step', type=int, default=1000)
parser.add_argument('--dt', type=float, default=0.05)
parser.add_argument('--test_num', type=int, default=1)
parser.add_argument('--path', type=str, default="")
parser.add_argument('--net', type=str, default="ppo")
parser.add_argument('--hidden_state_dim', type=int, default=128)
# parser.add_argument('--town', type=str, default='Town03')
# parser.add_argument('--task_mode', type=str, default='urbanroad')
parser.add_argument('--action_space', type=int, default=None)
parser.add_argument('--noise_std', type=float, default=0.01)
parser.add_argument('--noise_interval', type=int, default=1)
parser.add_argument('--if_noise_dt', default=False, action="store_true", )
args = parser.parse_args()
# args.net = "cppo"
# print(f'# {args.net}')
# print("town07-v1")
# args.max_step = 800
# print("00")
# # args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-12-13-39-39_cuda:1/model00'
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-12-13-26-49_cuda:1/model00'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-12-00-10-03_cuda:1/model00'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-11-18-13-47_cuda:1/model00'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r3_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-11-12-21-00_cuda:1/model00'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town07-V1/constriant/AgentConstriantPPO2_None_clip/r15_v2/0.1_0.01_bad_gap0_exp_2021-12-09-23-30-00_cuda:1/model00'
# policy = ActorPPO(mid_dim=2 ** 8, state_dim=STATE_DIM, action_dim=ACTION_DIM)
# demo(policy, args)
# print("01")
# # args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-12-13-39-39_cuda:1/model01'
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-12-13-26-49_cuda:1/model01'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-12-00-10-03_cuda:1/model01'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r4_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-11-18-13-47_cuda:1/model01'
# # args.path='/home/zgy/repos/ray_elegantrl/veh_control_logs/carla-v2_Town07_mountainroad_s50_a2_r3_tr200_ms200_False/AgentConstriantPPO2_None_clip/exp_2021-12-11-12-21-00_cuda:1/model01'
# # args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town07-V1/constriant/AgentConstriantPPO2_None_clip/r15_v2/0.1_0.01_bad_gap0_exp_2021-12-09-23-30-00_cuda:1/model01'
# policy = ActorPPO(mid_dim=2 ** 8, state_dim=STATE_DIM, action_dim=ACTION_DIM)
# demo(policy, args)
# print("town07-v2")
# args.max_step = 4000
# print("00")
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town07-V2/AgentConstriantPPO2_None_clip/exp_2021-12-12-19-46-35_cuda:1/model00'
# policy = ActorPPO(mid_dim=2 ** 8, state_dim=STATE_DIM, action_dim=ACTION_DIM)
# demo(policy, args)
# print("01")
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town07-V2/AgentConstriantPPO2_None_clip/exp_2021-12-12-19-46-35_cuda:1/model01'
# policy = ActorPPO(mid_dim=2 ** 8, state_dim=STATE_DIM, action_dim=ACTION_DIM)
# demo(policy, args)
# print("town03-v1")
# args.town = 'Town03'
# args.task_mode = 'urbanroad'
# args.max_step = 4000
# print("00")
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town-03-V1/AgentConstriantPPO2_None_clip/exp_2021-12-12-21-56-36_cuda:1/model00'
# policy = ActorPPO(mid_dim=2 ** 8, state_dim=STATE_DIM, action_dim=ACTION_DIM)
# demo(policy, args)
# print("01")
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town-03-V1/AgentConstriantPPO2_None_clip/exp_2021-12-12-21-56-36_cuda:1/model01'
# policy = ActorPPO(mid_dim=2 ** 8, state_dim=STATE_DIM, action_dim=ACTION_DIM)
# demo(policy, args)
# args.net = "ppo"
# print(f'# {args.net}')
# print("town07-v1")
# print("00")
# args.max_step = 800
# args.path = '/home/zgy/repos/ray_elegantrl/veh_control_logs/veh_control/town07-V1/continous/AgentPPO2_None_clip/exp_2021-12-03-21-56-07_cuda:1/model'
# print("town07-v2")
# print("00")
# args.max_step = 4000
| |
import argparse
import logging
from keras.models import Sequential
from keras.layers import Conv3D, Dense
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
import xarray as xr
# ----------------------------------------------------------------------------------------------------------------------
# set up a basic, global _logger which will write to the console as standard error
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
_logger = logging.getLogger(__name__)
# ----------------------------------------------------------------------------------------------------------------------
def pull_vars_into_array(dataset,
variables,
level,
hemisphere=None):
"""
Create a Numpy array from the specified variables of an xarray DataSet.
:param dataset: xarray.DataSet
:param variables: list of variables to be extracted from the DataSet and included in the resulting DataFrame
:param level: the level index (all times, lats, and lons included from this indexed level)
:param hemisphere: 'north', 'south', or None
:return: an array with shape (ds.time.size, ds.lat.size, ds.lon.size, len(variables)) and dtype float
"""
# slice the dataset down to a hemisphere, if specified
if hemisphere is not None:
if hemisphere == 'north':
dataset = dataset.sel(lat=(dataset.lat >= 0))
elif hemisphere == 'south':
dataset = dataset.sel(lat=(dataset.lat < 0))
else:
raise ValueError("Unsupported hemisphere argument: {hemi}".format(hemi=hemisphere))
# the array we'll populate and return
arr = np.empty(shape=[dataset.time.size, dataset.lat.size, dataset.lon.size, len(variables)], dtype=float)
# loop over each variable, adding each into the dataframe
for index, var_name in enumerate(variables):
# if we have (time, lev, lat, lon), then use level parameter
dimensions = dataset.variables[var_name].dims
if dimensions == ('time', 'lev', 'lat', 'lon'):
values = dataset[var_name].values[:, level, :, :]
elif dimensions == ('time', 'lat', 'lon'):
values = dataset[var_name].values[:, :, :]
else:
raise ValueError("Unsupported variable dimensions: {dims}".format(dims=dimensions))
# add the values into the array at the variable's position
arr[:, :, :, index] = values
return arr
# ----------------------------------------------------------------------------------------------------------------------
def split_into_hemisphere_arrays(features_dataset,
labels_dataset,
feature_vars,
label_vars,
level_ix):
"""
Split the features and labels datasets into train and test arrays, using the northern hemisphere
for training and the southern hemisphere for testing. Assumes a regular global grid with full
northern and southern hemispheres.
:param features_dataset: xarray.DataSet
:param labels_dataset: xarray.DataSet
:param feature_vars: list of variables to include from the features DataSet
:param label_vars: list of variables to include from the labels DataSet
:param level_ix: level coordinate index, assumes a 'lev' coordinate for all specified feature and label variables
:return:
"""
# make DataFrame from features, using the northern hemisphere for training data
train_features = pull_vars_into_array(features_dataset,
feature_vars,
level_ix,
hemisphere='north')
# make DataFrame from features, using the southern hemisphere for testing data
test_features = pull_vars_into_array(features_dataset,
feature_vars,
level_ix,
hemisphere='south')
# make DataFrame from labels, using the northern hemisphere for training data
train_labels = pull_vars_into_array(labels_dataset,
label_vars,
level_ix,
hemisphere='north')
# make DataFrame from labels, using the southern hemisphere for testing data
test_labels = pull_vars_into_array(labels_dataset,
label_vars,
level_ix,
hemisphere='south')
return train_features, test_features, train_labels, test_labels
# ----------------------------------------------------------------------------------------------------------------------
def define_model_cnn(num_times,
num_lats,
num_lons,
num_features,
num_labels):
"""
Define a model using convolutional neural network layers.
Input data is expected to have shape (1, times, lats, lons, features) and output data
will have shape (1, times, lats, lons, labels).
:param num_times: the number of times in the input's time dimension
:param num_lats: the number of lats in the input's lat dimension
:param num_lons: the number of lons in the input's lon dimension
:param num_features: the number of features (input attributes) in the input's channel dimension
:param num_labels: the number of labels (output attributes) in the output's channel dimension
:return: a Keras neural network model that uses convolutional layers
"""
# define the model
cnn_model = Sequential()
# add an initial 3-D convolutional layer
cnn_model.add(Conv3D(filters=32,
kernel_size=(3, 3, 3),
activation="relu",
data_format="channels_last",
input_shape=(num_times, num_lats, num_lons, num_features),
padding='same'))
# add a fully-connected hidden layer with twice the number of neurons as input attributes (features)
cnn_model.add(Dense(num_features * 2, activation='relu'))
# output layer uses no activation function since we are interested
# in predicting numerical values directly without transform
cnn_model.add(Dense(num_labels))
# compile the model using the ADAM optimization algorithm and a mean squared error loss function
cnn_model.compile(optimizer='adam', loss='mse')
return cnn_model
# ----------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
"""
This module is used to showcase ML modeling of the climate using neural networks,
initially using NCAR CAM files as inputs.
"""
try:
# parse the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--learn_features",
help="NetCDF files containing flow variables used to train/test the model",
nargs='*',
required=True)
parser.add_argument("--learn_labels",
help="NetCDF files containing time tendency forcing variables used to train/test the model",
nargs='*',
required=True)
parser.add_argument("--predict_features",
help="NetCDF files containing flow variables used as prediction inputs",
nargs='*',
required=True)
parser.add_argument("--predict_labels",
help="NetCDF file to contain predicted time tendency forcing variables",
required=True)
args = parser.parse_args()
# train/fit/score models using the dry features and corresponding labels
features = ['PS', 'T', 'U', 'V']
labels = ['PTTEND']
# open the features (flows) and labels (tendencies) as xarray DataSets
ds_learn_features = xr.open_mfdataset(paths=args.learn_features)
ds_learn_labels = xr.open_mfdataset(paths=args.learn_labels)
ds_predict_features = xr.open_mfdataset(paths=args.predict_features)
# confirm that we have learning datasets that match on the time, lev, lat, and lon dimension/coordinate
if np.any(ds_learn_features.variables['time'].values != ds_learn_labels.variables['time'].values):
raise ValueError('Non-matching time values between feature and label datasets')
if np.any(ds_learn_features.variables['lev'].values != ds_learn_labels.variables['lev'].values):
raise ValueError('Non-matching level values between feature and label datasets')
if np.any(ds_learn_features.variables['lat'].values != ds_learn_labels.variables['lat'].values):
raise ValueError('Non-matching lat values between feature and label datasets')
if np.any(ds_learn_features.variables['lon'].values != ds_learn_labels.variables['lon'].values):
raise ValueError('Non-matching lon values between feature and label datasets')
# confirm that the learning and prediction datasets match on the lev, lat, and lon dimension/coordinate
# it's likely that we'll use more times for training than for prediction, so we ignore those differences
if np.any(ds_learn_features.variables['lev'].values != ds_predict_features.variables['lev'].values):
raise ValueError('Non-matching level values between train and predict feature datasets')
if np.any(ds_learn_features.variables['lat'].values != ds_predict_features.variables['lat'].values):
raise ValueError('Non-matching lat values between train and predict feature datasets')
if np.any(ds_learn_features.variables['lon'].values != ds_predict_features.variables['lon'].values):
raise ValueError('Non-matching lon values between train and predict feature datasets')
# trim out all non-relevant data variables from the datasets
for var in ds_learn_features.data_vars:
if var not in features:
ds_learn_features = ds_learn_features.drop(var)
for var in ds_learn_labels.data_vars:
if var not in labels:
ds_learn_labels = ds_learn_labels.drop(var)
for var in ds_predict_features.data_vars:
if var not in features:
ds_predict_features = ds_predict_features.drop(var)
# get data dimension sizes
size_time = ds_learn_features.time.size
size_lev = ds_learn_features.lev.size
size_lat = ds_learn_features.lat.size
size_lon = ds_learn_features.lon.size
# allocate an array for a single predicted variable based on the above dimension sizes
# TODO do this for all labels, for the case where there are multiple labels to predict
prediction = np.empty(dtype=float, shape=(ds_predict_features.time.size, size_lev, size_lat, size_lon))
# define the model
model = define_model_cnn(size_time, size_lat, size_lon, len(features), len(labels))
# display the model summary
model.summary()
# initialize a list to store scalers for each feature/label
scalers_x = [MinMaxScaler(feature_range=(0, 1))] * len(features)
scalers_y = [MinMaxScaler(feature_range=(0, 1))] * len(labels)
# loop over each level, keeping a record of the error rate for each level, for later visualization
for lev in range(size_lev):
# get the array of features for this level (all times/lats/lons)
train_x = pull_vars_into_array(ds_learn_features,
features,
lev)
# get the array of labels for this level (all times/lats/lons)
train_y = pull_vars_into_array(ds_learn_labels,
labels,
lev)
# get the new features from which we'll predict new label(s)
predict_x = pull_vars_into_array(ds_predict_features,
features,
lev)
# data is 4-D with shape (times, lats, lons, vars), scalers can only work on 2-D arrays,
# so for each feature we scale the corresponding 3-D array of values after flattening it,
# then reshape back into the original shape
for feature_ix in range(len(features)):
scaler = scalers_x[feature_ix]
feature_train = train_x[:, :, :, feature_ix].flatten().reshape(-1, 1)
feature_predict = predict_x[:, :, :, feature_ix].flatten().reshape(-1, 1)
scaled_train = scaler.fit_transform(feature_train)
scaled_predict = scaler.fit_transform(feature_predict)
reshaped_scaled_train = np.reshape(scaled_train, newshape=(size_time, size_lat, size_lon))
reshaped_scaled_predict = np.reshape(scaled_predict, newshape=(predict_x.shape[0], size_lat, size_lon))
train_x[:, :, :, feature_ix] = reshaped_scaled_train
predict_x[:, :, :, feature_ix] = reshaped_scaled_predict
for label_ix in range(len(labels)):
scaler = scalers_y[label_ix]
label_train = train_y[:, :, :, label_ix].flatten().reshape(-1, 1)
scaled_train = scaler.fit_transform(label_train)
reshaped_scaled_train = np.reshape(scaled_train, newshape=(size_time, size_lat, size_lon))
train_y[:, :, :, label_ix] = reshaped_scaled_train
# reshape from 4-D to 5-D (expected model input shape)
train_x = np.reshape(train_x, newshape=(1, ) + train_x.shape)
train_y = np.reshape(train_y, newshape=(1, ) + train_y.shape)
predict_x = np.reshape(predict_x, newshape=(1, ) + predict_x.shape)
# train the model for this level
model.fit(train_x, train_y, shuffle=True, epochs=8, verbose=2)
# use the model to predict label values from new inputs
predict_y = model.predict(predict_x, verbose=1)
# unscale the predicted labels | |
password: IQFeed subscriber's pwd
The user of the app must have a subscription to IQFeed. Pass the user's
password either here or in cmd line options when IQFeed is started.
process_current_password called on listeners on success.
"""
self._send_cmd("S,SET PASSWORD,%<PASSWORD>" % password)
def set_autoconnect(self, autoconnect: bool = True) -> None:
"""
Tells IQFeed to autoconnect to DTN servers on startup or not
:param autoconnect: True means autoconnect, False means don't
process_autoconnect_[on/off] called on listeners to acknowledge
success.
"""
if autoconnect:
self._send_cmd("S,SET AUTOCONNECT,On\r\n")
else:
self._send_cmd("S,SET AUTOCONNECT,Off\r\n")
def save_login_info(self, save_info: bool = True) -> None:
"""
Tells IQFeed to save the login info
:param save_info: True means save info, False means don't
process_login_info_[saved/no_saved] called on listeners to acknowledge
success.
"""
if save_info:
self._send_cmd("S,SET SAVE LOGIN INFO,On\r\n")
else:
self._send_cmd("S,SET SAVE LOGIN INFO,Off\r\n")
def client_stats_on(self) -> None:
"""
Request client statistics from IQFeed.
Call this is you want IQFeed to send you a message every second about
the status of every connection. Lets you know things like number of
subscriptions and if the connection is buffering.
process_client_stats is called on listeners every second for each
connection to IQFeed when you request client statistics.
"""
self._send_cmd("S,CLIENTSTATS ON\r\n")
def client_stats_off(self) -> None:
"""Turn off client statistics."""
self._send_cmd("S,CLIENTSTATS OFF\r\n")
def set_admin_variables(self, product: str, login: str, password: str,
autoconnect: bool = True,
save_info: bool = True) -> None:
"""Set the administrative variables."""
self.register_client_app(product)
self.set_login(login)
self.set_password(password)
self.set_autoconnect(autoconnect)
self.save_login_info(save_info)
class HistoryConn(FeedConn):
"""
HistoryConn is used to get historical data from IQFeed's lookup socket.
This class returns historical data as the return value from the function
used to request the data. So a listener is not strictly necessary.
However it derives from FeedConn so basic administrative
messages etc are still available via a generic IQFeedListener. If you
aren't getting what you expect, it may be a good idea to listen for these
messages to see if that tells you why.
For more details see:
www.iqfeed.net/dev/api/docs/HistoricalviaTCPIP.cfm
"""
host = FeedConn.host
port = FeedConn.lookup_port
# Tick data is returned as a numpy array of this dtype. Note that
# "tick-data" in IQFeed parlance means every trade with the latest top of
# book quote at the time of the trade, NOT every quote and every trade.
tick_type = np.dtype([('tick_id', 'u8'),
('date', 'M8[D]'), ('time', 'm8[us]'),
('last', 'f8'), ('last_sz', 'u8'),
('last_type', 'S1'), ('mkt_ctr', 'u4'),
('tot_vlm', 'u8'), ('bid', 'f8'), ('ask', 'f8'),
('cond1', 'u1'), ('cond2', 'u1'), ('cond3', 'u1'),
('cond4', 'u1')])
tick_h5_type = np.dtype([('tick_id', 'u8'),
('date', 'i8'), ('time', 'i8'),
('last', 'f8'), ('last_sz', 'u8'),
('last_type', 'S1'), ('mkt_ctr', 'u4'),
('tot_vlm', 'u8'), ('bid', 'f8'), ('ask', 'f8'),
('cond1', 'u1'), ('cond2', 'u1'), ('cond3', 'u1'),
('cond4', 'u1')])
# Bar data is returned as a numpy array of this type.
bar_type = np.dtype([('date', 'M8[D]'), ('time', 'm8[us]'),
('open_p', 'f8'), ('high_p', 'f8'),
('low_p', 'f8'), ('close_p', 'f8'),
('tot_vlm', 'u8'), ('prd_vlm', 'u8'),
('num_trds', 'u8')])
bar_h5_type = np.dtype([('date', 'i8'), ('time', 'i8'),
('open_p', 'f8'), ('high_p', 'f8'),
('low_p', 'f8'), ('close_p', 'f8'),
('tot_vlm', 'u8'), ('prd_vlm', 'u8'),
('num_trds', 'u8')])
# Daily data is returned as a numpy array of this type.
# Daily data means daily, weekly, monthly and annual data.
daily_type = np.dtype(
[('date', 'M8[D]'), ('open_p', 'f8'), ('high_p', 'f8'),
('low_p', 'f8'), ('close_p', 'f8'), ('prd_vlm', 'u8'),
('open_int', 'u8')])
daily_h5_type = np.dtype(
[('date', 'i8'), ('open_p', 'f8'), ('high_p', 'f8'),
('low_p', 'f8'), ('close_p', 'f8'), ('prd_vlm', 'u8'),
('open_int', 'u8')])
# Private data structure
_databuf = namedtuple("_databuf",
['failed', 'err_msg', 'num_pts', 'raw_data'])
def __init__(self, name: str = "HistoryConn", host: str = FeedConn.host,
port: int = port):
super().__init__(name, host, port)
self._set_message_mappings()
self._req_num = 0
self._req_buf = {}
self._req_numlines = {}
self._req_event = {}
self._req_failed = {}
self._req_err = {}
self._req_lock = threading.RLock()
self._req_num_lock = threading.RLock()
def _set_message_mappings(self) -> None:
"""Set the message mappings"""
super()._set_message_mappings()
self._pf_dict['H'] = self._process_datum
def _send_connect_message(self):
"""The lookup socket does not accept connect messages."""
pass
def _process_datum(self, fields: Sequence[str]) -> None:
req_id = fields[0]
if 'E' == fields[1]:
# Error
self._req_failed[req_id] = True
err_msg = "Unknown Error"
if len(fields) > 2:
if fields[2] != "":
err_msg = fields[2]
self._req_err[req_id] = err_msg
elif '!ENDMSG!' == fields[1]:
self._req_event[req_id].set()
else:
self._req_buf[req_id].append(fields)
self._req_numlines[req_id] += 1
def _get_next_req_id(self) -> str:
with self._req_num_lock:
req_id = "H_%.10d" % self._req_num
self._req_num += 1
return req_id
def _cleanup_request_data(self, req_id: str) -> None:
with self._req_lock:
del self._req_failed[req_id]
del self._req_err[req_id]
del self._req_buf[req_id]
del self._req_numlines[req_id]
def _setup_request_data(self, req_id: str) -> None:
"""Setup empty buffers and other variables for a request."""
with self._req_lock:
self._req_buf[req_id] = deque()
self._req_numlines[req_id] = 0
self._req_failed[req_id] = False
self._req_err[req_id] = ""
self._req_event[req_id] = threading.Event()
def _get_data_buf(self, req_id: str) -> namedtuple:
"""Get the data buffer associated with a specific request."""
with self._req_lock:
buf = HistoryConn._databuf(
failed=self._req_failed[req_id],
err_msg=self._req_err[req_id],
num_pts=self._req_numlines[req_id],
raw_data=self._req_buf[req_id])
self._cleanup_request_data(req_id)
return buf
def _read_ticks(self, req_id: str) -> np.array:
"""Get buffer for req_id and transform to a numpy array of ticks."""
res = self._get_data_buf(req_id)
if res.failed:
return np.array([res.err_msg], dtype='object')
else:
data = np.empty(res.num_pts, HistoryConn.tick_type)
line_num = 0
while res.raw_data and (line_num < res.num_pts):
dl = res.raw_data.popleft()
(dt, tm) = fr.read_posix_ts_us(dl[1])
data[line_num]['date'] = dt
data[line_num]['time'] = tm
data[line_num]['last'] = np.float64(dl[2])
data[line_num]['last_sz'] = np.uint64(dl[3])
data[line_num]['tot_vlm'] = np.uint64(dl[4])
data[line_num]['bid'] = np.float64(dl[5])
data[line_num]['ask'] = np.float64(dl[6])
data[line_num]['tick_id'] = np.uint64(dl[7])
data[line_num]['last_type'] = dl[8]
data[line_num]['mkt_ctr'] = np.uint32(dl[9])
cond_str = dl[10]
num_cond = len(cond_str) / 2
if num_cond > 0:
data[line_num]['cond1'] = np.uint8(int(cond_str[0:2], 16))
else:
data[line_num]['cond1'] = 0
if num_cond > 1:
data[line_num]['cond2'] = np.uint8(int(cond_str[2:4], 16))
else:
data[line_num]['cond2'] = 0
if num_cond > 2:
data[line_num]['cond3'] = np.uint8(int(cond_str[4:6], 16))
else:
data[line_num]['cond3'] = 0
if num_cond > 3:
data[line_num]['cond4'] = np.uint8(int(cond_str[6:8], 16))
else:
data[line_num]['cond4'] = 0
line_num += 1
if line_num >= res.num_pts:
assert len(res.raw_data) == 0
if len(res.raw_data) == 0:
assert line_num >= res.num_pts
return data
def request_ticks(self, ticker: str, max_ticks: int, ascend: bool = False,
timeout: int = None) -> np.array:
"""
Request historical tickdata. Including upto the last second.
:param ticker: Ticker symbol
:param max_ticks: The most recent max_ticks trades.
:param ascend: True means sorted oldest to latest, False opposite
:param timeout: Wait for timeout seconds. Default None
:return: A numpy array of dtype HistoryConn.tick_type
HTX,[Symbol],[MaxDatapoints],[DataDirection],[RequestID],
DatapointsPerSend]<CR><LF>
"""
req_id = self._get_next_req_id()
self._setup_request_data(req_id)
pts_per_batch = min((max_ticks, 100))
req_cmd = ("HTX,%s,%d,%d,%s,%d\r\n" % (
ticker, max_ticks, ascend, req_id, pts_per_batch))
self._send_cmd(req_cmd)
self._req_event[req_id].wait(timeout=timeout)
data = self._read_ticks(req_id)
if data.dtype == object:
iqfeed_err = str(data[0])
err_msg = "Request: %s, Error: %s" % (req_cmd, iqfeed_err)
if iqfeed_err == '!NO_DATA!':
raise NoDataError(err_msg)
elif iqfeed_err == "Unauthorized user ID.":
raise UnauthorizedError(err_msg)
else:
raise RuntimeError(err_msg)
else:
return data
def request_ticks_for_days(self, ticker: str, num_days: int,
bgn_flt: datetime.time = None,
end_flt: datetime.time = None,
ascend: bool = False, max_ticks: int = None,
timeout: int = None) -> np.array:
"""
Request tickdata for a certain number of days in the past.
:param ticker: Ticker symbol
:param num_days: Number of calendar days. 1 means today only.
:param bgn_flt: Each day's data starting at bgn_flt
:param end_flt: Each day's data no later than end_flt
:param ascend: True means sorted oldest to latest, False opposite
:param max_ticks: Only the most recent max_ticks trades. Default None
:param timeout: Wait upto timeout seconds. Default None
:return: A numpy array of dtype HistoryConn.tick_type
HTD,[Symbol],[Days],[MaxDatapoints],[BeginFilterTime],[EndFilterTime],
[DataDirection],[RequestID],[DatapointsPerSend]<CR><LF>
"""
req_id = self._get_next_req_id()
self._setup_request_data(req_id)
bf_str = fr.time_to_hhmmss(bgn_flt)
ef_str = fr.time_to_hhmmss(end_flt)
mt_str = fr.blob_to_str(max_ticks)
pts_per_batch = 100
if max_ticks is not None:
pts_per_batch = min((max_ticks, 100))
req_cmd = ("HTD,%s,%d,%s,%s,%s,%d,%s,%d\r\n" % (
ticker, num_days, mt_str, bf_str, ef_str, ascend, req_id,
pts_per_batch))
self._send_cmd(req_cmd)
self._req_event[req_id].wait(timeout=timeout)
data = self._read_ticks(req_id)
if data.dtype == object:
iqfeed_err = str(data[0])
err_msg = "Request: %s, Error: %s" % (req_cmd, iqfeed_err)
if iqfeed_err == '!NO_DATA!':
raise NoDataError(err_msg)
elif iqfeed_err == "Unauthorized user ID.":
raise UnauthorizedError(err_msg)
else:
raise RuntimeError(err_msg)
else:
return data
def request_ticks_in_period(self, ticker: str, bgn_prd: datetime.datetime,
end_prd: datetime.datetime,
bgn_flt: datetime.time = None,
end_flt: datetime.time = None,
ascend: bool = False, max_ticks: int = None,
timeout: int = None) -> np.array:
"""
Request tickdata in a certain period.
:param ticker: Ticker symbol.
:param bgn_prd: Start of the period.
:param end_prd: End of the period.
:param bgn_flt: Each day's data starting at bgn_flt
:param end_flt: Each day's data no later than end_flt
:param ascend: True | |
from logging import getLogger
from os.path import dirname, isfile, splitext, basename
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg,
NavigationToolbar2QT as NavigationToolbar,
)
from ezdxf import readfile
from numpy import angle as np_angle
from numpy import array, pi, argmax, argmin
from numpy import max as np_max, min as np_min
from PySide2.QtCore import QUrl, Qt
from PySide2.QtGui import QIcon, QPixmap, QDesktopServices
from PySide2.QtWidgets import (
QComboBox,
QDialog,
QFileDialog,
QMessageBox,
QPushButton,
QHeaderView,
)
from ...Classes.HoleUD import HoleUD
from ...Classes.Magnet import Magnet
from ...Classes.SurfLine import SurfLine
from ...GUI.Dxf.dxf_to_pyleecan import dxf_to_pyleecan_list, convert_dxf_with_FEMM
from ...GUI.Resources import pixmap_dict
from ...GUI.Tools.MPLCanvas import MPLCanvas
from ...GUI.Tools.FloatEdit import FloatEdit
from ...GUI import gui_option
from ...loggers import GUI_LOG_NAME
from .Ui_DXF_Surf import Ui_DXF_Surf
from ...Functions.labels import HOLEM_LAB, HOLEV_LAB
from ...Functions.init_fig import init_fig
# Column index for table
DEL_COL = 0
HL_COL = 1
TYPE_COL = 2
REF_COL = 3
OFF_COL = 4
ICON_SIZE = 24
# Unselected, selected, selected-bottom-mag
COLOR_LIST = ["k", "r", "c"]
Z_TOL = 1e-4 # Point comparison tolerance
class DXF_Surf(Ui_DXF_Surf, QDialog):
"""Dialog to create Vents or BoreUD objects from DXF files"""
convert_dxf_with_FEMM = convert_dxf_with_FEMM
def __init__(self, dxf_path=None, Zh=None, lam=None, is_vent=True):
"""Initialize the Dialog
Parameters
----------
self : DXF_Surf
a DXF_Surf object
dxf_path : str
Path to a dxf file to read
"""
# Widget setup
QDialog.__init__(self)
self.setupUi(self)
# Tutorial video link
self.url = "https://pyleecan.org/videos.html#feature-tutorials"
self.b_tuto.setEnabled(False)
# Initialize the graph
self.init_graph()
# Set default values
if Zh is not None:
self.si_Zh.setValue(Zh)
if lam is None:
self.lam = lam
else:
self.lam = lam.copy()
# Init properties
self.line_list = list() # List of line from DXF
self.selected_list = list() # List of currently selected lines
self.Zcenter = 0 # For translate offset
# Set DXF edit widget
self.lf_center_x.setValue(0)
self.lf_center_y.setValue(0)
self.lf_scaling.validator().setBottom(0)
self.lf_scaling.setValue(1)
# Not available Yet (for BoreUD)
self.in_per_a.hide()
self.si_per_a.hide()
# Load the DXF file if provided
self.dxf_path = dxf_path
if dxf_path is not None and isfile(dxf_path):
self.open_document()
# Setup Path selector for DXF files
self.w_path_selector.obj = self
self.w_path_selector.param_name = "dxf_path"
self.w_path_selector.verbose_name = "DXF File"
self.w_path_selector.extension = "DXF file (*.dxf)"
self.w_path_selector.set_path_txt(self.dxf_path)
self.w_path_selector.update()
# Connect signals to slot
self.w_path_selector.pathChanged.connect(self.open_document)
self.b_save.pressed.connect(self.save)
self.b_plot.pressed.connect(self.plot)
self.b_reset.pressed.connect(self.update_graph)
self.b_cancel.pressed.connect(self.remove_selection)
self.b_tuto.pressed.connect(self.open_tuto)
self.is_convert.toggled.connect(self.enable_tolerance)
self.lf_center_x.editingFinished.connect(self.set_center)
self.lf_center_y.editingFinished.connect(self.set_center)
# Display the GUI
self.show()
def enable_tolerance(self):
"""Enable/Disable tolerance widget"""
self.lf_tol.setEnabled(self.is_convert.isChecked())
self.in_tol.setEnabled(self.is_convert.isChecked())
def open_document(self):
"""Open a new dxf in the viewer
Parameters
----------
self : DXF_Surf
a DXF_Surf object
"""
# Check convertion
if self.is_convert.isChecked():
getLogger(GUI_LOG_NAME).info("Converting dxf file: " + self.dxf_path)
self.dxf_path = self.convert_dxf_with_FEMM(
self.dxf_path, self.lf_tol.value()
)
self.w_path_selector.blockSignals(True)
self.w_path_selector.set_path_txt(self.dxf_path)
self.w_path_selector.blockSignals(False)
getLogger(GUI_LOG_NAME).debug("Reading dxf file: " + self.dxf_path)
# Read the DXF file
try:
document = readfile(self.dxf_path)
modelspace = document.modelspace()
# Convert DXF to pyleecan objects
self.line_list = dxf_to_pyleecan_list(modelspace)
# Display
# selected line: 0: unselected, 1:selected
self.selected_list = [0 for line in self.line_list]
self.surf_list = list()
self.update_graph()
except Exception as e:
QMessageBox().critical(
self,
self.tr("Error"),
self.tr("Error while reading dxf file:\n" + str(e)),
)
def init_graph(self):
"""Initialize the viewer
Parameters
----------
self : DXF_Surf
a DXF_Surf object
"""
# Init fig
fig, axes = plt.subplots(tight_layout=False)
self.fig = fig
self.axes = axes
# Set plot layout
canvas = FigureCanvasQTAgg(fig)
toolbar = NavigationToolbar(canvas, self)
# Remove Subplots button
unwanted_buttons = ["Subplots", "Customize", "Save"]
for x in toolbar.actions():
if x.text() in unwanted_buttons:
toolbar.removeAction(x)
# Adding custom icon on mpl toobar
icons_buttons = [
"Home",
"Pan",
"Zoom",
"Back",
"Forward",
]
for action in toolbar.actions():
if action.text() in icons_buttons and "mpl_" + action.text() in pixmap_dict:
action.setIcon(QIcon(pixmap_dict["mpl_" + action.text()]))
# Change default file name
canvas.get_default_filename = "DXF_Surf_visu.png"
self.layout_plot.insertWidget(1, toolbar)
self.layout_plot.insertWidget(2, canvas)
self.canvas = canvas
axes.set_axis_off()
self.toolbar = toolbar
self.xlim = self.axes.get_xlim()
self.ylim = self.axes.get_ylim()
def on_draw(event):
self.xlim = self.axes.get_xlim()
self.ylim = self.axes.get_ylim()
# Setup interaction with graph
def select_line(event):
"""Function to select/unselect the closest line from click"""
# Ignore if matplotlib action is clicked
is_ignore = False
for action in self.toolbar.actions():
if action.isChecked():
is_ignore = True
if not is_ignore:
X = event.xdata # X position of the click
Y = event.ydata # Y position of the click
# Get closer pyleecan object
Z = X + 1j * Y
min_dist = float("inf")
closest_id = -1
for ii, line in enumerate(self.line_list):
line_dist = line.comp_distance(Z)
if line_dist < min_dist:
closest_id = ii
min_dist = line_dist
# Select/unselect line
if self.selected_list[closest_id] == 0: # Unselected to selected
self.selected_list[closest_id] = 1
elif self.selected_list[closest_id] == 1:
# selected to Unselected
self.selected_list[closest_id] = 0
# Change line color
point_list = array(self.line_list[closest_id].discretize(20))
color = COLOR_LIST[self.selected_list[closest_id]]
axes.plot(point_list.real, point_list.imag, color, zorder=2)
self.axes.set_xlim(self.xlim)
self.axes.set_ylim(self.ylim)
self.canvas.draw()
def zoom(event):
"""Function to zoom/unzoom according the mouse wheel"""
base_scale = 0.8 # Scaling factor
# get the current x and y limits
ax = self.axes
cur_xlim = ax.get_xlim()
cur_ylim = ax.get_ylim()
cur_xrange = (cur_xlim[1] - cur_xlim[0]) * 0.5
cur_yrange = (cur_ylim[1] - cur_ylim[0]) * 0.5
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
if event.button == "down":
# deal with zoom in
scale_factor = 1 / base_scale
elif event.button == "up":
# deal with zoom out
scale_factor = base_scale
else:
# deal with something that should never happen
scale_factor = 1
# set new limits
ax.set_xlim(
[xdata - cur_xrange * scale_factor, xdata + cur_xrange * scale_factor]
)
ax.set_ylim(
[ydata - cur_yrange * scale_factor, ydata + cur_yrange * scale_factor]
)
self.canvas.draw() # force re-draw
# Connect the function
self.canvas.mpl_connect("draw_event", on_draw)
self.canvas.mpl_connect("button_press_event", select_line)
self.canvas.mpl_connect("scroll_event", zoom)
# Axis cleanup
axes.axis("equal")
axes.set_axis_off()
def set_center(self):
"""Update the position of the center"""
self.Zcenter = self.lf_center_x.value() + 1j * self.lf_center_y.value()
self.update_graph()
def update_graph(self):
"""Clean and redraw all the lines in viewer
Parameters
----------
self : DXF_Surf
a DXF_Surf object
"""
fig, axes = self.fig, self.axes
axes.clear()
axes.set_axis_off()
# Draw the lines in the correct color
for ii, line in enumerate(self.line_list):
point_list = array(line.discretize(20))
color = COLOR_LIST[self.selected_list[ii]]
axes.plot(point_list.real, point_list.imag, color, zorder=1)
# Add lamination center
axes.plot(self.Zcenter.real, self.Zcenter.imag, "rx", zorder=0)
axes.text(self.Zcenter.real, self.Zcenter.imag, "O")
self.canvas.draw()
def check_selection(self):
"""Check if every line in the selection form a surface
Parameters
----------
self : DXF_Surf
a DXF_Surf object
Returns
-------
is_surf : bool
True if it forms a surface
"""
# Create list of begin and end point for all lines
point_list = list()
for ii, line in enumerate(self.line_list):
if self.selected_list[ii]:
point_list.append(line.get_begin())
point_list.append(line.get_end())
# Check with a tolerance if every point is twice in the list
if len(point_list) == 0:
return False
for p1 in point_list:
count = 0
for p2 in point_list:
if abs(p1 - p2) < Z_TOL:
count += 1
if count != 2:
return False
return True
def get_surface(self):
"""Validate the selection and create a surface object
Parameters
----------
self : DXF_Surf
a DXF_Surf object
"""
# Get all the selected lines
line_list = list()
index_list = list()
for ii, line in enumerate(self.line_list):
if self.selected_list[ii]:
index_list.append(str(ii))
line_list.append(line.copy())
# Sort the lines (begin = end)
curve_list = list()
curve_list.append(line_list.pop())
while len(line_list) > 0:
end = curve_list[-1].get_end()
for ii in range(len(line_list)):
if abs(line_list[ii].get_begin() - end) < Z_TOL:
break
if abs(line_list[ii].get_end() - end) < Z_TOL:
line_list[ii].reverse()
break
curve_list.append(line_list.pop(ii))
# Create the Surface object
surf = SurfLine(line_list=curve_list)
surf.comp_point_ref(is_set=True)
return surf
def remove_selection(self):
# Remove selection
self.selected_list = [0 for line in self.line_list]
# Redraw all the lines (in black)
for ii, line in enumerate(self.line_list):
point_list = array(line.discretize(20))
color = COLOR_LIST[self.selected_list[ii]]
self.axes.plot(point_list.real, point_list.imag, color, zorder=2)
self.canvas.draw()
def get_hole(self):
"""Generate the HoleUD object corresponding to the selected surfaces
Parameters
----------
self : DXF_Surf
a DXF_Surf object
Returns
-------
hole : HoleUD
User defined hole according to selected surfaces
"""
if self.lf_scaling.value() == 0: # Avoid error
self.lf_scaling.setValue(1)
surf = self.get_surface()
surf.scale(self.lf_scaling.value())
surf.label = HOLEV_LAB
hole = HoleUD(surf_list=[surf])
# Translate
if self.Zcenter != 0:
surf.translate(-self.Zcenter * self.lf_scaling.value())
# Rotation
surf.rotate(-1 * np_angle(surf.point_ref))
# Set metadata
hole.Zh = self.si_Zh.value()
# Remove materials => To be set in GUI
hole.mat_void = None
return hole
def plot(self):
"""Plot the current state of the hole
Parameters
----------
self : DXF_Surf
a DXF_Surf object
"""
hole = self.get_hole()
if self.lam is None:
hole.plot(is_add_arrow=True)
else:
fig, (ax1, ax2) = plt.subplots(1, 2)
hole.plot(fig=fig, ax=ax1, is_add_arrow=True, is_add_ref=False)
self.lam.axial_vent = [hole]
self.lam.plot(fig=fig, ax=ax2)
def save(self):
"""Save the HoleUD object in a json file
Parameters
----------
self : DXF_Surf
a DXF_Surf object
"""
hole = self.get_hole()
save_file_path = QFileDialog.getSaveFileName(
self, self.tr("Save file"), | |
<filename>FactorToConvertUnits.py
# <NAME>, Apr 2013, ISC RAS, Ivanovo, Russia
#
# Copyright 2013 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys,math
from copy import copy
from numpy import isnan
# Info variables
init_date='13.04.2013'; init_author='<NAME>'; init_place='Ivanovo, ISC RAS'
lastmod_date='25.07.2014'; version='1.5'; lastmod_author='<NAME>'; lastmod_place='Massy, Paris'
# Universal constants
Na=6.02214129e23
pi=math.pi
kB=1.3806488e-23
T298=298.15
### Conversion factors
# Internal units:
# Energy = 'kJ'
# Number = 'mol'
# Distance = 'nm'
# Angle = 'degree'
# The list of conversion factors to internal units
# Extend this list if units/unit types you need are misiing
UnitFact = {'Energy' : {'kj':1.0,'kcal':0.239005736, 'kbt':1.0/(kB*T298/1000.0),'j':1000, 'kb': 1000/kB},
'Distance': {'nm':1.0,'angstr':10.0,'m':1.0e-9,'cm':1.0e-7,'dm':1e-8},
'Angle' : {'degree':1.0,'rad':1*pi/180},
'Number' : {'mol':1.0,'number':Na}
}
kcal_mol_angstr_rad = { 'Energy' : 'kcal',
'Distance': 'angstr',
'Angle' : 'rad',
'Number' : 'mol'
}
kj_mol_nm_rad = { 'Energy' : 'kj',
'Distance': 'nm',
'Angle' : 'rad',
'Number' : 'mol'
}
GMXunits = copy(kj_mol_nm_rad)
WHAMunits = copy(kcal_mol_angstr_rad)
AMBERunits = copy(kcal_mol_angstr_rad)
CHARMMunits = copy(kcal_mol_angstr_rad)
RISMMOLunits = copy(kcal_mol_angstr_rad)
# Mind lower case letters for the dictionary keys
SpecialKeyUnits = { 'togmx': GMXunits,
'towham': WHAMunits,
'toamber': AMBERunits,
'tocharmm': CHARMMunits,
'torismmol': RISMMOLunits,
'kj_mol_nm_rad': kj_mol_nm_rad,
'kcal_mol_angstr_rad': kcal_mol_angstr_rad
}
#-------------------------------------------------------------------------------
# Internal functions:
# The function returns the factor to conver units
def FactorToConvertUnits(UnitIn,UnitOut):
# Vars in:
# UnitIn - string with the units to convert from
# UnitOut - string with the units to convert to
# Returning: the conversion factor, or nan if error occured
# The function parses a string with units
def SplitUnitString(unitstring):
# Vars in:
# unitstring - string with units (e.g. "kJ*mol^-1")
# Returning:
# ulv - list with the unit sequence in the given string (e.g. ['kJ','mol'])
# ulp - list with the unit power sequence (e.g. [1,-1])
ustr=unitstring.replace(' ','')
ustr=ustr.replace('_','*')
ul_init=ustr
ul=[] # list for units
pf=[1.0] # list for unit power factors (e.g. if there is / sign, then the power should be inversed)
tmp=ustr
for l in ustr:
if l == '*':
val,tmp=tmp.split('*',1)
ul.append(val)
pf.append(1.0)
elif l == '/':
val,tmp=tmp.split('/',1)
ul.append(val)
pf.append(-1.0)
else:
continue
ul.append(tmp)
ulv=[]
ulp=[]
for i,val in enumerate(ul):
if '^' in val:
tmp=val.split('^');
if len(tmp) != 2:
sys.stderr.write('!Error in SplitUnitString: more than 2 power signs [^] in a field. Returning NaN.\n')
return float('NaN')
unit=tmp[0]
try: power=float(tmp[1])*pf[i]
except:
sys.stderr.write('!Error in SplitUnitString: cant evaluate power for unit ['+unit+']. Either power is NaN ['+tmp[1]+'] or power factor is NaN ['+str(pf[i])+']. Returning NaN.\n')
return float('NaN')
else:
unit=val
try: power=1.0*pf[i]
except:
sys.stderr.write('!Error in SplitUnitString: cant evaluate power for unit ['+unit+']. Either power is NaN ['+tmp[1]+'] or power factor is NaN ['+str(pf[i])+']. Returning NaN.\n')
return float('NaN')
ulv.append(unit)
ulp.append(power)
ult=[]
for v in ulv: uts = get_unit_type(v); ult.append(uts)
return (ulv,ulp,ult)
# Function calculates the conversion factor for an element in the list [ulv] having in mind he power [ulp]
def FactorForUnit(unit1,p1, unit2,p2):
# Vars in:
# unit1 - string unit to convert from (e.g. "kJ")
# p1 - power for the unit (e.g. "1")
# unit2 - string unit to convert to (e.g. "kcal")
# p2 - power for the unit (e.g. "1")
# Returning:
# factor to convert unit1^p1 to unit2^p1 (p1 must be equal to p2)
f1=float('NaN')
f2=float('NaN')
for UF in UnitFact.itervalues():
unit1=unit1.lower()
unit2=unit2.lower()
#print unit1,UF.keys()
if unit1 in UF.keys():
f1=UF[unit1]
if unit2 in UF.keys():
f2=UF[unit2]
else:
sys.stderr.write('!Error in FactorForUnit: unit2 ['+unit2+'] is not known OR it is not in the same group as unit1 ['+unit1+']. Returning NaN.\n')
return float('NaN')
#else:
#break
#continue
if isnan(f1):
sys.stderr.write('!Error in FactorForUnit: unit1 ['+unit1+'] is not known. Returning NaN.\n')
return float('NaN')
if p1 != p2:
sys.stderr.write('!Error in FactorForUnit: power1 ['+str(p1)+'] is not equal to power2 ['+str(p2)+']. Returning NaN.\n')
return float('NaN')
else:
try: p=float(p1)
except:
sys.stderr.write('!Error in FactorForUnit: power1 ['+str(p1)+'] is not a number. Returning NaN.\n')
return float('NaN')
return (f2/f1)**p
# The function determines the unit type for given unit string
def get_unit_type(unit):
# Vars in: unit - string unit (e.g. "kJ")
# Returning: unit type (e.g. "Energy")
unit=unit.lower()
for UF,UFname in zip(UnitFact.itervalues(), UnitFact):
#pnrint UF,UFname
if unit in UF.keys():
return UFname
return 'none'
# Parse the given unit strings
[ulv1,ulp1,ult1]=SplitUnitString(UnitIn)
[ulv2,ulp2,ult2]=SplitUnitString(UnitOut)
# Special cases
if ulv2[0].lower() in SpecialKeyUnits.keys():
ult2=ult1
ulp2=ulp1
key=ulv2[0].lower()
ulv2=[]
for v in ult1:
if v!='none': ulv2.append(SpecialKeyUnits[key][v])
else: ulv2.append('none')
# Special cases
#if ulv2[0].lower() == 'togmx':
# ult2=ult1
# ulp2=ulp1
# ulv2=[]
# for v in ult1:
# if v!='none': ulv2.append(GMXunits[v])
# else: ulv2.append('none')
#if ulv2[0].lower() == 'towham':
# ult2=ult1
# ulp2=ulp1
# ulv2=[]
# for v in ult1:
# if v!='none': ulv2.append(WHAMunits[v])
# else: ulv2.append('none')
#print ulv1,ulp1,ult1
#print ulv2,ulp2,ult2
# Take care of the cases when the Number units are not specified explicitly (e.g. one converts "mol*m^-3" "nm^-3")
if len(ulv1)!=len(ulv2):
if len(ulv1)>len(ulv2): longer_arr=ulv1; shorter_arr=ulv2 ; lap=ulp1; sap=ulp2; utll=ult1; utls=ult2
else: longer_arr=ulv2; shorter_arr=ulv1; lap=ulp2; sap=ulp1 ; utll=ult2; utls=ult1
#utls=[]; utll=[]
#for v in shorter_arr: uts = get_unit_type(v); utls.append(uts)
#for v in longer_arr: utl = get_unit_type(v); utll.append(utl)
for i,v in enumerate(longer_arr):
ut1=get_unit_type(v)
if i<=(len(shorter_arr)-1): ut2=get_unit_type(shorter_arr[i])
else: ut2='none'
if ut1!=ut2:
shorter_arr.insert(i,"number") ; sap.insert(i,lap[i]); utls.insert(i,utll[i])
if utls != utll:
sys.stderr.write('!Error in FactorForUnits: the unit type sequences you specified WERE NOT equal AND still not equal after trying to deduce missing unit (we have: for shorter sequence: '+str(utls)+' and for longer sequence: '+str(utll)+'). This might be caused together or independently by the following reasons: 1) the missing unit is not of type "number", 2) some of the units are not known, but this could not be caugth automatically. Please, consult help for known units. Returning NaN.\n')
return float('NaN')
elif sap != lap:
sys.stderr.write('!Error in FactorForUnits: the unit sequences equal but the sequence of unit powers mismatch (for shorter sequence: '+str(sap)+' and for longer sequence: '+str(lap)+'). Returning NaN.\n')
return float('NaN')
else:
pass
# Calculate the conversion factor
factor=1.0
#print ulv1, ulp1, ulv2, ulp2
for u1,p1,u2,p2 in zip(ulv1,ulp1,ulv2,ulp2):
f=FactorForUnit(u1,p1,u2,p2)
factor=factor*f
return factor
#---------------------------------------------------------------------
# Function to show the help
def ShowHelp():
print '------------------------------------------------------------------------------------------'
print ' The unit converter. Written on '+init_date+' by '+init_author+' in '+init_place
print ' The current version '+version+' is released on '+lastmod_date+' by '+lastmod_author+' in '+lastmod_place
print
print " EXAMPLE USAGE: "+sys.argv[0]+" kJ/mol/rad^2 kcal/mol/rad^2 "
print " EXAMPLE USAGE: "+sys.argv[0]+" mol*m^-3 nm^-3 "
print " EXAMPLE USAGE: "+sys.argv[0]+" -h "
print " EXAMPLE USAGE: "+sys.argv[0]+" kcal/mol toGMX "
print
print " The script takes exactly two command line arguments. It returns the factor to convert units in the first argument to units in the second argument. The special signs [*] and [_] mean multiplication, [/] means division, [^] means power. Case insensitive. If the first argument is -h or --help then the help message will be printed and nothing returned. If the second argument is a special unitkey (e.g. [toGMX]) then the units to convert to are generated from a special prestored list, based on the unit type sequence given in the first argument (e.g. [unitconv.py kcal/mol toGMX] corresponds to [unitconv.py kcal/mol kJ/mol], because [kJ] and [mol] are intenal units of Gromacs code (GMX)). If the scripts fails the float(\'NaN\') is retuned."
print
print ' The following units supported so far (easy to extend in the source code):'
for UF,UFname in zip(UnitFact.itervalues(),UnitFact):
print ' '+UFname.ljust(8)+':',UF.keys()
unitkeys=['togmx','towham']
unitkeysinfo=['convert to Gromacs (www.gromacs.org) internal units',
'convert to WHAM code by Grossfield lab (http://membrane.urmc.rochester.edu/content/wham/) units' ]
unitkeydict=['GMXunits','WHAMunits']
print
print ' The following special unitkeys supported so far (easy to extend in the source code):'
for uk,uki,ukd in zip(unitkeys,unitkeysinfo,unitkeydict):
sys.stdout.write(' '+uk.ljust(8)+'- '+uki+': '); | |
#!/usr/bin/env python
from bs4 import BeautifulSoup
import codecs
from collections import defaultdict, OrderedDict
import copy
import glob
from le_utils.constants import licenses, content_kinds, file_formats
import hashlib
import json
import logging
import ntpath
import os
from pathlib import Path
import re
import requests
from ricecooker.classes.licenses import get_license
from ricecooker.chefs import JsonTreeChef
from ricecooker.utils import downloader, html_writer
from ricecooker.utils.caching import CacheForeverHeuristic, FileCache, CacheControlAdapter
from ricecooker.utils.jsontrees import write_tree_to_json_tree, SUBTITLES_FILE
import time
from urllib.error import URLError
from urllib.parse import urljoin
from utils import if_dir_exists, get_name_from_url, clone_repo, build_path
from utils import if_file_exists, get_video_resolution_format, remove_links
from utils import get_name_from_url_no_ext, get_node_from_channel, get_level_map
from utils import remove_iframes, get_confirm_token, save_response_content
import youtube_dl
BASE_URL = "https://www.youtube.com/user/kkudl/playlists"
DATA_DIR = "chefdata"
COPYRIGHT_HOLDER = "King Khaled University in Abha, Saudi Arabia"
LICENSE = get_license(licenses.CC_BY,
copyright_holder=COPYRIGHT_HOLDER).as_dict()
AUTHOR = "King Khaled University in Abha, Saudi Arabia"
LOGGER = logging.getLogger()
__logging_handler = logging.StreamHandler()
LOGGER.addHandler(__logging_handler)
LOGGER.setLevel(logging.INFO)
DOWNLOAD_VIDEOS = True
LOAD_VIDEO_LIST = False
sess = requests.Session()
cache = FileCache('.webcache')
basic_adapter = CacheControlAdapter(cache=cache)
forever_adapter = CacheControlAdapter(heuristic=CacheForeverHeuristic(), cache=cache)
sess.mount('http://', basic_adapter)
sess.mount(BASE_URL, forever_adapter)
# Run constants
################################################################################
#CHANNEL_NAME = "" # Name of channel
#CHANNEL_SOURCE_ID = "" # Channel's unique id
CHANNEL_DOMAIN = "https://www.youtube.com/user/kkudl/playlists" # Who is providing the content
CHANNEL_LANGUAGE = "ar" # Language of channel
CHANNEL_DESCRIPTION = None # Description of the channel (optional)
CHANNEL_THUMBNAIL = "https://yt3.ggpht.com/a-/AN66SAz9fwCzHEBXcCczoBEGfXr7xKzhooqj0yqVwQ=s288-mo-c-c0xffffffff-rj-k-no" # Local path or url to image file (optional)
# Additional constants
################################################################################
def title_has_numeration(title):
unit_name_ar = ["الوحده", "الوحدة"]
for unit_name in unit_name_ar:
if unit_name in title:
index = title.find(unit_name)
match = re.search("(?P<int>\d+)", title)
if match:
num = int(match.group("int"))
return title[index: index+len(unit_name)] + " " + str(num), num
else:
return title[index: index+len(unit_name)], None
numbers = list(map(str, [1,2,3,4,5,6,7,8,9]))
arab_nums = ["١", "٢", "٣", "٤", "٥"]
title = title.replace("-", " ")
for elem in title.split(" "):
elem = elem.strip()
for num in numbers:
if elem == num:
return title.replace(elem, "").strip(), int(num)
for arab_num in title:
index = title.find(arab_num)
if index != -1 and index >= len(title) - 1:
return title.replace(arab_num, "").strip(), 1
return False, None
def title_patterns(title):
title = re.sub(' +', ' ' , title)
pattern01 = r"\d+\-\d+"
match = re.search(pattern01, title)
if match:
index = match.span()
numbers = title[index[0]:index[1]]
number_unit = numbers.split("-")[0].strip()
return "Unit {}".format(number_unit), int(number_unit)
pattern02 = r"\d+\s+\d+"
match = re.search(pattern02, title)
if match:
index = match.span()
numbers = title[index[0]:index[1]]
number_unit = int(title[index[1]:].strip())
return "Unit {}".format(number), number_unit
title_unit, unit_num = title_has_numeration(title)
if title_unit is not False and unit_num is not None:
return title_unit, unit_num
elif title_unit is not False and unit_num is None:
return title_unit, 1
else:
return title, 1
def remove_units_number(title):
match = re.search(r'\|.*\|', title)
if match:
index = match.span()
new_title = "{} | {}".format(title[:index[0]].strip(), title[index[1]:].strip())
return new_title.strip()
return title
def remove_special_case(title):
title = title.replace("مهارات في علم الرياضيات", "")
title = title.replace("-", "")
return title.strip()
class Node(object):
def __init__(self, title, source_id, lang="en"):
self.title = title
self.source_id = source_id
self.tree_nodes = OrderedDict()
self.lang = lang
self.description = None
def add_node(self, obj):
node = obj.to_node()
if node is not None:
self.tree_nodes[node["source_id"]] = node
def to_node(self):
return dict(
kind=content_kinds.TOPIC,
source_id=self.source_id,
title=self.title,
description=self.description,
language=self.lang,
author=AUTHOR,
license=LICENSE,
children=list(self.tree_nodes.values())
)
class Subject(Node):
def __init__(self, *args, **kwargs):
super(Subject, self).__init__(*args, **kwargs)
self.topics = []
def load(self, filename, auto_parse=False):
with open(filename, "r") as f:
topics = json.load(f)
for topic in topics:
topic_obj = Topic(topic["title"], topic["source_id"], lang=CHANNEL_LANGUAGE)
for unit in topic["units"]:
units = Topic.auto_generate_units(unit["source_id"],
title=unit["title"], lang=unit["lang"],
auto_parse=auto_parse, only_folder_name=unit.get("only", None))
topic_obj.units.extend(units)
self.topics.append(topic_obj)
class Topic(Node):
def __init__(self, *args, **kwargs):
super(Topic, self).__init__(*args, **kwargs)
self.units = []
@staticmethod
def auto_generate_units(url, title=None, lang="en", auto_parse=False, only_folder_name=None):
youtube = YouTubeResource(url)
units = defaultdict(list)
if title is not None:
if only_folder_name is not None:
for subtitle, url in youtube.playlist_name_links():
if subtitle.startswith(only_folder_name):
units[title].append((1, url))
else:
for _, url in youtube.playlist_name_links():
units[title].append((1, url))
else:
for name, url in youtube.playlist_name_links():
unit_name_list = name.split("|")
if len(unit_name_list) > 1 and auto_parse is False:
unit = unit_name_list[1]
unit_name = unit.strip().split(" ")[0]
number_unit = 1
else:
unit_name, number_unit = title_patterns(name)
units[unit_name].append((number_unit, url))
units = sorted(units.items(), key=lambda x: x[1][0], reverse=False)
for title, urls in units:
unit = Unit(title, title, lang=lang)
unit.urls = [url for _, url in urls]
yield unit
class Unit(Node):
def __init__(self, *args, **kwargs):
super(Unit, self).__init__(*args, **kwargs)
self.urls = []
def download(self, download=True, base_path=None):
for url in self.urls:
youtube = YouTubeResource(url, lang=self.lang)
youtube.download(download, base_path)
youtube.title = remove_special_case(remove_units_number(youtube.title))
self.add_node(youtube)
def to_node(self):
children = list(self.tree_nodes.values())
if len(children) == 1:
return children[0]
else:
return dict(
kind=content_kinds.TOPIC,
source_id=self.source_id,
title=self.title,
description=self.description,
language=self.lang,
author=AUTHOR,
license=LICENSE,
children=children
)
class YouTubeResource(object):
def __init__(self, source_id, name=None, type_name="Youtube", lang="ar",
embeded=False, section_title=None):
LOGGER.info(" + Resource Type: {}".format(type_name))
LOGGER.info(" - URL: {}".format(source_id))
self.filename = None
self.type_name = type_name
self.filepath = None
self.name = name
self.section_title = section_title
if embeded is True:
self.source_id = YouTubeResource.transform_embed(source_id)
else:
self.source_id = self.clean_url(source_id)
self.file_format = file_formats.MP4
self.lang = lang
self.is_valid = False
def clean_url(self, url):
if url[-1] == "/":
url = url[:-1]
return url.strip()
@property
def title(self):
return self.name if self.name is not None else self.filename
@title.setter
def title(self, v):
if self.name is not None:
self.name = v
else:
self.filename = v
@classmethod
def is_youtube(self, url, get_channel=False):
youtube = url.find("youtube") != -1 or url.find("youtu.be") != -1
if get_channel is False:
youtube = youtube and url.find("user") == -1 and url.find("/c/") == -1
return youtube
@classmethod
def transform_embed(self, url):
url = "".join(url.split("?")[:1])
return url.replace("embed/", "watch?v=").strip()
def playlist_links(self):
ydl_options = {
'no_warnings': True,
'restrictfilenames':True,
'continuedl': True,
'quiet': False,
'format': "bestvideo[height<={maxheight}][ext=mp4]+bestaudio[ext=m4a]/best[height<={maxheight}][ext=mp4]".format(maxheight='480'),
'noplaylist': False
}
playlist_videos_url = []
with youtube_dl.YoutubeDL(ydl_options) as ydl:
try:
ydl.add_default_info_extractors()
info = ydl.extract_info(self.source_id, download=False)
for entry in info["entries"]:
playlist_videos_url.append(entry["webpage_url"])
except(youtube_dl.utils.DownloadError, youtube_dl.utils.ContentTooShortError,
youtube_dl.utils.ExtractorError) as e:
LOGGER.info('An error occured ' + str(e))
LOGGER.info(self.source_id)
except KeyError as e:
LOGGER.info(str(e))
return playlist_videos_url
def playlist_name_links(self):
name_url = []
source_id_hash = hashlib.sha1(self.source_id.encode("utf-8")).hexdigest()
base_path = build_path([DATA_DIR, CHANNEL_SOURCE_ID])
videos_url_path = os.path.join(base_path, "{}.json".format(source_id_hash))
if if_file_exists(videos_url_path) and LOAD_VIDEO_LIST is True:
with open(videos_url_path, "r") as f:
name_url = json.load(f)
else:
for url in self.playlist_links():
youtube = YouTubeResource(url)
info = youtube.get_video_info(None, False)
name_url.append((info["title"], url))
with open(videos_url_path, "w") as f:
json.dump(name_url, f)
return name_url
def get_video_info(self, download_to=None, subtitles=True):
ydl_options = {
'writesubtitles': subtitles,
'allsubtitles': subtitles,
'no_warnings': True,
'restrictfilenames':True,
'continuedl': True,
'quiet': False,
'format': "bestvideo[height<={maxheight}][ext=mp4]+bestaudio[ext=m4a]/best[height<={maxheight}][ext=mp4]".format(maxheight='480'),
'outtmpl': '{}/%(id)s'.format(download_to),
'noplaylist': True
}
with youtube_dl.YoutubeDL(ydl_options) as ydl:
try:
ydl.add_default_info_extractors()
info = ydl.extract_info(self.source_id, download=(download_to is not None))
return info
except(youtube_dl.utils.DownloadError, youtube_dl.utils.ContentTooShortError,
youtube_dl.utils.ExtractorError) as e:
LOGGER.info('An error occured ' + str(e))
LOGGER.info(self.source_id)
except KeyError as e:
LOGGER.info(str(e))
def subtitles_dict(self):
subs = []
video_info = self.get_video_info()
if video_info is not None:
video_id = video_info["id"]
if 'subtitles' in video_info:
subtitles_info = video_info["subtitles"]
for language in subtitles_info.keys():
subs.append(dict(file_type=SUBTITLES_FILE, youtube_id=video_id, language=language))
return subs
#youtubedl has some troubles downloading videos in youtube,
#sometimes raises connection error
#for that I choose pafy for downloading
def download(self, download=True, base_path=None):
if not "watch?" in self.source_id or "/user/" in self.source_id or\
download is False:
return
download_to = build_path([base_path, 'videos'])
for i in range(4):
try:
info = self.get_video_info(download_to=download_to, subtitles=False)
if info is not None:
LOGGER.info(" + Video resolution: {}x{}".format(info.get("width", ""), info.get("height", "")))
self.filepath = os.path.join(download_to, "{}.mp4".format(info["id"]))
self.filename = info["title"]
if self.filepath is not None and os.stat(self.filepath).st_size == 0:
LOGGER.info(" + Empty file")
self.filepath = None
except (ValueError, IOError, OSError, URLError, ConnectionResetError) as e:
LOGGER.info(e)
LOGGER.info("Download retry")
time.sleep(.8)
except (youtube_dl.utils.DownloadError, youtube_dl.utils.ContentTooShortError,
youtube_dl.utils.ExtractorError, OSError) as e:
LOGGER.info(" + An error ocurred, may be the video is not available.")
return
except OSError:
return
else:
return
def to_node(self):
if self.filepath is not None:
files = [dict(file_type=content_kinds.VIDEO, path=self.filepath)]
files += self.subtitles_dict()
node = dict(
kind=content_kinds.VIDEO,
source_id=self.source_id,
title=self.title,
description='',
author=AUTHOR,
files=files,
language=self.lang,
license=LICENSE
)
return node
# The chef subclass
################################################################################
class KingKhaledChef(JsonTreeChef):
HOSTNAME = BASE_URL
TREES_DATA_DIR = os.path.join(DATA_DIR, 'trees')
def __init__(self):
build_path([KingKhaledChef.TREES_DATA_DIR])
super(KingKhaledChef, self).__init__()
def pre_run(self, args, options):
channel_tree = self.scrape(args, options)
self.write_tree_to_json(channel_tree)
def k12_lessons(self):
global CHANNEL_SOURCE_ID
self.RICECOOKER_JSON_TREE = 'ricecooker_json_tree_k12.json'
CHANNEL_NAME = "ELD King Khaled University Learning (العربيّة)"
CHANNEL_SOURCE_ID = "sushi-chef-eld-k12-ar"
channel_tree = dict(
source_domain=KingKhaledChef.HOSTNAME,
source_id=CHANNEL_SOURCE_ID,
title=CHANNEL_NAME,
description="""تحتوي هذه القناة على مجموعة من الدروس في اللغة العربية والتجويد واللغة الإنجليزية والرياضيات الأساسية، وهي مجموعة من المقررات التي صممتها جامعة الملك خالد كجزء من مقرراتها الرقمية المفتوحة. وتناسب هذه الدروس طلاب المرحلة الثانوية ويمكن ملاءمتها مع بعض الصفوف للمرحلة الإعدادية أيضاً."""
[:400], #400 UPPER LIMIT characters allowed
thumbnail=CHANNEL_THUMBNAIL,
author=AUTHOR,
language=CHANNEL_LANGUAGE,
children=[],
license=LICENSE,
)
subject_en = Subject(title="English Language Skills اللغة الإنجليزية",
source_id="English Language Skills اللغة الإنجليزية")
subject_en.load("resources_en_lang_skills.json")
subject_ar = Subject(title="Arabic Language Skills اللغة العربية",
source_id="Arabic Language Skills اللغة الإنجليزية")
subject_ar.load("resources_ar_lang_skills.json")
subject_ar_st = Subject(title="Islamic Studies الثقافة الإسلامية",
source_id="Islamic Studies الثقافة الإسلامية")
subject_ar_st.load("resources_ar_islamic_studies.json")
subject_ar_math | |
value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class IpFreqLimit(AbstractModel):
"""IP限频配置。
"""
def __init__(self):
"""
:param Switch: IP限频配置开关,on或off。
:type Switch: str
:param Qps: 每秒请求数。
注意:此字段可能返回 null,表示取不到有效值。
:type Qps: int
"""
self.Switch = None
self.Qps = None
def _deserialize(self, params):
self.Switch = params.get("Switch")
self.Qps = params.get("Qps")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class IpStatus(AbstractModel):
"""节点 IP 信息
"""
def __init__(self):
"""
:param Ip: 节点 IP
:type Ip: str
:param District: 节点所属区域
:type District: str
:param Isp: 节点所属运营商
:type Isp: str
:param City: 节点所在城市
:type City: str
:param Status: 节点状态
online:上线状态,正常调度服务中
offline:下线状态
:type Status: str
:param CreateTime: 节点 IP 添加时间
:type CreateTime: str
"""
self.Ip = None
self.District = None
self.Isp = None
self.City = None
self.Status = None
self.CreateTime = None
def _deserialize(self, params):
self.Ip = params.get("Ip")
self.District = params.get("District")
self.Isp = params.get("Isp")
self.City = params.get("City")
self.Status = params.get("Status")
self.CreateTime = params.get("CreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class Origin(AbstractModel):
"""源站配置。
"""
def __init__(self):
"""
:param Origins: 主源站列表,IP与域名源站不可混填。配置源站端口["origin1:port1", "origin2:port2"],配置回源权重["origin1::weight1", "origin2::weight2"],同时配置端口与权重 ["origin1:port1:weight1", "origin2:port2:weight2"],权重值有效范围为0-100。
:type Origins: list of str
:param OriginType: 主源站类型,支持domain,ip,分别表示域名源站,ip源站。
设置Origins时必须填写。
注意:此字段可能返回 null,表示取不到有效值。
:type OriginType: str
:param ServerName: 回源时Host头部值。
注意:此字段可能返回 null,表示取不到有效值。
:type ServerName: str
:param OriginPullProtocol: 回源协议类型,支持http,follow,https,分别表示强制http回源,协议跟随回源,https回源。
不传入的情况下默认为http回源.
注意:此字段可能返回 null,表示取不到有效值。
:type OriginPullProtocol: str
:param BackupOrigins: 备份源站列表。
:type BackupOrigins: list of str
:param BackupOriginType: 备份源站类型,同OriginType。
设置BackupOrigins时必须填写。
注意:此字段可能返回 null,表示取不到有效值。
:type BackupOriginType: str
"""
self.Origins = None
self.OriginType = None
self.ServerName = None
self.OriginPullProtocol = None
self.BackupOrigins = None
self.BackupOriginType = None
def _deserialize(self, params):
self.Origins = params.get("Origins")
self.OriginType = params.get("OriginType")
self.ServerName = params.get("ServerName")
self.OriginPullProtocol = params.get("OriginPullProtocol")
self.BackupOrigins = params.get("BackupOrigins")
self.BackupOriginType = params.get("BackupOriginType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PurgePathCacheRequest(AbstractModel):
"""PurgePathCache请求参数结构体
"""
def __init__(self):
"""
:param Paths: 要刷新的目录列表,必须包含协议头部。
:type Paths: list of str
:param FlushType: 刷新类型,flush 代表刷新有更新的资源,delete 表示刷新全部资源。
:type FlushType: str
"""
self.Paths = None
self.FlushType = None
def _deserialize(self, params):
self.Paths = params.get("Paths")
self.FlushType = params.get("FlushType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PurgePathCacheResponse(AbstractModel):
"""PurgePathCache返回参数结构体
"""
def __init__(self):
"""
:param TaskId: 刷新任务Id,前十位为提交任务时的UTC时间。
:type TaskId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PurgeTask(AbstractModel):
"""刷新任务日志详情
"""
def __init__(self):
"""
:param TaskId: 刷新任务ID。
:type TaskId: str
:param Url: 刷新Url。
:type Url: str
:param Status: 刷新任务状态,fail表示失败,done表示成功,process表示刷新中。
:type Status: str
:param PurgeType: 刷新类型,url表示url刷新,path表示目录刷新。
:type PurgeType: str
:param FlushType: 刷新资源方式,flush代表刷新更新资源,delete代表刷新全部资源。
:type FlushType: str
:param CreateTime: 刷新任务提交时间
:type CreateTime: str
"""
self.TaskId = None
self.Url = None
self.Status = None
self.PurgeType = None
self.FlushType = None
self.CreateTime = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.Url = params.get("Url")
self.Status = params.get("Status")
self.PurgeType = params.get("PurgeType")
self.FlushType = params.get("FlushType")
self.CreateTime = params.get("CreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PurgeUrlsCacheRequest(AbstractModel):
"""PurgeUrlsCache请求参数结构体
"""
def __init__(self):
"""
:param Urls: 要刷新的Url列表,必须包含协议头部。
:type Urls: list of str
"""
self.Urls = None
def _deserialize(self, params):
self.Urls = params.get("Urls")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class PurgeUrlsCacheResponse(AbstractModel):
"""PurgeUrlsCache返回参数结构体
"""
def __init__(self):
"""
:param TaskId: 刷新任务Id,前十位为提交任务时的UTC时间。
:type TaskId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class Quota(AbstractModel):
"""刷新用量及刷新配额
"""
def __init__(self):
"""
:param Batch: 单次批量提交配额上限。
:type Batch: int
:param Total: 每日提交配额上限。
:type Total: int
:param Available: 每日剩余的可提交配额。
:type Available: int
"""
self.Batch = None
self.Total = None
self.Available = None
def _deserialize(self, params):
self.Batch = params.get("Batch")
self.Total = params.get("Total")
self.Available = params.get("Available")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class ResourceData(AbstractModel):
"""查询对象及其对应的访问明细数据
"""
def __init__(self):
"""
:param Resource: 资源名称,根据查询条件不同分为以下几类:
具体域名:表示该域名明细数据
multiDomains:表示多域名汇总明细数据
项目 ID:指定项目查询时,显示为项目 ID
all:账号维度明细数据
:type Resource: str
:param EcdnData: 资源对应的数据明细
:type EcdnData: :class:`tencentcloud.ecdn.v20191012.models.EcdnData`
"""
self.Resource = None
self.EcdnData = None
def _deserialize(self, params):
self.Resource = params.get("Resource")
if params.get("EcdnData") is not None:
self.EcdnData = EcdnData()
self.EcdnData._deserialize(params.get("EcdnData"))
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class ResponseHeader(AbstractModel):
"""自定义响应头配置。
"""
def __init__(self):
"""
:param Switch: 自定义响应头开关,on或off。
:type Switch: str
:param HeaderRules: 自定义响应头规则数组。
注意:此字段可能返回 null,表示取不到有效值。
:type HeaderRules: list of HttpHeaderPathRule
"""
self.Switch = None
self.HeaderRules = None
def _deserialize(self, params):
self.Switch = params.get("Switch")
if params.get("HeaderRules") is not None:
self.HeaderRules = []
for item in params.get("HeaderRules"):
obj = HttpHeaderPathRule()
obj._deserialize(item)
self.HeaderRules.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class ServerCert(AbstractModel):
"""https服务端证书配置。
"""
def __init__(self):
"""
:param CertId: 服务器证书id,当证书为腾讯云托管证书时必填。
注意:此字段可能返回 null,表示取不到有效值。
:type CertId: str
:param CertName: 服务器证书名称,当证书为腾讯云托管证书时必填。
注意:此字段可能返回 null,表示取不到有效值。
:type CertName: str
:param Certificate: 服务器证书信息,上传自有证书时必填,必须包含完整的证书链信息。
注意:此字段可能返回 null,表示取不到有效值。
:type Certificate: str
:param PrivateKey: 服务器密钥信息,上传自有证书时必填。
注意:此字段可能返回 null,表示取不到有效值。
:type PrivateKey: str
:param ExpireTime: 证书过期时间。
注意:此字段可能返回 null,表示取不到有效值。
:type ExpireTime: str
:param DeployTime: 证书颁发时间。
注意:此字段可能返回 null,表示取不到有效值。
:type DeployTime: str
:param Message: 证书备注信息。
注意:此字段可能返回 null,表示取不到有效值。
:type Message: str
"""
self.CertId = None
self.CertName = None
self.Certificate = None
self.PrivateKey = None
self.ExpireTime = None
self.DeployTime = None
self.Message = None
def _deserialize(self, params):
self.CertId = params.get("CertId")
self.CertName = params.get("CertName")
self.Certificate = params.get("Certificate")
self.PrivateKey = params.get("PrivateKey")
self.ExpireTime = params.get("ExpireTime")
self.DeployTime = params.get("DeployTime")
self.Message = params.get("Message")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class Sort(AbstractModel):
"""查询结果排序条件。
"""
def __init__(self):
"""
:param Key: 排序字段,当前支持:
createTime,域名创建时间
certExpireTime,证书过期时间
:type Key: str
:param Sequence: asc/desc,默认desc。
:type Sequence: str
"""
self.Key = None
self.Sequence = None
def _deserialize(self, params):
self.Key = params.get("Key")
self.Sequence = params.get("Sequence")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class StartEcdnDomainRequest(AbstractModel):
"""StartEcdnDomain请求参数结构体
"""
def __init__(self):
"""
:param Domain: 待启用域名。
:type Domain: str
"""
self.Domain = None
def _deserialize(self, params):
self.Domain = params.get("Domain")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class StartEcdnDomainResponse(AbstractModel):
"""StartEcdnDomain返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class StopEcdnDomainRequest(AbstractModel):
"""StopEcdnDomain请求参数结构体
"""
def __init__(self):
"""
:param Domain: 待停用域名。
:type Domain: str
"""
self.Domain = None
def _deserialize(self, params):
self.Domain = params.get("Domain")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class StopEcdnDomainResponse(AbstractModel):
"""StopEcdnDomain返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set), Warning)
class Tag(AbstractModel):
"""标签键和标签值
"""
def __init__(self):
"""
:param TagKey: 标签键
注意:此字段可能返回 null,表示取不到有效值。
:type TagKey: str
:param TagValue: 标签值
注意:此字段可能返回 null,表示取不到有效值。
:type TagValue: str
"""
self.TagKey = None
self.TagValue = None
def _deserialize(self, params):
self.TagKey = params.get("TagKey")
self.TagValue = params.get("TagValue")
memeber_set | |
if vdom:
LOG.debug("vdom is: %s", vdom)
if vdom == "global":
url_postfix += '?global=1'
else:
url_postfix += '?vdom=' + vdom
url = self.url_prefix + url_postfix
LOG.debug("urlbuild is %s with crsf: %s", url, self._session.headers)
return url
def mon_url(self, path, name, vdom=None, mkey=None):
self.check_session()
# return builded URL
url_postfix = '/api/v2/monitor/' + path + '/' + name
if mkey:
url_postfix = url_postfix + '/' + \
urlencoding.quote(str(mkey), safe='')
if vdom:
LOG.debug("vdom is: %s", vdom)
if vdom == "global":
url_postfix += '?global=1'
else:
url_postfix += '?vdom=' + vdom
url = self.url_prefix + url_postfix
return url
def download(self, path, name, vdom=None, mkey=None, parameters=None):
"""
Use the download call on the monitoring part of the API.
Can get the config, logs etc..
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/cmdb/<path>/<name>
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add parameters understood by the API call in json. Must set \"destination\": \"file\" and scope
:return:
The file is part of the returned json
"""
url = self.mon_url(path, name, vdom=vdom, mkey=mkey)
res = self._session.get(url, params=parameters, timeout=self.timeout)
LOG.debug("in DOWNLOAD function")
LOG.debug(" result download : %s", res.content)
return res
def upload(self, path, name, vdom=None, mkey=None,
parameters=None, data=None, files=None):
"""
Upload a file (refer to the monitoring part), used for license, config, certificates etc.. uploads.
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/cmdb/<path>/<name>
:param data: json containing the param/values of the object to be set
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add on parameters understood by the API call can be \"&select=\" for example
:param files: the file to be uploaded
:return:
A formatted json with the last response from the API
"""
# TODO should be file not files
# TODO add a test
url = self.mon_url(path, name, vdom=vdom, mkey=mkey)
res = self._session.post(url, params=parameters,
data=data, files=files, timeout=self.timeout)
LOG.debug("in UPLOAD function")
return res
def get(self, path, name, vdom=None, mkey=None, parameters=None):
"""
Execute a GET on the cmdb (i.e. configuration part) of the Fortios API
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/cmdb/<path>/<name>
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add on parameters understood by the API call can be \"&select=\" for example
:return:
A formatted json with the last response from the API, values are in return['results']
"""
url = self.cmdb_url(path, name, vdom, mkey=mkey)
LOG.debug("Calling GET ( %s, %s)", url, parameters)
res = self._session.get(url, params=parameters, timeout=self.timeout)
LOG.debug("in GET function")
return self.formatresponse(res, vdom=vdom)
def monitor(self, path, name, vdom=None, mkey=None, parameters=None):
"""
Execute a GET on the montioring part of the Fortios API
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/monitor/<path>/<name>
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add on parameters understood by the API call can be \"&select=\" for example
:return:
A formatted json with the last response from the API, values are in return['results']
"""
url = self.mon_url(path, name, vdom, mkey)
LOG.debug("in monitor url is %s", url)
res = self._session.get(url, params=parameters, timeout=self.timeout)
LOG.debug("in MONITOR function")
return self.formatresponse(res, vdom=vdom)
def schema(self, path, name, vdom=None):
# vdom or global is managed in cmdb_url
if vdom is None:
url = self.cmdb_url(path, name) + "?action=schema"
else:
url = self.cmdb_url(path, name, vdom=vdom) + "&action=schema"
res = self._session.get(url, timeout=self.timeout)
if res.status_code is 200:
if vdom == "global":
return json.loads(res.content.decode('utf-8'))[0]['results']
else:
return json.loads(res.content.decode('utf-8'))['results']
else:
return json.loads(res.content.decode('utf-8'))
def get_name_path_dict(self, vdom=None):
# return builded URL
url_postfix = '/api/v2/cmdb/'
if vdom is not None:
url_postfix += '?vdom=' + vdom + "&action=schema"
else:
url_postfix += "?action=schema"
url = self.url_prefix + url_postfix
cmdbschema = self._session.get(url, timeout=self.timeout)
self.logging(cmdbschema)
j = json.loads(cmdbschema.content.decode('utf-8'))['results']
dict = []
for keys in j:
if "__tree__" not in keys['path']:
dict.append(keys['path'] + " " + keys['name'])
return dict
def post(self, path, name, data, vdom=None,
mkey=None, parameters=None):
"""
Execute a REST POST on the API. It will fail if the targeted object already exist.
When post to the upper name/path the mkey is in the data.
So we can ensure the data set is correctly filled in case mkey is passed.
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/cmdb/<path>/<name>
:param data: json containing the param/values of the object to be set
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add on parameters understood by the API call can be \"&select=\" for example
:return:
A formatted json with the last response from the API
"""
LOG.debug("in POST function")
if mkey:
mkeyname = self.get_mkeyname(path, name, vdom)
LOG.debug("in post calculated mkeyname : %s mkey: %s ",
mkeyname, mkey)
# if mkey is forced on the function call then we change it in the data
# even if inconsistent data/mkey is passed
data[mkeyname] = mkey
# post with mkey will return a 404 as the next level is not there yet
# we pushed mkey in data if needed.
url = self.cmdb_url(path, name, vdom, mkey=None)
LOG.debug("POST sent data : %s", json.dumps(data))
res = self._session.post(
url, params=parameters, data=json.dumps(data), timeout=self.timeout)
LOG.debug("POST raw results: %s", res)
return self.formatresponse(res, vdom=vdom)
def execute(self, path, name, data, vdom=None,
mkey=None, parameters=None):
"""
Execute is an action done on a running fortigate
it is actually doing a post to the monitor part of the API
we choose this name for clarity
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/monitor/<path>/<name>
:param data: json containing the param/values of the object to be set
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add on parameters understood by the API call can be \"&select=\" for example
:return:
A formatted json with the last response from the API
"""
LOG.debug("in EXEC function")
url = self.mon_url(path, name, vdom, mkey=mkey)
LOG.debug("EXEC sent data : %s", json.dumps(data))
res = self._session.post(
url, params=parameters, data=json.dumps(data), timeout=self.timeout)
LOG.debug("EXEC raw results: %s", res)
return self.formatresponse(res, vdom=vdom)
def put(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
"""
Execute a REST PUT on the specified object with parameters in the data field as
a json formatted field
:param path: first part of the Fortios API URL like
:param name: https://myfgt:8040/api/v2/cmdb/<path>/<name>
:param data: json containing the param/values of the object to be set
:param mkey: when the cmdb object have a subtable mkey represent the subobject.
It is optionnal at creation the code will find the mkey name for you.
:param vdom: the vdom on which you want to apply config or global for global settings
:param parameters: Add on parameters understood by the API call can be \"&select=\" for example
:return:
A formatted json with the last response from the API
"""
if | |
<reponame>CLARIAH/DANE-util
# Copyright 2020-present, Netherlands Institute for Sound and Vision (Nanne van Noord)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from elasticsearch7 import Elasticsearch
from elasticsearch7 import exceptions as EX
from elasticsearch7 import helpers
import json
import os
import logging
from functools import partial
from urllib.parse import urlsplit
import hashlib
import datetime
from dane import Document, Task, Result
from dane.handlers import base_handler
from dane.errors import(
DocumentExistsError,
UnregisteredError,
TaskAssignedError,
TaskExistsError,
ResultExistsError
)
import threading
logger = logging.getLogger('DANE')
class ESHandler(base_handler):
def __init__(self, config, queue=None):
super().__init__(config)
self.es = None
self.INDEX = self.config.ELASTICSEARCH.INDEX
self.connect()
self.queue = queue
def connect(self):
self.es = Elasticsearch(self.config.ELASTICSEARCH.HOST,
http_auth=(self.config.ELASTICSEARCH.USER, self.config.ELASTICSEARCH.PASSWORD),
scheme=self.config.ELASTICSEARCH.SCHEME,
port=self.config.ELASTICSEARCH.PORT,
timeout=self.config.ELASTICSEARCH.TIMEOUT,
retry_on_timeout=(self.config.ELASTICSEARCH.MAX_RETRIES > 0),
max_retries=self.config.ELASTICSEARCH.MAX_RETRIES
)
try:
if not self.es.ping():
logger.info("Tried connecting to ES at {}:{}".format(self.config.ELASTICSEARCH.HOST,
self.config.ELASTICSEARCH.PORT))
raise ConnectionError("ES could not be Pinged")
except Exception as e:
logger.exception("ES Connection Failed")
raise ConnectionError("ES Connection Failed")
if not self.es.indices.exists(index=self.INDEX):
self.es.indices.create(index=self.INDEX, body={
"settings" : {
"index" : {
"number_of_shards" : self.config.ELASTICSEARCH.SHARDS,
"number_of_replicas" : self.config.ELASTICSEARCH.REPLICAS
}
},
"mappings": {
"properties": {
"role": {
"type": "join",
"relations": {
"document": "task",
"task": "result"
}
},
# shared prop
"created_at": {
"type": "date",
"format": "date_hour_minute_second"
},
"updated_at": {
"type": "date",
"format": "date_hour_minute_second"
},
# document properties
"target": {
"properties": {
"id": { "type": "keyword" },
"url": { "type": "text" },
"type": { "type": "keyword" }
}
},
"creator": {
"properties": {
"id": { "type": "keyword" },
"type": { "type": "keyword" },
"name": { "type": "text" }
}
},
# task properties
"task": {
"properties": {
"priority": { "type": "byte" },
"key": { "type": "keyword" },
"state": { "type": "short" },
"msg": { "type": "text" },
"args": { "type": "object" }
}
},
# result properties:
"result": {
"properties": {
"generator": {
"properties": {
"id": { "type": "keyword" },
"type": { "type": "keyword" },
"name": { "type": "keyword" },
"homepage": { "type": "text" }
}
},
"payload": {
"type": "object"
}
}
}
}
}
})
def registerDocument(self, document):
doc = json.loads(document.to_json())
doc['role'] = 'document'
doc['created_at'] = doc['updated_at'] = \
datetime.datetime.now().replace(microsecond=0).isoformat()
_id = hashlib.sha1(
(str(document.target['id']) + str(document.creator['id'])
).encode('utf-8')).hexdigest()
try:
res = self.es.index(index=self.INDEX, body=json.dumps(doc),
id=_id, refresh=True, op_type='create')
except EX.ConflictError as e:
raise DocumentExistsError('A document with target.id `{}`, '\
'and creator.id `{}` already exists'.format(
document.target['id'],
document.creator['id']))
document._id = res['_id']
document.created_at = doc['created_at']
document.updated_at = doc['updated_at']
logger.debug("Registered new document #{}".format(document._id))
return document._id
def registerDocuments(self, documents):
actions = []
for document in documents:
doc = {}
doc['_op_type'] = 'create'
doc['_index'] = self.INDEX
doc['_source'] = json.loads(document.to_json())
doc['_source']['role'] = 'document'
doc['_source']['created_at'] = doc['_source']['updated_at'] = \
datetime.datetime.now().replace(microsecond=0).isoformat()
document._id = doc['_id'] = hashlib.sha1(
(str(document.target['id']) + str(document.creator['id'])
).encode('utf-8')).hexdigest()
document.created_at = doc['_source']['created_at']
document.updated_at = doc['_source']['updated_at']
actions.append(doc)
succeeded, errors = helpers.bulk(self.es, actions, raise_on_error=False)
logger.debug("Batch registration: Success {} Failed {}".format(
succeeded, len(errors)))
if len(errors) == 0:
return documents, []
else:
success = []
failed = []
errors = { e['create']['_id'] : e['create'] for e in errors }
for document in documents:
if document._id in errors.keys():
if errors[document._id]['status'] == 409:
failed.append({'document': document,
'error':'A document with target.id `{}`, '\
'and creator.id `{}` already exists'.format(
document.target['id'],
document.creator['id'])})
else:
failed.append({'document': document,
'error': "[{}] {}".format(
errors[document._id]['status'],
errors[document._id]['error']['reason'])})
else:
success.append(document)
return success, failed
def deleteDocument(self, document):
if document._id is None:
logger.error("Can only delete registered documents")
raise UnregisteredError("Failed to delete unregistered document")
try:
# delete tasks assigned to this document first,
# and results assigned to those tasks
query = {
"query": {
"bool": {
"should": [
{ "bool": {
# all tasks with this as parent
"must": [
{
"has_parent": {
"parent_type": "document",
"query": {
"match": {
"_id": document._id
}
}
}
},
{ "exists": {
"field": "task.key"
}
}
]
} },
{ "bool": {
# all results that hang below a task with this as parent
"must": [
{
"has_parent": {
"parent_type": "task",
"query": {
"has_parent": {
"parent_type": "document",
"query": {
"match": {
"_id": document._id
}
}
}
}
}
},
{ "exists": {
"field": "result.generator.id"
}
}
]
} }
]
}
}
}
self.es.delete_by_query(self.INDEX, body=query)
self.es.delete(self.INDEX, document._id, refresh=True)
logger.debug("Deleted document #{}".format(document._id))
return True
except EX.NotFoundError as e:
logger.debug("Unable to delete non-existing document #{}".format(
document._id))
return False
def assignTask(self, task, document_id):
if not self.es.get(index=self.INDEX, id=document_id)['found']:
raise DocumentExistsError('No document with id `{}` found'.format(
document_id))
_id = hashlib.sha1(
(document_id + task.key).encode('utf-8')).hexdigest()
task.state = 201
task.msg = 'Created'
t = {'task': json.loads(task.to_json())}
t['role'] = { 'name': 'task', 'parent': document_id }
t['created_at'] = t['updated_at'] = \
datetime.datetime.now().replace(microsecond=0).isoformat()
try:
res = self.es.index(index=self.INDEX,
routing=document_id,
body=json.dumps(t),
id=_id,
refresh=True, op_type='create')
except EX.ConflictError as e:
raise TaskAssignedError('Task `{}` '\
'already assigned to document `{}`'.format(
task.key,
document_id))
task._id = res['_id']
task.created_at = t['created_at']
task.updated_at = t['updated_at']
logger.debug("Assigned task {}({}) to document #{}".format(task.key,
task._id,
document_id))
return task.run()
def assignTaskToMany(self, task, document_ids):
failed = []
searches = []
for document_id in document_ids:
searches.append("{}")
searches.append(json.dumps({"query": { "match": {
"_id": document_id} },
"_source": "false" }))
docs = []
for d, d_id in zip(self.es.msearch("\n".join(searches), index=self.INDEX)['responses'], document_ids):
if d['hits']['total']['value'] == 1:
docs.append(d_id)
elif d['hits']['total']['value'] == 0:
failed.append({'document_id': d_id,
'error': "[404] 'No document with id `{}` found'".format(
document_id)})
else:
failed.append({'document_id': d_id,
'error': "[500] 'Multiple documents found with id `{}`'".format(
document_id)})
document_ids = docs
del docs
task.state = 201
task.msg = 'Created'
actions = []
tasks = []
for document_id in document_ids:
t = {}
tc = task.__copy__()
t['_source'] = { 'task': json.loads(tc.to_json())}
t['_source']['role'] = { 'name': 'task', 'parent': document_id }
t['_source']['created_at'] = t['_source']['updated_at'] = \
datetime.datetime.now().replace(microsecond=0).isoformat()
t['_op_type'] = 'create'
t['_index'] = self.INDEX
t['_routing'] = document_id
tc._id = t['_id'] = hashlib.sha1(
(document_id + tc.key).encode('utf-8')).hexdigest()
tc.created_at = tc.updated_at = t['_source']['created_at']
tasks.append(tc)
actions.append(t)
succeeded, errors = helpers.bulk(self.es, actions, raise_on_error=False, refresh=True)
logger.debug("Batch task registration: Success {} Failed {}".format(
succeeded, len(errors)))
success = []
errors = { e['create']['_id'] : e['create'] for e in errors }
for task, document_id in zip(tasks, document_ids):
if task._id in errors.keys():
if errors[task._id]['status'] == 409:
failed.append({'document_id': document_id,
'error':'Task `{}` '\
'already assigned to document `{}`'.format(
task.key,
document_id)})
else:
if 'caused_by' in errors[task._id]['error'].keys():
errors[task._id]['error']['reason'] += " > " + \
errors[task._id]['error']['caused_by']['reason']
failed.append({'document_id': document_id,
'error': "[{}] {}".format(
errors[task._id]['status'],
errors[task._id]['error']['reason'])})
else:
success.append(task)
# run tasks from thread, so it doesnt block API response
t = threading.Thread(target=self._run_async, args=(success,))
t.daemon = True
t.start()
return success, failed
def _run_async(self, tasks):
for task in tasks:
try:
task.run()
except Exception as e:
logger.exception("Exception during async run")
pass # ignore exceptions, and just GO GO GO
def deleteTask(self, task):
try:
# delete results assigned to this task
query = {
"query": {
"bool": {
"must": [
{
"has_parent": {
"parent_type": "task",
"query": {
"match": {
"_id": task._id
}
}
}
},
{ "exists": {
"field": "result.generator.id"
}
}
]
}
}
}
self.es.delete_by_query(self.INDEX, body=query)
self.es.delete(self.INDEX, task._id, refresh=True)
return True
except EX.NotFoundError as e:
return False
def taskFromTaskId(self, task_id):
query = {
"_source": ["task", "created_at", "updated_at"],
"query": {
"bool": {
"must": [
{
"has_parent": {
"parent_type": "document",
"query": { # since we must have a query..
"exists": {
"field": "target.id"
}
}
}
},
{
"match": {
"_id": task_id
}
},
{ "exists": {
"field": "task.key"
}
}
]
}
}
}
result = self.es.search(index=self.INDEX, body=query)
if result['hits']['total']['value'] == 1:
# hacky way to pass _id to Task
result['hits']['hits'][0]['_source']['task']['_id'] = \
result['hits']['hits'][0]['_id']
task = Task.from_json(result['hits']['hits'][0]['_source'])
task.set_api(self)
return task
else:
raise TaskExistsError("No result for task id: {}".format(task_id))
def getTaskState(self, task_id):
return int(self.taskFromTaskId(task_id).state)
def getTaskKey(self, task_id):
return self.taskFromTaskId(task_id).key
def _set_task_states(self, states, task):
tid = task.task_id
for s in states:
if s['task_id'] == tid:
task.task_state = int(s['task_state'])
task.task_msg = s['task_msg']
return
def documentFromDocumentId(self, document_id):
result = self.es.get(index=self.INDEX, id=document_id,
_source_excludes=['role'],
| |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['SecurityServiceArgs', 'SecurityService']
@pulumi.input_type
class SecurityServiceArgs:
def __init__(__self__, *,
type: pulumi.Input[str],
description: Optional[pulumi.Input[str]] = None,
dns_ip: Optional[pulumi.Input[str]] = None,
domain: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
ou: Optional[pulumi.Input[str]] = None,
password: Optional[pulumi.Input[str]] = None,
region: Optional[pulumi.Input[str]] = None,
server: Optional[pulumi.Input[str]] = None,
user: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a SecurityService resource.
:param pulumi.Input[str] type: The security service type - can either be active\_directory,
kerberos or ldap. Changing this updates the existing security service.
:param pulumi.Input[str] description: The human-readable description for the security service.
Changing this updates the description of the existing security service.
:param pulumi.Input[str] dns_ip: The security service DNS IP address that is used inside the
tenant network.
:param pulumi.Input[str] domain: The security service domain.
:param pulumi.Input[str] name: The name of the security service. Changing this updates the name
of the existing security service.
:param pulumi.Input[str] ou: The security service ou. An organizational unit can be added to
specify where the share ends up. New in Manila microversion 2.44.
:param pulumi.Input[str] password: The <PASSWORD>, if you specify a user.
:param pulumi.Input[str] region: The region in which to obtain the V2 Shared File System client.
A Shared File System client is needed to create a security service. If omitted, the
`region` argument of the provider is used. Changing this creates a new
security service.
:param pulumi.Input[str] server: The security service host name or IP address.
:param pulumi.Input[str] user: The security service user or group name that is used by the
tenant.
"""
pulumi.set(__self__, "type", type)
if description is not None:
pulumi.set(__self__, "description", description)
if dns_ip is not None:
pulumi.set(__self__, "dns_ip", dns_ip)
if domain is not None:
pulumi.set(__self__, "domain", domain)
if name is not None:
pulumi.set(__self__, "name", name)
if ou is not None:
pulumi.set(__self__, "ou", ou)
if password is not None:
pulumi.set(__self__, "password", password)
if region is not None:
pulumi.set(__self__, "region", region)
if server is not None:
pulumi.set(__self__, "server", server)
if user is not None:
pulumi.set(__self__, "user", user)
@property
@pulumi.getter
def type(self) -> pulumi.Input[str]:
"""
The security service type - can either be active\_directory,
kerberos or ldap. Changing this updates the existing security service.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: pulumi.Input[str]):
pulumi.set(self, "type", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The human-readable description for the security service.
Changing this updates the description of the existing security service.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter(name="dnsIp")
def dns_ip(self) -> Optional[pulumi.Input[str]]:
"""
The security service DNS IP address that is used inside the
tenant network.
"""
return pulumi.get(self, "dns_ip")
@dns_ip.setter
def dns_ip(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "dns_ip", value)
@property
@pulumi.getter
def domain(self) -> Optional[pulumi.Input[str]]:
"""
The security service domain.
"""
return pulumi.get(self, "domain")
@domain.setter
def domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "domain", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the security service. Changing this updates the name
of the existing security service.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def ou(self) -> Optional[pulumi.Input[str]]:
"""
The security service ou. An organizational unit can be added to
specify where the share ends up. New in Manila microversion 2.44.
"""
return pulumi.get(self, "ou")
@ou.setter
def ou(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "ou", value)
@property
@pulumi.getter
def password(self) -> Optional[pulumi.Input[str]]:
"""
The user password, if you specify a user.
"""
return pulumi.get(self, "password")
@password.setter
def password(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "password", value)
@property
@pulumi.getter
def region(self) -> Optional[pulumi.Input[str]]:
"""
The region in which to obtain the V2 Shared File System client.
A Shared File System client is needed to create a security service. If omitted, the
`region` argument of the provider is used. Changing this creates a new
security service.
"""
return pulumi.get(self, "region")
@region.setter
def region(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "region", value)
@property
@pulumi.getter
def server(self) -> Optional[pulumi.Input[str]]:
"""
The security service host name or IP address.
"""
return pulumi.get(self, "server")
@server.setter
def server(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "server", value)
@property
@pulumi.getter
def user(self) -> Optional[pulumi.Input[str]]:
"""
The security service user or group name that is used by the
tenant.
"""
return pulumi.get(self, "user")
@user.setter
def user(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "user", value)
@pulumi.input_type
class _SecurityServiceState:
def __init__(__self__, *,
description: Optional[pulumi.Input[str]] = None,
dns_ip: Optional[pulumi.Input[str]] = None,
domain: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
ou: Optional[pulumi.Input[str]] = None,
password: Optional[pulumi.Input[str]] = None,
project_id: Optional[pulumi.Input[str]] = None,
region: Optional[pulumi.Input[str]] = None,
server: Optional[pulumi.Input[str]] = None,
type: Optional[pulumi.Input[str]] = None,
user: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering SecurityService resources.
:param pulumi.Input[str] description: The human-readable description for the security service.
Changing this updates the description of the existing security service.
:param pulumi.Input[str] dns_ip: The security service DNS IP address that is used inside the
tenant network.
:param pulumi.Input[str] domain: The security service domain.
:param pulumi.Input[str] name: The name of the security service. Changing this updates the name
of the existing security service.
:param pulumi.Input[str] ou: The security service ou. An organizational unit can be added to
specify where the share ends up. New in Manila microversion 2.44.
:param pulumi.Input[str] password: The user password, if you specify a user.
:param pulumi.Input[str] project_id: The owner of the Security Service.
:param pulumi.Input[str] region: The region in which to obtain the V2 Shared File System client.
A Shared File System client is needed to create a security service. If omitted, the
`region` argument of the provider is used. Changing this creates a new
security service.
:param pulumi.Input[str] server: The security service host name or IP address.
:param pulumi.Input[str] type: The security service type - can either be active\_directory,
kerberos or ldap. Changing this updates the existing security service.
:param pulumi.Input[str] user: The security service user or group name that is used by the
tenant.
"""
if description is not None:
pulumi.set(__self__, "description", description)
if dns_ip is not None:
pulumi.set(__self__, "dns_ip", dns_ip)
if domain is not None:
pulumi.set(__self__, "domain", domain)
if name is not None:
pulumi.set(__self__, "name", name)
if ou is not None:
pulumi.set(__self__, "ou", ou)
if password is not None:
pulumi.set(__self__, "password", password)
if project_id is not None:
pulumi.set(__self__, "project_id", project_id)
if region is not None:
pulumi.set(__self__, "region", region)
if server is not None:
pulumi.set(__self__, "server", server)
if type is not None:
pulumi.set(__self__, "type", type)
if user is not None:
pulumi.set(__self__, "user", user)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
The human-readable description for the security service.
Changing this updates the description of the existing security service.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter(name="dnsIp")
def dns_ip(self) -> Optional[pulumi.Input[str]]:
"""
The security service DNS IP address that is used inside the
tenant network.
"""
return pulumi.get(self, "dns_ip")
@dns_ip.setter
def dns_ip(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "dns_ip", value)
@property
@pulumi.getter
def domain(self) -> Optional[pulumi.Input[str]]:
"""
The security service domain.
"""
return pulumi.get(self, "domain")
@domain.setter
def domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "domain", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the security service. Changing this updates the name
of the existing security service.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def ou(self) -> Optional[pulumi.Input[str]]:
"""
The security service ou. An organizational unit can be added to
specify where the share ends up. New in Manila microversion 2.44.
"""
return pulumi.get(self, "ou")
@ou.setter
def ou(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "ou", value)
@property
@pulumi.getter
def password(self) -> Optional[pulumi.Input[str]]:
"""
The user password, if you specify a user.
"""
return pulumi.get(self, "password")
@password.setter
def password(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "password", value)
@property
@pulumi.getter(name="projectId")
def project_id(self) -> Optional[pulumi.Input[str]]:
"""
The owner of the Security Service.
"""
return pulumi.get(self, "project_id")
@project_id.setter
def project_id(self, | |
<filename>tests/test_node_flood.py
import time
import common.ttypes
import constants
import encoding.ttypes
import node
import packet_common
import timer
# pylint: disable=line-too-long
MY_NAME = "name"
MY_SYSTEM_ID = 999
MY_LEVEL = 9
SOUTH = constants.DIR_SOUTH
NORTH = constants.DIR_NORTH
EW = constants.DIR_EAST_WEST
NODE = common.ttypes.TIETypeType.NodeTIEType
PREFIX = common.ttypes.TIETypeType.PrefixTIEType
POSITIVE_DISAGGREGATION_PREFIX = common.ttypes.TIETypeType.PositiveDisaggregationPrefixTIEType
PG_PREFIX = common.ttypes.TIETypeType.PGPrefixTIEType
KEY_VALUE = common.ttypes.TIETypeType.KeyValueTIEType
REQUEST_MISSING = 1 # TIE-DB is missing a TIE-ID which is reported in TIDE. Request it.
REQUEST_OLDER = 2 # TIE-DB has older version of TIE-ID than in TIDE/TIRE. Request it.
START_EXTRA = 3 # TIE-DB has extra TIE-ID which is not in TIDE. Start sending it.
START_NEWER = 4 # TIE-DB has newer version of TIE-ID than in TIDE/TIRE. Start sending it.
STOP_SAME = 5 # TIE-DB has same version of TIE-ID as in TIDE. Stop sending it.
ACK = 6 # TIE-DB has same version of TIE-ID than in TIRE. Treat it as an ACK.
def test_compare_tie_header():
# Exactly same
header1 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=500)
header2 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=500)
assert node.compare_tie_header_age(header1, header2) == 0
# Almost same, lifetime is different but close enough to call it same (within 300 seconds)
header1 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=1)
header2 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=300)
assert node.compare_tie_header_age(header1, header2) == 0
# Different: lifetime is the tie breaker (more than 300 seconds difference)
header1 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=1)
header2 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=600)
assert node.compare_tie_header_age(header1, header2) == -1
assert node.compare_tie_header_age(header2, header1) == 1
# Different: lifetime is the tie breaker; the difference is less than 300 but one is zero and
# the other is non-zero. The one with zero lifetime is considered older.
header1 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=0)
header2 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=7,
lifetime=299)
assert node.compare_tie_header_age(header1, header2) == -1
assert node.compare_tie_header_age(header2, header1) == 1
# Different: seq_nr is the tie breaker.
header1 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=20,
lifetime=1)
header2 = packet_common.make_tie_header(
direction=NORTH,
originator=1,
tie_type=PREFIX,
tie_nr=6,
seq_nr=19,
lifetime=600)
assert node.compare_tie_header_age(header1, header2) == 1
assert node.compare_tie_header_age(header2, header1) == -1
def test_add_prefix_tie():
packet_common.add_missing_methods_to_thrift()
test_node = make_test_node()
prefix_tie_packet_1 = packet_common.make_prefix_tie_packet(
direction=common.ttypes.TieDirectionType.South,
originator=222,
tie_nr=333,
seq_nr=444,
lifetime=555)
packet_common.add_ipv4_prefix_to_prefix_tie(prefix_tie_packet_1, "1.2.3.0/24", 2, [77, 88], 12345)
packet_common.add_ipv6_prefix_to_prefix_tie(prefix_tie_packet_1, "1234:abcd::/64", 3)
test_node.store_tie_packet(prefix_tie_packet_1)
prefix_tie_packet_2 = packet_common.make_prefix_tie_packet(
direction=common.ttypes.TieDirectionType.North,
originator=777,
tie_nr=888,
seq_nr=999,
lifetime=0)
packet_common.add_ipv4_prefix_to_prefix_tie(prefix_tie_packet_2, "0.0.0.0/0", 10)
test_node.store_tie_packet(prefix_tie_packet_2)
assert test_node.find_tie_meta(prefix_tie_packet_1.header.tieid).tie_packet == prefix_tie_packet_1
assert test_node.find_tie_meta(prefix_tie_packet_2.header.tieid).tie_packet == prefix_tie_packet_2
missing_tie_id = encoding.ttypes.TIEID(
direction=common.ttypes.TieDirectionType.South,
originator=321,
tietype=common.ttypes.TIETypeType.PrefixTIEType,
tie_nr=654)
assert test_node.find_tie_meta(missing_tie_id) is None
tab = test_node.tie_db_table()
tab_str = tab.to_string()
assert (tab_str ==
"+-----------+------------+--------+--------+--------+----------+--------------------------+\n"
"| Direction | Originator | Type | TIE Nr | Seq Nr | Lifetime | Contents |\n"
"+-----------+------------+--------+--------+--------+----------+--------------------------+\n"
"| South | 222 | Prefix | 333 | 444 | 555 | Prefix: 1.2.3.0/24 |\n"
"| | | | | | | Metric: 2 |\n"
"| | | | | | | Tag: 77 |\n"
"| | | | | | | Tag: 88 |\n"
"| | | | | | | Monotonic-clock: 12345 |\n"
"| | | | | | | Prefix: 1234:abcd::/64 |\n"
"| | | | | | | Metric: 3 |\n"
"+-----------+------------+--------+--------+--------+----------+--------------------------+\n"
"| North | 777 | Prefix | 888 | 999 | 0 | Prefix: 0.0.0.0/0 |\n"
"| | | | | | | Metric: 10 |\n"
"+-----------+------------+--------+--------+--------+----------+--------------------------+\n")
def tie_headers_with_disposition(test_node, header_info_list, filter_dispositions):
tie_headers = []
for header_info in header_info_list:
(direction, originator, _tietype, tie_nr, seq_nr, lifetime, disposition) = header_info
if disposition in filter_dispositions:
if disposition in [START_EXTRA, START_NEWER]:
tie_id = packet_common.make_tie_id(direction, originator, PREFIX, tie_nr)
seq_nr = test_node.tie_metas[tie_id].tie_packet.header.seq_nr
lifetime = test_node.tie_metas[tie_id].tie_packet.header.remaining_lifetime
elif disposition == REQUEST_MISSING:
seq_nr = 0
lifetime = 0
tie_header = packet_common.make_tie_header(direction, originator, PREFIX, tie_nr,
seq_nr, lifetime)
tie_headers.append(tie_header)
return tie_headers
def check_process_tide_common(test_node, start_range, end_range, header_info_list):
# pylint:disable=too-many-locals
# Prepare the TIDE packet
tide_packet = packet_common.make_tide_packet(start_range, end_range)
for header_info in header_info_list:
(direction, originator, _prefixtype, tie_nr, seq_nr, lifetime, disposition) = header_info
# START_EXTRA refers to a TIE-ID which is only in the TIE-DB and not in the TIDE, so don't
# add those.
if disposition != START_EXTRA:
tie_header = packet_common.make_tie_header(direction, originator, PREFIX, tie_nr,
seq_nr, lifetime)
packet_common.add_tie_header_to_tide(tide_packet, tie_header)
# Process the TIDE packet
result = test_node.process_received_tide_packet(tide_packet)
(request_tie_headers, start_sending_tie_headers, stop_sending_tie_headers) = result
# Check results
compare_header_lists(
tie_headers_with_disposition(test_node, header_info_list, [REQUEST_MISSING, REQUEST_OLDER]),
request_tie_headers)
compare_header_lists(
tie_headers_with_disposition(test_node, header_info_list, [START_EXTRA, START_NEWER]),
start_sending_tie_headers)
compare_header_lists(
tie_headers_with_disposition(test_node, header_info_list, [STOP_SAME]),
stop_sending_tie_headers)
def check_process_tide_1(test_node):
start_range = packet_common.make_tie_id(SOUTH, 10, PREFIX, 1)
end_range = packet_common.make_tie_id(NORTH, 8, PREFIX, 999)
header_info_list = [
# pylint:disable=bad-whitespace
# Direction Originator Type Tie-Nr Seq-Nr Lifetime Disposition
( SOUTH, 8, PREFIX, 1, None, 100, START_EXTRA),
( SOUTH, 10, PREFIX, 1, None, 100, START_EXTRA),
( SOUTH, 10, PREFIX, 2, None, 100, START_EXTRA),
( SOUTH, 10, PREFIX, 10, 10, 100, STOP_SAME),
( SOUTH, 10, PREFIX, 11, 1, 100, REQUEST_MISSING),
( SOUTH, 10, PREFIX, 12, None, 100, START_EXTRA),
( SOUTH, 10, PREFIX, 13, 5, 100, REQUEST_OLDER),
( NORTH, 3, PREFIX, 15, 5, 100, START_NEWER),
( NORTH, 4, PREFIX, 1, None, 100, START_EXTRA)]
check_process_tide_common(test_node, start_range, end_range, header_info_list)
def check_process_tide_2(test_node):
start_range = packet_common.make_tie_id(NORTH, 20, PREFIX, 1)
end_range = packet_common.make_tie_id(NORTH, 100, PREFIX, 1)
header_info_list = [
# pylint:disable=bad-whitespace
# Direction Originator Type Tie-Nr Seq-Nr Lifetime Disposition
( NORTH, 10, PREFIX, 7, None, 100, START_EXTRA),
( NORTH, 21, PREFIX, 15, 5, 100, REQUEST_OLDER)]
check_process_tide_common(test_node, start_range, end_range, header_info_list)
def check_process_tide_3(test_node):
start_range = packet_common.make_tie_id(NORTH, 200, PREFIX, 1)
end_range = packet_common.make_tie_id(NORTH, 300, PREFIX, 1)
header_info_list = [
# pylint:disable=bad-whitespace
# Direction Originator Type Tie-Nr Seq-Nr Lifetime Disposition
( NORTH, 110, PREFIX, 40, None, 100, START_EXTRA),
( NORTH, 210, PREFIX, 6, None, 100, START_EXTRA)]
check_process_tide_common(test_node, start_range, end_range, header_info_list)
def make_test_node(db_tie_info_list=None):
if db_tie_info_list is None:
db_tie_info_list = []
config = {
"name": "test",
"systemid": MY_SYSTEM_ID,
"skip-self-orginated-ties": True
}
test_node = node.Node(config)
for db_tie_info in db_tie_info_list:
(direction, origin, tietype, tie_nr, seq_nr, lifetime) = db_tie_info
if tietype == NODE:
db_tie_packet = packet_common.make_node_tie_packet(
name=MY_NAME,
level=MY_LEVEL,
direction=direction,
originator=origin,
tie_nr=tie_nr,
seq_nr=seq_nr,
lifetime=lifetime)
elif tietype == PREFIX:
db_tie_packet = packet_common.make_prefix_tie_packet(
direction,
origin,
tie_nr,
seq_nr,
lifetime)
else:
assert False
test_node.store_tie_packet(db_tie_packet)
return test_node
def make_rx_tie_packet(header_info):
(direction, origin, prefixtype, tie_nr, seq_nr, lifetime, _disposition) = header_info
if prefixtype == NODE:
rx_tie_packet = packet_common.make_node_tie_packet(
name=MY_NAME,
level=MY_LEVEL,
direction=direction,
originator=origin,
tie_nr=tie_nr,
seq_nr=seq_nr,
lifetime=lifetime)
elif prefixtype == PREFIX:
rx_tie_packet = packet_common.make_prefix_tie_packet(
direction,
origin,
tie_nr,
seq_nr,
lifetime)
else:
assert False
return rx_tie_packet
def test_process_tide():
# pylint:disable=too-many-locals
# TODO: Also have other TIEs than prefix TIEs
packet_common.add_missing_methods_to_thrift()
db_tie_info_list = [
# pylint:disable=bad-whitespace
# Direction Origin Type TieNr SeqNr Lifetime Disposition
( SOUTH, 8, PREFIX, 1, 1, 100), # In gap before TIDE-1; start
( SOUTH, 10, PREFIX, 1, 2, 100), # Not in TIDE-1 (start gap); start
( SOUTH, 10, PREFIX, 2, 5, 100), # Not in TIDE-1 (start gap); start
( SOUTH, 10, PREFIX, 10, 10, 100), # Same version as in TIDE; stop
( SOUTH, 10, PREFIX, 12, 5, 100), # Not in TIDE-1 (middle gap); start
( SOUTH, 10, PREFIX, 13, 3, 100), # Older version than in TIDE-1; request
( NORTH, 3, PREFIX, 15, 7, 100), # Newer version than in TIDE-1; start
( NORTH, 4, PREFIX, 1, 1, 100), # Not in TIDE-1 (end gap); start
( NORTH, 10, PREFIX, 7, 6, 100), # In TIDE-1...TIDE-2 gap; start
( NORTH, 21, PREFIX, 15, 3, 100), # Older version than in TIDE-2; request
( NORTH, 110, PREFIX, 40, 1, 100), # In TIDE-2...TIDE-3 gap; start
( NORTH, 210, PREFIX, 6, 6, 100)] # Not in TIDE-3 (empty); start
test_node = make_test_node(db_tie_info_list)
check_process_tide_1(test_node)
check_process_tide_2(test_node)
check_process_tide_3(test_node)
# Test wrap-around. Finished sending all TIDEs, now send first TIDE again. The key test is
# whether the TIE in the TIE-DB in the gap before TIDE-1 is put on the send queue again.
check_process_tide_1(test_node)
def compare_header_lists(headers1, headers2):
# Order does not matter in comparison. This is maybe not the most efficient way of doing it,
# but it makes it easier to debug test failures (most clear error messages)
for header in headers1:
assert header in headers2
for header in headers2:
assert header in headers1
def check_process_tire_common(test_node, header_info_list):
# pylint:disable=too-many-locals
# Prepare the TIRE packet
tire = packet_common.make_tire_packet()
for header_info in header_info_list:
(direction, originator, _prefixtype, tie_nr, seq_nr, lifetime, _disposition) = header_info
tie_header = packet_common.make_tie_header(direction, originator, PREFIX, tie_nr,
seq_nr, lifetime)
| |
a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_run(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity: project name, hub name, registry name, ... (required)
:param str uuid: Uuid identifier of the sub-entity (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.archive_run_with_http_info(owner, entity, uuid, **kwargs) # noqa: E501
def archive_run_with_http_info(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Archive run # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_run_with_http_info(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity: project name, hub name, registry name, ... (required)
:param str uuid: Uuid identifier of the sub-entity (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'entity',
'uuid'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method archive_run" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'owner' is set
if self.api_client.client_side_validation and ('owner' not in local_var_params or # noqa: E501
local_var_params['owner'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `owner` when calling `archive_run`") # noqa: E501
# verify the required parameter 'entity' is set
if self.api_client.client_side_validation and ('entity' not in local_var_params or # noqa: E501
local_var_params['entity'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `entity` when calling `archive_run`") # noqa: E501
# verify the required parameter 'uuid' is set
if self.api_client.client_side_validation and ('uuid' not in local_var_params or # noqa: E501
local_var_params['uuid'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `uuid` when calling `archive_run`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner' in local_var_params:
path_params['owner'] = local_var_params['owner'] # noqa: E501
if 'entity' in local_var_params:
path_params['entity'] = local_var_params['entity'] # noqa: E501
if 'uuid' in local_var_params:
path_params['uuid'] = local_var_params['uuid'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey'] # noqa: E501
return self.api_client.call_api(
'/api/v1/{owner}/{entity}/runs/{uuid}/archive', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def archive_runs(self, owner, project, body, **kwargs): # noqa: E501
"""Archive runs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_runs(owner, project, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str project: Project under namesapce (required)
:param V1Uuids body: Uuids of the entities (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.archive_runs_with_http_info(owner, project, body, **kwargs) # noqa: E501
def archive_runs_with_http_info(self, owner, project, body, **kwargs): # noqa: E501
"""Archive runs # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_runs_with_http_info(owner, project, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str project: Project under namesapce (required)
:param V1Uuids body: Uuids of the entities (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'owner',
'project',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method archive_runs" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'owner' is set
if self.api_client.client_side_validation and ('owner' not in local_var_params or # noqa: E501
local_var_params['owner'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `owner` when calling `archive_runs`") # noqa: E501
# verify the required parameter 'project' is set
if self.api_client.client_side_validation and ('project' not in local_var_params or # noqa: E501
local_var_params['project'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `project` when calling `archive_runs`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `archive_runs`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner' in local_var_params:
path_params['owner'] = local_var_params['owner'] # noqa: E501
if 'project' in local_var_params:
path_params['project'] = local_var_params['project'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['ApiKey'] # noqa: E501
return self.api_client.call_api(
'/api/v1/{owner}/{project}/runs/archive', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def bookmark_run(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Bookmark run # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.bookmark_run(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
:param str entity: Entity: project name, hub name, registry name, ... (required)
:param str uuid: Uuid identifier of the sub-entity (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.bookmark_run_with_http_info(owner, entity, uuid, **kwargs) # noqa: E501
def bookmark_run_with_http_info(self, owner, entity, uuid, **kwargs): # noqa: E501
"""Bookmark run # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.bookmark_run_with_http_info(owner, entity, uuid, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str owner: Owner of the namespace (required)
| |
between min and
max.
Args:
min: the minimum acceptable value
max: the maximum acceptable value
sigma: the number of standard deviations between the center and min or max
Returns:
a value chosen randomly between min and max
"""
center = (max+min)*0.5
delta = math.fabs(max-min)*0.5
ratio = delta/sigma
while True:
x = np.random.normal(scale=ratio, loc=center)
if x > min and x < max:
return x
def get_tol(specie):
"""
Given an atomic specie name, return the covalent radius.
Args:
specie: a string for the atomic symbol
Returns:
the covalent radius in Angstroms
"""
return Element(specie).covalent_radius
tols_from_species = np.vectorize(get_tol)
"""
Given a list of atomic species names, returns a list of
covalent radii
Args:
species: a list of strings for atomic species names or symbols
Returns:
A 1D numpy array of distances in Angstroms
"""
def check_distance(coord1, coord2, species1, species2, lattice, PBC=[1,1,1], tm=Tol_matrix(prototype="atomic"), d_factor=1.0):
"""
Check the distances between two set of atoms. Distances between coordinates
within the first set are not checked, and distances between coordinates within
the second set are not checked. Only distances between points from different
sets are checked.
Args:
coord1: a list of fractional coordinates e.g. [[.1,.6,.4]
[.3,.8,.2]]
coord2: a list of new fractional coordinates e.g. [[.7,.8,.9],
[.4,.5,.6]]
species1: a list of atomic species or numbers for coord1
species2: a list of atomic species or numbers for coord2
lattice: matrix describing the unit cell vectors
PBC: A periodic boundary condition list, where 1 means periodic, 0 means not periodic.
Ex: [1,1,1] -> full 3d periodicity, [0,0,1] -> periodicity along the z axis
tm: a Tol_matrix object, or a string representing the type of Tol_matrix
to use
d_factor: the tolerance is multiplied by this amount. Larger values
mean atoms must be farther apart
Returns:
a bool for whether or not the atoms are sufficiently far enough apart
"""
#Check that there are points to compare
if len(coord1) < 1 or len(coord2) < 1:
return True
#Create tolerance matrix from subset of tm
tols = np.zeros((len(species1),len(species2)))
for i1, specie1 in enumerate(species1):
for i2, specie2 in enumerate(species2):
tols[i1][i2] = tm.get_tol(specie1, specie2)
#Calculate the distance between each i, j pair
d = distance_matrix(coord1, coord2, lattice, PBC=PBC)
if (np.array(d) < np.array(tols)).any():
return False
else:
return True
def check_images(coords, species, lattice, PBC=[1,1,1], tm=Tol_matrix(prototype="atomic"), tol=None, d_factor=1.0):
"""
Given a set of (unfiltered) fractional coordinates, checks if the periodic images are too close.
Args:
coords: a list of fractional coordinates
species: the atomic species of each coordinate
lattice: a 3x3 lattice matrix
PBC: the periodic boundary conditions
tm: a Tol_matrix object
tol: a single override value for the distance tolerances
d_factor: the tolerance is multiplied by this amount. Larger values
mean atoms must be farther apart
Returns:
False if distances are too close. True if distances are not too close
"""
#If no PBC, there are no images to check
if PBC == [0,0,0]:
return True
#Create image coords from given coords and PBC
coords = np.array(coords)
m = create_matrix(PBC=PBC)
new_coords = []
new_species = []
for v in m:
#Omit the [0,0,0] vector
if (v == [0,0,0]).all(): continue
for v2 in coords+v:
new_coords.append(v2)
new_coords = np.array(new_coords)
#Create a distance matrix
dm = distance_matrix(coords, new_coords, lattice, PBC=[0,0,0])
#Define tolerances
if tol is None:
tols = np.zeros((len(species), len(species)))
for i, s1 in enumerate(species):
for j, s2 in enumerate(species):
if i <= j:
tols[i][j] = tm.get_tol(s1, s2)
tols[j][i] = tm.get_tol(s1, s2)
tols2 = np.tile(tols, int(len(new_coords) / len(coords)))
if (dm < tols2).any():
return False
else:
return True
elif tol is not None:
if (dm < tol).any():
return False
else:
return True
return True
def get_center(xyzs, lattice, PBC=[1,1,1]):
"""
Finds the geometric centers of the clusters under periodic boundary
conditions.
Args:
xyzs: a list of fractional coordinates
lattice: a matrix describing the unit cell
PBC: A periodic boundary condition list, where 1 means periodic, 0 means not periodic.
Ex: [1,1,1] -> full 3d periodicity, [0,0,1] -> periodicity along the z axis
Returns:
x,y,z coordinates for the center of the input coordinate list
"""
matrix0 = create_matrix(PBC=PBC)
xyzs -= np.round(xyzs)
matrix_min = [0,0,0]
for atom1 in range(1,len(xyzs)):
dist_min = 10.0
for atom2 in range(0, atom1):
#shift atom1 to position close to atom2
matrix = matrix0 + (xyzs[atom1] - xyzs[atom2])
matrix = np.dot(matrix, lattice)
dists = cdist(matrix, [[0,0,0]])
if np.min(dists) < dist_min:
dist_min = np.min(dists)
matrix_min = matrix0[np.argmin(dists)]
xyzs[atom1] += matrix_min
center = xyzs.mean(0)
return center
def para2matrix(cell_para, radians=True, format='lower'):
"""
Given a set of lattic parameters, generates a matrix representing the
lattice vectors
Args:
cell_para: a 1x6 list of lattice parameters [a, b, c, alpha, beta,
gamma]. a, b, and c are the length of the lattice vectos, and
alpha, beta, and gamma are the angles between these vectors. Can
be generated by matrix2para
radians: if True, lattice parameters should be in radians. If False,
lattice angles should be in degrees
format: a string ('lower', 'symmetric', or 'upper') for the type of
matrix to be output
Returns:
a 3x3 matrix representing the unit cell. By default (format='lower'),
the a vector is aligined along the x-axis, and the b vector is in the
y-z plane
"""
a = cell_para[0]
b = cell_para[1]
c = cell_para[2]
alpha = cell_para[3]
beta = cell_para[4]
gamma = cell_para[5]
if radians is not True:
rad = pi/180.
alpha *= rad
beta *= rad
gamma *= rad
cos_alpha = math.cos(alpha)
cos_beta = math.cos(beta)
cos_gamma = math.cos(gamma)
sin_gamma = math.sin(gamma)
sin_alpha = math.sin(alpha)
matrix = np.zeros([3,3])
if format == 'lower':
#Generate a lower-diagonal matrix
c1 = c*cos_beta
c2 = (c*(cos_alpha - (cos_beta * cos_gamma))) / sin_gamma
matrix[0][0] = a
matrix[1][0] = b * cos_gamma
matrix[1][1] = b * sin_gamma
matrix[2][0] = c1
matrix[2][1] = c2
matrix[2][2] = math.sqrt(c**2 - c1**2 - c2**2)
elif format == 'symmetric':
#TODO: allow generation of symmetric matrices
pass
elif format == 'upper':
#Generate an upper-diagonal matrix
a3 = a*cos_beta
a2 = (a*(cos_gamma - (cos_beta * cos_alpha))) / sin_alpha
matrix[2][2] = c
matrix[1][2] = b * cos_alpha
matrix[1][1] = b * sin_alpha
matrix[0][2] = a3
matrix[0][1] = a2
matrix[0][0] = math.sqrt(a**2 - a3**2 - a2**2)
pass
return matrix
def Add_vacuum(lattice, coor, vacuum=10, PBC=[0,0,0]):
"""
Adds space above and below a 2D or 1D crystal. This allows for treating the
structure as a 3D crystal during energy optimization
Args:
lattice: the lattice matrix of the crystal
coor: the relative coordinates of the crystal
vacuum: the amount of space, in Angstroms, to add above and below
PBC: A periodic boundary condition list, where 1 means periodic, 0 means not periodic.
Ex: [1,1,1] -> full 3d periodicity, [0,0,1] -> periodicity along the z axis
Returns:
lattice, coor: The transformed lattice and coordinates after the
vacuum space is added
"""
absolute_coords = np.dot(coor, lattice)
for i, a in enumerate(PBC):
if not a:
lattice[i] += (lattice[i]/np.linalg.norm(lattice[i])) * vacuum
new_coor = np.dot(absolute_coords, np.linalg.inv(lattice))
return lattice, new_coor
def matrix2para(matrix, radians=True):
"""
Given a 3x3 matrix representing a unit cell, outputs a list of lattice
parameters.
Args:
matrix: a 3x3 array or list, where the first, second, and third rows
represent the a, b, and c vectors respectively
radians: if True, outputs angles in radians. If False, outputs in
degrees
Returns:
a 1x6 list of lattice parameters [a, b, c, alpha, beta, gamma]. a, b,
and c are the length of the lattice vectos, and alpha, beta, and gamma
are the angles between these vectors (in radians by default)
"""
cell_para = np.zeros(6)
#a
cell_para[0] = np.linalg.norm(matrix[0])
#b
cell_para[1] = np.linalg.norm(matrix[1])
#c
cell_para[2] = np.linalg.norm(matrix[2])
#alpha
cell_para[3] = angle(matrix[1], matrix[2])
#beta
cell_para[4] = angle(matrix[0], matrix[2])
#gamma
cell_para[5] = angle(matrix[0], matrix[1])
if not radians:
#convert radians to degrees
deg = 180./pi
cell_para[3] *= deg
cell_para[4] *= deg
cell_para[5] *= deg
return cell_para
def cellsize(group, dim=3):
"""
Returns the number of duplicate atoms in the conventional lattice (in
contrast to the primitive cell). Based on the type of cell centering (P,
A, C, I, R, or F)
Args:
| |
if DEBUG:
raise
# print(self.ui.openglview.width()-30, self.ui.openglview.height()-50)
content = write_html.write(mol, self.ui.openglview.width() - 30, self.ui.openglview.height() - 50)
p2 = Path(os.path.join(application_path, "./displaymol/jsmol.htm"))
p2.write_text(data=content, encoding="utf-8", errors='ignore')
self.view.reload()
def clear_molecule(self):
"""
Deletes the current molecule display.
:return:
"""
p2 = Path(os.path.join(application_path, "./displaymol/jsmol.htm"))
p2.write_text(data='', encoding="utf-8", errors='ignore')
self.view.reload()
@pyqtSlot('QString')
def find_dates(self, date1: str, date2: str) -> list:
"""
Returns a list if id between date1 and date2
"""
if not date1:
date1 = '0000-01-01'
if not date2:
date2 = 'NOW'
result = self.structures.find_by_date(date1, date2)
return result
@pyqtSlot('QString')
def search_text(self, search_string: str) -> bool:
"""
searches db for given text
"""
self.ui.searchCellLineEDit.clear()
self.ui.cifList_treeWidget.clear()
try:
if not self.structures:
return False # Empty database
except Exception:
return False # No database cursor
searchresult = []
if len(search_string) == 0:
self.show_full_list()
return False
if len(search_string) >= 2 and "*" not in search_string:
search_string = "{}{}{}".format('*', search_string, '*')
try:
searchresult = self.structures.find_by_strings(search_string)
except AttributeError as e:
print(e)
try:
self.statusBar().showMessage("Found {} structures.".format(len(searchresult)))
for structure_id, filename, dataname, path in searchresult:
self.add_table_row(filename, path, dataname, structure_id)
self.set_columnsize()
except Exception:
self.statusBar().showMessage("Nothing found.")
def search_cell_idlist(self, cell: list) -> list:
"""
Searches for a unit cell and resturns a list of found database ids.
This method does not validate the cell. This has to be done before!
"""
if self.apexdb == 1: # needs less accurate search:
if self.ui.moreResultsCheckBox.isChecked() or self.ui.adv_moreResultscheckBox.isChecked():
# more results:
vol_threshold = 0.09
ltol = 0.1
atol = 1.0
else:
# regular:
vol_threshold = 0.03
ltol = 0.06
atol = 0.5
else: # regular database:
if self.ui.moreResultsCheckBox.isChecked() or self.ui.adv_moreResultscheckBox.isChecked():
# more results:
print('more results on')
vol_threshold = 0.04
ltol = 0.08
atol = 1.0
else:
# regular:
vol_threshold = 0.02
ltol = 0.025
atol = 0.2
try:
volume = misc.vol_unitcell(*cell)
# the fist number in the result is the structureid:
cells = self.structures.find_by_volume(volume, vol_threshold)
print(len(cells), 'cells to check at {}% theshold.'.format(vol_threshold * 100))
if self.ui.sublattCheckbox.isChecked() or self.ui.adv_superlatticeCheckBox.isChecked():
# sub- and superlattices:
for v in [volume * x for x in [2.0, 3.0, 4.0, 6.0, 8.0, 10.0]]:
# First a list of structures where the volume is similar:
cells.extend(self.structures.find_by_volume(v, vol_threshold))
cells = list(set(cells))
except (ValueError, AttributeError):
if not self.full_list:
self.ui.cifList_treeWidget.clear()
self.statusBar().showMessage('Found 0 structures.')
return []
# Real lattice comparing in G6:
idlist = []
if cells:
lattice1 = lattice.Lattice.from_parameters(*cell)
self.statusBar().clearMessage()
for num, curr_cell in enumerate(cells):
self.progressbar(num, 0, len(cells) - 1)
try:
lattice2 = lattice.Lattice.from_parameters(*curr_cell[1:7])
except ValueError:
continue
mapping = lattice1.find_mapping(lattice2, ltol, atol, skip_rotation_matrix=True)
if mapping:
idlist.append(curr_cell[0])
# print("After match: ", len(idlist), sorted(idlist))
return idlist
@pyqtSlot('QString', name='search_cell')
def search_cell(self, search_string: str) -> bool:
"""
searches db for given cell via the cell volume
"""
cell = is_valid_cell(search_string)
self.ui.adv_unitCellLineEdit.setText(' '.join([str(x) for x in cell]))
if self.ui.cellSearchCSDLineEdit.isEnabled() and cell:
self.ui.cellSearchCSDLineEdit.setText(' '.join([str(x) for x in cell]))
self.ui.txtSearchEdit.clear()
if not cell:
if str(self.ui.searchCellLineEDit.text()):
self.statusBar().showMessage('Not a valid unit cell!', msecs=3000)
return False
else:
self.full_list = True # Set status where full list is displayed
self.show_full_list()
if self.full_list:
return False
return False
try:
if not self.structures:
return False # Empty database
except Exception:
return False # No database cursor
idlist = self.search_cell_idlist(cell)
if not idlist:
self.ui.cifList_treeWidget.clear()
self.statusBar().showMessage('Found 0 structures.', msecs=0)
return False
searchresult = self.structures.get_all_structure_names(idlist)
self.statusBar().showMessage('Found {} structures.'.format(len(idlist)))
self.ui.cifList_treeWidget.clear()
self.full_list = False
for structure_id, _, path, name, data in searchresult:
self.add_table_row(name, path, data, structure_id)
self.set_columnsize()
# self.ui.cifList_treeWidget.sortByColumn(0, 0)
# self.ui.cifList_treeWidget.resizeColumnToContents(0)
return True
def search_elements(self, elements: str, excluding: str, onlythese: bool = False) -> list:
"""
list(set(l).intersection(l2))
"""
self.statusBar().showMessage('')
res = []
try:
formula = misc.get_list_of_elements(elements)
except KeyError:
self.statusBar().showMessage('Error: Wrong list of Elements!', msecs=5000)
return []
try:
formula_ex = misc.get_list_of_elements(excluding)
except KeyError:
self.statusBar().showMessage('Error: Wrong list of Elements!', msecs=5000)
return []
try:
res = self.structures.find_by_elements(formula, excluding=formula_ex, onlyincluded=onlythese)
except AttributeError:
pass
return list(res)
def add_table_row(self, filename: str, path: str, data: bytes, structure_id: str) -> None:
"""
Adds a line to the search results table.
"""
if isinstance(filename, bytes):
filename = filename.decode("utf-8", "surrogateescape")
if isinstance(path, bytes):
path = path.decode("utf-8", "surrogateescape")
if isinstance(data, bytes):
data = data.decode("utf-8", "surrogateescape")
tree_item = QTreeWidgetItem()
tree_item.setText(0, filename) # name
tree_item.setText(1, data) # data
tree_item.setText(2, path) # path
tree_item.setData(3, 0, structure_id) # id
self.ui.cifList_treeWidget.addTopLevelItem(tree_item)
def get_import_filename_from_dialog(self, dir: str = './'):
return QFileDialog.getOpenFileName(self, caption='Open File', directory=dir, filter="*.sqlite")[0]
def open_database_file(self, fname=None) -> bool:
"""
Import a new database.
"""
self.tmpfile = False
self.close_db()
if not fname:
print('####', self.settings.load_last_workdir())
with suppress(FileNotFoundError, OSError):
os.chdir(self.settings.load_last_workdir())
fname = self.get_import_filename_from_dialog(dir=self.settings.load_last_workdir())
if not fname:
return False
print("Opened {}.".format(fname))
self.dbfilename = fname
self.structures = database_handler.StructureTable(self.dbfilename)
try:
self.show_full_list()
except DatabaseError:
self.moving_message('Database file is corrupt!')
self.close_db()
return False
try:
if self.structures:
pass
except (TypeError, ProgrammingError):
return False
self.settings.save_current_dir(str(Path(fname).parent))
os.chdir(str(Path(fname).parent))
self.ui.saveDatabaseButton.setEnabled(True)
self.ui.DatabaseNameDisplayLabel.setText('Database opened: {}'.format(fname))
return True
def open_apex_db(self, user: str, password: str, host: str) -> bool:
"""
Opens the APEX db to be displayed in the treeview.
"""
self.ui.DatabaseNameDisplayLabel.setText('')
self.apx = apeximporter.ApexDB()
connok = False
try:
connok = self.apx.initialize_db(user, password, host)
except Exception:
self.passwd_handler()
self.ui.saveDatabaseButton.setEnabled(True)
if connok:
self.ui.DatabaseNameDisplayLabel.setText('Database opened: APEX')
return connok
def get_name_from_p4p(self):
"""
Reads a p4p file to get the included unit cell for a cell search.
"""
fname, _ = QFileDialog.getOpenFileName(self, caption='Open p4p File', directory='./',
filter="*.p4p *.cif *.res *.ins")
fname = str(fname)
_, ending = os.path.splitext(fname)
if ending == '.p4p':
self.search_for_p4pcell(fname)
if ending in ['.res', '.ins']:
self.search_for_res_cell(fname)
if ending == '.cif':
self.search_for_cif_cell(fname)
def search_for_p4pcell(self, fname):
if fname:
p4plist = read_file_to_list(fname)
p4p = P4PFile(p4plist)
else:
return
if p4p:
if p4p.cell:
try:
self.ui.searchCellLineEDit.setText('{:<6.3f} {:<6.3f} {:<6.3f} '
'{:<6.3f} {:<6.3f} {:<6.3f}'.format(*p4p.cell))
except TypeError:
pass
else:
self.moving_message('Could not read P4P file!')
else:
self.moving_message('Could not read P4P file!')
def search_for_res_cell(self, fname):
if fname:
shx = ShelXFile(fname)
else:
return
if shx:
if shx.cell:
try:
self.ui.searchCellLineEDit.setText('{:<6.3f} {:<6.3f} {:<6.3f} '
'{:<6.3f} {:<6.3f} {:<6.3f}'.format(*shx.cell))
except TypeError:
pass
else:
self.moving_message('Could not read res file!')
else:
self.moving_message('Could not read res file!')
def search_for_cif_cell(self, fname):
if fname:
cif = Cif()
try:
cif.parsefile(Path(fname).read_text(encoding='utf-8',
errors='ignore').splitlines(keepends=True))
except FileNotFoundError:
self.moving_message('File not found.')
else:
return
if cif:
if cif.cell:
try:
self.ui.searchCellLineEDit.setText('{:<6.3f} {:<6.3f} {:<6.3f} '
'{:<6.3f} {:<6.3f} {:<6.3f}'.format(*cif.cell[:6]))
except TypeError:
pass
else:
self.moving_message('Could not read cif file!')
else:
self.moving_message('Could not read cif file!')
def moving_message(self, message="", times=20):
for s in range(times):
time.sleep(0.05)
self.statusBar().showMessage("{}{}".format(' ' * s, message))
def import_apex_db(self, user: str = '', password: str = '', host: str = '') -> None:
"""
Imports data from apex into own db
"""
self.apexdb = 1
self.statusBar().showMessage('')
self.close_db()
self.start_db()
self.ui.cifList_treeWidget.show()
# self.abort_import_button.show()
n = 1
num = 0
time1 = time.perf_counter()
conn = self.open_apex_db(user, password, host)
# if not conn:
# self.abort_import_button.hide()
# return None
cif = Cif()
if conn:
for i in self.apx.get_all_data():
if num == 20:
num = 0
self.progressbar(num, 0, 20)
cif.cif_data['_cell_length_a'] = i[1]
cif.cif_data['_cell_length_b'] = i[2]
cif.cif_data['_cell_length_c'] = i[3]
cif.cif_data['_cell_angle_alpha'] = i[4]
cif.cif_data['_cell_angle_beta'] = i[5]
cif.cif_data['_cell_angle_gamma'] = i[6]
cif.cif_data["data"] = i[8]
cif.cif_data['_diffrn_radiation_wavelength'] = i[13]
cif.cif_data['_exptl_crystal_colour'] = i[29]
cif.cif_data['_exptl_crystal_size_max'] = i[16]
cif.cif_data['_exptl_crystal_size_mid'] = i[17]
cif.cif_data['_exptl_crystal_size_min'] = i[18]
cif.cif_data["_chemical_formula_sum"] = i[25]
cif.cif_data['_diffrn_reflns_av_R_equivalents'] = i[21] # rint
cif.cif_data['_diffrn_reflns_av_unetI/netI'] = i[22] # rsig
cif.cif_data['_diffrn_reflns_number'] = i[23]
comp = i[26]
cif.cif_data["_space_group_centring_type"] = i[28]
if comp:
cif.cif_data['_diffrn_measured_fraction_theta_max'] = comp / 100
try:
tst = filecrawler.fill_db_with_cif_data(cif=cif, filename=i[8], path=i[12], structure_id=n,
structures=self.structures)
except Exception as err:
if DEBUG:
print(str(err) + "\nIndexing error in file {}{}{} - Id: {}".format(i[12], os.path.sep, i[8], n))
raise
continue
if not tst:
continue
self.add_table_row(filename=i[8], data=i[8], path=i[12], structure_id=str(n))
n += 1
if n % 300 == 0:
self.structures.database.commit_db()
num += 1
# if not self.decide_import:
# # This means, import was aborted.
# self.abort_import_button.hide()
# self.decide_import = True
# break
time2 = time.perf_counter()
diff = time2 - time1
self.progress.hide()
m, s = divmod(diff, 60)
h, m = divmod(m, 60)
if n == 0:
n += 1
self.ui.statusbar.showMessage('Added {} APEX entries in: {:>2d} h, {:>2d} m, {:>3.2f} s'
.format(n - 1, int(h), int(m), s), msecs=0)
# self.ui.cifList_treeWidget.resizeColumnToContents(0)
self.set_columnsize()
self.structures.database.init_textsearch()
self.structures.populate_fulltext_search_table()
self.structures.database.commit_db("Committed")
# self.abort_import_button.hide()
def set_columnsize(self):
"""
Sets columnsize of main structure list.
"""
self.ui.cifList_treeWidget.sortByColumn(0, 0)
treewidth = self.ui.cifList_treeWidget.width()
self.ui.cifList_treeWidget.setColumnWidth(0, int(treewidth / 4.0))
self.ui.cifList_treeWidget.setColumnWidth(1, int(treewidth / 5.0))
# self.ui.cifList_treeWidget.resizeColumnToContents(0)
# self.ui.cifList_treeWidget.resizeColumnToContents(1)
def show_full_list(self) -> None:
"""
Displays the complete list of structures
[structure_id, meas, path, filename, data]
"""
self.ui.cifList_treeWidget.clear()
structure_id = 0
try:
if self.structures:
pass
| |
#!/usr/bin/env python3
#Test suite for Problem Set 4 (Drug Simulation)
import sys
import unittest
import numpy as np
import ps4
population = [[100, 115, 122, 129, 134, 138, 151, 167, 174, 183, 196, 208, 215, 223, 233,
240, 253, 268, 284, 294, 306, 316, 325, 338, 360, 372, 378, 388, 399, 415, 414, 431, 456,
477, 485, 493, 510, 530, 547, 569, 575, 580, 579, 588, 597, 605, 625, 626, 632, 640, 653,
660, 668, 681, 685, 690, 695, 691, 693, 689, 696, 706, 720, 717, 718, 713, 720, 723, 726,
731, 728, 721, 727, 731, 734, 741, 751, 748, 750, 750, 752, 752, 745, 753, 752, 756, 753,
745, 747, 747, 750, 745, 751, 759, 753, 754, 762, 765, 754, 764, 767, 769, 770, 775, 784,
787, 789, 786, 783, 773, 770, 764, 764, 767, 767, 768, 765, 765, 750, 753, 745, 745, 746,
753, 754, 763, 767, 777, 778, 784, 782, 782, 783, 788, 790, 782, 786, 792, 799, 792, 779,
778, 768, 768, 768, 775, 774, 783, 782, 778, 778, 789, 771, 775, 770, 780, 778, 780, 771,
765, 762, 758, 768, 762, 777, 774, 776, 779, 771, 768, 781, 783, 793, 801, 803, 798, 794,
798, 799, 801, 804, 802, 807, 795, 776, 773, 779, 775, 777, 783, 791, 787, 778, 782, 789,
782, 773, 775, 782, 779, 778, 774, 776, 782, 770, 773, 775, 772, 777, 772, 772, 774, 771,
760, 764, 766, 758, 759, 758, 745, 744, 754, 760, 770, 765, 764, 754, 769, 760, 762, 762,
765, 754, 762, 762, 764, 757, 762, 759, 758, 748, 752, 764, 758, 762, 761, 755, 747, 746,
744, 750, 748, 746, 756, 762, 758, 754, 758, 754, 747, 750, 752, 744, 741, 744, 756, 768,
773, 772, 768, 764, 762, 754, 761, 760, 749, 746, 744, 741, 748, 745, 751, 753, 744, 736,
746, 749, 749, 762, 756, 762, 762, 756, 761, 762, 762, 755, 763, 772, 761], [100, 113, 125,
129, 136, 151, 166, 177, 186, 196, 208, 215, 219, 235, 239, 257, 270, 288, 299, 310, 322, 335,
344, 354, 375, 395, 408, 429, 446, 451, 471, 497, 515, 528, 525, 542, 558, 567, 580, 593, 604,
613, 619, 628, 631, 645, 656, 676, 676, 685, 704, 711, 715, 724, 724, 725, 725, 725, 740, 737,
736, 752, 757, 759, 762, 762, 771, 759, 755, 754, 752, 752, 755, 765, 766, 766, 761, 766, 761,
752, 755, 756, 765, 769, 768, 770, 769, 772, 766, 770, 771, 773, 782, 771, 768, 767, 769, 781,
779, 780, 775, 772, 761, 759, 760, 762, 761, 763, 756, 758, 766, 759, 748, 751, 750, 750, 761,
756, 767, 776, 780, 780, 767, 762, 759, 760, 757, 761, 766, 770, 757, 758, 763, 759, 754, 746,
754, 760, 755, 758, 757, 769, 773, 773, 764, 770, 770, 770, 774, 768, 775, 779, 779, 769, 766,
766, 769, 759, 749, 756, 776, 770, 771, 761, 765, 766, 771, 783, 782, 774, 774, 771, 765, 753,
767, 770, 771, 769, 770, 767, 764, 757, 763, 769, 766, 767, 776, 773, 771, 775, 771, 776, 767,
756, 760, 764, 757, 753, 745, 745, 759, 751, 752, 749, 740, 748, 740, 740, 742, 740, 737, 744,
739, 744, 750, 753, 751, 750, 764, 775, 759, 762, 767, 772, 774, 781, 776, 772, 778, 785, 771,
762, 757, 752, 747, 754, 757, 757, 763, 766, 765, 758, 762, 760, 757, 765, 769, 764, 761, 762,
764, 762, 751, 752, 747, 747, 750, 752, 765, 771, 766, 765, 755, 751, 750, 743, 749, 750, 743,
752, 749, 736, 750, 749, 746, 754, 744, 743, 730, 730, 719, 721, 724, 731, 732, 735, 746, 740,
741, 750, 750, 740, 738, 741, 734, 728, 745, 740, 732, 738], [100, 112, 117, 130, 139, 149,
156, 169, 172, 189, 200, 216, 223, 233, 247, 257, 268, 280, 292, 302, 308, 323, 338, 346, 359,
379, 388, 390, 410, 427, 447, 462, 469, 485, 499, 521, 536, 548, 557, 555, 566, 571, 577, 580,
592, 607, 612, 620, 628, 629, 629, 635, 647, 657, 661, 672, 689, 694, 697, 713, 715, 720, 724,
734, 746, 749, 736, 740, 752, 763, 759, 751, 753, 749, 741, 743, 750, 751, 758, 769, 775, 784,
784, 786, 789, 790, 798, 800, 794, 802, 796, 801, 803, 791, 795, 785, 779, 768, 758, 752, 753,
749, 759, 763, 754, 754, 753, 761, 772, 765, 768, 769, 771, 772, 768, 766, 764, 761, 770, 771,
773, 771, 768, 760, 756, 759, 755, 763, 758, 753, 757, 756, 764, 765, 763, 768, 770, 776, 776,
776, 778, 765, 769, 760, 763, 759, 770, 772, 778, 768, 777, 779, 782, 777, 774, 783, 776, 771,
775, 766, 769, 767, 763, 759, 749, 751, 746, 747, 746, 740, 743, 749, 757, 750, 752, 762, 768,
771, 769, 779, 775, 779, 772, 777, 785, 784, 782, 793, 784, 786, 788, 780, 781, 779, 773, 778,
780, 774, 766, 767, 765, 764, 766, 770, 765, 776, 785, 785, 792, 788, 786, 790, 785, 788, 793,
793, 788, 792, 789, 774, 775, 769, 770, 770, 773, 775, 770, 769, 763, 758, 766, 776, 776, 776,
778, 771, 775, 777, 776, 770, 773, 767, 761, 765, 762, 770, 772, 775, 781, 779, 767, 766, 767,
763, 763, 755, 753, 751, 758, 761, 764, 771, 772, 762, 764, 758, 756, 754, 752, 752, 748, 753,
763, 766, 766, 758, 756, 752, 759, 753, 749, 754, 751, 750, 751, 749, 751, 747, 751, 753, 739,
747, 745, 747, 748, 746, 755, 755, 760, 766], [100, 106, 113, 111, 117, 124, 136, 139, 152,
154, 161, 168, 176, 182, 194, 210, 226, 239, 256, 274, 287, 297, 314, 329, 343, 355, 356, 362,
376, 394, 405, 421, 432, 448, 471, 497, 508, 520, 525, 530, 538, 560, 576, 595, 604, 619, 635,
654, 656, 672, 683, 683, 692, 705, 704, 706, 705, 703, 710, 710, 714, 712, 722, 736, 737, 730,
727, 735, 734, 743, 752, 757, 751, 755, 769, 764, 769, 763, 764, 767, 762, 753, 744, 751, 741,
733, 733, 729, 734, 733, 745, 748, 750, 751, 746, 755, 751, 754, 755, 750, 753, 752, 754, 757,
760, 767, 768, 761, 763, 752, 748, 747, 747, 749, 765, 771, 774, 765, 763, 760, 758, 756, 754,
752, 736, 744, 751, 760, 757, 756, 755, 773, 775, 769, 765, 768, 773, 779, 771, 778, 765, 766,
760, 754, 746, 747, 749, 756, 757, 757, 761, 758, 746, 739, 745, 748, 756, 764, 765, 772, 776,
778, 772, 780, 777, 772, 763, 764, 771, 777, 776, 775, 780, 769, 770, 765, 759, 761, 758, 762,
759, 766, 774, 769, 769, 770, 773, 773, 777, 770, 770, 769, 761, 760, 767, 766, 765, 762, 758,
763, 760, 767, 760, 761, 762, 766, 765, 778, 776, 782, 773, 770, 782, 778, 776, 770, 767, 766,
755, 756, 753, 747, 744, 759, 760, 742, 746, 744, 748, 762, 759, 762, 770, 774, 784, 773, 763,
749, 742, 747, 731, 728, 731, 736, 745, 743, 737, 736, 736, 739, 739, 743, 740, 748, 760, 754,
757, 765, 772, 766, 767, 764, 751, 750, 750, 750, 753, 763, 767, 762, 765, 768, 774, 770, 768,
766, 765, 752, 745, 749, 751, 750, 750, 753, 747, 755, 762, 762, 770, 762, 756, 754, 754, 757,
763, 760, 752, 753, 765, 770], [100, 109, 121, 127, 135, 146, 150, 160, 167, 180, 196, 206,
226, 244, 254, 263, 277, 303, 310, 321, 325, 342, 356, 372, 383, 394, 407, 418, 422, 430, 459,
477, 485, 504, 517, 518, 520, 532, 542, 558, 574, 594, 607, 602, 606, 615, 628, 636, 654, 660,
656, 660, 662, 673, 684, 686, 698, 714, 715, 723, 727, 739, 736, 733, 741, 744, 744, 742, 751,
757, 758, 753, 754, 755, 758, 757, 763, 757, 754, 743, 740, 738, 739, 740, 739, 745, 739, 741,
736, 726, 737, 737, 740, 749, 750, 756, 754, 761, 774, 783, 781, 781, 773, 759, 754, 752, 754,
761, 749, 740, 739, 732, 727, 730, 744, 753, 763, 753, 752, 753, 761, 759, 759, 753, 743, 749,
743, 730, 734, 735, 737, 748, 756, 760, 754, | |
http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPer6Hour = CommonUCUMUnitsCode("g/(6.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPer72Hour = CommonUCUMUnitsCode("g/(72.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_8_Hour = CommonUCUMUnitsCode("g/(8.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_8_Kilogram_Hour = CommonUCUMUnitsCode("g/(8.kg.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_Kilogram_Hour = CommonUCUMUnitsCode("g/(kg.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_Kilogram_Minute = CommonUCUMUnitsCode("g/(kg.min)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_TotalWeight = CommonUCUMUnitsCode("g/{TotalWeight}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerDay = CommonUCUMUnitsCode("g/d")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerDeciliter = CommonUCUMUnitsCode("g/dL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerGram = CommonUCUMUnitsCode("g/g")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_GramCre = CommonUCUMUnitsCode("g/g{Cre}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_GramCreat = CommonUCUMUnitsCode("g/g{creat}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerGramOfTissue = CommonUCUMUnitsCode("g/g{tissue}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerHour = CommonUCUMUnitsCode("g/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerHourPerSquareMeter = CommonUCUMUnitsCode("g/h/m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerKilogram = CommonUCUMUnitsCode("g/kg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerKilogramPerDay = CommonUCUMUnitsCode("g/kg/d")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerLiter = CommonUCUMUnitsCode("g/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramsPerSquareMeter = CommonUCUMUnitsCode("g/m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerMilligram = CommonUCUMUnitsCode("g/mg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerMinute = CommonUCUMUnitsCode("g/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerMilliliter = CommonUCUMUnitsCode("g/mL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerMillimole = CommonUCUMUnitsCode("g/mmol")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Gram_MillimoleCreat = CommonUCUMUnitsCode("g/mmol{creat}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GramPerMole = CommonUCUMUnitsCode("g/mol")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
GigaBecquerel = CommonUCUMUnitsCode("GBq")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Hour = CommonUCUMUnitsCode("h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Hectoliter = CommonUCUMUnitsCode("hL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Hertz = CommonUCUMUnitsCode("Hz")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
InternationalUnit = CommonUCUMUnitsCode("[iU]")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Joule = CommonUCUMUnitsCode("J")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
JoulePerLiter = CommonUCUMUnitsCode("J/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kelvin = CommonUCUMUnitsCode("K")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kelvin_Watt = CommonUCUMUnitsCode("K/W")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloInternationalUnitPerLiter = CommonUCUMUnitsCode("k[IU]/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloInternationalUnitPerMilliliter = CommonUCUMUnitsCode("k[IU]/mL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Katal_Kilogram = CommonUCUMUnitsCode("kat/kg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Katal_Liter = CommonUCUMUnitsCode("kat/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloBecquerel = CommonUCUMUnitsCode("kBq")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilocalorie = CommonUCUMUnitsCode("kcal")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilocalorie_8_Hour = CommonUCUMUnitsCode("kcal/(8.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KilocaloriePerHour = CommonUCUMUnitsCode("kcal/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilogram = CommonUCUMUnitsCode("kg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KilogramMeterPerSecond = CommonUCUMUnitsCode("kg.m/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KilogramPerSecondPerSquareMeter = CommonUCUMUnitsCode("kg/(s.m2)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KilogramPerHour = CommonUCUMUnitsCode("kg/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KilogramPerLiter = CommonUCUMUnitsCode("kg/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilogram_meter_2_ = CommonUCUMUnitsCode("kg/m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilogram_meter_3_ = CommonUCUMUnitsCode("kg/m3")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilogram_Minute = CommonUCUMUnitsCode("kg/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KilogramPerMole = CommonUCUMUnitsCode("kg/mol")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilogram_Second = CommonUCUMUnitsCode("kg/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kiloliter = CommonUCUMUnitsCode("kL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilometer = CommonUCUMUnitsCode("km")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloPascal = CommonUCUMUnitsCode("kPa")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Kilosecond = CommonUCUMUnitsCode("ks")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloenzymeUnitPerGram = CommonUCUMUnitsCode("kU/g")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloUnit_Hour = CommonUCUMUnitsCode("kU/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloenzymeUnitPerLiter = CommonUCUMUnitsCode("kU/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
KiloEnzymeUnitPerMilliliter = CommonUCUMUnitsCode("kU/mL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Liter = CommonUCUMUnitsCode("L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Liter_second_2_Second = CommonUCUMUnitsCode("L.s2/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPer8Hour = CommonUCUMUnitsCode("L/(8.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPerMinutePerSquareMeter = CommonUCUMUnitsCode("L/(min.m2)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPerDay = CommonUCUMUnitsCode("L/d")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPerHour = CommonUCUMUnitsCode("L/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPerKilogram = CommonUCUMUnitsCode("L/kg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPerLiter = CommonUCUMUnitsCode("L/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
LiterPerMinute = CommonUCUMUnitsCode("L/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Liter_Second = CommonUCUMUnitsCode("L/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Lumen_meter_2_ = CommonUCUMUnitsCode("lm/m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Meter = CommonUCUMUnitsCode("m")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MeterPerSecond = CommonUCUMUnitsCode("m/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MeterPerSquareSecond = CommonUCUMUnitsCode("m/s2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliinternationalUnit = CommonUCUMUnitsCode("m[iU]")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliInternationalUnitPerLiter = CommonUCUMUnitsCode("m[IU]/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliInternationalUnitPerMilliliter = CommonUCUMUnitsCode("m[IU]/mL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
SquareMeter = CommonUCUMUnitsCode("m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
SquareMeterPerSecond = CommonUCUMUnitsCode("m2/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
CubicMeterPerSecond = CommonUCUMUnitsCode("m3/s")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliAmp_re = CommonUCUMUnitsCode("mA")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Millibar = CommonUCUMUnitsCode("mbar")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MillibarSecondPerLiter = CommonUCUMUnitsCode("mbar.s/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MegaBecquerel = CommonUCUMUnitsCode("MBq")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliCurie = CommonUCUMUnitsCode("mCi")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milliequivalent = CommonUCUMUnitsCode("meq")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPer12Hour = CommonUCUMUnitsCode("meq/(12.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPer2Hour = CommonUCUMUnitsCode("meq/(2.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPer24Hour = CommonUCUMUnitsCode("meq/(24.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPer8Hour = CommonUCUMUnitsCode("meq/(8.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milliequivalents_8_Hour_Kilogram = CommonUCUMUnitsCode("meq/(8.h.kg)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milliequivalents_Kilogram_Day = CommonUCUMUnitsCode("meq/(kg.d)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milliequivalents_Specimen = CommonUCUMUnitsCode("meq/{Specimen}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerDay = CommonUCUMUnitsCode("meq/d")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerDeciliter = CommonUCUMUnitsCode("meq/dL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerGram = CommonUCUMUnitsCode("meq/g")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milliequivalents_GramCre = CommonUCUMUnitsCode("meq/g{Cre}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerHour = CommonUCUMUnitsCode("meq/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerKilogram = CommonUCUMUnitsCode("meq/kg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerKilogramPerHour = CommonUCUMUnitsCode("meq/kg/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milliequivalents_Kilogram_Minute = CommonUCUMUnitsCode("meq/kg/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerLiter = CommonUCUMUnitsCode("meq/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerSquareMeter = CommonUCUMUnitsCode("meq/m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerMinute = CommonUCUMUnitsCode("meq/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilliequivalentPerMilliliter = CommonUCUMUnitsCode("meq/mL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram = CommonUCUMUnitsCode("mg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer10Hour = CommonUCUMUnitsCode("mg/(10.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer12Hour = CommonUCUMUnitsCode("mg/(12.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer18Hour = CommonUCUMUnitsCode("mg/(18.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer2Hour = CommonUCUMUnitsCode("mg/(2.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer24Hour = CommonUCUMUnitsCode("mg/(24.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer72Hour = CommonUCUMUnitsCode("mg/(72.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPer8Hour = CommonUCUMUnitsCode("mg/(8.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_8_Hour_Kilogram = CommonUCUMUnitsCode("mg/(8.h.kg)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Kilogram_Hour = CommonUCUMUnitsCode("mg/(kg.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Hgb_Gram = CommonUCUMUnitsCode("mg/{Hgb}/g")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Specimen = CommonUCUMUnitsCode("mg/{Specimen}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Tot_Volume = CommonUCUMUnitsCode("mg/{Tot'Volume}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Volume = CommonUCUMUnitsCode("mg/{Volume}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerDay = CommonUCUMUnitsCode("mg/d")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Day_173_theNumberTenForArbitraryPowers_2_meter_2_ = CommonUCUMUnitsCode(
"mg/d/(173.10*-2.m2)"
)
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerDeciliter = CommonUCUMUnitsCode("mg/dL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerGram = CommonUCUMUnitsCode("mg/g")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_GramCre = CommonUCUMUnitsCode("mg/g{Cre}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerGramOfCreatinine = CommonUCUMUnitsCode("mg/g{creat}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerHour = CommonUCUMUnitsCode("mg/h")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerKilogram = CommonUCUMUnitsCode("mg/kg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_Kilogram_24_Hour = CommonUCUMUnitsCode("mg/kg/(24.h)")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerKilogramPerDay = CommonUCUMUnitsCode("mg/kg/d")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerKilogramPerMinute = CommonUCUMUnitsCode("mg/kg/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerLiter = CommonUCUMUnitsCode("mg/L")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerSquareMeter = CommonUCUMUnitsCode("mg/m2")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerCubicMeter = CommonUCUMUnitsCode("mg/m3")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerMilligram = CommonUCUMUnitsCode("mg/mg")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_MilligramCre = CommonUCUMUnitsCode("mg/mg{cre}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerMinute = CommonUCUMUnitsCode("mg/min")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerMilliliter = CommonUCUMUnitsCode("mg/mL")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerMillimole = CommonUCUMUnitsCode("mg/mmol")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
Milligram_MillimoleCre = CommonUCUMUnitsCode("mg/mmol{Cre}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerMillimoleOfCreatinine = CommonUCUMUnitsCode("mg/mmol{creat}")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPerWeek = CommonUCUMUnitsCode("mg/wk")
"""
From: http://hl7.org/fhir/ValueSet/ucum-common in valuesets.xml
"""
MilligramPhenylketones_Deciliter = CommonUCUMUnitsCode("mg{Phenylketones}/dL")
"""
From: | |
"""SNR Project GUI Module.
Classes to create widgets for SNR program.
Authors: <NAME>, <NAME>, <NAME>
Version: April 1st, 2019
"""
import tkinter as tk
from tkinter import ttk
import platform
OS = platform.system()
##############################################################################################################################
##############################################################################################################################
class InputParam:
"""Create and grid label widgets for an input parameter.
Attributes:
label_options (dict): display options for label
input_options (dict): display options for input widget
instances (dict): all InputParam widgets, uses identifiers as keys
identifier (str): string used as key in instances dictionary
row (int): row of the container frame in which the widget should be placed
label (str): input parameter label
previous (float): widget value that passed validation conditions
value_var (tk.StringVar): variable to store input parameter value
"""
label_options = {"font": "-size 10", "padding": 5}
input_options = {"font": "-size 10"}
instances = {}
##############################################################################################################################
def __init__(self, master, identifier=None, label=None, default=None, padding=True):
"""Create and grid input parameter label.
Args:
master (ttk.Frame): widget container frame
identifier (str, optional): string used as key in instances dictionary
label (str, optional): input parameter label (includes units)
default (float/str, optional): default value of parameter
padding (tuple/int, optional): padding for label, set to default 5 if not specified
"""
self.identifier = identifier
self.row = get_row(master)
if padding != True:
self.label_options = self.label_options.copy()
if not padding:
self.label_options.pop("padding")
else:
self.label_options["padding"] = padding
if label is not None:
self.label = ttk.Label(master, text=label, **self.label_options)
self.label.grid(row=self.row, column=0, sticky="w")
if default is not None:
self.previous = default
self.value_var = tk.StringVar(master, str(default))
if identifier is not None:
root = "." + master.winfo_parent().split(".")[1]
if root not in self.instances:
self.instances[root] = {}
self.instances[root][identifier] = self
##############################################################################################################################
def get_value(self):
"""Get current input parameter value.
Returns:
float/str: current input parameter value, as a float if possible
"""
try:
return float(self.value_var.get())
except ValueError:
return self.value_var.get()
##############################################################################################################################
@classmethod
def get_values(cls, root):
"""Get all input parameter values.
Args:
root (str): ID of window to access widgets from
Returns:
dict: current input parameter values for all widgets in root window with valid identifiers
"""
values = {}
for identifier, widget in cls.instances[root].items():
values[identifier] = widget.get_value()
return values
##############################################################################################################################
##############################################################################################################################
class InputEntry(InputParam):
"""Create entry widget with labels for input parameter.
Attributes:
label_options (dict): display options for label
input_options (dict): display options for input widget
instances (dict): all InputParam widgets, uses identifiers as keys
identifier (str): string used as key in instances dictionary
row (int): row of the container frame in which the widget should be placed
label (str): input parameter label
previous (float): widget value that passed validation conditions
value_var (tk.StringVar): variable to store input parameter value
input (ttk.Entry): entry widget for input parameter
condition (function): function that must return True for input to be valid
"""
input_options = InputParam.input_options.copy()
input_options.update({"width": 7})
##############################################################################################################################
def __init__(self, master, identifier, label, default, callback=None, condition=lambda *args: True, **kwargs):
"""Create and grid input entry widget.
Args:
master (ttk.Frame): widget container frame
identifier (str): string used as key in instances dictionary
label (str): input parameter label (includes units)
default (float/str): default value of parameter
callback (function, optional): function to run when focus leaves widget
condition (function, optional): condition that must return true for new value to be accepted
**kwargs: additional options for input widget
"""
InputParam.__init__(self, master, identifier, label, default, padding=kwargs.pop("padding", True))
self.input_options = InputEntry.input_options.copy()
self.input_options.update(**kwargs)
self.input = ttk.Entry(master, textvariable=self.value_var, **self.input_options, validate="focusout")
self.input.config(validatecommand=(self.input.register(self.check_input), "%P"))
self.input.config(invalidcommand=self.revert_value)
self.input.grid(row=self.row, column=1, sticky="ew")
if callback is not None:
self.input.bind("<FocusOut>", lambda e: callback())
self.input.callback = callback
self.condition = condition
##############################################################################################################################
def check_input(self, inp):
"""Check that user input is positive and satisfies any additional conditions specified.
Args:
inp (str): user input
Returns:
bool: True if user input satisfies conditions, False otherwise
"""
try:
current = float(inp)
if current >= 0 and self.condition(current):
self.previous = inp
return True
else:
return False
except ValueError:
return False
##############################################################################################################################
def revert_value(self):
"""Revert input to previous acceptable value."""
self.value_var.set(self.previous)
##############################################################################################################################
##############################################################################################################################
class InputDropdown(InputParam):
"""Create combobox widget (dropdown menu) with labels for input parameter.
Attributes:
label_options (dict): display options for label
input_options (dict): display options for input widget
instances (dict): all InputParam widgets, uses identifiers as keys
identifier (str): string used as key in instances dictionary
row (int): row of the container frame in which the widget should be placed
label (str): input parameter label
previous (float): widget value that passed validation conditions
value_var (tk.StringVar): variable to store input parameter value
input (ttk.Combobox): combobox widget for input parameter
"""
input_options = InputParam.input_options.copy()
input_options.update({"width": 4, "state": "readonly"})
##############################################################################################################################
def __init__(self, master, identifier, label, default, callback, values, **kwargs):
"""Create and grid input dropdown widget.
Args:
master (ttk.Frame): widget container frame
identifier (str): string used as key in instances dictionary
label (str): input parameter label (includes units)
default (float/str): default value of parameter
callback (function, optional): function to run when focus leaves widget
values (tuple): tuple of values for dropdown
**kwargs: additional options for input widget
"""
padding = kwargs.pop("padding", True)
InputParam.__init__(self, master, identifier, label, default, padding=padding)
self.input_options = InputDropdown.input_options.copy()
self.input_options.update(kwargs)
self.input = ttk.Combobox(master, textvariable=self.value_var, values=values, **self.input_options)
self.input.grid(row=self.row, column=1, sticky="ew")
self.input.bind("<<ComboboxSelected>>", lambda e: callback())
self.input.callback = callback
##############################################################################################################################
##############################################################################################################################
class InputRadio(InputParam):
"""Create combobox widget (dropdown menu) with labels for input parameter.
Attributes:
label_options (dict): display options for label
input_options (dict): display options for input widget
instances (dict): all InputParam widgets, uses identifiers as keys
identifier (str): string used as key in instances dictionary
row (int): row of the container frame in which the widget should be placed
label (str): input parameter label
previous (float): widget value that passed validation conditions
value_var (tk.StringVar): variable to store input parameter value
input (dict): dictionary of radio button widgets for input parameter
"""
input_options = {}#InputParam.input_options.copy()
#input_options.update({"width": 5, "state": "readonly"})
##############################################################################################################################
def __init__(self, master, identifier, label, default, callback, values, **kwargs):
"""Create and grid input radio button widgets.
Args:
master (ttk.Frame): widget container frame
identifier (str): string used as key in instances dictionary
label (str): input parameter label (includes units)
default (float/str): default value of parameter
callback (function, optional): function to run when focus leaves widget
values (tuples): tuple of tuples, each associated with a radio button in the form (value, text)
**kwargs: additional options for input widget
"""
InputParam.__init__(self, master, identifier, label, default)
self.input_options = InputRadio.input_options.copy()
self.input_options.update(**kwargs)
frame = ttk.Frame(master)
frame.grid(row=self.row, column=1, sticky="w")
self.input = {}
row = ttk.Frame(frame)
row.pack(fill="x")
for item in values:
if "\n" in item:
row = ttk.Frame(frame)
row.pack(fill="x")
self.input[item[0]] = ttk.Radiobutton(row, variable=self.value_var, value=item[0],
text=item[1], **self.input_options)
self.input[item[0]].pack(side="left")
#self.input.bind("<FocusOut>", lambda e: callback())
self.value_var.trace("w", callback)
##############################################################################################################################
##############################################################################################################################
class InputSpinbox(InputEntry):
"""A spinbox widget with a text label.
Attributes:
label_options (dict): display options for label
input_options (dict): display options for input widget
instances (dict): all InputParam widgets, uses identifiers as keys
identifier (str): string used as key in instances dictionary
row (int): row of the container frame in which the widget should be placed
label (str): input parameter label
previous (float): widget value that passed validation conditions
value_var (tk.StringVar): variable to store input parameter value
input (ttk.Entry): entry widget for input parameter
"""
input_options = InputParam.input_options.copy()
##############################################################################################################################
def __init__(self, master, identifier, label, default, callback, condition=lambda *args: True, **kwargs):
"""Create and grid input spinbox widget.
Args:
master (ttk.Frame): widget container frame
identifier (str): string used as key in instances dictionary
label (str): input parameter label (includes units)
default (float/str): default value of parameter
callback (function, optional): function to run when focus leaves widget
condition (function, optional): condition that must return true for new value to be accepted
**kwargs: additional options for input widget
"""
InputParam.__init__(self, master, identifier, label, default)
self.input_options = InputSpinbox.input_options.copy()
self.input_options.update(kwargs)
self.input = ttk.Entry(master, "ttk::spinbox", textvariable=self.value_var, **self.input_options, validate="focusout")
self.input.config(validatecommand=(self.input.register(self.check_input), "%P"))
self.input.config(invalidcommand=self.revert_value)
self.input.grid(row=self.row, column=1)
self.input.bind("<FocusOut>", lambda e: callback(self))
self.input.bind("<<Increment>>", lambda e: callback(self, 1))
self.input.bind("<<Decrement>>", lambda e: callback(self, -1))
self.input.callback = callback
self.condition = condition
##############################################################################################################################
##############################################################################################################################
class InputCheckbox(InputParam):
"""A checkbox widget with a text label.
Attributes:
label_options (dict): display options for label
input_options (dict): display options for input widget
instances (dict): all InputParam widgets, uses identifiers as keys
identifier (str): string used as key in instances dictionary
row (int): row of the container frame in which the widget should be placed
label (str): input parameter label
previous (float): widget value that passed validation conditions
value_var (tk.StringVar): variable to store | |
= data['i'][()]
if group == True:
sex_mask = data['sex'][()]
class_mask = data['Binge'][()]
self.ho_Other = [y, ID, sex_mask, class_mask]
else:
self.ho_Other = [y, ID]
X.shape, len(X_col_names)
return self.ho_X, self.ho_X_col_names, self.ho_Other
# def __str__(self):
# pass
class RUN_loader:
def __init__(self, DATA_DIR="/ritter/share/data/IMAGEN"):
""" Set up path
Parameters
----------
DATA_DIR : string, optional
Directory IMAGEN absolute path
"""
# Set the directory path: IMAGEN
self.DATA_DIR = DATA_DIR
def set_RUN(self, run_file, save=False):
""" Save the ML RUN result in one file &
Generate the RUN classification report for posthoc analysis
Parameters
----------
run_file : string
ML models result run.csv path
save : boolean
if save == True, then save it as .csv
Returns
-------
DF3 : pandas.dataframe
The RUN dataframe
Examples
--------
>>> from imagen_posthocloader import *
>>> DATA = IMAGEN_instrument()
>>> DF3 = DATA.set_RUN(
... run_file) # RUN
>>> DF_FU3 = DF3.groupby('Session').get_group('fu3')
"""
df = pd.read_csv(run_file, low_memory = False)
DF = []
for i in range(len(df)):
test_ids = eval(df['test_ids'].values[i])
test_lbls = eval(df['test_lbls'].values[i])
test_probs = [probs[1] for probs in eval(df['test_probs'].values[i])]
holdout_ids = eval(df['holdout_ids'].values[i])
holdout_lbls = eval(df['holdout_lbls'].values[i])
holdout_preds = [probs[1] for probs in eval(df['holdout_probs'].values[i])]
# generate the dataframe
DF_TEST = pd.DataFrame({
# Model configuration
"i" : df.iloc[i][7],
"o" : df.iloc[i][8],
"io" : df.iloc[i][1],
"technique" : df.iloc[i][2],
"Session" : df.iloc[i][25],
"Trial" : df.iloc[i][4],
"path" : df.iloc[i][24],
"n_samples" : df.iloc[i][5],
"n_samples_cc" : df.iloc[i][6],
"i_is_conf" : df.iloc[i][9],
"o_is_conf" : df.iloc[i][10],
"Model" : df.iloc[i][3],
"model_SVM-rbf__C" : df.iloc[i][18],
"model_SVM-rbf__gamma" : df.iloc[i][19],
"runtime" : df.iloc[i][20],
"model_SVM-lin__C" : df.iloc[i][21],
"model_GB__learning_rate" : df.iloc[i][22],
"model_LR__C" : df.iloc[i][23],
# Result
"train_score" : df.iloc[i][11],
"valid_score" : df.iloc[i][12],
"test_score" : df.iloc[i][13],
"roc_auc" : df.iloc[i][14],
"holdout_score" : df.iloc[i][26],
"holdout_roc_auc" : df.iloc[i][27],
# Test
"dataset" : "Test set",
"ID" : test_ids,
"true_label" : test_lbls,
"prediction" : test_probs,
})
DF_HOLDOUT = pd.DataFrame({
# Model configuration
"i" : df.iloc[i][7],
"o" : df.iloc[i][8],
"io" : df.iloc[i][1],
"technique" : df.iloc[i][2],
"Session" : df.iloc[i][25],
"Trial" : df.iloc[i][4],
"path" : df.iloc[i][24],
"n_samples" : df.iloc[i][5],
"n_samples_cc" : df.iloc[i][6],
"i_is_conf" : df.iloc[i][9],
"o_is_conf" : df.iloc[i][10],
"Model" : df.iloc[i][3],
"model_SVM-rbf__C" : df.iloc[i][18],
"model_SVM-rbf__gamma" : df.iloc[i][19],
"runtime" : df.iloc[i][20],
"model_SVM-lin__C" : df.iloc[i][21],
"model_GB__learning_rate" : df.iloc[i][22],
"model_LR__C" : df.iloc[i][23],
# Result
"train_score" : df.iloc[i][11],
"valid_score" : df.iloc[i][12],
"test_score" : df.iloc[i][13],
"roc_auc" : df.iloc[i][14],
"holdout_score" : df.iloc[i][26],
"holdout_roc_auc" : df.iloc[i][27],
# Holdout
"dataset" : "Holdout set",
"ID" : holdout_ids,
"true_label" : holdout_lbls,
"prediction" : holdout_preds
})
DF.append(DF_TEST)
DF.append(DF_HOLDOUT)
# generate the columns
DF2 = pd.concat(DF).reset_index(drop=True)
TP = (DF2.true_label == 1.0) & (DF2.prediction >= 0.5)
TN = (DF2.true_label == 0.0) & (DF2.prediction < 0.5)
FP = (DF2.true_label == 0.0) & (DF2.prediction >= 0.5)
FN = (DF2.true_label == 1.0) & (DF2.prediction < 0.5)
DF2['TP prob'] = DF2[TP]['prediction']
DF2['TN prob'] = DF2[TN]['prediction']
DF2['FP prob'] = DF2[FP]['prediction']
DF2['FN prob'] = DF2[FN]['prediction']
DF2['T prob'] = DF2[TP | TN]['prediction']
DF2['F prob'] = DF2[FP | FN]['prediction']
conditionlist = [
(DF2['TP prob'] >= 0.5) ,
(DF2['TN prob'] < 0.5) ,
(DF2['FP prob'] >= 0.5),
(DF2['FN prob'] < 0.5)]
choicelist = ['TP', 'TN', 'FP', 'FN']
DF2['Prob'] = np.select(conditionlist, choicelist,
default='Not Specified')
conditionlist2 = [
(DF2['Prob'] == 'TP') | (DF2['Prob'] == 'TN'),
(DF2['Prob'] == 'FP') | (DF2['Prob'] == 'FN')]
choicelist2 = ['TP & TN', 'FP & FN']
DF2['Predict TF'] = np.select(conditionlist2, choicelist2,
default='Not Specified')
conditionlist3 = [
(DF2['Prob'] == 'TP') | (DF2['Prob'] == 'FP'),
(DF2['Prob'] == 'TN') | (DF2['Prob'] == 'FN')]
choicelist3 = ['TP & FP', 'TN & FN']
DF2['Model PN'] = np.select(conditionlist3, choicelist3,
default='Not Specified')
conditionlist4 = [
(DF2['Prob'] == 'TP') | (DF2['Prob'] == 'FN'),
(DF2['Prob'] == 'TN') | (DF2['Prob'] == 'FP')]
choicelist4 = ['TP & FN', 'TN & FP']
DF2['Label PN'] = np.select(conditionlist4, choicelist4,
default='Not Specified')
# rename the values may be needed
DF2['Session'] = DF2['Session'].map({'bl':'BL',
'fu1':'FU1',
'fu2':'FU2',
'fu3':'FU3'})
if save == True:
save_path = f"{self.DATA_DIR}/posthoc/all_RUN.csv"
if not os.path.isdir(os.path.dirname(save_path)):
os.makedirs(os.path.dirname(save_path))
DF2.to_csv(save_path, index=None)
return DF2
def get_RUN(self, RUN_file):
""" Load the RUN file
Parameters
----------
RUN_file : string
The IMAGEN's RUN file (*.csv)
Returns
-------
DF : pandas.dataframe
The RUN dataframe
Notes
-----
This function select the RUN
Examples
--------
>>> from imagen_posthocloader import *
>>> DATA = IMAGEN_instrument()
>>> DF = DATA.get_RUN(
... RUN_file) # RUN
>>> DF_FU3 = DF.groupby('Session').get_group('FU3')
"""
# Load the instrument file
run_path = f"{self.DATA_DIR}/posthoc/{RUN_file}"
DF = pd.read_csv(run_path, low_memory=False)
return DF
# def __str__(self):
# pass
class SHAP_loader:
def __init__(self, DATA_DIR="/ritter/share/data/IMAGEN"):
""" Set up path
Parameters
----------
DATA_DIR : string, optional
Directory IMAGEN absolute path
"""
# Set the directory path: IMAGEN
self.DATA_DIR = DATA_DIR
def get_model(self, MODEL_DIR):
""" Load the model
Parameters
----------
MODEL_DIR : string
Directory saved Model path
Returns
-------
self.MODELS : dictionary
model configuration
Examples
--------
>>> from imagen_posthocloader import *
>>> MODEL = SHAP_loader()
>>> DICT = MODEL.get_model(
... 'MODEL_DIR') # MODELS
Notes
-----
All the models weighted files are contained in same folder.
"""
models_dir = sorted(glob(MODEL_DIR))[-1]
models = {}
model_names = list(set([f.split("_")[0] for f in os.listdir(models_dir) if f.split(".")[-1]=="model"]))
for model_name in model_names:
models.update({model_name: [load(f) for f in glob(models_dir+f"/{model_name}_cb_*.model")]})
self.MODELS = models
self.MODEL_NAME = model_names
return self.MODELS
def get_list(self, MODELS, X, md='All'):
""" Generate the SHAP input value list
Parameters
----------
MODELS : dictionary
model configuration
X : numpy.ndarray
Data, hdf5 file
md : string
Specify the model: SVM-RBF, SVM-LIN, LR, GB
Returns
-------
self.INPUT : list
SHAP input combination list
Examples
--------
>>> from imagen_posthocloader import *
>>> DATA = SHAP_loader()
>>> INPUT = DATA.get_list(
... 'MODELS', # MODELS
... 'X', # X
... md='All') # model
Notes
-----
Expected output below:
INPUT = [
[['SVM-RBF'], X, 0],
[['SVM-RBF'], X, 1],
[['SVM-RBF'], X, 2],
[['SVM-RBF'], X, 3],
...
[['GB'], X, 5],
[['GB'], X, 6]
]
"""
INPUT = []
for model_name in MODELS:
for i, model in enumerate(MODELS[model_name]):
LIST = [model_name.upper(), X, i]
INPUT.append(LIST)
if md =='All':
self.INPUT = INPUT
else:
self.INPUT = INPUT = [i for i in INPUT if i[0]==md]
return self.INPUT
def get_SHAP(self, INPUT, NAME, save = True):
""" Generate the SHAP value
Parameters
----------
INPUT: list
SHAP INPUT: Model name, X, and N - trial number
save : boolean
Defualt save the shap_value
Examples
--------
>>> from imagen_posthocloader import *
>>> DATA = SHAP_loader()
>>> _ = DATA.to_SHAP(
... 'INPUT', # INPUT
... save=True) # save
Notes
-----
explainers generate the SHAP value
"""
MODEL = INPUT[0]
X = INPUT[1]
N = INPUT[2]
# 100 instances for use as the background distribution
X100 = shap.utils.sample(X, len(X))
for model_name in self.MODELS:
if (model_name.upper() not in MODEL):
# print(f"skipping model {model_name}")
continue
# print(f"generating SHAP values for model = {model_name} ..")
for i, model in enumerate(self.MODELS[model_name]):
if i!=N:
# print(f"Skipping model '{model_name}': {i}' as it is taking too long")
continue
if i==N:
# print(f"generating SHAP values for model = {model_name}:{i} ..")
explainer = shap.Explainer(model.predict, X100, output_names=["Healthy","AUD-risk"])
shap_values = explainer(X)
if save == True:
if not os.path.isdir("test"):
os.makedirs("test")
with open(f"test/{model_name+str(i)}_{NAME}.sav", "wb") as f:
pickle.dump(shap_values, f)
def load_abs_SHAP(self, SHAP):
""" Generate the mean and std of|SHAP value|
Parameters
----------
SHAP : .sav file
Load the SHAP value
Examples
--------
>>> from imagen_posthocloader import *
>>> DATA = SHAP_loader()
>>> mean_SHAP, std_SHAP = DATA.load_SHAP(
... 'SHAP') # SHAP
"""
with open(self.DATA_DIR+"/posthoc/explainers/"+SHAP, 'rb') as fp:
load_shap_values = pickle.load(fp)
SHAP_list = []
for data in load_shap_values:
value = [data[i].values for i in range(data.shape[0])]
SHAP_list.append(value)
DF_SHAP = pd.DataFrame(SHAP_list)
mean_SHAP = list(DF_SHAP.apply(abs).mean())
std_SHAP = list(DF_SHAP.apply(abs).std())
return mean_SHAP, std_SHAP
def load_SHAP(self, HDF5, SHAP, save=False):
""" Generate the pandas dataframe of the SHAP value
Parameters
----------
HDF5 : .hdf5 file
Load the ID, X_Col_names value
SHAP : .sav file
Load the SHAP value
Returns
-------
DF : pandas.dataframe
SHAP value dataframe
Note
----
Sex mask is not implemented
Examples
--------
>>> from imagen_posthocloader import *
>>> DATA = SHAP_loader()
>>> mean_SHAP, std_SHAP | |
+ "/C6_RL_8col_agg_rough_270K.dat", False)
data_path = os.path.join(os.path.dirname(__file__), 'bulk_c6_tables')
self.bulk_table["E3_ice"] = load_bulk_scat_file(
data_path + "/bulk_RL_C6PSD_c6_8col_ice_agg_rough_270K.dat")
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_RL_C6PSD_mie_liq.dat")
self.bulk_table["mie_ice_E3_PSD"] = load_bulk_scat_file(data_path + "/bulk_RL_C6PSD_mie_ice.dat")
# CESM/E3SM bulk
data_path = os.path.join(os.path.dirname(__file__), 'mDAD_tables')
self.scat_table["CESM_ice"] = load_scat_file(data_path + "/mDAD_RL_ice.dat", False, param_type="mDAD")
data_path = os.path.join(os.path.dirname(__file__), 'bulk_mDAD_tables')
self.bulk_table["CESM_ice"] = load_bulk_scat_file(
data_path + "/bulk_RL_mDAD_mDAD_ice_263K.dat", param_type="mDAD")
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_RL_mDAD_mie_liq.nc")
self.bulk_table["mie_ice_CESM_PSD"] = load_bulk_scat_file(data_path + "/bulk_RL_mDAD_mie_ice.dat",
param_type="mDAD")
class HSRL(Instrument):
def __init__(self, *args):
"""
This stores the information for 532 nm lidars ,e.g., the High
Spectral Resolution Lidar (HSRL), micropulse lidar (MPL).
"""
super().__init__(wavelength=0.532 * ureg.micrometer)
self.instrument_class = "lidar"
self.instrument_str = "HSRL"
self.beta_p_phase_thresh = [{'class': 'ice', 'class_ind': 2,
'LDR': [0., 0.1, 0.100001, 0.2, 1.],
'beta_p': [2e-5, 2e-5, 2e-6, 5e-7, 5e-7]},
{'class': 'undef2', 'class_ind': 4,
'LDR': [0., 0.1, 0.100001, 0.2, 0.200001, 1.],
'beta_p': [2e-5, 2e-5, 2e-6, 9e-6, 1., 1.]},
{'class': 'undef1', 'class_ind': 3,
'LDR': [0., 0.1, 0.100001, 0.2, 0.200001, 1.],
'beta_p': [2e-5, 2e-5, 1.41421e-4, 1e-3, 1., 1.]},
{'class': 'liquid', 'class_ind': 1,
'LDR': [0., 0.2, 0.200001, 1.],
'beta_p': [2e-5, 1e-3, 1., 1.]}]
self.ext_OD = 4
self.OD_from_sfc = True
self.eta = 1
self.K_w = np.nan
self.eps_liq = (1.337273 + 1.7570744e-9j) ** 2
self.pt = np.nan
self.theta = np.nan
self.gain = np.nan
self.Z_min_1km = np.nan
self.lr = np.nan
self.pr_noise_ge = np.nan
self.pr_noise_md = np.nan
self.tau_ge = np.nan
self.tau_md = np.nan
# Load mie tables
data_path = os.path.join(os.path.dirname(__file__), 'mie_tables')
self.mie_table["cl"] = load_mie_file(data_path + "/MieHSRL_liq.dat")
self.mie_table["pl"] = load_mie_file(data_path + "/MieHSRL_liq.dat")
self.mie_table["ci"] = load_mie_file(data_path + "/MieHSRL_ci.dat")
if 'DHARMA' in args:
self.mie_table["pi"] = load_mie_file(
data_path + "/MieHSRL_pi1.dat") # pi1 for 100 kg/m^2 (DHARMA)
else:
self.mie_table["pi"] = load_mie_file(data_path + "/MieHSRL_pi.dat")
# ModelE3 bulk
data_path = os.path.join(os.path.dirname(__file__), 'c6_tables')
self.scat_table["E3_ice"] = load_scat_file(data_path + "/C6_HSRL_8col_agg_rough_270K.dat", False)
data_path = os.path.join(os.path.dirname(__file__), 'bulk_c6_tables')
self.bulk_table["E3_ice"] = load_bulk_scat_file(
data_path + "/bulk_HSRL_C6PSD_c6_8col_ice_agg_rough_270K.dat")
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_HSRL_C6PSD_mie_liq.dat")
self.bulk_table["mie_ice_E3_PSD"] = load_bulk_scat_file(data_path + "/bulk_HSRL_C6PSD_mie_ice.dat")
# CESM/E3SM bulk
data_path = os.path.join(os.path.dirname(__file__), 'mDAD_tables')
self.scat_table["CESM_ice"] = load_scat_file(data_path + "/mDAD_HSRL_ice.dat", False, param_type="mDAD")
data_path = os.path.join(os.path.dirname(__file__), 'bulk_mDAD_tables')
self.bulk_table["CESM_ice"] = load_bulk_scat_file(
data_path + "/bulk_HSRL_mDAD_mDAD_ice_263K.dat", param_type="mDAD")
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_HSRL_mDAD_mie_liq.nc")
self.bulk_table["mie_ice_CESM_PSD"] = load_bulk_scat_file(data_path + "/bulk_HSRL_mDAD_mie_ice.dat",
param_type="mDAD")
class CEIL(Instrument):
def __init__(self, supercooled=True, *args):
"""
This stores the information for 910 nm lidars ,e.g., the CL31 ceilometer.
"""
super().__init__(wavelength=0.910 * ureg.micrometer)
self.instrument_class = "lidar"
self.instrument_str = "CEIL"
self.ext_OD = 4
self.OD_from_sfc = True
self.eta = 1
self.K_w = np.nan
if supercooled:
self.eps_liq = (1.3251203 + 5.1409006e-7j) ** 2
else:
self.eps_liq = (1.323434 + 5.6988883e-7j) ** 2
self.pt = np.nan
self.theta = np.nan
self.gain = np.nan
self.Z_min_1km = np.nan
self.lr = np.nan
self.pr_noise_ge = np.nan
self.pr_noise_md = np.nan
self.tau_ge = np.nan
self.tau_md = np.nan
# Load mie tables
data_path = os.path.join(os.path.dirname(__file__), 'mie_tables')
if supercooled:
self.mie_table["cl"] = load_mie_file(data_path + "/MieCEIL_liq_c.dat") # Rowe et al. (2020) -10 C
self.mie_table["pl"] = load_mie_file(data_path + "/MieCEIL_liq_c.dat")
else:
self.mie_table["cl"] = load_mie_file(data_path + "/MieCEIL_liq.dat") # Segelstein (1981)
self.mie_table["pl"] = load_mie_file(data_path + "/MieCEIL_liq.dat")
self.mie_table["ci"] = load_mie_file(data_path + "/MieCEIL_ci.dat")
if 'DHARMA' in args:
self.mie_table["pi"] = load_mie_file(
data_path + "/MieCEIL_pi1.dat") # pi1 for 100 kg/m^2 (DHARMA)
else:
self.mie_table["pi"] = load_mie_file(data_path + "/MieCEIL_pi.dat")
# ModelE3 bulk
data_path = os.path.join(os.path.dirname(__file__), 'c6_tables')
self.scat_table["E3_ice"] = load_scat_file(data_path + "/C6_CEIL_8col_agg_rough_270K.dat", False)
data_path = os.path.join(os.path.dirname(__file__), 'bulk_c6_tables')
self.bulk_table["E3_ice"] = load_bulk_scat_file(
data_path + "/bulk_CEIL_C6PSD_c6_8col_ice_agg_rough_270K.dat")
if supercooled:
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_CEIL_C6PSD_mie_liq_c.dat")
else:
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_CEIL_C6PSD_mie_liq.dat")
self.bulk_table["mie_ice_E3_PSD"] = load_bulk_scat_file(data_path + "/bulk_CEIL_C6PSD_mie_ice.dat")
# CESM/E3SM bulk
data_path = os.path.join(os.path.dirname(__file__), 'mDAD_tables')
self.scat_table["CESM_ice"] = load_scat_file(data_path + "/mDAD_CEIL_ice.dat", False, param_type="mDAD")
data_path = os.path.join(os.path.dirname(__file__), 'bulk_mDAD_tables')
self.bulk_table["CESM_ice"] = load_bulk_scat_file(
data_path + "/bulk_CEIL_mDAD_mDAD_ice_263K.dat", param_type="mDAD")
if supercooled:
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_CEIL_mDAD_mie_liq_c.nc")
else:
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_CEIL_mDAD_mie_liq.nc")
self.bulk_table["mie_ice_CESM_PSD"] = load_bulk_scat_file(data_path + "/bulk_CEIL_mDAD_mie_ice.dat",
param_type="mDAD")
class Ten64nm(Instrument):
def __init__(self, supercooled=True, *args):
"""
This stores the information for the 1064 nm lidars, e.g., the 2-ch HSRL.
"""
super().__init__(wavelength=1.064 * ureg.micrometer)
self.instrument_class = "lidar"
self.instrument_str = "1064nm"
self.ext_OD = 4
self.OD_from_sfc = True
self.eta = 1
self.K_w = np.nan
if supercooled:
self.eps_liq = (1.3235222 + 1.2181699e-6j) ** 2
else:
self.eps_liq = (1.320416 + 1.2588968e-6j) ** 2
self.pt = np.nan
self.theta = np.nan
self.gain = np.nan
self.Z_min_1km = np.nan
self.lr = np.nan
self.pr_noise_ge = np.nan
self.pr_noise_md = np.nan
self.tau_ge = np.nan
self.tau_md = np.nan
# Load mie tables
data_path = os.path.join(os.path.dirname(__file__), 'mie_tables')
if supercooled:
self.mie_table["cl"] = load_mie_file(data_path + "/Mie1064nm_liq_c.dat") # Rowe et al. (2020) -10 C
self.mie_table["pl"] = load_mie_file(data_path + "/Mie1064nm_liq_c.dat")
else:
self.mie_table["cl"] = load_mie_file(data_path + "/Mie1064nm_liq.dat") # Segelstein (1981) 25 C
self.mie_table["pl"] = load_mie_file(data_path + "/Mie1064nm_liq.dat")
self.mie_table["ci"] = load_mie_file(data_path + "/Mie1064nm_ci.dat")
self.mie_table["pi"] = load_mie_file(data_path + "/Mie1064nm_pi.dat")
if 'DHARMA' in args:
self.mie_table["pi"] = load_mie_file(
data_path + "/Mie1064nm_pi1.dat") # pi1 for 100 kg/m^2 (DHARMA)
else:
self.mie_table["pi"] = load_mie_file(data_path + "/Mie1064nm_pi.dat")
# ModelE3 bulk
data_path = os.path.join(os.path.dirname(__file__), 'c6_tables')
self.scat_table["E3_ice"] = load_scat_file(data_path + "/C6_1064nm_8col_agg_rough_270K.dat", False)
data_path = os.path.join(os.path.dirname(__file__), 'bulk_c6_tables')
self.bulk_table["E3_ice"] = load_bulk_scat_file(
data_path + "/bulk_1064nm_C6PSD_c6_8col_ice_agg_rough_270K.dat")
if supercooled:
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_1064nm_C6PSD_mie_liq_c.dat")
else:
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_1064nm_C6PSD_mie_liq.dat")
self.bulk_table["mie_ice_E3_PSD"] = load_bulk_scat_file(data_path + "/bulk_1064nm_C6PSD_mie_ice.dat")
# CESM/E3SM bulk
data_path = os.path.join(os.path.dirname(__file__), 'mDAD_tables')
self.scat_table["CESM_ice"] = load_scat_file(data_path + "/mDAD_1064nm_ice.dat", False, param_type="mDAD")
data_path = os.path.join(os.path.dirname(__file__), 'bulk_mDAD_tables')
self.bulk_table["CESM_ice"] = load_bulk_scat_file(
data_path + "/bulk_1064nm_mDAD_mDAD_ice_263K.dat", param_type="mDAD")
if supercooled:
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_1064nm_mDAD_mie_liq_c.nc")
else:
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_1064nm_mDAD_mie_liq.nc")
self.bulk_table["mie_ice_CESM_PSD"] = load_bulk_scat_file(data_path + "/bulk_1064nm_mDAD_mie_ice.dat",
param_type="mDAD")
class NEXRAD(Instrument):
def __init__(self, supercooled=True, *args):
"""
This stores the information for the NOAA NEXRAD radar
Based on https://www.roc.noaa.gov/WSR88D/Engineering/NEXRADTechInfo.aspx.
"""
super().__init__(frequency=3.0 * ureg.GHz)
self.instrument_class = "radar"
self.instrument_str = "NEXRAD"
self.ext_OD = np.nan
self.K_w = 0.92
if supercooled:
self.eps_liq = (8.851160 + 1.940795j)**2
else:
self.eps_liq = (8.743107 + 0.64089981j)**2
self.theta = 0.925
self.pt = 700000.
self.gain = 10**4.58
self.Z_min_1km = -50.96 # long pulse at 1 km range (-23.0 dBZ at 25 km)
self.Z_min_1km_short = -41.48 # short pulse at 1 km range (-7.5 dBZ at 50 km)
self.lr = np.nan
self.pr_noise_ge = 0.
self.tau_ge = 1.57
self.tau_md = 4.71
data_path = os.path.join(os.path.dirname(__file__), 'mie_tables')
if supercooled:
self.mie_table["cl"] = load_mie_file(data_path + "/MieNEXRAD_liq_c.dat") # Turner et al. (2016) -10 C
self.mie_table["pl"] = load_mie_file(data_path + "/MieNEXRAD_liq_c.dat")
else:
self.mie_table["cl"] = load_mie_file(data_path + "/MieNEXRAD_liq.dat")
self.mie_table["pl"] = load_mie_file(data_path + "/MieNEXRAD_liq.dat")
self.mie_table["ci"] = load_mie_file(data_path + "/MieNEXRAD_ci.dat")
if 'DHARMA' in args:
self.mie_table["pi"] = load_mie_file(data_path + "/MieNEXRAD_pi1.dat") # pi1 for 100 kg/m^2 (DHARMA)
else:
self.mie_table["pi"] = load_mie_file(data_path + "/MieNEXRAD_pi.dat")
# ModelE3 bulk
data_path = os.path.join(os.path.dirname(__file__), 'c6_tables')
self.scat_table["E3_ice"] = load_scat_file(
data_path + "/C6_NEXRAD_8col_agg_rough_270K.dat", True)
data_path = os.path.join(os.path.dirname(__file__), 'bulk_c6_tables')
self.bulk_table["E3_ice"] = load_bulk_scat_file(
data_path + "/bulk_NEXRAD_C6PSD_c6_8col_ice_agg_rough_270K.dat")
if supercooled:
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_NEXRAD_C6PSD_mie_liq_c.dat")
else:
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_NEXRAD_C6PSD_mie_liq.dat")
self.bulk_table["mie_ice_E3_PSD"] = load_bulk_scat_file(data_path + "/bulk_NEXRAD_C6PSD_mie_ice.dat")
# CESM/E3SM bulk
data_path = os.path.join(os.path.dirname(__file__), 'mDAD_tables')
self.scat_table["CESM_ice"] = load_scat_file(data_path + "/mDAD_NEXRAD_ice.dat", True, param_type="mDAD")
data_path = os.path.join(os.path.dirname(__file__), 'bulk_mDAD_tables')
self.bulk_table["CESM_ice"] = load_bulk_scat_file(
data_path + "/bulk_NEXRAD_mDAD_mDAD_ice_263K.dat", param_type="mDAD")
if supercooled:
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_NEXRAD_mDAD_mie_liq_c.nc")
else:
self.bulk_table["CESM_liq"] = xr.open_dataset(data_path + "/bulk_NEXRAD_mDAD_mie_liq.nc")
self.bulk_table["mie_ice_CESM_PSD"] = load_bulk_scat_file(data_path + "/bulk_NEXRAD_mDAD_mie_ice.dat",
param_type="mDAD")
class CALIOP(Instrument):
def __init__(self, *args):
"""
This stores the information for 532 nm spaceborne lidars ,e.g.,
the CALIOP on-board the CALIPSO satellite.
"""
super().__init__(wavelength=0.532 * ureg.micrometer)
self.instrument_class = "lidar"
self.instrument_str = "HSRL"
self.beta_p_phase_thresh = [{'class': 'ice', 'class_ind': 2,
'LDR': [0., 0.1, 0.100001, 0.2, 1.],
'beta_p': [2e-5, 2e-5, 2e-6, 5e-7, 5e-7]},
{'class': 'undef2', 'class_ind': 4,
'LDR': [0., 0.1, 0.100001, 0.2, 0.200001, 1.],
'beta_p': [2e-5, 2e-5, 2e-6, 9e-6, 1., 1.]},
{'class': 'undef1', 'class_ind': 3,
'LDR': [0., 0.1, 0.100001, 0.2, 0.200001, 1.],
'beta_p': [2e-5, 2e-5, 1.41421e-4, 1e-3, 1., 1.]},
{'class': 'liquid', 'class_ind': 1,
'LDR': [0., 0.2, 0.200001, 1.],
'beta_p': [2e-5, 1e-3, 1., 1.]}]
self.ext_OD = 4
self.OD_from_sfc = False
self.eta = 0.7
self.K_w = np.nan
self.eps_liq = (1.337273 + 1.7570744e-9j) ** 2
self.pt = np.nan
self.theta = np.nan
self.gain = np.nan
self.Z_min_1km = np.nan
self.lr = np.nan
self.pr_noise_ge = np.nan
self.pr_noise_md = np.nan
self.tau_ge = np.nan
self.tau_md = np.nan
# Load mie tables
data_path = os.path.join(os.path.dirname(__file__), 'mie_tables')
self.mie_table["cl"] = load_mie_file(data_path + "/MieHSRL_liq.dat")
self.mie_table["pl"] = load_mie_file(data_path + "/MieHSRL_liq.dat")
self.mie_table["ci"] = load_mie_file(data_path + "/MieHSRL_ci.dat")
if 'DHARMA' in args:
self.mie_table["pi"] = load_mie_file(
data_path + "/MieHSRL_pi1.dat") # pi1 for 100 kg/m^2 (DHARMA)
else:
self.mie_table["pi"] = load_mie_file(data_path + "/MieHSRL_pi.dat")
# ModelE3 bulk
data_path = os.path.join(os.path.dirname(__file__), 'c6_tables')
self.scat_table["E3_ice"] = load_scat_file(data_path + "/C6_HSRL_8col_agg_rough_270K.dat", False)
data_path = os.path.join(os.path.dirname(__file__), 'bulk_c6_tables')
self.bulk_table["E3_ice"] = load_bulk_scat_file(
data_path + "/bulk_HSRL_C6PSD_c6_8col_ice_agg_rough_270K.dat")
self.bulk_table["E3_liq"] = load_bulk_scat_file(data_path + "/bulk_HSRL_C6PSD_mie_liq.dat")
self.bulk_table["mie_ice_E3_PSD"] = load_bulk_scat_file(data_path + "/bulk_HSRL_C6PSD_mie_ice.dat")
# CESM/E3SM bulk
data_path = os.path.join(os.path.dirname(__file__), 'mDAD_tables')
self.scat_table["CESM_ice"] = load_scat_file(data_path + | |
not t[1].isalpha():
symb = t[0]
else:
symb = t[0:2]
for i in range(1, 100):
name = f'{symb}{i}'
if name in type_translator.values():
continue
else:
type_translator[t] = name
break
return type_translator
def _cell_section(self, cell):
cell_section = (
'\ncell\n'
f"{round(cell.a, 6)} "
f"{round(cell.b, 6)} "
f"{round(cell.c, 6)} "
f"{round(cell.alpha, 6)} "
f"{round(cell.beta, 6)} "
f"{round(cell.gamma, 6)} "
# No fixes.
"0 0 0 0 0 0\n"
)
return cell_section
def _position_section(self, mol, type_translator):
position_section = '\ncartesian\n'
for atom in mol.get_atoms():
atom_type = type_translator[self.atom_labels[
atom.get_id()
][0]]
position = mol.get_centroid(atom_ids=atom.get_id())
posi_string = (
f'{atom_type} core {round(position[0], 5)} '
f'{round(position[1], 5)} {round(position[2], 5)}\n'
)
position_section += posi_string
return position_section
def _bond_section(self, mol, metal_atoms):
bond_section = '\n'
for bond in mol.get_bonds():
atom_types = [
self.atom_labels[i.get_id()][0]
for i in [bond.get_atom1(), bond.get_atom2()]
]
# Set bond orders.
if has_h_atom(bond):
# H has bond order of 1.
bond_type = ''
elif has_metal_atom(bond, metal_atoms):
bond_type = self._metal_ligand_bond_order
elif '_R' in atom_types[0] and '_R' in atom_types[1]:
bond_type = 'resonant'
elif bond.get_order() == 1:
bond_type = ''
elif bond.get_order() == 2:
bond_type = 'double'
elif bond.get_order() == 3:
bond_type = 'triple'
string = (
f'connect {bond.get_atom1().get_id()+1} '
f'{bond.get_atom2().get_id()+1} {bond_type}'
)
bond_section += string+'\n'
return bond_section
def _species_section(self, type_translator):
species_section = '\nspecies\n'
for spec in type_translator:
name = type_translator[spec]
species_section += f'{name} {spec}\n'
return species_section
def _write_gulp_file(
self,
mol,
metal_atoms,
in_file,
output_xyz,
cell=None,
):
type_translator = self._type_translator()
top_line = 'opti '
if self._conjugate_gradient:
top_line += 'conj unit '
if self._periodic:
# Constant pressure.
top_line += 'conp '
cell_section = self._cell_section(cell)
# Output CIF.
output_cif = output_xyz.replace('xyz', 'cif')
periodic_output = f'output cif {output_cif}\n'
else:
# Constant volume.
top_line += 'conv '
cell_section = ''
periodic_output = ''
top_line += 'noautobond fix molmec cartesian\n'
position_section = self._position_section(mol, type_translator)
bond_section = self._bond_section(mol, metal_atoms)
species_section = self._species_section(type_translator)
library = '\nlibrary uff4mof.lib\n'
output_section = (
'\n'
f'maxcyc {self._maxcyc}\n'
'terse inout potentials\n'
'terse in cell\n'
'terse in structure\n'
'terse inout derivatives\n'
f'output xyz {output_xyz}\n'
f'{periodic_output}'
# 'output movie xyz steps_.xyz\n'
)
with open(in_file, 'w') as f:
f.write(top_line)
f.write(cell_section)
f.write(position_section)
f.write(bond_section)
f.write(species_section)
f.write(library)
f.write(output_section)
def _move_cif(self, filename, output_cif):
"""
Move CIF from optimisation folder to filename.
Parameters
----------
filename : :class:`str`
The name of CIF file to be written.
Returns
-------
None : :class:`NoneType`
"""
os.rename(f'{self._output_dir}/{output_cif}', filename)
def assign_FF(self, mol):
"""
Assign forcefield types to molecule.
Parameters
----------
mol : :class:`stk.Molecule`
The molecule to be optimized.
Returns
-------
None : :class:`NoneType`
"""
metal_atoms = get_metal_atoms(mol)
metal_ids = [i.get_id() for i in metal_atoms]
if len(metal_ids) > 1 and self._metal_FF is None:
raise ExpectedMetal(
'No metal FF provivded, but metal atoms were found ('
f'{metal_atoms})'
)
metal_bonds, _ = get_metal_bonds(mol, metal_atoms)
edit_mol = to_rdkit_mol_without_metals(
mol=mol,
metal_atoms=metal_atoms,
metal_bonds=metal_bonds
)
# Get forcefield parameters.
rdkit.SanitizeMol(edit_mol)
self.atom_labels = {}
for i in range(edit_mol.GetNumAtoms()):
if i in metal_ids:
self.atom_labels[i] = [None, 'metal', None]
else:
atom = edit_mol.GetAtomWithIdx(i)
atom_label = self._get_atom_label(atom)
self.atom_labels[i] = [atom_label, None, None]
# Write UFF4MOF specific forcefield parameters.
# Metals.
for atomid in self.atom_labels:
if self.atom_labels[atomid][1] == 'metal':
atom, = mol.get_atoms(atomid)
atom_no = atom.get_atomic_number()
self.atom_labels[atomid][0] = self._metal_FF[atom_no]
def _run_gulp(self, in_file, out_file):
cmd = f'{self._gulp_path} < {in_file}'
with open(out_file, 'w') as f:
# Note that sp.call will hold the program until completion
# of the calculation.
sp.call(
cmd,
stdin=sp.PIPE,
stdout=f,
stderr=sp.PIPE,
# Shell is required to run complex arguments.
shell=True
)
def _move_generated_files(self, files):
if not os.path.exists(self._output_dir):
os.mkdir(self._output_dir)
for file in files:
if os.path.exists(file):
os.rename(file, f'{self._output_dir}/{file}')
def extract_final_energy(self, file):
nums = re.compile(r"[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?")
with open(file, 'r') as f:
for line in f.readlines():
if 'Final energy =' in line:
string = nums.search(line.rstrip()).group(0)
return float(string)
def optimize(self, mol, cell=None, cif_filename=None):
"""
Optimize `mol` and `cell`.
Parameters
----------
mol : :class:`stk.Molecule`
The molecule to be optimized.
cell : :class:`.Cell`, optional
The cell to be optimized if optimization is periodic.
Returns
-------
mol : :class:`.Molecule`
The optimized molecule.
"""
if cell is None and self._periodic:
raise ExpectedCell(
'Optimisation expected a cell because periodic is True'
)
if self._output_dir is None:
output_dir = str(uuid.uuid4().int)
else:
output_dir = self._output_dir
output_dir = os.path.abspath(output_dir)
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.mkdir(output_dir)
in_file = 'gulp_opt.gin'
out_file = 'gulp_opt.ginout'
output_xyz = 'gulp_opt.xyz'
output_cif = output_xyz.replace('xyz', 'cif')
metal_atoms = get_metal_atoms(mol)
# Write GULP file.
self._write_gulp_file(
mol=mol,
metal_atoms=metal_atoms,
in_file=in_file,
output_xyz=output_xyz,
cell=cell,
)
# Run.
self._run_gulp(in_file, out_file)
# Update from output.
mol = mol.with_structure_from_file(output_xyz)
# Move files.
self._move_generated_files(
files=[in_file, out_file, output_xyz, output_cif]
)
# Save CIF.
if self._periodic and cif_filename is not None:
self._move_cif(
filename=cif_filename,
output_cif=output_cif
)
return mol
class GulpUFFMDOptimizer(GulpUFFOptimizer):
"""
Applies forcefield MD that can handle metal centres.
Notes
-----
By default, :meth:`optimize` will run a MD run using the UFF4MOF.
This forcefield requires some explicit metal atom definitions,
which are determined by the user.
"""
def __init__(
self,
gulp_path,
metal_FF=None,
metal_ligand_bond_order=None,
output_dir=None,
integrator='stochastic',
ensemble='nvt',
temperature=300,
equilbration=1.0,
production=10.0,
timestep=1.0,
N_conformers=10,
opt_conformers=True,
save_conformers=False,
):
"""
Initialize a :class:`GulpUFFOptimizer` instance.
Parameters
----------
gulp_path : :class:`str`
Path to GULP executable.
metal_FF : :class:`dict`, optional
Dictionary with metal atom forcefield assignments.
Key: :class:`int` : atomic number.
Value: :class:`str` : UFF4MOF forcefield type.
metal_ligand_bond_order : :class:`str`, optional
Bond order to use for metal-ligand bonds. Defaults to
`half`, but using `resonant` can increase the force
constant for stronger metal-ligand interactions.
output_dir : :class:`str`, optional
The name of the directory into which files generated during
the calculation are written, if ``None`` then
:func:`uuid.uuid4` is used.
integrator : :class:`str`, optional
Integrator for GULP to use.
Defaults to 'stochastic'.
ensemble : :class:`str`, optional
Ensemble for GULP to use.
Defaults to 'nvt'.
temperature : :class:`float`, optional
Temperature to run simulation at in Kelvin.
Defaults to 300.
equilbration : :class:`float`, optional
Time spent equilibrating system in ps.
Defaults to 1.0.
production : :class:`float`, optional
Time spent running production simulation of system in ps.
Defaults to 10.0.
timestep : :class:`float`, optional
Timestep of simulation in fs.
Defaults to 1.0.
N_conformers : :class:`int`, optional
Number of conformers to sample.
Defaults to 10.
opt_conformers : :class:`bool`, optional
Whether or not to optimise each conformer using UFF4MOF.
Defaults to ``True``.
save_conformers : :class:`bool`, optional
Whether or not to save to file each conformer.
Defaults to ``False``.
"""
self._gulp_path = gulp_path
self._metal_FF = metal_FF
self._metal_ligand_bond_order = (
'half' if metal_ligand_bond_order is None
else metal_ligand_bond_order
)
self._output_dir = output_dir
self._integrator = integrator
self._ensemble = ensemble
self._temperature = temperature
self._equilbration = float(equilbration)
self._production = float(production)
self._timestep = timestep
self._N_conformers = N_conformers
samples = float(self._production) / float(self._N_conformers)
self._sample = samples
self._write = samples
self._opt_conformers = opt_conformers
self._save_conformers = save_conformers
def _write_gulp_file(
self,
mol,
metal_atoms,
in_file,
output_traj
):
type_translator = self._type_translator()
top_line = 'md conv noautobond fix molmec cartesian\n'
position_section = self._position_section(mol, type_translator)
bond_section = self._bond_section(mol, metal_atoms)
species_section = self._species_section(type_translator)
library = '\nlibrary uff4mof.lib\n'
md_section = (
'\n'
"mdmaxtemp 100000000\n"
f"integrator {self._integrator}\n"
f"ensemble {self._ensemble}\n"
f"temperature {self._temperature}\n"
f"equilbration {self._equilbration} ps\n"
f"production {self._production} ps\n"
f"timestep {self._timestep} fs\n"
f"sample {self._sample} ps\n"
f"write {self._write} ps\n"
'\n'
)
output_section = (
'\n'
'terse inout potentials\n'
'terse inout cell\n'
'terse in structure\n'
'terse inout derivatives\n'
f'output trajectory ascii {output_traj}\n'
)
with open(in_file, 'w') as f:
f.write(top_line)
f.write(position_section)
f.write(bond_section)
f.write(species_section)
f.write(library)
f.write(md_section)
f.write(output_section)
def _convert_traj_to_xyz(self, output_xyz, output_traj, xyz_traj):
# Get atom types from an existing xyz file.
atom_types = []
with open(output_xyz, 'r') as f:
for line in f.readlines()[2:]:
atom_types.append(line.rstrip().split(' ')[0])
# Read in lines from trajectory file.
with open(output_traj, 'r') as f:
lines = f.readlines()
# Split file using strings.
id = 0
s_times = {}
s_coords = {}
s_vels = {}
s_derivs = {}
s_sites = {}
coords = []
vels = []
derivs = []
sites = []
switch = None
for line in lines:
li = line.rstrip()
if '# Time/KE/E/T' in li:
switch = 'times'
s_coords[id] = coords
coords = []
s_vels[id] = vels
vels = []
s_derivs[id] = derivs
derivs = []
s_sites[id] = sites
sites = []
id += 1
elif '# Coordinates' in li:
switch = 'coords'
elif '# Velocities' in li:
switch = 'vels'
elif '# Derivatives' in li:
switch | |
that processName's"\
# # "daughter nodes.")
# #Use a method to get the list of potential samples from the packedEventID -> Probably method that calls a common dictionarymethod.
# #Return std::vector<std::string> to iterate through, will include such things as ttbb_DL-GF, ttbbJets, ttll_DL, ttcc_SL, etc... fully complex-stitchable
# #for processName in packedEventProcessNames:
# #filterNodes[processName] = collections.OrderedDict()
# #filterNodes[processName]["BaseNode"] = ("packedEventID == getPackedEventID('processName');", "{}".format(processName), processName, None, None, None, None)
# #nodes[processName] = collections.OrderedDict()
# #nodes[processName]["BaseNode"] = nodes["BaseNode"].Filter(packedEventID code goes here)
# #countNodes[processName] = collections.OrderedDict()
# #countNodes[processName]["BaseNode"] = nodes[processName]["BaseNode"].Count()
# #WE ARE DONE, prepared for systematic variation-dependent code looping through channels,
# #nodes[processName][chan]["BaseNode"] = input_df.Filter(packedEventID).Filter(chan) #pseudocode for creating these nodes
# #Might need to do continue statements on "BaseNode" when it's the key in future loops
# #Preparateion complete? Now we must create filters later on when we loop through the systematic variations
# #Overall key set will be nodes[processName][decayChannel][scaleVariation-dependent-HTandZWindow==L0Nodes][nBTags==L1Nodes][nJet==L2Nodes]
# #Histograms can be attached to L0 - L2 nodes, with the processName, decayChannel, HT/ZWindow, nBTags, nJets derived from the keys in the 5 nested for loops
# else:
# processName = era + "___" + sampleName #Easy case without on-the-fly ttbb, ttcc, etc. categorization
# nodes["BaseNode"] = input_df #Always store the base node we'll build upon in the next level
# #The below references branchpostfix since we only need nodes for these types of scale variations...
# if processName not in nodes:
# #L-2 filter, should be the packedEventID filter in that case
# # filterNodes[processName] = collections.OrderedDict()
# filterNodes[processName] = dict()
# filterNodes[processName]["BaseNode"] = ("return true;", "{}".format(processName), processName, None, None, None, None)
# # nodes[processName] = collections.OrderedDict()
# nodes[processName] = dict()
# nodes[processName]["BaseNode"] = nodes["BaseNode"].Filter(filterNodes[processName]["BaseNode"][0], filterNodes[processName]["BaseNode"][1])
# # countNodes[processName] = collections.OrderedDict()
# countNodes[processName] = dict()
# countNodes[processName]["BaseNode"] = nodes[processName]["BaseNode"].Count()
# diagnosticNodes[processName] = dict()
# #defineNodes[processName] = collections.OrderedDict()
# defineNodes[processName] = dict()
# if processName not in histoNodes:
# #histoNodes[processName] = collections.OrderedDict()
# histoNodes[processName] = dict()
#Make sure the nominal is done first so that categorization is successful
for sysVar, sysDict in sorted(sysVariations.items(), key=lambda x: "$NOMINAL" in x[0], reverse=True):
#skip systematic variations on data, only do the nominal
if isData and sysVar != "$NOMINAL":
continue
#skip making MET corrections unless it is: Nominal or a scale variation (i.e. JES up...)
isWeightVariation = sysDict.get("weightVariation", False)
#jetMask = sysDict.get("jet_mask")
#jetPt = sysDict.get("jet_pt_var")
#jetMass = sysDict.get("jet_mass_var")
#Name histograms with their actual systematic variation postfix, using the convention that HISTO_NAME__nom is
# the nominal and HISTO_NAME__$SYSTEMATIC is the variation, like so:
syspostfix = "__nom" if sysVar == "$NOMINAL" else "_{}".format(sysVar)
#name branches for filling with the nominal postfix if weight variations, and systematic postfix if scale variation (jes_up, etc.)
branchpostfix = None
if isWeightVariation:
branchpostfix = "__nom"
else:
branchpostfix = "_" + sysVar.replace("$NOMINAL", "_nom")
leppostfix = sysDict.get("lep_postfix", "") #No variation on this yet, but just in case
fillJet = "FTAJet{bpf}".format(bpf=branchpostfix)
fillJet_pt = "FTAJet{bpf}_pt".format(bpf=branchpostfix)
fillJet_phi = "FTAJet{bpf}_phi".format(bpf=branchpostfix)
fillJet_eta = "FTAJet{bpf}_eta".format(bpf=branchpostfix)
fillJet_mass = "FTAJet{bpf}_mass".format(bpf=branchpostfix)
fillMET_pt = "FTAMET{bpf}_pt".format(bpf=branchpostfix)
fillMET_phi = "FTAMET{bpf}_phi".format(bpf=branchpostfix)
fillMET_uncorr_pt = sysDict.get("met_pt_var", "MET_pt")
fillMET_uncorr_phi = sysDict.get("met_phi_var", "MET_phi")
if verbose:
print("Systematic: {spf} - Branch: {bpf} - Jets: {fj}=({fjp}, {fji}, {fje}, {fjm}) - MET: ({mpt}, {mph})".format(spf=syspostfix,
bpf=branchpostfix,
fj=fillJet,
fjp=fillJet_pt,
fji=fillJet_phi,
fje=fillJet_eta,
fjm=fillJet_mass,
mpt=fillMET_pt,
mph=fillMET_phi)
)
#We need to create filters that depend on scale variations like jesUp/Down, i.e. HT and Jet Pt can and will change
#Usually weight variations will be based upon the _nom (nominal) calculations/filters,
#Scale variations will usually have a special branch defined. Exeption is sample-based variations like ttbar hdamp, where the nominal branch is used for calculations
#but even there, the inputs should be tailored to point to 'nominal' jet pt
if not isWeightVariation:
#cycle through processes here, should we have many packed together in the sample (ttJets -> lepton decay channel, heavy flavor, light flavor, etc.
for processName in nodes:
if processName.lower() == "basenode": continue
if processName not in histoNodes:
histoNodes[processName] = dict()
listOfColumns = nodes[processName]["BaseNode"].GetColumnNames()
#Get the appropriate weight defined in defineFinalWeights function
# wgtVar = sysDict.get("wgt_final", "wgt__nom")
wgtVar = "wgt{spf}".format(spf=syspostfix)
if verbose:
print("\tFor systematic variation {}, weight branch is {}".format(syspostfix.replace("__", ""), wgtVar))
if wgtVar not in listOfColumns:
print("{} not found as a valid weight variation, no backup solution implemented".format(wgtVar))
raise RuntimeError("Couldn't find a valid fallback weight variation in fillHistos()")
print("{} chosen as the weight for {} variation".format(wgtVar, syspostfix))
#potentially add other channels here, like "IsoMuNonisoEl", etc. for QCD studies, or lpf-dependency
#NOTE: we append an extra underscore (postfixes should always have 1 to begin with) to enable use of split("__") to re-deduce postfix outside this
#deeply nested loop
for decayChannel in ["ElMu{lpf}".format(lpf=leppostfix),
"MuMu{lpf}".format(lpf=leppostfix),
"ElEl{lpf}".format(lpf=leppostfix),
]:
testInputChannel = channel.lower().replace("_baseline", "").replace("_selection", "")
testLoopChannel = decayChannel.lower().replace("{lpf}".format(lpf=leppostfix), "").replace("_baseline", "").replace("_selection", "")
if testInputChannel == "all":
pass
elif testInputChannel != testLoopChannel:
print("Skipping channel {chan} in process {proc} for systematic {spf}".format(chan=decayChannel, proc=processName, spf=syspostfix))
continue
#Regarding keys: we'll insert the systematic when we insert all th L0 X L1 X L2 keys in the dictionaries, not here in the L($N) keys
if decayChannel == "ElMu{lpf}".format(lpf=leppostfix):
channelFilter = "nFTALepton{lpf} == 2 && nFTAMuon{lpf} == 1 && nFTAElectron{lpf}== 1 && ((abs(FTALepton{lpf}_eta.at(0)) <= 1.2 && abs(FTALepton{lpf}_eta.at(1)) >= 1.6) || (abs(FTALepton{lpf}_eta.at(0)) >= 1.6 && abs(FTALepton{lpf}_eta.at(1)) <= 1.2))".format(lpf=leppostfix)
channelFiltName = "1 el, 1 mu ({lpf})".format(lpf=leppostfix)
L0String = "HT{bpf} >= {htc}".format(bpf=branchpostfix, htc=HTCut)
L0Name = "HT{bpf} >= {htc}"\
.format(bpf=branchpostfix, htc=HTCut, lpf=leppostfix, met=fillMET_pt, metcut=ZMassMETWindow[1], zwidth=ZMassMETWindow[0])
L0Key = "HT{htc}_ZWindowMET{metcut}Width{zwidth}".format(spf=syspostfix, htc=str(HTCut).replace(".", "p"), metcut=str(0).replace(".", "p"),
zwidth=0)
elif decayChannel == "MuMu{lpf}".format(lpf=leppostfix):
channelFilter = "nFTALepton{lpf} == 2 && nFTAMuon{lpf} == 2 && ((abs(FTALepton{lpf}_eta.at(0)) <= 1.2 && abs(FTALepton{lpf}_eta.at(1)) >= 1.6) || (abs(FTALepton{lpf}_eta.at(0)) >= 1.6 && abs(FTALepton{lpf}_eta.at(1)) <= 1.2))".format(lpf=leppostfix)
channelFiltName = "2 mu ({lpf})".format(lpf=leppostfix)
L0String = "HT{bpf} >= {htc} && {met} >= {metcut} && FTAMuon{lpf}_InvariantMass > 20 && abs(FTAMuon{lpf}_InvariantMass - 91.2) > {zwidth}"\
.format(lpf=leppostfix, met=fillMET_pt, metcut=ZMassMETWindow[1], zwidth=ZMassMETWindow[0], bpf=branchpostfix, htc=HTCut)
L0Name = "HT{bpf} >= {htc}, {met} >= {metcut}, Di-Muon Resonance > 20GeV and outside {zwidth}GeV Z Window"\
.format(bpf=branchpostfix, htc=HTCut, lpf=leppostfix, met=fillMET_pt, metcut=ZMassMETWindow[1], zwidth=ZMassMETWindow[0])
L0Key = "HT{htc}_ZWindowMET{metcut}Width{zwidth}".format(spf=syspostfix, htc=str(HTCut).replace(".", "p"),
metcut=str(ZMassMETWindow[1]).replace(".", "p"),
zwidth=str(ZMassMETWindow[0]).replace(".", "p"))
elif decayChannel == "ElEl{lpf}".format(lpf=leppostfix):
channelFilter = "nFTALepton{lpf} == 2 && nFTAElectron{lpf}== 2 && ((abs(FTALepton{lpf}_eta.at(0)) <= 1.2 && abs(FTALepton{lpf}_eta.at(1)) >= 1.6) || (abs(FTALepton{lpf}_eta.at(0)) >= 1.6 && abs(FTALepton{lpf}_eta.at(1)) <= 1.2))".format(lpf=leppostfix)
channelFiltName = "2 el ({lpf})".format(lpf=leppostfix)
L0String = "HT{bpf} >= {htc} && {met} >= {metcut} && FTAElectron{lpf}_InvariantMass > 20 && abs(FTAElectron{lpf}_InvariantMass - 91.2) > {zwidth}"\
.format(lpf=leppostfix, met=fillMET_pt, metcut=ZMassMETWindow[1], zwidth=ZMassMETWindow[0], bpf=branchpostfix, htc=HTCut)
L0Name = "HT{bpf} >= {htc}, {met} >= {metcut}, Di-Electron Resonance > 20GeV and outside {zwidth}GeV Z Window"\
.format(bpf=branchpostfix, htc=HTCut, lpf=leppostfix, met=fillMET_pt, metcut=ZMassMETWindow[1], zwidth=ZMassMETWindow[0])
L0Key = "HT{htc}_ZWindowMET{metcut}Width{zwidth}".format(spf=syspostfix, htc=str(HTCut).replace(".", "p"),
metcut=str(ZMassMETWindow[1]).replace(".", "p"),
zwidth=str(ZMassMETWindow[0]).replace(".", "p"))
else:
raise NotImplementedError("No definition for decayChannel = {} yet".format(decayChannel))
#filter define, filter name, process, channel, L0 (HT/ZWindow <cross> SCALE variations), L1 (nBTags), L2 (nJet)
#This is the layer -1 key, insert and proceed to layer 0
if decayChannel not in nodes[processName]:
#protect against overwriting, as these nodes will be shared amongst non-weight variations!
#There will be only one basenode per decay channel
# filterNodes[processName][decayChannel] = collections.OrderedDict()
filterNodes[processName][decayChannel] = dict()
filterNodes[processName][decayChannel]["BaseNode"] = (channelFilter, channelFiltName, processName, decayChannel, None, None, None) #L-1 filter
# nodes[processName][decayChannel] = collections.OrderedDict()
nodes[processName][decayChannel] = dict()
nodes[processName][decayChannel]["BaseNode"] = nodes[processName]["BaseNode"].Filter(filterNodes[processName][decayChannel]["BaseNode"][0],
filterNodes[processName][decayChannel]["BaseNode"][1])
# countNodes[processName][decayChannel] = collections.OrderedDict()
countNodes[processName][decayChannel] = dict()
countNodes[processName][decayChannel]["BaseNode"] = nodes[processName][decayChannel]["BaseNode"].Count()
#more freeform diagnostic nodes
diagnosticNodes[processName][decayChannel] = dict()
#Make some key for the histonodes, lets stop at decayChannel for now for the tuples, but keep a dict with histoName as key for histos...
defineNodes[processName][decayChannel] = []
if decayChannel not in histoNodes[processName]:
histoNodes[processName][decayChannel] = collections.OrderedDict()
#NOTE: This structure requires no dependency of L0 and higher nodes upon processName, leppostfix... potential problem later if that changes
#The layer 0 key filter, this is where we intend to start doing histograms (plus subsequently nested nodes on layers 1 and 2
if "L0Nodes" not in filterNodes[processName][decayChannel]:
filterNodes[processName][decayChannel]["L0Nodes"] = []
filterNodes[processName][decayChannel]["L1Nodes"] = []
filterNodes[processName][decayChannel]["L2Nodes"] = []
#We need some indices to be able to sub-select the filter nodes we need to apply, | |
<reponame>TugberkArkose/MLScheduler
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate Leakage': 0.00662954,
'Peak Dynamic': 0.0,
'Runtime Dynamic': 0.0,
'Subthreshold Leakage': 0.0691322,
'Subthreshold Leakage with power gating': 0.0259246},
'Core': [{'Area': 32.6082,
'Execution Unit/Area': 8.2042,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 5.66814e-06,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202693,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 2.02403e-05,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.122718,
'Execution Unit/Instruction Scheduler/Area': 2.17927,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.328073,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00115349,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.20978,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.357856,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.017004,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00962066,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00730101,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 1.00996,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00529112,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 2.07911,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.619677,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0800117,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0455351,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 4.84781,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.841232,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.000856399,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.55892,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.355402,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.0178624,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00897339,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 1.33293,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.114878,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.0641291,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.353722,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 5.57023,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 3.82383e-06,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.0129726,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0938103,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.09594,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0938142,
'Execution Unit/Register Files/Runtime Dynamic': 0.108913,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0442632,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00607074,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.226686,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.582618,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.0920413,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0345155,
'Execution Unit/Runtime Dynamic': 2.63254,
'Execution Unit/Subthreshold Leakage': 1.83518,
'Execution Unit/Subthreshold Leakage with power gating': 0.709678,
'Gate Leakage': 0.372997,
'Instruction Fetch Unit/Area': 5.86007,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00404391,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00404391,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00354112,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.00138115,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.00137819,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.0130071,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0380981,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0590479,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0922296,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 5.86659,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.347548,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.313253,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 8.37418,
'Instruction Fetch Unit/Runtime Dynamic': 0.804136,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932587,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.408542,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0708991,
'L2/Runtime Dynamic': 0.0156825,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80969,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 4.03428,
'Load Store Unit/Data Cache/Runtime Dynamic': 1.36645,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0351387,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0904947,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0904948,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 4.46335,
'Load Store Unit/Runtime Dynamic': 1.90323,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.223144,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.446289,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591622,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283406,
'Memory Management Unit/Area': 0.434579,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0791947,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0799696,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00813591,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.364763,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0578344,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.660174,
'Memory Management Unit/Runtime Dynamic': 0.137804,
'Memory Management Unit/Subthreshold Leakage': 0.0769113,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0399462,
'Peak Dynamic': 23.7005,
'Renaming Unit/Area': 0.369768,
'Renaming Unit/FP Front End RAT/Area': 0.168486,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 3.33511,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 1.3648e-05,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925,
'Renaming Unit/Free List/Area': 0.0414755,
'Renaming Unit/Free List/Gate Leakage': 4.15911e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0401324,
'Renaming Unit/Free List/Runtime Dynamic': 0.0182989,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000670426,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000377987,
'Renaming Unit/Gate Leakage': 0.00863632,
'Renaming Unit/Int Front End RAT/Area': 0.114751,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.00038343,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.86945,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.185277,
'Renaming Unit/Int Front End RAT/Subthreshold | |
from datetime import timedelta
from typing import Any, List, Optional, Dict, Union
import subprocess
from uuid import UUID
import time
from subprocess import run
from sys import platform
import gc
import uuid
import logging
from pathlib import Path
import os
import requests_cache
import responses
from sqlalchemy import create_engine, text
import posthog
import numpy as np
import psutil
import pytest
import requests
from haystack.nodes.base import BaseComponent
try:
from milvus import Milvus
milvus1 = True
except ImportError:
milvus1 = False
from pymilvus import utility
try:
from elasticsearch import Elasticsearch
from haystack.document_stores.elasticsearch import ElasticsearchDocumentStore
import weaviate
from haystack.document_stores.weaviate import WeaviateDocumentStore
from haystack.document_stores import MilvusDocumentStore, PineconeDocumentStore
from haystack.document_stores.graphdb import GraphDBKnowledgeGraph
from haystack.document_stores.faiss import FAISSDocumentStore
from haystack.document_stores.sql import SQLDocumentStore
except (ImportError, ModuleNotFoundError) as ie:
from haystack.utils.import_utils import _optional_component_not_installed
_optional_component_not_installed("test", "test", ie)
from haystack.document_stores import BaseDocumentStore, DeepsetCloudDocumentStore, InMemoryDocumentStore
from haystack.nodes import BaseReader, BaseRetriever
from haystack.nodes.answer_generator.transformers import Seq2SeqGenerator
from haystack.nodes.answer_generator.transformers import RAGenerator
from haystack.nodes.ranker import SentenceTransformersRanker
from haystack.nodes.document_classifier.transformers import TransformersDocumentClassifier
from haystack.nodes.retriever.sparse import FilterRetriever, BM25Retriever, TfidfRetriever
from haystack.nodes.retriever.dense import DensePassageRetriever, EmbeddingRetriever, TableTextRetriever
from haystack.nodes.reader.farm import FARMReader
from haystack.nodes.reader.transformers import TransformersReader
from haystack.nodes.reader.table import TableReader, RCIReader
from haystack.nodes.summarizer.transformers import TransformersSummarizer
from haystack.nodes.translator import TransformersTranslator
from haystack.nodes.question_generator import QuestionGenerator
from haystack.modeling.infer import Inferencer, QAInferencer
from haystack.schema import Document
# To manually run the tests with default PostgreSQL instead of SQLite, switch the lines below
SQL_TYPE = "sqlite"
# SQL_TYPE = "postgres"
SAMPLES_PATH = Path(__file__).parent / "samples"
# to run tests against Deepset Cloud set MOCK_DC to False and set the following params
DC_API_ENDPOINT = "https://DC_API/v1"
DC_TEST_INDEX = "document_retrieval_1"
DC_API_KEY = "NO_KEY"
MOCK_DC = True
# Disable telemetry reports when running tests
posthog.disabled = True
# Cache requests (e.g. huggingface model) to circumvent load protection
# See https://requests-cache.readthedocs.io/en/stable/user_guide/filtering.html
requests_cache.install_cache(urls_expire_after={"huggingface.co": timedelta(hours=1), "*": requests_cache.DO_NOT_CACHE})
def _sql_session_rollback(self, attr):
"""
Inject SQLDocumentStore at runtime to do a session rollback each time it is called. This allows to catch
errors where an intended operation is still in a transaction, but not committed to the database.
"""
method = object.__getattribute__(self, attr)
if callable(method):
try:
self.session.rollback()
except AttributeError:
pass
return method
SQLDocumentStore.__getattribute__ = _sql_session_rollback
def pytest_collection_modifyitems(config, items):
# add pytest markers for tests that are not explicitly marked but include some keywords
name_to_markers = {
"generator": [pytest.mark.generator],
"summarizer": [pytest.mark.summarizer],
"tika": [pytest.mark.tika, pytest.mark.integration],
"parsr": [pytest.mark.parsr, pytest.mark.integration],
"ocr": [pytest.mark.ocr, pytest.mark.integration],
"elasticsearch": [pytest.mark.elasticsearch],
"faiss": [pytest.mark.faiss],
"milvus": [pytest.mark.milvus, pytest.mark.milvus1],
"weaviate": [pytest.mark.weaviate],
"pinecone": [pytest.mark.pinecone],
# FIXME GraphDB can't be treated as a regular docstore, it fails most of their tests
"graphdb": [pytest.mark.integration],
}
for item in items:
for name, markers in name_to_markers.items():
if name in item.nodeid.lower():
for marker in markers:
item.add_marker(marker)
# if the cli argument "--document_store_type" is used, we want to skip all tests that have markers of other docstores
# Example: pytest -v test_document_store.py --document_store_type="memory" => skip all tests marked with "elasticsearch"
document_store_types_to_run = config.getoption("--document_store_type")
document_store_types_to_run = [docstore.strip() for docstore in document_store_types_to_run.split(",")]
keywords = []
for i in item.keywords:
if "-" in i:
keywords.extend(i.split("-"))
else:
keywords.append(i)
for cur_doc_store in ["elasticsearch", "faiss", "sql", "memory", "milvus1", "milvus", "weaviate", "pinecone"]:
if cur_doc_store in keywords and cur_doc_store not in document_store_types_to_run:
skip_docstore = pytest.mark.skip(
reason=f'{cur_doc_store} is disabled. Enable via pytest --document_store_type="{cur_doc_store}"'
)
item.add_marker(skip_docstore)
if "milvus1" in keywords and not milvus1:
skip_milvus1 = pytest.mark.skip(reason="Skipping Tests for 'milvus1', as Milvus2 seems to be installed.")
item.add_marker(skip_milvus1)
elif "milvus" in keywords and milvus1:
skip_milvus = pytest.mark.skip(reason="Skipping Tests for 'milvus', as Milvus1 seems to be installed.")
item.add_marker(skip_milvus)
# Skip PineconeDocumentStore if PINECONE_API_KEY not in environment variables
if not os.environ.get("PINECONE_API_KEY", False) and "pinecone" in keywords:
skip_pinecone = pytest.mark.skip(reason="PINECONE_API_KEY not in environment variables.")
item.add_marker(skip_pinecone)
#
# Empty mocks, as a base for unit tests.
#
# Monkeypatch the methods you need with either a mock implementation
# or a unittest.mock.MagicMock object (https://docs.python.org/3/library/unittest.mock.html)
#
class MockNode(BaseComponent):
outgoing_edges = 1
def run(self, *a, **k):
pass
def run_batch(self, *a, **k):
pass
class MockDocumentStore(BaseDocumentStore):
outgoing_edges = 1
def _create_document_field_map(self, *a, **k):
pass
def delete_documents(self, *a, **k):
pass
def delete_labels(self, *a, **k):
pass
def get_all_documents(self, *a, **k):
pass
def get_all_documents_generator(self, *a, **k):
pass
def get_all_labels(self, *a, **k):
pass
def get_document_by_id(self, *a, **k):
pass
def get_document_count(self, *a, **k):
pass
def get_documents_by_id(self, *a, **k):
pass
def get_label_count(self, *a, **k):
pass
def query_by_embedding(self, *a, **k):
pass
def write_documents(self, *a, **k):
pass
def write_labels(self, *a, **k):
pass
def delete_index(self, *a, **k):
pass
class MockRetriever(BaseRetriever):
outgoing_edges = 1
def retrieve(self, query: str, top_k: int):
pass
def retrieve_batch(self, queries: List[str], top_k: int):
pass
class MockDenseRetriever(MockRetriever):
def __init__(self, document_store: BaseDocumentStore, embedding_dim: int = 768):
self.embedding_dim = embedding_dim
self.document_store = document_store
def embed_queries(self, texts):
return [np.random.rand(self.embedding_dim)] * len(texts)
def embed_documents(self, docs):
return [np.random.rand(self.embedding_dim)] * len(docs)
class MockReader(BaseReader):
outgoing_edges = 1
def predict(self, query: str, documents: List[Document], top_k: Optional[int] = None):
pass
def predict_batch(self, query_doc_list: List[dict], top_k: Optional[int] = None, batch_size: Optional[int] = None):
pass
#
# Document collections
#
@pytest.fixture
def docs_all_formats() -> List[Union[Document, Dict[str, Any]]]:
return [
# metafield at the top level for backward compatibility
{
"content": "My name is Paul and I live in New York",
"meta_field": "test2",
"name": "filename2",
"date_field": "2019-10-01",
"numeric_field": 5.0,
},
# "dict" format
{
"content": "My name is Carla and I live in Berlin",
"meta": {"meta_field": "test1", "name": "filename1", "date_field": "2020-03-01", "numeric_field": 5.5},
},
# Document object
Document(
content="My name is Christelle and I live in Paris",
meta={"meta_field": "test3", "name": "filename3", "date_field": "2018-10-01", "numeric_field": 4.5},
),
Document(
content="My name is Camila and I live in Madrid",
meta={"meta_field": "test4", "name": "filename4", "date_field": "2021-02-01", "numeric_field": 3.0},
),
Document(
content="My name is Matteo and I live in Rome",
meta={"meta_field": "test5", "name": "filename5", "date_field": "2019-01-01", "numeric_field": 0.0},
),
]
@pytest.fixture
def docs(docs_all_formats) -> List[Document]:
return [Document.from_dict(doc) if isinstance(doc, dict) else doc for doc in docs_all_formats]
@pytest.fixture
def docs_with_ids(docs) -> List[Document]:
# Should be already sorted
uuids = [
UUID("190a2421-7e48-4a49-a639-35a86e202dfb"),
UUID("20ff1706-cb55-4704-8ae8-a3459774c8dc"),
UUID("5078722f-07ae-412d-8ccb-b77224c4bacb"),
UUID("81d8ca45-fad1-4d1c-8028-d818ef33d755"),
UUID("f985789f-1673-4d8f-8d5f-2b8d3a9e8e23"),
]
uuids.sort()
for doc, uuid in zip(docs, uuids):
doc.id = str(uuid)
return docs
@pytest.fixture
def docs_with_random_emb(docs) -> List[Document]:
for doc in docs:
doc.embedding = np.random.random([768])
return docs
@pytest.fixture
def docs_with_true_emb():
return [
Document(
content="The capital of Germany is the city state of Berlin.",
embedding=np.loadtxt(SAMPLES_PATH / "embeddings" / "embedding_1.txt"),
),
Document(
content="Berlin is the capital and largest city of Germany by both area and population.",
embedding=np.loadtxt(SAMPLES_PATH / "embeddings" / "embedding_2.txt"),
),
]
@pytest.fixture(autouse=True)
def gc_cleanup(request):
"""
Run garbage collector between tests in order to reduce memory footprint for CI.
"""
yield
gc.collect()
@pytest.fixture(scope="session")
def elasticsearch_fixture():
# test if a ES cluster is already running. If not, download and start an ES instance locally.
try:
client = Elasticsearch(hosts=[{"host": "localhost", "port": "9200"}])
client.info()
except:
print("Starting Elasticsearch ...")
status = subprocess.run(["docker rm haystack_test_elastic"], shell=True)
status = subprocess.run(
[
'docker run -d --name haystack_test_elastic -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.9.2'
],
shell=True,
)
if status.returncode:
raise Exception("Failed to launch Elasticsearch. Please check docker container logs.")
time.sleep(30)
@pytest.fixture(scope="session")
def milvus_fixture():
# test if a Milvus server is already running. If not, start Milvus docker container locally.
# Make sure you have given > 6GB memory to docker engine
try:
milvus_server = Milvus(uri="tcp://localhost:19530", timeout=5, wait_timeout=5)
milvus_server.server_status(timeout=5)
except:
print("Starting Milvus ...")
status = subprocess.run(
[
"docker run -d --name milvus_cpu_0.10.5 -p 19530:19530 -p 19121:19121 "
"milvusdb/milvus:0.10.5-cpu-d010621-4eda95"
],
shell=True,
)
time.sleep(40)
@pytest.fixture(scope="session")
def weaviate_fixture():
# test if a Weaviate server is already running. If not, start Weaviate docker container locally.
# Make sure you have given > 6GB memory to docker engine
try:
weaviate_server = weaviate.Client(url="http://localhost:8080", timeout_config=(5, 15))
weaviate_server.is_ready()
except:
print("Starting Weaviate servers ...")
status = subprocess.run(["docker rm haystack_test_weaviate"], shell=True)
status = subprocess.run(
["docker run -d --name haystack_test_weaviate -p 8080:8080 semitechnologies/weaviate:1.11.0"], shell=True
)
if status.returncode:
raise Exception("Failed to launch Weaviate. Please check docker container logs.")
time.sleep(60)
@pytest.fixture(scope="session")
def graphdb_fixture():
# test if a GraphDB instance is already running. If not, download and start a GraphDB instance locally.
try:
kg = GraphDBKnowledgeGraph()
# fail if not running GraphDB
kg.delete_index()
except:
print("Starting GraphDB ...")
status = subprocess.run(["docker rm haystack_test_graphdb"], shell=True)
status = subprocess.run(
[
"docker run -d -p 7200:7200 --name haystack_test_graphdb docker-registry.ontotext.com/graphdb-free:9.4.1-adoptopenjdk11"
],
shell=True,
)
if status.returncode:
raise Exception("Failed to launch GraphDB. Please check docker container logs.")
time.sleep(30)
@pytest.fixture(scope="session")
def tika_fixture():
try:
tika_url = "http://localhost:9998/tika"
ping = requests.get(tika_url)
if ping.status_code != 200:
raise Exception("Unable to connect Tika. Please check tika endpoint {0}.".format(tika_url))
except:
print("Starting Tika ...")
status = subprocess.run(["docker run -d --name tika -p 9998:9998 apache/tika:1.24.1"], shell=True)
if status.returncode:
raise Exception("Failed to launch Tika. Please check docker container logs.")
time.sleep(30)
@pytest.fixture(scope="session")
def xpdf_fixture():
verify_installation = run(["pdftotext"], shell=True)
if verify_installation.returncode == 127:
if platform.startswith("linux"):
platform_id = "linux"
sudo_prefix = "sudo"
elif platform.startswith("darwin"):
platform_id = "mac"
# | |
index):
if (index < self.get_count()):
return self.get_item(index)
else:
raise IndexError("The index (" + str(index) + ") is out of range")
def __nonzero__(self): return True
__swig_destroy__ = _gui.delete_GuiFilenameFieldSet
__del__ = lambda self: None
GuiFilenameFieldSet_swigregister = _gui.GuiFilenameFieldSet_swigregister
GuiFilenameFieldSet_swigregister(GuiFilenameFieldSet)
def GuiFilenameFieldSet_get_linear_search_threshold():
return _gui.GuiFilenameFieldSet_get_linear_search_threshold()
GuiFilenameFieldSet_get_linear_search_threshold = _gui.GuiFilenameFieldSet_get_linear_search_threshold
class GuiNumberField(GuiWidget):
__swig_setmethods__ = {}
for _s in [GuiWidget]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, GuiNumberField, name, value)
__swig_getmethods__ = {}
for _s in [GuiWidget]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, GuiNumberField, name)
__repr__ = _swig_repr
def __init__(self, *args):
if self.__class__ == GuiNumberField:
_self = None
else:
_self = self
this = _gui.new_GuiNumberField(_self, *args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this
self.__pycreated__ = True
self.__collect__()
def enable(self):
return _gui.GuiNumberField_enable(self)
def disable(self):
return _gui.GuiNumberField_disable(self)
def set_tooltip(self, tooltip):
return _gui.GuiNumberField_set_tooltip(self, tooltip)
def resize(self, x, y, w, h):
return _gui.GuiNumberField_resize(self, x, y, w, h)
def draw(self, dc):
return _gui.GuiNumberField_draw(self, dc)
def redraw(self):
return _gui.GuiNumberField_redraw(self)
def process_event(self, event):
return _gui.GuiNumberField_process_event(self, event)
def set_focus(self):
return _gui.GuiNumberField_set_focus(self)
def has_focus(self):
return _gui.GuiNumberField_has_focus(self)
def lose_focus(self):
return _gui.GuiNumberField_lose_focus(self)
if _newclass:
get_smart_increment = staticmethod(_gui.GuiNumberField_get_smart_increment)
else:
get_smart_increment = _gui.GuiNumberField_get_smart_increment
def get_format(self):
return _gui.GuiNumberField_get_format(self)
def set_format(self, format):
return _gui.GuiNumberField_set_format(self, format)
def set_display_format(self, format):
return _gui.GuiNumberField_set_display_format(self, format)
def set_force_unit_format(self, format):
return _gui.GuiNumberField_set_force_unit_format(self, format)
def set_label(self, label):
return _gui.GuiNumberField_set_label(self, label)
def get_expression_operator(self):
return _gui.GuiNumberField_get_expression_operator(self)
def get_expression_value(self):
return _gui.GuiNumberField_get_expression_value(self)
def get_value(self):
return _gui.GuiNumberField_get_value(self)
def get_value_with_precision(self):
return _gui.GuiNumberField_get_value_with_precision(self)
def set_value(self, value):
return _gui.GuiNumberField_set_value(self, value)
def get_delta_value(self):
return _gui.GuiNumberField_get_delta_value(self)
def get_float_precision(self):
return _gui.GuiNumberField_get_float_precision(self)
def set_float_precision(self, precision):
return _gui.GuiNumberField_set_float_precision(self, precision)
def is_range_enabled(self):
return _gui.GuiNumberField_is_range_enabled(self)
def enable_range(self, enable):
return _gui.GuiNumberField_enable_range(self, enable)
def get_range(self, low, high):
return _gui.GuiNumberField_get_range(self, low, high)
def set_range(self, low, high):
return _gui.GuiNumberField_set_range(self, low, high)
def is_slider_range_enabled(self):
return _gui.GuiNumberField_is_slider_range_enabled(self)
def enable_slider_range(self, enable):
return _gui.GuiNumberField_enable_slider_range(self, enable)
def get_slider_range(self, low, high):
return _gui.GuiNumberField_get_slider_range(self, low, high)
def set_slider_range(self, low, high):
return _gui.GuiNumberField_set_slider_range(self, low, high)
def set_increment(self, increment):
return _gui.GuiNumberField_set_increment(self, increment)
def set_unit_type(self, type_unit):
return _gui.GuiNumberField_set_unit_type(self, type_unit)
def set_force_unit_system(self, unit_system):
return _gui.GuiNumberField_set_force_unit_system(self, unit_system)
def set_force_unit_base(self, unit_base):
return _gui.GuiNumberField_set_force_unit_base(self, unit_base)
def show_slider(self, enable):
return _gui.GuiNumberField_show_slider(self, enable)
def set_read_only(self, value, draw_disable=False):
return _gui.GuiNumberField_set_read_only(self, value, draw_disable)
def is_read_only(self):
return _gui.GuiNumberField_is_read_only(self)
def set_clip_region(self, x, y, w, h):
return _gui.GuiNumberField_set_clip_region(self, x, y, w, h)
def set_roundness(self, roundness):
return _gui.GuiNumberField_set_roundness(self, roundness)
def get_roundness(self):
return _gui.GuiNumberField_get_roundness(self)
def update_size_and_position_components(self):
return _gui.GuiNumberField_update_size_and_position_components(self)
def select_text(self):
return _gui.GuiNumberField_select_text(self)
def deselect_text(self):
return _gui.GuiNumberField_deselect_text(self)
def set_null_label(self, null_label):
return _gui.GuiNumberField_set_null_label(self, null_label)
def get_null_label(self):
return _gui.GuiNumberField_get_null_label(self)
def set_null_value(self, null_value):
return _gui.GuiNumberField_set_null_value(self, null_value)
def get_null_value(self):
return _gui.GuiNumberField_get_null_value(self)
if _newclass:
class_info = staticmethod(_gui.GuiNumberField_class_info)
else:
class_info = _gui.GuiNumberField_class_info
if _newclass:
___class_destructor__ = staticmethod(_gui.GuiNumberField____class_destructor__)
else:
___class_destructor__ = _gui.GuiNumberField____class_destructor__
def get_class_info(self):
return _gui.GuiNumberField_get_class_info(self)
def __gui_destroy__(self):
return _gui.GuiNumberField___gui_destroy__(self)
def __collect__(self):
return _gui.GuiNumberField___collect__(self)
def __uncollect__(self):
return _gui.GuiNumberField___uncollect__(self)
def is_created_by_python(self):
if hasattr(self, '__pycreated__'):
return self.__pycreated__
else: return False
def destroy(self):
if self.is_created_by_python():
self.__disown__()
self.__gui_destroy__()
self.__uncollect__()
def __del__(self):
if not self.is_created_by_python(): return
if self.is_shown():
self.hide()
if self.is_destroyed():
if self.thisown: self.__disown__()
else: self.destroy()
def __disown__(self):
self.this.disown()
_gui.disown_GuiNumberField(self)
return weakref_proxy(self)
GuiNumberField_swigregister = _gui.GuiNumberField_swigregister
GuiNumberField_swigregister(GuiNumberField)
EVT_ID_NUMBER_FIELD_VALUE_CHANGING = cvar.EVT_ID_NUMBER_FIELD_VALUE_CHANGING
EVT_ID_NUMBER_FIELD_VALUE_CHANGED = cvar.EVT_ID_NUMBER_FIELD_VALUE_CHANGED
EVT_ID_NUMBER_FIELD_VALUE_VALIDATE = cvar.EVT_ID_NUMBER_FIELD_VALUE_VALIDATE
EVT_ID_NUMBER_FIELD_MENU_SHOW = cvar.EVT_ID_NUMBER_FIELD_MENU_SHOW
EVT_ID_NUMBER_FIELD_MENU_ITEM_SELECTED = cvar.EVT_ID_NUMBER_FIELD_MENU_ITEM_SELECTED
def GuiNumberField_get_smart_increment(range, division_of_range=200):
return _gui.GuiNumberField_get_smart_increment(range, division_of_range)
GuiNumberField_get_smart_increment = _gui.GuiNumberField_get_smart_increment
def GuiNumberField_class_info():
return _gui.GuiNumberField_class_info()
GuiNumberField_class_info = _gui.GuiNumberField_class_info
def GuiNumberField____class_destructor__(instance, is_array):
return _gui.GuiNumberField____class_destructor__(instance, is_array)
GuiNumberField____class_destructor__ = _gui.GuiNumberField____class_destructor__
class GuiNumberFieldBasicArray(base.CoreBaseType):
__swig_setmethods__ = {}
for _s in [base.CoreBaseType]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, GuiNumberFieldBasicArray, name, value)
__swig_getmethods__ = {}
for _s in [base.CoreBaseType]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, GuiNumberFieldBasicArray, name)
__repr__ = _swig_repr
INVALID_INDEX = _gui.GuiNumberFieldBasicArray_INVALID_INDEX
def __init__(self, *args):
this = _gui.new_GuiNumberFieldBasicArray(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this
__swig_destroy__ = _gui.delete_GuiNumberFieldBasicArray
__del__ = lambda self: None
def get_count(self):
return _gui.GuiNumberFieldBasicArray_get_count(self)
def get_item(self, index):
return _gui.GuiNumberFieldBasicArray_get_item(self, index)
def set_item(self, index, item):
return _gui.GuiNumberFieldBasicArray_set_item(self, index, item)
def front(self):
return _gui.GuiNumberFieldBasicArray_front(self)
def back(self):
return _gui.GuiNumberFieldBasicArray_back(self)
def exists(self, item):
return _gui.GuiNumberFieldBasicArray_exists(self, item)
def get_index(self, item):
return _gui.GuiNumberFieldBasicArray_get_index(self, item)
def sub(self, index, count):
return _gui.GuiNumberFieldBasicArray_sub(self, index, count)
def get_memory_size(self):
return _gui.GuiNumberFieldBasicArray_get_memory_size(self)
def begin(self, *args):
return _gui.GuiNumberFieldBasicArray_begin(self, *args)
def end(self, *args):
return _gui.GuiNumberFieldBasicArray_end(self, *args)
def get_class_info(self):
return _gui.GuiNumberFieldBasicArray_get_class_info(self)
if _newclass:
class_info = staticmethod(_gui.GuiNumberFieldBasicArray_class_info)
else:
class_info = _gui.GuiNumberFieldBasicArray_class_info
if _newclass:
___class_destructor__ = staticmethod(_gui.GuiNumberFieldBasicArray____class_destructor__)
else:
___class_destructor__ = _gui.GuiNumberFieldBasicArray____class_destructor__
def __setitem__(self, index, value):
return _gui.GuiNumberFieldBasicArray___setitem__(self, index, value)
def __len__(self):
return _gui.GuiNumberFieldBasicArray___len__(self)
def __getitem__(self, index):
if (index < self.get_count()):
return self.get_item(index)
else:
raise IndexError("The index (" + str(index) + ") is out of range")
def __nonzero__(self): return True
GuiNumberFieldBasicArray_swigregister = _gui.GuiNumberFieldBasicArray_swigregister
GuiNumberFieldBasicArray_swigregister(GuiNumberFieldBasicArray)
def GuiNumberFieldBasicArray_class_info():
return _gui.GuiNumberFieldBasicArray_class_info()
GuiNumberFieldBasicArray_class_info = _gui.GuiNumberFieldBasicArray_class_info
def GuiNumberFieldBasicArray____class_destructor__(instance, is_array):
return _gui.GuiNumberFieldBasicArray____class_destructor__(instance, is_array)
GuiNumberFieldBasicArray____class_destructor__ = _gui.GuiNumberFieldBasicArray____class_destructor__
class GuiNumberFieldArray(GuiNumberFieldBasicArray):
__swig_setmethods__ = {}
for _s in [GuiNumberFieldBasicArray]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, GuiNumberFieldArray, name, value)
__swig_getmethods__ = {}
for _s in [GuiNumberFieldBasicArray]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, GuiNumberFieldArray, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _gui.new_GuiNumberFieldArray(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this
__swig_destroy__ = _gui.delete_GuiNumberFieldArray
__del__ = lambda self: None
def append(self, *args):
return _gui.GuiNumberFieldArray_append(self, *args)
def get_count(self):
return _gui.GuiNumberFieldArray_get_count(self)
def remove_all(self):
return _gui.GuiNumberFieldArray_remove_all(self)
def resize(self, *args):
return _gui.GuiNumberFieldArray_resize(self, *args)
def copy_from(self, *args):
return _gui.GuiNumberFieldArray_copy_from(self, *args)
def copy_to(self, dest):
return _gui.GuiNumberFieldArray_copy_to(self, dest)
def get_list(self, list):
return _gui.GuiNumberFieldArray_get_list(self, list)
def set_list(self, list):
return _gui.GuiNumberFieldArray_set_list(self, list)
def get_memory_size(self):
return _gui.GuiNumberFieldArray_get_memory_size(self)
def get_class_info(self):
return _gui.GuiNumberFieldArray_get_class_info(self)
if _newclass:
class_info = staticmethod(_gui.GuiNumberFieldArray_class_info)
else:
class_info = _gui.GuiNumberFieldArray_class_info
if _newclass:
___class_destructor__ = staticmethod(_gui.GuiNumberFieldArray____class_destructor__)
else:
___class_destructor__ = _gui.GuiNumberFieldArray____class_destructor__
GuiNumberFieldArray_swigregister = _gui.GuiNumberFieldArray_swigregister
GuiNumberFieldArray_swigregister(GuiNumberFieldArray)
def GuiNumberFieldArray_class_info():
return _gui.GuiNumberFieldArray_class_info()
GuiNumberFieldArray_class_info = _gui.GuiNumberFieldArray_class_info
def GuiNumberFieldArray____class_destructor__(instance, is_array):
return _gui.GuiNumberFieldArray____class_destructor__(instance, is_array)
GuiNumberFieldArray____class_destructor__ = _gui.GuiNumberFieldArray____class_destructor__
class GuiNumberFieldVector(GuiNumberFieldBasicArray):
__swig_setmethods__ = {}
for _s in [GuiNumberFieldBasicArray]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, GuiNumberFieldVector, name, value)
__swig_getmethods__ = {}
for _s in [GuiNumberFieldBasicArray]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, GuiNumberFieldVector, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _gui.new_GuiNumberFieldVector(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this
__swig_destroy__ = _gui.delete_GuiNumberFieldVector
__del__ = lambda self: None
def append(self, *args):
return _gui.GuiNumberFieldVector_append(self, *args)
def add(self, element):
return _gui.GuiNumberFieldVector_add(self, element)
def insert(self, element, index):
return _gui.GuiNumberFieldVector_insert(self, element, index)
def remove_last(self):
return _gui.GuiNumberFieldVector_remove_last(self)
def empty(self):
return _gui.GuiNumberFieldVector_empty(self)
def remove_all(self):
return _gui.GuiNumberFieldVector_remove_all(self)
def clear(self, *args):
return _gui.GuiNumberFieldVector_clear(self, *args)
def remove(self, *args):
return _gui.GuiNumberFieldVector_remove(self, *args)
def is_empty(self):
return _gui.GuiNumberFieldVector_is_empty(self)
def remove_item(self, item, preserve_order):
return _gui.GuiNumberFieldVector_remove_item(self, item, preserve_order)
def remove_items(self, item):
return _gui.GuiNumberFieldVector_remove_items(self, item)
def get_count(self):
return _gui.GuiNumberFieldVector_get_count(self)
def get_capacity(self):
return _gui.GuiNumberFieldVector_get_capacity(self)
def set_count(self, *args):
return _gui.GuiNumberFieldVector_set_count(self, *args)
def set_capacity(self, *args):
return _gui.GuiNumberFieldVector_set_capacity(self, *args)
def refit(self):
return _gui.GuiNumberFieldVector_refit(self)
def swap(self, swap_v1, swap_v2):
return _gui.GuiNumberFieldVector_swap(self, swap_v1, swap_v2)
def resize(self, *args):
return _gui.GuiNumberFieldVector_resize(self, *args)
def reserve(self, *args):
return _gui.GuiNumberFieldVector_reserve(self, *args)
def copy_from(self, *args):
return _gui.GuiNumberFieldVector_copy_from(self, *args)
def copy_to(self, dest):
return _gui.GuiNumberFieldVector_copy_to(self, dest)
def get_list(self, list):
return _gui.GuiNumberFieldVector_get_list(self, list)
def set_list(self, list):
return _gui.GuiNumberFieldVector_set_list(self, list)
def get_array(self, array):
return _gui.GuiNumberFieldVector_get_array(self, array)
def set_array(self, array):
return _gui.GuiNumberFieldVector_set_array(self, array)
def move(self, arg2, to):
return _gui.GuiNumberFieldVector_move(self, arg2, to)
def item(self, index):
return _gui.GuiNumberFieldVector_item(self, index)
def get_memory_size(self):
return _gui.GuiNumberFieldVector_get_memory_size(self)
def get_class_info(self):
return _gui.GuiNumberFieldVector_get_class_info(self)
if _newclass:
class_info = staticmethod(_gui.GuiNumberFieldVector_class_info)
else:
class_info = _gui.GuiNumberFieldVector_class_info
if _newclass:
___class_destructor__ = staticmethod(_gui.GuiNumberFieldVector____class_destructor__)
else:
___class_destructor__ = _gui.GuiNumberFieldVector____class_destructor__
GuiNumberFieldVector_swigregister = _gui.GuiNumberFieldVector_swigregister
GuiNumberFieldVector_swigregister(GuiNumberFieldVector)
def GuiNumberFieldVector_class_info():
return _gui.GuiNumberFieldVector_class_info()
GuiNumberFieldVector_class_info = _gui.GuiNumberFieldVector_class_info
def GuiNumberFieldVector____class_destructor__(instance, is_array):
return _gui.GuiNumberFieldVector____class_destructor__(instance, is_array)
GuiNumberFieldVector____class_destructor__ = _gui.GuiNumberFieldVector____class_destructor__
class GuiNumberFieldSet(base.CoreBaseObject):
__swig_setmethods__ = {}
for _s in [base.CoreBaseObject]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, GuiNumberFieldSet, name, value)
__swig_getmethods__ = {}
for _s in [base.CoreBaseObject]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, GuiNumberFieldSet, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _gui.new_GuiNumberFieldSet(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this
def get_count(self):
return _gui.GuiNumberFieldSet_get_count(self)
def exists(self, *args):
return _gui.GuiNumberFieldSet_exists(self, *args)
def is_empty(self):
return _gui.GuiNumberFieldSet_is_empty(self)
def is_included(self, set):
return _gui.GuiNumberFieldSet_is_included(self, set)
def get_items(self):
return _gui.GuiNumberFieldSet_get_items(self)
def get_item(self, index):
return _gui.GuiNumberFieldSet_get_item(self, index)
def back(self, *args):
return _gui.GuiNumberFieldSet_back(self, *args)
def get_array(self, array):
return _gui.GuiNumberFieldSet_get_array(self, array)
def get_list(self, list):
return _gui.GuiNumberFieldSet_get_list(self, list)
def get_vector(self, vector):
return _gui.GuiNumberFieldSet_get_vector(self, vector)
def to_array(self):
return _gui.GuiNumberFieldSet_to_array(self)
def add(self, *args):
return _gui.GuiNumberFieldSet_add(self, *args)
def remove(self, index):
return _gui.GuiNumberFieldSet_remove(self, index)
def remove_item(self, item):
return _gui.GuiNumberFieldSet_remove_item(self, item)
def remove_set(self, set):
return _gui.GuiNumberFieldSet_remove_set(self, set)
def remove_all(self):
return _gui.GuiNumberFieldSet_remove_all(self)
def toggle(self, item):
return _gui.GuiNumberFieldSet_toggle(self, item)
def unite(self, set):
return _gui.GuiNumberFieldSet_unite(self, set)
def intersect(self, set):
return _gui.GuiNumberFieldSet_intersect(self, set)
def __eq__(self, set):
if not isinstance(obj, type(self)):
return False
return _gui.GuiNumberFieldSet___eq__(self, set)
def __ne__(self, set):
return _gui.GuiNumberFieldSet___ne__(self, set)
def begin(self, *args):
return _gui.GuiNumberFieldSet_begin(self, *args)
| |
n = re.subn('''^\s*SHOWERKT\s*=\s*[default\de\+\-\.]*\s*$''',
''' SHOWERKT = %s ''' % args[1].upper(), \
p_card, flags=(re.M+re.I))
if n==0:
p_card = '%s \n SHOWERKT= %s' % (p_card, args[1].upper())
with open(pythia_path, 'w') as fsock:
fsock.write(p_card)
return
card = '' #store which card need to be modify (for name conflict)
if args[0] == 'madweight_card':
if not self.mw_card:
logger.warning('Invalid Command: No MadWeight card defined.')
return
args[0] = 'MadWeight_card'
if args[0] == 'shower_card':
if not self.shower_card:
logger.warning('Invalid Command: No Shower card defined.')
return
args[0] = 'shower_card'
if args[0] == "madloop_card":
if not self.has_ml:
logger.warning('Invalid Command: No MadLoopParam card defined.')
return
args[0] = 'MadLoop_card'
if args[0] == "pythia8_card":
if not self.has_PY8:
logger.warning('Invalid Command: No Pythia8 card defined.')
return
args[0] = 'pythia8_card'
if args[0] == 'delphes_card':
if not self.has_delphes:
logger.warning('Invalid Command: No Delphes card defined.')
return
if args[1] == 'atlas':
logger.info("set default ATLAS configuration for Delphes", '$MG:BOLD')
files.cp(pjoin(self.me_dir,'Cards', 'delphes_card_ATLAS.dat'),
pjoin(self.me_dir,'Cards', 'delphes_card.dat'))
return
elif args[1] == 'cms':
logger.info("set default CMS configuration for Delphes",'$MG:BOLD')
files.cp(pjoin(self.me_dir,'Cards', 'delphes_card_CMS.dat'),
pjoin(self.me_dir,'Cards', 'delphes_card.dat'))
return
if args[0] in ['run_card', 'param_card', 'MadWeight_card', 'shower_card',
'delphes_card','madanalysis5_hadron_card','madanalysis5_parton_card']:
if args[1] == 'default':
logger.info('replace %s by the default card' % args[0],'$MG:BOLD')
files.cp(self.paths['%s_default' %args[0][:-5]], self.paths[args[0][:-5]])
if args[0] == 'param_card':
self.param_card = param_card_mod.ParamCard(self.paths['param'])
elif args[0] == 'run_card':
self.run_card = banner_mod.RunCard(self.paths['run'])
elif args[0] == 'shower_card':
self.shower_card = shower_card_mod.ShowerCard(self.paths['shower'])
return
else:
card = args[0]
start=1
if len(args) < 3:
logger.warning('Invalid set command: %s (not enough arguments)' % line)
return
elif args[0] in ['MadLoop_card']:
if args[1] == 'default':
logger.info('replace MadLoopParams.dat by the default card','$MG:BOLD')
self.MLcard = banner_mod.MadLoopParam(self.MLcardDefault)
self.MLcard.write(self.paths['ML'],
commentdefault=True)
return
else:
card = args[0]
start=1
if len(args) < 3:
logger.warning('Invalid set command: %s (not enough arguments)' % line)
return
elif args[0] in ['pythia8_card']:
if args[1] == 'default':
logger.info('replace pythia8_card.dat by the default card','$MG:BOLD')
self.PY8Card = self.PY8Card_class(self.PY8CardDefault)
self.PY8Card.write(pjoin(self.me_dir,'Cards','pythia8_card.dat'),
pjoin(self.me_dir,'Cards','pythia8_card_default.dat'),
print_only_visible=True)
return
else:
card = args[0]
start=1
if len(args) < 3:
logger.warning('Invalid set command: %s (not enough arguments)' % line)
return
elif args[0] in ['madspin_card']:
if args[1] == 'default':
logger.info('replace madspin_card.dat by the default card','$MG:BOLD')
files.cp(self.paths['MS_default'], self.paths['madspin'])
return
else:
logger.warning("""Command set not allowed for modifying the madspin_card.
Check the command \"decay\" instead.""")
return
#### RUN CARD
if args[start] in [l.lower() for l in self.run_card.keys()] and card in ['', 'run_card']:
if args[start] not in self.run_set:
if card in self.from_banner or 'run' in self.from_banner:
raise Exception("change not allowed for this card: event already generated!")
args[start] = [l for l in self.run_set if l.lower() == args[start]][0]
if args[start] in self.conflict and card == '':
text = 'Ambiguous name (present in more than one card). Will assume it to be referred to run_card.\n'
text += 'If this is not intended, please reset it in the run_card and specify the relevant card to \n'
text += 'edit, in the format < set card parameter value >'
logger.warning(text)
if args[start+1] == 'default':
default = banner_mod.RunCard(self.paths['run_default'])
if args[start] in list(default.keys()):
self.setR(args[start],default[args[start]])
else:
logger.info('remove information %s from the run_card' % args[start],'$MG:BOLD')
del self.run_card[args[start]]
else:
lower_name = args[0].lower()
if lower_name.startswith('sys_') or \
lower_name in self.run_card.list_parameter or \
lower_name in self.run_card.dict_parameter:
val = ' '.join(args[start+1:])
val = val.split('#')[0]
else:
val = ' '.join(args[start+1:])
self.setR(args[start], val)
self.modified_card.add('run') # delayed writing of the run_card
# special mode for set run_card nocut T (generated by set no_parton_cut
elif card == 'run_card' and args[start] in ['nocut', 'no_cut']:
logger.info("Going to remove all cuts from the run_card", '$MG:BOLD')
self.run_card.remove_all_cut()
self.modified_card.add('run') # delayed writing of the run_card
### PARAM_CARD WITH BLOCK NAME -----------------------------------------
elif self.param_card and (args[start] in self.param_card or args[start] == 'width') \
and card in ['','param_card']:
#special treatment for scan
if any(t.startswith('scan') for t in args):
index = [i for i,t in enumerate(args) if t.startswith('scan')][0]
args = args[:index] + [' '.join(args[index:])]
if args[start] in self.conflict and card == '':
text = 'ambiguous name (present in more than one card). Please specify which card to edit'
text += ' in the format < set card parameter value>'
logger.warning(text)
return
if args[start] == 'width':
args[start] = 'decay'
if args[start+1] in self.pname2block:
all_var = self.pname2block[args[start+1]]
key = None
for bname, lhaid in all_var:
if bname == args[start]:
key = lhaid
break
else:
logger.warning('%s is not part of block "%s" but "%s". please correct.' %
(args[start+1], args[start], bname))
return
else:
try:
key = tuple([int(i) for i in args[start+1:-1]])
except ValueError:
if args[start+1:-1] == ['all']:
for key in self.param_card[args[start]].param_dict:
if (args[start], key) in self.restricted_value:
continue
else:
self.setP(args[start], key, args[-1])
self.modified_card.add('param')
return
logger.warning('invalid set command %s (failed to identify LHA information)' % line)
return
if key in self.param_card[args[start]].param_dict:
if (args[start], key) in self.restricted_value:
text = "Note that this parameter seems to be ignore by MG.\n"
text += "MG will use instead the expression: %s\n" % \
self.restricted_value[(args[start], key)]
text += "You need to match this expression for external program (such pythia)."
logger.warning(text)
if args[-1].lower() in ['default', 'auto', 'auto@nlo'] or args[-1].startswith('scan'):
self.setP(args[start], key, args[-1])
else:
try:
value = float(args[-1])
except Exception:
logger.warning('Invalid input: Expected number and not \'%s\'' \
% args[-1])
return
self.setP(args[start], key, value)
else:
logger.warning('invalid set command %s' % line)
return
self.modified_card.add('param')
# PARAM_CARD NO BLOCK NAME ---------------------------------------------
elif args[start] in self.pname2block and card in ['','param_card']:
if args[start] in self.conflict and card == '':
text = 'ambiguous name (present in more than one card). Please specify which card to edit'
text += ' in the format < set card parameter value>'
logger.warning(text)
return
all_var = self.pname2block[args[start]]
for bname, lhaid in all_var:
new_line = 'param_card %s %s %s' % (bname,
' '.join([ str(i) for i in lhaid]), ' '.join(args[start+1:]))
self.do_set(new_line)
if len(all_var) > 1:
logger.warning('This variable correspond to more than one parameter in the param_card.')
for bname, lhaid in all_var:
logger.warning(' %s %s' % (bname, ' '.join([str(i) for i in lhaid])))
logger.warning('all listed variables have been modified')
# MadWeight_card with block name ---------------------------------------
elif self.has_mw and (args[start] in self.mw_card and args[start] != 'comment') \
and card in ['','MadWeight_card']:
if args[start] in self.conflict and card == '':
text = 'ambiguous name (present in more than one card). Please specify which card to edit'
text += ' in the format < set card parameter value>'
logger.warning(text)
return
block = args[start]
name = args[start+1]
value = args[start+2:]
self.setM(block, name, value)
self.mw_card.write(self.paths['MadWeight'])
# MadWeight_card NO Block name -----------------------------------------
elif self.has_mw and args[start] in self.mw_vars \
and card in ['', 'MadWeight_card']:
if args[start] in self.conflict and card == '':
text = 'ambiguous name (present in more than one card). Please specify which card to edit'
text += ' in the format < set card parameter value>'
logger.warning(text)
return
block = [b for b, data in self.mw_card.items() if args[start] in data]
if len(block) > 1:
logger.warning('%s is define in more than one block: %s.Please specify.'
% (args[start], ','.join(block)))
return
block = block[0]
name = args[start]
value = args[start+1:]
self.setM(block, name, value)
self.mw_card.write(self.paths['MadWeight'])
# MadWeight_card New Block ---------------------------------------------
elif self.has_mw and args[start].startswith('mw_') and len(args[start:]) == 3\
and card == 'MadWeight_card':
block = args[start]
name = args[start+1]
value = args[start+2]
self.setM(block, name, value)
self.mw_card.write(self.paths['MadWeight'])
#### SHOWER CARD
elif self.has_shower and args[start].lower() in [l.lower() for l in \
self.shower_card.keys()] and card in ['', 'shower_card']:
if args[start] not in self.shower_card:
args[start] = [l for l in self.shower_card if l.lower() == args[start].lower()][0]
if args[start] in self.conflict and card == '':
text = 'ambiguous name (present in more than one card). Please specify which card to edit'
text += ' in the format < set card parameter value>'
logger.warning(text)
return
if args[start+1].lower() == 'default':
default = shower_card_mod.ShowerCard(self.paths['shower_default'])
if args[start] in list(default.keys()):
self.shower_card.set_param(args[start],default[args[start]], self.paths['shower'])
else:
logger.info('remove information %s from the shower_card' % args[start],'$MG:BOLD')
del self.shower_card[args[start]]
elif args[start+1].lower() in ['t','.true.','true']:
self.shower_card.set_param(args[start],'.true.',self.paths['shower'])
elif args[start+1].lower() in ['f','.false.','false']:
self.shower_card.set_param(args[start],'.false.',self.paths['shower'])
elif args[start] in ['analyse', 'extralibs', 'extrapaths', 'includepaths'] or\
args[start].startswith('dm_'):
#case sensitive parameters
args = line.split()
args_str = ' '.join(str(a) for a in args[start+1:len(args)])
self.shower_card.set_param(args[start],args_str,pjoin(self.me_dir,'Cards','shower_card.dat'))
else:
args_str = ' '.join(str(a) for a in args[start+1:len(args)])
self.shower_card.set_param(args[start],args_str,self.paths['shower'])
# MadLoop Parameter ---------------------------------------------------
elif self.has_ml and | |
#!/usr/bin/env python
"""Utililies for modifying the GRR server configuration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import getpass
import os
import re
import socket
import subprocess
import sys
import time
# Usually we import concrete items from the builtins module. However, here we
# use `builtins.input` which is stubbed in the test, so we have to always use
# qualified version.
from future import builtins
from future.moves.urllib import parse as urlparse
from future.utils import iteritems
import MySQLdb
from MySQLdb.constants import CR as mysql_conn_errors
from MySQLdb.constants import ER as general_mysql_errors
import pkg_resources
from typing import Optional, Text
# pylint: disable=unused-import,g-bad-import-order
from grr_response_server import server_plugins
# pylint: enable=g-bad-import-order,unused-import
from grr_api_client import api
from grr_api_client import errors as api_errors
from grr_response_core import config as grr_config
from grr_response_core.lib import repacking
from grr_response_server import access_control
from grr_response_server import maintenance_utils
from grr_response_server import server_startup
from grr_response_server import signed_binary_utils
from grr_response_server.bin import api_shell_raw_access_lib
from grr_response_server.bin import config_updater_keys_util
from grr_response_server.gui.api_plugins import user as api_user
from grr_response_server.rdfvalues import objects as rdf_objects
try:
# Importing readline enables the raw_input calls to have history etc.
import readline # pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top
except ImportError:
# readline is not bundled with Python on Windows. Simply ignoring failing
# import then.
pass
# These control retry behavior when checking that GRR can connect to
# MySQL during config initialization.
_MYSQL_MAX_RETRIES = 2
_MYSQL_RETRY_WAIT_SECS = 2
# Python hacks or executables larger than this limit will not be uploaded.
_MAX_SIGNED_BINARY_BYTES = 30 << 20 # 30 MiB
# Batch size to use when fetching multiple items from the GRR API.
_GRR_API_PAGE_SIZE = 1000
class ConfigInitError(Exception):
"""Exception raised to abort config initialization."""
def __init__(self):
super(ConfigInitError, self).__init__(
"Aborting config initialization. Please run 'grr_config_updater "
"initialize' to retry initialization.")
class BinaryTooLargeError(Exception):
"""Exception raised when trying to upload overly large binaries."""
class UserAlreadyExistsError(Exception):
"""Exception raised when trying to create an already-existing user."""
class UserNotFoundError(Exception):
"""Exception raised when trying to fetch a non-existent user."""
def __init__(self, username):
super(UserNotFoundError,
self).__init__("User '%s' does not exist." % username)
def ImportConfig(filename, config):
"""Reads an old config file and imports keys and user accounts."""
sections_to_import = ["PrivateKeys"]
entries_to_import = [
"Client.executable_signing_public_key", "CA.certificate",
"Frontend.certificate"
]
options_imported = 0
old_config = grr_config.CONFIG.MakeNewConfig()
old_config.Initialize(filename)
for entry in old_config.raw_data:
try:
section = entry.split(".")[0]
if section in sections_to_import or entry in entries_to_import:
config.Set(entry, old_config.Get(entry))
print("Imported %s." % entry)
options_imported += 1
except Exception as e: # pylint: disable=broad-except
print("Exception during import of %s: %s" % (entry, e))
return options_imported
def RetryQuestion(question_text, output_re="", default_val=None):
"""Continually ask a question until the output_re is matched."""
while True:
if default_val is not None:
new_text = "%s [%s]: " % (question_text, default_val)
else:
new_text = "%s: " % question_text
# pytype: disable=wrong-arg-count
output = builtins.input(new_text) or str(default_val)
# pytype: enable=wrong-arg-count
output = output.strip()
if not output_re or re.match(output_re, output):
break
else:
print("Invalid input, must match %s" % output_re)
return output
def RetryBoolQuestion(question_text, default_bool):
if not isinstance(default_bool, bool):
raise ValueError(
"default_bool should be a boolean, not %s" % type(default_bool))
default_val = "Y" if default_bool else "N"
prompt_suff = "[Yn]" if default_bool else "[yN]"
return RetryQuestion("%s %s: " % (question_text, prompt_suff), "[yY]|[nN]",
default_val)[0].upper() == "Y"
def ConfigureHostnames(config, external_hostname = None):
"""This configures the hostnames stored in the config."""
if not external_hostname:
try:
external_hostname = socket.gethostname()
except (OSError, IOError):
print("Sorry, we couldn't guess your hostname.\n")
external_hostname = RetryQuestion(
"Please enter your hostname e.g. "
"grr.example.com", "^[\\.A-Za-z0-9-]+$", external_hostname)
print("""\n\n-=Server URL=-
The Server URL specifies the URL that the clients will connect to
communicate with the server. For best results this should be publicly
accessible. By default this will be port 8080 with the URL ending in /control.
""")
frontend_url = RetryQuestion("Frontend URL", "^http://.*/$",
"http://%s:8080/" % external_hostname)
config.Set("Client.server_urls", [frontend_url])
frontend_port = urlparse.urlparse(frontend_url).port or grr_config.CONFIG.Get(
"Frontend.bind_port")
config.Set("Frontend.bind_port", frontend_port)
print("""\n\n-=AdminUI URL=-:
The UI URL specifies where the Administrative Web Interface can be found.
""")
ui_url = RetryQuestion("AdminUI URL", "^http[s]*://.*$",
"http://%s:8000" % external_hostname)
config.Set("AdminUI.url", ui_url)
ui_port = urlparse.urlparse(ui_url).port or grr_config.CONFIG.Get(
"AdminUI.port")
config.Set("AdminUI.port", ui_port)
def CheckMySQLConnection(db_options):
"""Checks whether a connection can be established to MySQL.
Args:
db_options: A dict mapping GRR MySQL config options to their values.
Returns:
A boolean indicating whether a connection could be made to a MySQL server
instance with the given options.
"""
for tries_left in range(_MYSQL_MAX_RETRIES, -1, -1):
try:
connection_options = dict(
host=db_options["Mysql.host"],
port=db_options["Mysql.port"],
db=db_options["Mysql.database_name"],
user=db_options["Mysql.database_username"],
passwd=db_options["Mysql.database_password"],
charset="utf8")
ssl_enabled = "Mysql.client_key_path" in db_options
if ssl_enabled:
connection_options["ssl"] = {
"key": db_options["Mysql.client_key_path"],
"cert": db_options["Mysql.client_cert_path"],
"ca": db_options["Mysql.ca_cert_path"],
}
connection = MySQLdb.connect(**connection_options)
if ssl_enabled:
cursor = connection.cursor()
cursor.execute("SHOW VARIABLES LIKE 'have_ssl'")
res = cursor.fetchone()
if res[0] == "have_ssl" and res[1] == "YES":
print("SSL enabled successfully.")
else:
print("Unable to establish SSL connection to MySQL.")
return False
return True
except MySQLdb.OperationalError as mysql_op_error:
if len(mysql_op_error.args) < 2:
# We expect the exception's arguments to be an error-code and
# an error message.
print("Unexpected exception type received from MySQL. %d attempts "
"left: %s" % (tries_left, mysql_op_error))
time.sleep(_MYSQL_RETRY_WAIT_SECS)
continue
if mysql_op_error.args[0] == mysql_conn_errors.CONNECTION_ERROR:
print("Failed to connect to MySQL. Is it running? %d attempts left." %
tries_left)
elif mysql_op_error.args[0] == mysql_conn_errors.UNKNOWN_HOST:
print("Unknown-hostname error encountered while trying to connect to "
"MySQL.")
return False # No need for retry.
elif mysql_op_error.args[0] == general_mysql_errors.BAD_DB_ERROR:
# GRR db doesn't exist yet. That's expected if this is the initial
# setup.
return True
elif mysql_op_error.args[0] in (
general_mysql_errors.ACCESS_DENIED_ERROR,
general_mysql_errors.DBACCESS_DENIED_ERROR):
print("Permission error encountered while trying to connect to "
"MySQL: %s" % mysql_op_error)
return False # No need for retry.
else:
print("Unexpected operational error encountered while trying to "
"connect to MySQL. %d attempts left: %s" % (tries_left,
mysql_op_error))
except MySQLdb.Error as mysql_error:
print("Unexpected error encountered while trying to connect to MySQL. "
"%d attempts left: %s" % (tries_left, mysql_error))
time.sleep(_MYSQL_RETRY_WAIT_SECS)
return False
def ConfigureMySQLDatastore(config):
"""Prompts the user for configuration details for a MySQL datastore."""
print("GRR will use MySQL as its database backend. Enter connection details:")
datastore_init_complete = False
db_options = {}
while not datastore_init_complete:
db_options["Datastore.implementation"] = "MySQLAdvancedDataStore"
db_options["Mysql.host"] = RetryQuestion("MySQL Host", "^[\\.A-Za-z0-9-]+$",
config["Mysql.host"])
db_options["Mysql.port"] = int(
RetryQuestion("MySQL Port (0 for local socket)", "^[0-9]+$",
config["Mysql.port"]))
db_options["Mysql.database_name"] = RetryQuestion(
"MySQL Database", "^[A-Za-z0-9-]+$", config["Mysql.database_name"])
db_options["Mysql.database_username"] = RetryQuestion(
"MySQL Username", "[A-Za-z0-9-@]+$", config["Mysql.database_username"])
# TODO(hanuszczak): Incorrect type specification for `getpass`.
# pytype: disable=wrong-arg-types
db_options["Mysql.database_password"] = getpass.getpass(
prompt="Please enter password for database user %s: " %
db_options["Mysql.database_username"])
# pytype: enable=wrong-arg-types
use_ssl = RetryBoolQuestion("Configure SSL connections for MySQL?", False)
if use_ssl:
db_options["Mysql.client_key_path"] = RetryQuestion(
"Path to the client private key file",
default_val=config["Mysql.client_key_path"])
db_options["Mysql.client_cert_path"] = RetryQuestion(
"Path to the client certificate file",
default_val=config["Mysql.client_cert_path"])
db_options["Mysql.ca_cert_path"] = RetryQuestion(
"Path to the CA certificate file",
default_val=config["Mysql.ca_cert_path"])
if CheckMySQLConnection(db_options):
print("Successfully connected to MySQL with the provided details.")
datastore_init_complete = True
else:
print("Error: Could not connect to MySQL with the provided details.")
should_retry = RetryBoolQuestion(
"Re-enter MySQL details? Answering 'no' will abort config "
"initialization: ", True)
if should_retry:
db_options.clear()
else:
raise ConfigInitError()
for option, value in iteritems(db_options):
config.Set(option, value)
def ConfigureDatastore(config):
"""Guides the user through configuration of the datastore."""
print("\n\n-=GRR Datastore=-\n"
"For GRR to work each GRR server has to be able to communicate with\n"
"the datastore. To do this we need to configure a datastore.\n")
existing_datastore = grr_config.CONFIG.Get("Datastore.implementation")
if not existing_datastore or existing_datastore == "FakeDataStore":
ConfigureMySQLDatastore(config)
return
print("Found existing settings:\n Datastore: %s" % existing_datastore)
if existing_datastore == "SqliteDataStore":
set_up_mysql = RetryBoolQuestion(
"The SQLite datastore is no longer supported. Would you like to\n"
"set up a MySQL datastore? Answering 'no' will abort config "
"initialization.", True)
if set_up_mysql:
print("\nPlease note that no data will be migrated from SQLite to "
"MySQL.\n")
ConfigureMySQLDatastore(config)
else:
raise ConfigInitError()
elif existing_datastore == "MySQLAdvancedDataStore":
print(" MySQL Host: %s\n MySQL Port: %s\n MySQL Database: %s\n"
" MySQL Username: %s\n" %
(grr_config.CONFIG.Get("Mysql.host"),
grr_config.CONFIG.Get("Mysql.port"),
grr_config.CONFIG.Get("Mysql.database_name"),
grr_config.CONFIG.Get("Mysql.database_username")))
if grr_config.CONFIG.Get("Mysql.client_key_path"):
print(" MySQL client key file: %s\n"
" MySQL client cert file: %s\n"
" MySQL ca cert file: %s\n" %
(grr_config.CONFIG.Get("Mysql.client_key_path"),
grr_config.CONFIG.Get("Mysql.client_cert_path"),
grr_config.CONFIG.Get("Mysql.ca_cert_path")))
if not RetryBoolQuestion("Do you want to keep this configuration?", True):
ConfigureMySQLDatastore(config)
def ConfigureUrls(config, external_hostname = None):
"""Guides the user through configuration of various URLs used by GRR."""
print("\n\n-=GRR URLs=-\n"
"For GRR to work each client has to be able to communicate with the\n"
"server. To do this we normally need a public dns name or IP address\n"
"to communicate with. In the standard configuration this will be used\n"
"to host both the client facing server and the admin user | |
#
# Note on 'chunks_len' values used in tests:
# -----------------------------------------
# The BTC app tx parser requires the tx data to be sent in chunks. For some tx fields
# it doesn't matter where the field is cut but for others it does and the rule is unclear.
#
# Until I get a simple to use and working Tx parser class done, a workaround is
# used to split the tx in chunks of specific lengths, as done in ledgerjs' Btc.test.js
# file. Tx chunks lengths are gathered in a list, following the grammar below:
#
# chunks_lengths := list_of(chunk_desc,) i.e. [chunk_desc, chunk_desc,...]
# chunk_desc := offs_len_tuple | length | -1
# offs_len_tuple := (offset, length) | (length1, skip_length, length2)
#
# with:
# offset:
# the offset of the 1st byte in the tx for the data chunk to be sent. Allows to skip some
# parts of the tx which should not be sent to the tx parser.
# length:
# the length of the chunk to be sent
# length1, length2:
# the lengths of 2 non-contiguous chunks of data in the tx separated by a block of
# skip_length bytes. The 2 non-contiguous blocks are concatenated together and the bloc
# of skip_length bytes is ignored. This is used when 2 non-contiguous parts of the tx
# must be sent in the same APDU but without the in-between bytes.
# -1:
# the length of the chunk to be sent is the last byte of the previous chunk + 4. This is
# used to send input/output scripts + their following 4-byte sequence_number in chunks.
# Sequence_number can't be sent separately from its output script as it puts the
# BTC app's tx parser in an invalid state (sw 0x6F01 returned, not clear why). This implicit
# +4 is to work around that limitation (but design-wise, it introduces knowledge of the tx
# format in the _sendApdu() method used by the tests :/).
import pytest
from typing import Optional, List
from functools import reduce
from helpers.basetest import BaseTestBtc, BtcPublicKey, TxData
from helpers.deviceappbtc import DeviceAppBtc
utxos = [
bytes.fromhex(
# Version no (4 bytes) @offset 0
"02000000"
# Marker + Flag (optional 2 bytes, 0001 indicates the presence of witness data)
# /!\ Remove flag for `GetTrustedInput` @offset 4
"0001"
# In-counter (varint 1-9 bytes) @offset 6
"01"
# 1st Previous Transaction hash (32 bytes) @offset 7
"1541bf80c7b109c50032345d7b6ad6935d5868520477966448dc78ab8f493db1"
# 1st Previous Txout-index (4 bytes) @offset 39
"00000000"
# 1st Txin-script length (varint 1-9 bytes) @offset 43
"17"
# Txin-script (a.k.a scriptSig) because P2SH @offset 44
"160014d44d01d48f9a0d5dfa73dab21c30f7757aed846a"
# sequence_no (4 bytes) @offset 67
"feffffff"
# Out-counter (varint 1-9 bytes) @offset 71
"02"
# value in satoshis (8 bytes) @offset 72
"9b3242bf01000000" # 999681 satoshis = 0,00999681 BTC
# Txout-script length (varint 1-9 bytes) @offset 80
"17"
# Txout-script (a.k.a scriptPubKey) @offset 81
"a914ff31b9075c4ac9aee85668026c263bc93d016e5a87"
# value in satoshis (8 bytes) @offset 104
"1027000000000000" # 999681 satoshis = 0,00999681 BTC
# Txout-script length (varint 1-9 bytes) @offset 112
"17"
# Txout-script (a.k.a scriptPubKey) @offset 113
"a9141e852ac84f8385d76441c584e41f445aaf1624ea87"
# Witnesses (1 for each input if Marker+Flag=0001) @offset 136
# /!\ remove witnesses for GetTrustedInput
"0247"
"304402206e54747dabff52f5c88230a3036125323e21c6c950719f671332"
"cdd0305620a302204a2f2a6474f155a316505e2224eeab6391d5e6daf22a"
"cd76728bf74bc0b48e1a0121033c88f6ef44902190f859e4a6df23ecff4d"
"86a2114bd9cf56e4d9b65c68b8121d"
# lock_time (4 bytes) @offset @offset 243
"1f7f1900"
),
bytes.fromhex(
# Version (4bytes) @offset 0
"01000000"
# Segwit (2 bytes) version+flag @offset 4
"0001"
# Input count @offset 6
"02"
# Input #1 prevout_hash (32 bytes) @offset 7
"7ab1cb19a44db08984031508ec97de727b32a8176cc00fce727065e86984c8df"
# Input #1 prevout_idx (4 bytes) @offset 39
"00000000"
# Input #1 scriptSig len @offset 43
"17"
# Input #1 scriptSig (23 bytes) @offset 44
"160014d815dddcf8cf1b820419dcb1206a2a78cfa60320"
# Input #1 sequence (4 bytes) @offset 67
"ffffff00"
# Input #2 prevout_hash (32 bytes) @offset 71
"78958127caf18fc38733b7bc061d10bca72831b48be1d6ac91e296b888003327"
# Input #2 prevout_idx (4 bytes) @offset 103
"00000000"
# Input #2 scriptSig length @offset 107
"17"
# Input #1 scriptSig (23 bytes) @offset 108
"160014d815dddcf8cf1b820419dcb1206a2a78cfa60320"
# Input #2 sequence (4 bytes) @offset 131
"ffffff00"
# Output count @ @offset 135
"02"
# Output # 1 value (8 bytes) @offset 136
"1027000000000000"
# Output #1 scriptPubkey (24 bytes) @offset 144
"17"
"a91493520844497c54e709756c819afecfffaf28761187"
# Output #2 value (8 bytes) @offset 168
"c84b1a0000000000"
# Output #2 scriptPubkey (24 bytes) @offset 176
"17"
"a9148f1f7cf3c847e4057be46990c4a00be4271f3cfa87"
# Witnesses (214 bytes) @offset 200
"0247"
"3044022009116da9433c3efad4eaf5206a780115d6e4b2974152bdceba220c45"
"<KEY>"
"bef002c493d701210293137bc1a9b7993a1d2a462188efc45d965d135f53746b"
"6b146a3cec9905322602473044022034eceb661d9e5f777468089b262f6b25e1"
"41218f0ec9e435a98368d3f347944d02206041228b4e43a1e1fbd70ca15d3308"
"af730eedae9ec053afec97bd977be7685b01210293137bc1a9b7993a1d2a4621"
"88efc45d965d135f53746b6b146a3cec99053226"
# locktime (4 bytes) @offset 414 (or -4)
"00000000")
]
tx_to_sign = bytes.fromhex(
# Version
"01000000"
# Segwit flag+version
"0001"
# Input count
"02"
# Prevout hash (txid) @offset 7
"027a726f8aa4e81a45241099a9820e6cb7d8920a686701ad98000721101fa0aa"
# Prevout index @offset 39
"01000000"
# scriptSig @offset 43
"17"
"160014d815dddcf8cf1b820419dcb1206a2a78cfa60320"
# Input sequence @offset 67
"ffffff00"
# Input #2 prevout hash (32 bytes) @offset 71
"f0b7b7ad837b4d3535bea79a2fa355262df910873b7a51afa1e4279c6b6f6e6f"
# Input #2 prevout index (4 bytes) @offset 103
"00000000"
# Input #2 scriptSig @offset 107
"17"
"160014eee02beeb4a8f15bbe4926130c086bd47afe8dbc"
#Input #2 sequence (4 bytes) @offset 131
"ffffff00"
# Output count @offset 135
"02"
# Amount #1 @offset (8 bytes) 136
"1027000000000000"
# scriptPubkey #1 (24 bytes) @offset 144
"17"
"<KEY>"
# Amount #2 (8 bytes) @offset 168
"0e26000000000000"
# scriptPubkey #2 (24 bytes) @ offset 176
"17"
"a9143ae394774f1348be3a6bc2a55b67e3566d13408987"
# Signed DER-encoded withness from testnet (@offset 200)
# /!\ Do not send to UntrustedSignHash! But the signature it contains
# can be used to verify the test output, provided the same seed and
# derivation paths are used.
"02""48"
#Input #1 sig @offset 202
"30""45"
"02""21"
"00f4d05565991d98573629c7f98c4f575a4915600a83a0057716f1f4865054927f"
"02""20"
"10f30365e0685ee46d81586b50f5dd201ddedab39cfd7d16d3b17f94844ae6d5"
"01""21"
"0293137bc1a9b7993a1d2a462188efc45d965d135f53746b6b146a3cec99053226"
"02""47"
# Input #2 sig @offset 309
"30""44"
"02""20"
"30c4c770db75aa1d3ed877c6f995a1e6055be00c88efefb2fb2db8c596f2999a"
"02""20"
"5529649f4366427e1d9ed3cf8dc80fe25e04ce4ac19b71578fb6da2b5788d45b"
"01""21"
"03cfbca92ae924a3bd87529956cb4f372a45daeafdb443e12a781881759e6f48ce"
# locktime @offset -4
"00000000"
)
expected_der_sig = [
tx_to_sign[202:202+2+tx_to_sign[203]+1],
tx_to_sign[309:309+2+tx_to_sign[309]+1]
]
output_paths = [
bytes.fromhex("05""80000031""80000001""80000000""00000000""000001f6"), # 49'/1'/0'/0/502
bytes.fromhex("05""80000031""80000001""80000000""00000000""000001f7") # 49'/1'/0'/0/503
]
change_path = bytes.fromhex("05""80000031""80000001""80000000""00000001""00000045") # 49'/1'/0'/1/69
test12_data = TxData(
tx_to_sign=tx_to_sign,
utxos=utxos,
output_paths=output_paths,
change_path=change_path,
expected_sig=expected_der_sig
)
@pytest.mark.btc
@pytest.mark.manual
class TestBtcSegwitTxLjs(BaseTestBtc):
@pytest.mark.parametrize("test_data", [test12_data])
def test_sign_tx_with_multiple_trusted_segwit_inputs(self, test_data: TxData):
"""
Submit segwit input as TrustedInput for signature.
Signature obtained should be the same as no segwit inputs were used directly were used.
"""
# Start test
tx_to_sign = test_data.tx_to_sign
utxos = test_data.utxos
output_paths = test_data.output_paths
change_path = test_data.change_path
expected_der_sig = test_data.expected_sig
btc = DeviceAppBtc()
# 1. Get trusted inputs (submit output index + prevout tx)
output_indexes = [
tx_to_sign[39+4-1:39-1:-1], # out_index in tx_to_sign input must be passed BE as prefix to utxo tx
tx_to_sign[103+4-1:103-1:-1]
]
input_data = [out_idx + utxo for out_idx, utxo in zip(output_indexes, utxos)]
utxos_chunks_len = [
[ # utxo #1
(4+4, 2, 1), # len(prevout_index (BE)||version||input_count) - (skip 2-byte segwit Marker+flags)
37, # len(prevout_hash||prevout_index||len(scriptSig))
-1, # len(scriptSig, from last byte of previous chunk) + len(input_sequence)
1, # len(output_count)
32, # len(output_value #1||len(scriptPubkey #1)||scriptPubkey #1)
32, # len(output_value #2||len(scriptPubkey #2)||scriptPubkey #2)
(243+4, 4) # len(locktime) - skip witness data
],
[ # utxo #2
(4+4, 2, 1), # len(prevout_index (BE)||version||input_count) - (skip 2-byte segwit Marker+flags)
37, # len(prevout1_hash||prevout1_index||len(scriptSig1))
-1, # len(scriptSig1, from last byte of previous chunk) + len(input_sequence1)
37, # len(prevout2_hash||prevout2_index||len(scriptSig2))
-1, # len(scriptSig2, from last byte of previous chunk) + len(input_sequence2)
1, # len(output_count)
32, # len(output_value #1||len(scriptPubkey #1)||scriptPubkey #1)
32, # len(output_value #2||len(scriptPubkey #2)||scriptPubkey #2)
(414+4, 4) # len(locktime) - skip witness data
]
]
trusted_inputs = [
btc.getTrustedInput(
data=input_datum,
chunks_len=chunks_len
)
for (input_datum, chunks_len) in zip(input_data, utxos_chunks_len)
]
print(" OK")
out_amounts = [utxos[0][104:104+8], utxos[1][136:136+8]]
prevout_hashes = [tx_to_sign[7:7+32], tx_to_sign[71:71+32]]
for trusted_input, out_idx, out_amount, prevout_hash in zip(
trusted_inputs, output_indexes, out_amounts, prevout_hashes
):
self.check_trusted_input(
trusted_input,
out_index=out_idx[::-1], # LE for comparison w/ out_idx in trusted_input
out_amount=out_amount, # utxo output #1 is requested in tx to sign input
out_hash=prevout_hash # prevout hash in tx to sign
)
# 2.0 Get public keys for output paths & compute their hashes
print("\n--* Get Wallet Public Key - for each tx output path")
wpk_responses = [btc.getWalletPublicKey(output_path) for output_path in output_paths]
print(" OK")
pubkeys_data = [self.split_pubkey_data(data) for data in wpk_responses]
for pubkey in pubkeys_data:
print(pubkey)
# 2.1 Construct a pseudo-tx without input script, to be hashed 1st. The original segwit input
# being replaced with the previously obtained TrustedInput, it is prefixed it with the marker
# byte for TrustedInputs (0x01) | |
'CalibrationAngleCranCaud', False, 'CalibrationAngleCranCaud'),
"0019xx60" : ('SL', '1', 'CalibrationAngleRAOLAO', False, 'CalibrationAngleRAOLAO'),
"0019xx62" : ('SL', '1', 'CalibrationTableToFloorDist', False, 'CalibrationTableToFloorDist'),
"0019xx64" : ('SL', '1', 'CalibrationIsocenterToFloorDist', False, 'CalibrationIsocenterToFloorDist'),
"0019xx66" : ('SL', '1', 'CalibrationIsocenterToSourceDist', False, 'CalibrationIsocenterToSourceDist'),
"0019xx68" : ('SL', '1', 'CalibrationSourceToII', False, 'CalibrationSourceToII'),
"0019xx6a" : ('SL', '1', 'CalibrationIIZoom', False, 'CalibrationIIZoom'),
"0019xx6c" : ('SL', '1', 'CalibrationIIField', False, 'CalibrationIIField'),
"0019xx6e" : ('SL', '1', 'CalibrationFactor', False, 'CalibrationFactor'),
"0019xx70" : ('SL', '1', 'CalibrationObjectToImageDistance', False, 'CalibrationObjectToImageDistance'),
"0019xx72" : ('SL', '1-n', 'CalibrationSystemFactor', False, 'CalibrationSystemFactor'),
"0019xx74" : ('SL', '1-n', 'CalibrationSystemCorrection', False, 'CalibrationSystemCorrection'),
"0019xx76" : ('SL', '1-n', 'CalibrationSystemIIFormats', False, 'CalibrationSystemIIFormats'),
"0019xx78" : ('SL', '1', 'CalibrationGantryDataValid', False, 'CalibrationGantryDataValid'),
"0019xx7a" : ('SS', '1', 'CollimatorSquareBreadth', False, 'CollimatorSquareBreadth'),
"0019xx7c" : ('SS', '1', 'CollimatorSquareHeight', False, 'CollimatorSquareHeight'),
"0019xx7e" : ('SS', '1', 'CollimatorSquareDiameter', False, 'CollimatorSquareDiameter'),
"0019xx80" : ('SS', '1', 'CollimaterFingerTurnAngle', False, 'CollimaterFingerTurnAngle'),
"0019xx82" : ('SS', '1', 'CollimaterFingerPosition', False, 'CollimaterFingerPosition'),
"0019xx84" : ('SS', '1', 'CollimaterDiaphragmTurnAngle', False, 'CollimaterDiaphragmTurnAngle'),
"0019xx86" : ('SS', '1', 'CollimaterDiaphragmPosition1', False, 'CollimaterDiaphragmPosition1'),
"0019xx88" : ('SS', '1', 'CollimaterDiaphragmPosition2', False, 'CollimaterDiaphragmPosition2'),
"0019xx8a" : ('SS', '1', 'CollimaterDiaphragmMode', False, 'CollimaterDiaphragmMode'),
"0019xx8c" : ('SS', '1', 'CollimaterBeamLimitBreadth', False, 'CollimaterBeamLimitBreadth'),
"0019xx8e" : ('SS', '1', 'CollimaterBeamLimitHeight', False, 'CollimaterBeamLimitHeight'),
"0019xx90" : ('SS', '1', 'CollimaterBeamLimitDiameter', False, 'CollimaterBeamLimitDiameter'),
"0019xx92" : ('SS', '1', 'X-RayControlMOde', False, 'X-RayControlMOde'),
"0019xx94" : ('SS', '1', 'X-RaySystem', False, 'X-RaySystem'),
"0019xx96" : ('SS', '1', 'FocalSpot', False, 'FocalSpot'),
"0019xx98" : ('SS', '1', 'ExposureControl', False, 'ExposureControl'),
"0019xx9a" : ('SL', '1', 'XRayVoltage', False, 'XRayVoltage'),
"0019xx9c" : ('SL', '1', 'XRayCurrent', False, 'XRayCurrent'),
"0019xx9e" : ('SL', '1', 'XRayCurrentTimeProduct', False, 'XRayCurrentTimeProduct'),
"0019xxa0" : ('SL', '1', 'XRayPulseTime', False, 'XRayPulseTime'),
"0019xxa2" : ('SL', '1', 'XRaySceneTimeFluoroClock', False, 'XRaySceneTimeFluoroClock'),
"0019xxa4" : ('SS', '1', 'MaximumPulseRate', False, 'MaximumPulseRate'),
"0019xxa6" : ('SS', '1', 'PulsesPerScene', False, 'PulsesPerScene'),
"0019xxa8" : ('SL', '1', 'DoseAreaProductOfScene', False, 'DoseAreaProductOfScene'),
"0019xxaa" : ('SS', '1', 'Dose', False, 'Dose'),
"0019xxac" : ('SS', '1', 'DoseRate', False, 'DoseRate'),
"0019xxae" : ('SL', '1', 'IIToCoverDistance', False, 'IIToCoverDistance'),
"0019xxb0" : ('SS', '1', 'LastFramePhase1', False, 'LastFramePhase1'),
"0019xxb1" : ('SS', '1', 'FrameRatePhase1', False, 'FrameRatePhase1'),
"0019xxb2" : ('SS', '1', 'LastFramePhase2', False, 'LastFramePhase2'),
"0019xxb3" : ('SS', '1', 'FrameRatePhase2', False, 'FrameRatePhase2'),
"0019xxb4" : ('SS', '1', 'LastFramePhase3', False, 'LastFramePhase3'),
"0019xxb5" : ('SS', '1', 'FrameRatePhase3', False, 'FrameRatePhase3'),
"0019xxb6" : ('SS', '1', 'LastFramePhase4', False, 'LastFramePhase4'),
"0019xxb7" : ('SS', '1', 'FrameRatePhase4', False, 'FrameRatePhase4'),
"0019xxb8" : ('SS', '1', 'GammaOfNativeImage', False, 'GammaOfNativeImage'),
"0019xxb9" : ('SS', '1', 'GammaOfTVSystem', False, 'GammaOfTVSystem'),
"0019xxbb" : ('SL', '1', 'PixelshiftX', False, 'PixelshiftX'),
"0019xxbc" : ('SL', '1', 'PixelshiftY', False, 'PixelshiftY'),
"0019xxbd" : ('SL', '1', 'MaskAverageFactor', False, 'MaskAverageFactor'),
"0019xxbe" : ('SL', '1', 'BlankingCircleFlag', False, 'BlankingCircleFlag'),
"0019xxbf" : ('SL', '1', 'CircleRowStart', False, 'CircleRowStart'),
"0019xxc0" : ('SL', '1', 'CircleRowEnd', False, 'CircleRowEnd'),
"0019xxc1" : ('SL', '1', 'CircleColumnStart', False, 'CircleColumnStart'),
"0019xxc2" : ('SL', '1', 'CircleColumnEnd', False, 'CircleColumnEnd'),
"0019xxc3" : ('SL', '1', 'CircleDiameter', False, 'CircleDiameter'),
"0019xxc4" : ('SL', '1', 'RectangularCollimaterFlag', False, 'RectangularCollimaterFlag'),
"0019xxc5" : ('SL', '1', 'RectangleRowStart', False, 'RectangleRowStart'),
"0019xxc6" : ('SL', '1', 'RectangleRowEnd', False, 'RectangleRowEnd'),
"0019xxc7" : ('SL', '1', 'RectangleColumnStart', False, 'RectangleColumnStart'),
"0019xxc8" : ('SL', '1', 'RectangleColumnEnd', False, 'RectangleColumnEnd'),
"0019xxc9" : ('SL', '1', 'RectangleAngulation', False, 'RectangleAngulation'),
"0019xxca" : ('SL', '1', 'IrisCollimatorFlag', False, 'IrisCollimatorFlag'),
"0019xxcb" : ('SL', '1', 'IrisRowStart', False, 'IrisRowStart'),
"0019xxcc" : ('SL', '1', 'IrisRowEnd', False, 'IrisRowEnd'),
"0019xxcd" : ('SL', '1', 'IrisColumnStart', False, 'IrisColumnStart'),
"0019xxce" : ('SL', '1', 'IrisColumnEnd', False, 'IrisColumnEnd'),
"0019xxcf" : ('SL', '1', 'IrisAngulation', False, 'IrisAngulation'),
"0019xxd1" : ('SS', '1', 'NumberOfFramesPlane', False, 'NumberOfFramesPlane'),
"0019xxd2" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxd3" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxd4" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxd5" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxd6" : ('SS', '1-n', 'Internal', False, 'Internal'),
"0019xxd7" : ('SS', '1-n', 'Internal', False, 'Internal'),
"0019xxd8" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxd9" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxda" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxdb" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxdc" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxdd" : ('SL', '1', 'AnatomicBackground', False, 'AnatomicBackground'),
"0019xxde" : ('SL', '1-n', 'AutoWindowBase', False, 'AutoWindowBase'),
"0019xxdf" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xxe0" : ('SL', '1', 'Internal', False, 'Internal'),
},
'SIEMENS RA PLANE B' : {
"0011xx28" : ('SL', '1', 'FluoroTimerB', False, 'FluoroTimerB'),
"0011xx29" : ('SL', '1', 'FluoroSkinDoseB', False, 'FluoroSkinDoseB'),
"0011xx2a" : ('SL', '1', 'TotalSkinDoseB', False, 'TotalSkinDoseB'),
"0011xx2b" : ('SL', '1', 'FluoroDoseAreaProductB', False, 'FluoroDoseAreaProductB'),
"0011xx2c" : ('SL', '1', 'TotalDoseAreaProductB', False, 'TotalDoseAreaProductB'),
"0019xx18" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx19" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx1a" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx1b" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx1c" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx1d" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx1e" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx1f" : ('SS', '1', 'Internal', False, 'Internal'),
"0019xx20" : ('SL', '1-n', 'SystemCalibFactorPlaneB', False, 'SystemCalibFactorPlaneB'),
"0019xx22" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx24" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx26" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx28" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx2a" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx2c" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx2e" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx30" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx32" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx34" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx36" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx38" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx3a" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx3c" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx3e" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx40" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx42" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx44" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx46" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx48" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx4a" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx4c" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx4e" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx50" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx52" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx54" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx56" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx58" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx5a" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx5c" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx5e" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx60" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx62" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx64" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx66" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx68" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx6a" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx6c" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx6e" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx70" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx72" : ('UN', '1', 'Unknown', False, 'Unknown'),
"0019xx74" : ('UN', '1', 'Unknown', False, 'Unknown'),
"0019xx76" : ('UN', '1', 'Unknown', False, 'Unknown'),
"0019xx78" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx7a" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx7c" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx7e" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx80" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx82" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx84" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx86" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx88" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx8a" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx8c" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx8e" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx90" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx92" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx94" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx96" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx98" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xx9a" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx9c" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xx9e" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xxa0" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xxa2" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xxa4" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xxa6" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xxa8" : ('US', '1-n', 'Unknown', False, 'Unknown'),
"0019xxaa" : ('US', '1', 'Unknown', False, 'Unknown'),
"0019xxac" : ('US', '1', 'Unknown', False, 'Unknown'),
},
'SIEMENS RIS' : {
"0011xx10" : ('LT', '1', 'PatientUID', False, 'PatientUID'),
"0011xx11" : ('LT', '1', 'PatientID', False, 'PatientID'),
"0011xx20" : ('DA', '1', 'PatientRegistrationDate', False, 'PatientRegistrationDate'),
"0011xx21" : ('TM', '1', 'PatientRegistrationTime', False, 'PatientRegistrationTime'),
"0011xx30" : ('LT', '1', 'PatientnameRIS', False, 'PatientnameRIS'),
"0011xx31" : ('LT', '1', 'PatientprenameRIS', False, 'PatientprenameRIS'),
"0011xx40" : ('LT', '1', 'PatientHospitalStatus', False, 'PatientHospitalStatus'),
"0011xx41" : ('LT', '1', 'MedicalAlerts', False, 'MedicalAlerts'),
"0011xx42" : ('LT', '1', 'ContrastAllergies', False, 'ContrastAllergies'),
"0031xx10" : ('LT', '1', 'RequestUID', | |
> 0:
return rz
return {'return': 0}
##############################################################################
# received from web (if needed) and unzip archive
def get_and_unzip_archive(i):
"""
Input: {
zip - zip filename or URL
path - path to extract
(overwrite) - if 'yes', overwrite files when unarchiving
(path_to_remove) - if !='', remove this part of the path from extracted archive
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
o = i.get('out', '')
zp = i['zip']
p = i['path']
pr = i.get('path_to_remove', '')
overwrite = i.get('overwrite', '')
# If zip, get (download) and unzip file ...
rm_zip = False
if zp.find('://') >= 0:
if o == 'con':
ck.out('Downloading CK archive ('+zp+') - it may take some time ...')
rm_zip = True
# Generate tmp file
import tempfile
# suffix is important - CK will delete such file!
fd, fn = tempfile.mkstemp(suffix='.tmp', prefix='ck-')
os.close(fd)
os.remove(fn)
# Import modules compatible with Python 2.x and 3.x
import urllib
try:
import urllib.request as urllib2
except:
import urllib2
# Prepare request
request = urllib2.Request(zp)
# Connect
try:
f = urllib2.urlopen(request)
except Exception as e:
return {'return': 1, 'error': 'Failed downloading CK archive ('+format(e)+')'}
import time
t = time.time()
t0 = t
chunk = 32767
size = 0
try:
fo = open(fn, 'wb')
except Exception as e:
return {'return': 1, 'error': 'problem opening file='+fn+' ('+format(e)+')'}
# Read from Internet
try:
while True:
s = f.read(chunk)
if not s:
break
fo.write(s)
size += len(s)
if o == 'con' and (time.time()-t) > 3:
speed = '%.1d' % (size/(1000*(time.time()-t0)))
ck.out(' Downloaded '+str(int(size/1000)) +
' KB ('+speed+' KB/sec.) ...')
t = time.time()
f.close()
except Exception as e:
return {'return': 1, 'error': 'Failed downlading CK archive ('+format(e)+')'}
fo.close()
zp = fn
# Unzip if zip
if zp != '':
if o == 'con':
ck.out(' Extracting to '+p+' ...')
import zipfile
f = open(zp, 'rb')
z = zipfile.ZipFile(f)
# First, try to find .ckr.json
xprefix = ''
for dx in z.namelist():
if pr != '' and dx.startswith(pr):
dx = dx[len(pr):]
if dx.endswith(ck.cfg['repo_file']):
xprefix = dx[:-len(ck.cfg['repo_file'])]
break
# Second, extract files
for dx in z.namelist():
dx1 = dx
if pr != '' and dx1.startswith(pr):
dx1 = dx1[len(pr):]
if xprefix != '' and dx1.startswith(xprefix):
dx1 = dx1[len(xprefix):]
if dx1 != '':
pp = os.path.join(p, dx1)
if dx.endswith('/'):
# create directory
if not os.path.exists(pp):
os.makedirs(pp)
else:
# extract file
ppd = os.path.dirname(pp)
if not os.path.exists(ppd):
os.makedirs(ppd)
if os.path.isfile(pp) and overwrite != 'yes':
if o == 'con':
ck.out(
'File '+dx+' already exists in the entry - skipping ...')
else:
fo = open(pp, 'wb')
fo.write(z.read(dx))
fo.close()
f.close()
if rm_zip:
os.remove(zp)
return {'return': 0}
##############################################################################
# import repo from current path
def import_repo(i):
"""
Input: {
See action 'add' where import=yes
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
i['import'] = 'yes'
return add(i)
##############################################################################
# resolve dependencies for a repo
def deps(i):
"""
Input: {
(data_uoa) - repo UOA
or
(path) - path to .cmr.json
(current_repos) - list of repos being updated (to avoid infinite recursion)
(how) - 'pull' (default) or 'add'
(version) - checkout version (default - stable)
(branch) - git branch
(checkout) - git checkout
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
import os
o = i.get('out', '')
duoa = i.get('data_uoa', '')
if ck.cfg.get('force_lower', '') == 'yes':
duoa = duoa.lower()
# Added repos to avoid duplication/recursion
cr = i.get('current_repos', [])
how = i.get('how', '')
if how == '':
how = 'pull'
p = i.get('path', '')
if p == '':
r = ck.access({'action': 'load',
'module_uoa': work['self_module_uoa'],
'data_uoa': duoa})
if r['return'] > 0:
return r
dr = r['dict']
p = dr.get('path', '')
if p != '':
# path to repo description
pp = os.path.join(p, ck.cfg['repo_file'])
if os.path.isfile(pp):
r = ck.load_json_file({'json_file': pp})
if r['return'] > 0:
return r
d = r['dict']
# Check checkouts
version = i.get('version', '')
branch = i.get('branch', '')
checkout = i.get('checkout', '')
if version != '':
cx = d.get('dict', {}).get('checkouts', {}).get(version, {})
branch = cx.get('branch', '')
checkout = cx.get('checkout', '')
ppp = os.getcwd()
os.chdir(p)
if branch != '':
if o == 'con':
ck.out(' ====================================')
ck.out(' git checkout '+branch)
ck.out('')
r = ck.run_and_get_stdout({'cmd': ['git', 'checkout', branch]})
ck.out(r.get('stdout', ''))
ck.out(r.get('stderr', ''))
if checkout != '':
if o == 'con':
ck.out(' ====================================')
ck.out(' git checkout '+checkout)
ck.out('')
r = ck.run_and_get_stdout(
{'cmd': ['git', 'checkout', checkout]})
ck.out(r.get('stdout', ''))
ck.out(r.get('stderr', ''))
os.chdir(ppp)
rp1 = d.get('dict', {}).get('repo_deps', [])
if len(rp1) == 0:
rp1 = d.get('repo_deps', []) # for backwards compatibility ...
rp2 = []
rp = []
if len(rp1) > 0:
for xruoa in rp1:
if type(xruoa) != list: # for backwards compatibility
ruoa = xruoa.get('repo_uoa', '')
if xruoa.get('repo_uid', '') != '':
ruoa = xruoa['repo_uid']
if ruoa != '' and ruoa not in cr:
rp2.append(xruoa)
# Add dependencies on other repositories (but avoid duplication)
if len(rp2) == 0:
if o == 'con':
ck.out(' No dependencies on other repositories found!')
else:
for xruoa in rp2:
ruoa = xruoa.get('repo_uoa', '')
if xruoa.get('repo_uid', '') != '':
ruoa = xruoa['repo_uid']
rurl = xruoa.get('repo_url', '')
if ruoa != '':
x = ' Dependency on repository '+ruoa+' '
# Check if this repo exists
r = ck.access({'action': 'load',
'module_uoa': work['self_module_uoa'],
'data_uoa': ruoa})
if r['return'] > 0:
if r['return'] != 16:
return r
rp.append(xruoa)
x += ': should be resolved ...'
else:
# If explicit branch, still add !
branch = xruoa.get('branch', '')
checkout = xruoa.get('checkout', '')
stable = xruoa.get('stable', '')
version = xruoa.get('version', '')
if branch != '' or checkout != '' or stable != '' or version != '':
xruoa['ignore_pull'] = 'yes'
rp.append(xruoa)
x += ': should be switched to explicit branch ...'
else:
x += ': Ok'
if o == 'con':
ck.out(x)
if len(rp) > 0:
for xruoa in rp:
ruoa = xruoa.get('repo_uoa', '')
ruid = xruoa.get('repo_uid', '')
rurl = xruoa.get('repo_url', '')
branch = xruoa.get('branch', '')
checkout = xruoa.get('checkout', '')
stable = xruoa.get('stable', '')
version = xruoa.get('version', '')
ignore_pull = xruoa.get('ignore_pull', '')
if o == 'con':
ck.out('')
x = ''
if ruid != '':
x = ' ('+ruid+')'
ck.out(' Resolving dependency on repo: '+ruoa+x)
ck.out('')
if ruid != '':
cr.append(ruid)
else:
cr.append(ruoa)
ii = {'action': how,
'module_uoa': work['self_module_uoa'],
'data_uoa': ruoa,
'current_repos': cr,
'url': rurl,
'ignore_pull': ignore_pull,
'branch': branch,
'checkout': checkout,
'stable': stable,
'version': version,
'out': o}
if ruid != '':
ii['data_uid'] = ruid
if how == 'add':
ii['gitzip'] = 'yes'
r = ck.access(ii)
if r['return'] > 0:
return r
return {'return': 0, 'current_repos': cr}
##############################################################################
# print dependencies on other shared repositories
def print_deps(i):
"""
Input: {
data_uoa - data UOA of the repo
or
repo_deps - dict with dependencies on other shared repos
(out_prefix) - output prefix befor each string
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
repo_deps
}
"""
o = i.get('out', '')
op = i.get('out_prefix', '')
duoa = i.get('data_uoa', '')
if duoa != '':
# Get configuration
r = ck.load_repo_info_from_cache({'repo_uoa': duoa})
if r['return'] > 0:
return r
d = r['dict']
rp1 = d.get('dict', {}).get('repo_deps', [])
else:
rp1 = i['repo_deps']
if len(rp1) == 0:
rp1 = d.get('repo_deps', []) # for compatibility ...
if o == 'con' and len(rp1) > 0:
for q in rp1:
ruoa = q.get('repo_uoa', '')
ruid = q.get('repo_uid', '')
rurl = q.get('repo_url', '')
x = op+ruoa
if ruid != '':
x += '; '+ruid
elif rurl != '':
x += '; '
if rurl != '':
x += '; '+rurl
ck.out(x)
return {'return': 0, 'repo_deps': rp1}
##############################################################################
# add more dependencies
def add_more_deps(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
repo_deps - list with dependencies | |
= ssl_ca_certs
# Keep track of resets, so we notice sockets created before the most
# recent reset and close them.
self.pool_id = 0
if HAS_SSL and use_ssl and not ssl_cert_reqs:
self.ssl_cert_reqs = ssl.CERT_NONE
self.motor_sock_counter = 0
self.queue = collections.deque()
# Timeout handles to expire waiters after wait_queue_timeout.
self.waiter_timeouts = {}
if self.wait_queue_multiple is None:
self.max_waiters = None
else:
self.max_waiters = self.max_size * self.wait_queue_multiple
def reset(self):
self.pool_id += 1
sockets, self.sockets = self.sockets, set()
for sock_info in sockets:
sock_info.close()
def resolve(self, host, port, family):
"""Return list of (family, address) pairs."""
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Should be on child greenlet"
def handler(exc_typ, exc_val, exc_tb):
# If netutil.Resolver is configured to use TwistedResolver.
if DomainError and issubclass(exc_typ, DomainError):
exc_typ = socket.gaierror
exc_val = socket.gaierror(str(exc_val))
# Depending on the resolver implementation, we could be on any
# thread or greenlet. Return to the loop's thread and raise the
# exception on the calling greenlet from there.
self.io_loop.add_callback(functools.partial(
child_gr.throw, exc_typ, exc_val, exc_tb))
return True # Don't propagate the exception.
with stack_context.ExceptionStackContext(handler):
self.resolver.resolve(host, port, family, callback=child_gr.switch)
return main.switch()
def create_connection(self):
"""Connect and return a socket object.
"""
host, port = self.pair
# Check if dealing with a unix domain socket
if host.endswith('.sock'):
if not hasattr(socket, "AF_UNIX"):
raise pymongo.errors.ConnectionFailure(
"UNIX-sockets are not supported on this system")
addrinfos = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, host)]
else:
# Don't try IPv6 if we don't support it. Also skip it if host
# is 'localhost' (::1 is fine). Avoids slow connect issues
# like PYTHON-356.
family = socket.AF_INET
if socket.has_ipv6 and host != 'localhost':
family = socket.AF_UNSPEC
# resolve() returns list of (family, address) pairs.
addrinfos = [
(af, socket.SOCK_STREAM, 0, sa) for af, sa in
self.resolve(host, port, family)]
err = None
for res in addrinfos:
af, socktype, proto, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
motor_sock = MotorSocket(
sock, self.io_loop, use_ssl=self.use_ssl,
certfile=self.ssl_certfile, keyfile=self.ssl_keyfile,
ca_certs=self.ssl_ca_certs, cert_reqs=self.ssl_cert_reqs)
if af != getattr(socket, 'AF_UNIX', None):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
motor_sock.settimeout(self.conn_timeout or 20.0)
# Important to increment the count before beginning to connect.
self.motor_sock_counter += 1
# MotorSocket pauses this greenlet and resumes when connected.
motor_sock.connect(sa, server_hostname=host)
return motor_sock
except socket.error as e:
self.motor_sock_counter -= 1
err = e
if sock is not None:
sock.close()
if err is not None:
raise err
else:
# This likely means we tried to connect to an IPv6 only
# host with an OS/kernel or Python interpreter that doesn't
# support IPv6. The test case is Jython2.5.1 which doesn't
# support IPv6 at all.
raise socket.error('getaddrinfo failed')
def connect(self):
"""Connect to Mongo and return a new connected MotorSocket. Note that
the pool does not keep a reference to the socket -- you must call
maybe_return_socket() when you're done with it.
"""
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Should be on child greenlet"
if self.max_size and self.motor_sock_counter >= self.max_size:
if self.max_waiters and len(self.queue) >= self.max_waiters:
raise self._create_wait_queue_timeout()
waiter = stack_context.wrap(child_gr.switch)
self.queue.append(waiter)
if self.wait_queue_timeout is not None:
deadline = self.io_loop.time() + self.wait_queue_timeout
timeout = self.io_loop.add_timeout(
deadline,
functools.partial(
child_gr.throw,
pymongo.errors.ConnectionFailure,
self._create_wait_queue_timeout()))
self.waiter_timeouts[waiter] = timeout
# Yield until maybe_return_socket passes spare socket in.
return main.switch()
else:
motor_sock = self.create_connection()
motor_sock.settimeout(self.net_timeout)
return SocketInfo(motor_sock, self.pool_id, self.pair[0])
def get_socket(self, force=False):
"""Get a socket from the pool.
Returns a :class:`SocketInfo` object wrapping a connected
:class:`MotorSocket`, and a bool saying whether the socket was from
the pool or freshly created.
:Parameters:
- `force`: optional boolean, forces a connection to be returned
without blocking, even if `max_size` has been reached.
"""
forced = False
if force:
# If we're doing an internal operation, attempt to play nicely with
# max_size, but if there is no open "slot" force the connection
# and mark it as forced so we don't decrement motor_sock_counter
# when it's returned.
if self.motor_sock_counter >= self.max_size:
forced = True
if self.sockets:
sock_info, from_pool = self.sockets.pop(), True
sock_info = self._check(sock_info)
else:
sock_info, from_pool = self.connect(), False
sock_info.forced = forced
sock_info.last_checkout = time.time()
return sock_info
def start_request(self):
raise NotImplementedError("Motor doesn't implement requests")
in_request = end_request = start_request
def discard_socket(self, sock_info):
"""Close and discard the active socket."""
if sock_info:
sock_info.close()
def maybe_return_socket(self, sock_info):
"""Return the socket to the pool.
In PyMongo this method only returns the socket if it's not the request
socket, but Motor doesn't do requests.
"""
if not sock_info:
return
if sock_info.closed:
if not sock_info.forced:
self.motor_sock_counter -= 1
return
# Give it to the greenlet at the head of the line, or return it to the
# pool, or discard it.
if self.queue:
waiter = self.queue.popleft()
if waiter in self.waiter_timeouts:
self.io_loop.remove_timeout(self.waiter_timeouts.pop(waiter))
with stack_context.NullContext():
self.io_loop.add_callback(functools.partial(waiter, sock_info))
elif (len(self.sockets) < self.max_size
and sock_info.pool_id == self.pool_id):
self.sockets.add(sock_info)
else:
sock_info.close()
if not sock_info.forced:
self.motor_sock_counter -= 1
if sock_info.forced:
sock_info.forced = False
def _check(self, sock_info):
"""This side-effecty function checks if this pool has been reset since
the last time this socket was used, or if the socket has been closed by
some external network error, and if so, attempts to create a new socket.
If this connection attempt fails we reset the pool and reraise the
error.
Checking sockets lets us avoid seeing *some*
:class:`~pymongo.errors.AutoReconnect` exceptions on server
hiccups, etc. We only do this if it's been > 1 second since
the last socket checkout, to keep performance reasonable - we
can't avoid AutoReconnects completely anyway.
"""
error = False
if sock_info.closed:
error = True
elif self.pool_id != sock_info.pool_id:
sock_info.close()
error = True
elif time.time() - sock_info.last_checkout > 1:
if _closed(sock_info.sock):
sock_info.close()
error = True
if not error:
return sock_info
else:
try:
return self.connect()
except socket.error:
self.reset()
raise
def __del__(self):
# Avoid ResourceWarnings in Python 3.
for sock_info in self.sockets:
sock_info.close()
self.resolver.close()
def _create_wait_queue_timeout(self):
return pymongo.errors.ConnectionFailure(
'Timed out waiting for socket from pool with max_size %r and'
' wait_queue_timeout %r' % (
self.max_size, self.wait_queue_timeout))
def motor_coroutine(f):
"""A coroutine that accepts an optional callback.
Given a callback, the function returns None, and the callback is run
with (result, error). Without a callback the function returns a Future.
"""
coro = gen.coroutine(f)
@functools.wraps(f)
def wrapper(*args, **kwargs):
callback = kwargs.pop('callback', None)
if callback and not callable(callback):
raise callback_type_error
future = coro(*args, **kwargs)
if callback:
def _callback(future):
try:
result = future.result()
callback(result, None)
except Exception as e:
callback(None, e)
future.add_done_callback(_callback)
else:
return future
return wrapper
def mangle_delegate_name(motor_class, name):
if name.startswith('__') and not name.endswith("__"):
# Mangle, e.g. Cursor.__die -> Cursor._Cursor__die
classname = motor_class.__delegate_class__.__name__
return '_%s%s' % (classname, name)
else:
return name
def asynchronize(motor_class, sync_method, has_write_concern, doc=None):
"""Decorate `sync_method` so it accepts a callback or returns a Future.
The method runs on a child greenlet and calls the callback or resolves
the Future when the greenlet completes.
:Parameters:
- `motor_class`: Motor class being created, e.g. MotorClient.
- `sync_method`: Unbound method of pymongo Collection, Database,
MongoClient, or Cursor
- `has_write_concern`: Whether the method accepts getLastError options
- `doc`: Optionally override sync_method's docstring
"""
@functools.wraps(sync_method)
def method(self, *args, **kwargs):
check_deprecated_kwargs(kwargs)
loop = self.get_io_loop()
callback = kwargs.pop('callback', None)
if callback:
if not callable(callback):
raise callback_type_error
future = None
else:
future = TracebackFuture()
def call_method():
# Runs on child greenlet.
try:
result = sync_method(self.delegate, *args, **kwargs)
if callback:
# Schedule callback(result, None) on main greenlet.
loop.add_callback(functools.partial(
callback, result, None))
else:
# Schedule future to be resolved on main greenlet.
loop.add_callback(functools.partial(
future.set_result, result))
except Exception as e:
if callback:
loop.add_callback(functools.partial(
callback, None, e))
else:
loop.add_callback(functools.partial(
future.set_exc_info, sys.exc_info()))
# Schedule the operation on a greenlet.
loop.add_callback(greenlet.greenlet(call_method).switch)
return future
# This is for the benefit of motor_extensions.py, which needs this info to
# generate documentation with Sphinx.
method.is_async_method = True
method.has_write_concern = has_write_concern
name = sync_method.__name__
method.pymongo_method_name = mangle_delegate_name(motor_class, name)
if doc is not None:
method.__doc__ = doc
return method
class MotorAttributeFactory(object):
"""Used by Motor classes to mark attributes that delegate in some way to
PyMongo. At module import time, each Motor class is created, and MotorMeta
calls create_attribute() for each attr | |
rho, n.in_units("kg/m**3", equivalence="number_density", mu=0.75)
)
rho.convert_to_units("cm**-3", "number_density", mu=0.75)
assert rho.units == (1 / u.cm ** 3).units
assert n.units == (1 / u.m ** 3).units
assert_allclose_units(n, rho)
rho.convert_to_units("kg/m**3", "number_density", mu=0.75)
assert_allclose_units(u.mp / u.m ** 3, rho)
assert rho.units == (u.kg / u.m ** 3).units
# Effective temperature
T = 1e4 * u.K
F = T.in_units("W/m**2", equivalence="effective_temperature")
assert_allclose_units(F, u.stefan_boltzmann_constant * T ** 4)
assert_allclose_units(T, F.in_units("K", equivalence="effective_temperature"))
T.convert_to_units("erg/s/cm**2", "effective_temperature")
assert_allclose_units(T, F)
assert T.units == u.Unit("erg/cm**2/s")
assert F.units == u.W / u.m ** 2
assert_almost_equal(T.in_units("K", "effective_temperature").value, 1e4)
T.convert_to_units("K", "effective_temperature")
assert_almost_equal(T.value, 1e4)
assert T.units == u.K
# to_value test
assert_allclose_units(
F.value, T.to_value("W/m**2", equivalence="effective_temperature")
)
assert_allclose_units(
n.value, rho.to_value("m**-3", equivalence="number_density", mu=0.75)
)
def test_electromagnetic():
import unyt as u
# Various tests of SI and CGS electromagnetic units
t = 1.0 * u.Tesla
g = 1.0 * u.gauss
assert t.to("gauss") == 1e4 * u.gauss
assert g.to("T") == 1e-4 * u.Tesla
assert t.in_mks() == t
assert g.in_cgs() == g
t.convert_to_mks()
assert t == 1.0 * u.Tesla
g.convert_to_cgs()
assert g == 1.0 * u.gauss
qp_mks = u.qp_cgs.in_units("C")
assert_equal(qp_mks.units.dimensions, dimensions.charge_mks)
assert_almost_equal(qp_mks.v, 10.0 * u.qp.v / speed_of_light_cm_per_s)
qp = 1.0 * u.qp_cgs
assert_equal(qp, u.qp_cgs.in_units("esu"))
qp.convert_to_units("C")
assert_equal(qp.units.dimensions, dimensions.charge_mks)
assert_almost_equal(qp.v, 10 * u.qp.v / u.clight.v)
qp_cgs = u.qp.in_units("esu")
assert_array_almost_equal(qp_cgs, u.qp_cgs)
assert_equal(qp_cgs.units.dimensions, u.qp_cgs.units.dimensions)
qp = u.qp.copy()
qp.convert_to_units("esu")
assert_almost_equal(qp_cgs, qp_cgs)
assert qp.units == u.esu.units
qp.convert_to_units("C")
assert_almost_equal(u.qp, qp)
assert qp.units == u.C.units
qp_mks_k = u.qp_cgs.in_units("kC")
assert_array_almost_equal(qp_mks_k.v, 1.0e-2 * u.qp_cgs.v / speed_of_light_cm_per_s)
qp = 1.0 * u.qp_cgs
qp.convert_to_units("kC")
assert_almost_equal(qp, qp_mks_k)
B = 1.0 * u.T
B_cgs = B.in_units("gauss")
assert_equal(B.units.dimensions, dimensions.magnetic_field_mks)
assert_equal(B_cgs.units.dimensions, dimensions.magnetic_field_cgs)
assert_array_almost_equal(B_cgs, unyt_quantity(1.0e4, "gauss"))
B_cgs = B.in_cgs()
assert_equal(B.units.dimensions, dimensions.magnetic_field_mks)
assert_equal(B_cgs.units.dimensions, dimensions.magnetic_field_cgs)
assert_array_almost_equal(B_cgs, unyt_quantity(1.0e4, "gauss"))
B_cgs = B.in_base("cgs")
assert_equal(B.units.dimensions, dimensions.magnetic_field_mks)
assert_equal(B_cgs.units.dimensions, dimensions.magnetic_field_cgs)
assert_array_almost_equal(B_cgs, unyt_quantity(1.0e4, "gauss"))
B.convert_to_cgs()
assert_almost_equal(B, B_cgs)
B.convert_to_mks()
B_cgs2 = B.to("gauss")
assert_almost_equal(B_cgs, B_cgs2)
B_mks2 = B_cgs2.to("T")
assert_almost_equal(B, B_mks2)
B = 1.0 * u.T
u_mks = B * B / (2 * u.mu_0)
assert_equal(u_mks.units.dimensions, dimensions.pressure)
u_cgs = B_cgs * B_cgs / (8 * np.pi)
assert_equal(u_mks, u_cgs.to(u_mks.units))
assert_equal(u_mks.to(u_cgs.units), u_cgs)
assert_equal(u_mks.in_cgs(), u_cgs)
assert_equal(u_cgs.in_mks(), u_mks)
current = 1.0 * u.A
I_cgs = current.in_units("statA")
assert_array_almost_equal(
I_cgs, unyt_quantity(0.1 * speed_of_light_cm_per_s, "statA")
)
assert_array_almost_equal(I_cgs.in_units("mA"), current.in_units("mA"))
assert_equal(I_cgs.units.dimensions, dimensions.current_cgs)
current.convert_to_units("statA")
assert current.units == u.statA.units
current.convert_to_units("A")
assert current.units == u.A.units
I_cgs2 = current.to("statA")
assert I_cgs2.units == u.statA.units
assert_array_almost_equal(
I_cgs2, unyt_quantity(0.1 * speed_of_light_cm_per_s, "statA")
)
current = 1.0 * u.A
R = unyt_quantity(1.0, "ohm")
R_cgs = R.in_units("statohm")
P_mks = current * current * R
P_cgs = I_cgs * I_cgs * R_cgs
assert_equal(P_mks.units.dimensions, dimensions.power)
assert_equal(P_cgs.units.dimensions, dimensions.power)
assert_almost_equal(P_cgs.in_cgs(), P_cgs)
assert_almost_equal(P_mks.in_cgs(), P_cgs)
assert_almost_equal(P_cgs.in_mks(), P_mks)
assert_almost_equal(P_mks.in_mks(), P_mks)
V = unyt_quantity(1.0, "statV")
V_mks = V.in_units("V")
assert_array_almost_equal(V_mks.v, 1.0e8 * V.v / speed_of_light_cm_per_s)
data = 1.0 * u.C * u.T * u.V
with pytest.raises(UnitConversionError):
data.to("statC*G*statV")
with pytest.raises(UnitConversionError):
data.convert_to_units("statC*G*statV")
with pytest.raises(UnitsNotReducible):
data.in_cgs()
data = 1.0 * u.statC * u.G * u.statV
with pytest.raises(UnitConversionError):
data.to("C*T*V")
with pytest.raises(UnitConversionError):
data.convert_to_units("C*T*V")
assert_almost_equal(data.in_mks(), 6.67408e-18 * u.m ** 5 / u.s ** 4)
mu_0 = 4.0e-7 * math.pi * u.N / u.A ** 2
eps_0 = 8.85418781782e-12 * u.m ** -3 / u.kg * u.s ** 4 * u.A ** 2
assert_almost_equal((1.0 / (u.clight ** 2 * mu_0)).in_units(eps_0.units), eps_0)
def test_ytarray_coercion():
a = unyt_array([1, 2, 3], "cm")
q = unyt_quantity(3, "cm")
na = np.array([1, 2, 3])
assert_isinstance(a * q, unyt_array)
assert_isinstance(q * na, unyt_array)
assert_isinstance(q * 3, unyt_quantity)
assert_isinstance(q * np.float64(3), unyt_quantity)
assert_isinstance(q * np.array(3), unyt_quantity)
def test_numpy_wrappers():
a1 = unyt_array([1, 2, 3], "cm")
a2 = unyt_array([2, 3, 4, 5, 6], "cm")
a3 = unyt_array([[1, 2, 3], [4, 5, 6]], "cm")
a4 = unyt_array([7, 8, 9, 10, 11], "cm")
catenate_answer = [1, 2, 3, 2, 3, 4, 5, 6]
intersect_answer = [2, 3]
union_answer = [1, 2, 3, 4, 5, 6]
vstack_answer = [[2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]
vstack_answer_last_axis = [[2, 7], [3, 8], [4, 9], [5, 10], [6, 11]]
cross_answer = [-2, 4, -2]
norm_answer = np.sqrt(1 ** 2 + 2 ** 2 + 3 ** 2)
arr_norm_answer = [norm_answer, np.sqrt(4 ** 2 + 5 ** 2 + 6 ** 2)]
dot_answer = 14
assert_array_equal(unyt_array(catenate_answer, "cm"), uconcatenate((a1, a2)))
assert_array_equal(catenate_answer, np.concatenate((a1, a2)))
assert_array_equal(unyt_array(intersect_answer, "cm"), uintersect1d(a1, a2))
assert_array_equal(intersect_answer, np.intersect1d(a1, a2))
assert_array_equal(unyt_array(union_answer, "cm"), uunion1d(a1, a2))
assert_array_equal(union_answer, np.union1d(a1, a2))
assert_array_equal(
unyt_array(cross_answer, "cm**2"), ucross(a1, a1 + (2 * a1.units))
)
assert_array_equal(cross_answer, np.cross(a1.v, a1.v + 2))
assert_array_equal(unorm(a1), unyt_quantity(norm_answer, "cm"))
assert_array_equal(np.linalg.norm(a1), norm_answer)
assert_array_equal(unorm(a3, axis=1), unyt_array(arr_norm_answer, "cm"))
assert_array_equal(np.linalg.norm(a3, axis=1), arr_norm_answer)
assert_array_equal(udot(a1, a1), unyt_quantity(dot_answer, "cm**2"))
assert_array_equal(np.array(catenate_answer), uconcatenate((a1.v, a2.v)))
with pytest.raises(RuntimeError):
uconcatenate((a1, a2.v))
with pytest.raises(RuntimeError):
uconcatenate((a1.to("m"), a2))
assert_array_equal(unyt_array(vstack_answer, "cm"), uvstack([a2, a4]))
assert_array_equal(vstack_answer, np.vstack([a2, a4]))
assert_array_equal(unyt_array(vstack_answer, "cm"), ustack([a2, a4]))
assert_array_equal(vstack_answer, np.stack([a2, a4]))
assert_array_equal(
unyt_array(vstack_answer_last_axis, "cm"), ustack([a2, a4], axis=-1)
)
assert_array_equal(vstack_answer_last_axis, np.stack([a2, a4], axis=-1))
def test_dimensionless_conversion():
a = unyt_quantity(1, "Zsun")
b = a.in_units("Zsun")
a.convert_to_units("Zsun")
assert a.units.base_value == metallicity_sun
assert b.units.base_value == metallicity_sun
def test_modified_unit_division():
reg1 = UnitRegistry()
reg2 = UnitRegistry()
reg1.modify("g", 50)
a = unyt_quantity(3, "g", registry=reg1)
b = unyt_quantity(3, "g", registry=reg2)
ret = a / b
assert ret == 50000.0
assert ret.units.is_dimensionless
assert ret.units.base_value == 1.0
def test_loadtxt_and_savetxt():
tmpdir = tempfile.mkdtemp()
curdir = os.getcwd()
os.chdir(tmpdir)
a = unyt_array(np.random.random(10), "kpc")
b = unyt_array(np.random.random(10), "Msun")
c = unyt_array(np.random.random(10), "km/s")
savetxt("arrays.dat", [a, b, c], delimiter=",")
d, e = loadtxt("arrays.dat", usecols=(1, 2), delimiter=",")
assert_array_equal(b, d)
assert_array_equal(c, e)
# adding newlines to the file doesn't matter
savetxt("arrays.dat", [a, b, c], delimiter=",")
with open("arrays.dat", "r+") as f:
content = f.read()
f.seek(0, 0)
f.write("\n" + content)
d, e = loadtxt("arrays.dat", usecols=(1, 2), delimiter=",")
assert_array_equal(b, d)
assert_array_equal(c, e)
# data saved by numpy savetxt are loaded without units
np.savetxt("arrays.dat", np.squeeze(np.transpose([a.v, b.v, c.v])), delimiter=",")
d, e = loadtxt("arrays.dat", usecols=(1, 2), delimiter=",")
assert_array_equal(b.v, d)
assert_array_equal(c.v, e)
# save a single array
savetxt("arrays.dat", a)
d = loadtxt("arrays.dat")
assert_array_equal(a, d)
# save an array with no units and an array with units with a header
savetxt("arrays.dat", [a.v, b], header="this is a header!")
d, e = loadtxt("arrays.dat")
assert_array_equal(a.v, d)
assert_array_equal(b, e)
os.chdir(curdir)
shutil.rmtree(tmpdir)
def test_trig_ufunc_degrees():
for ufunc in (np.sin, np.cos, np.tan):
degree_values = np.random.random(10) * degree
radian_values = degree_values.in_units("radian")
assert_array_equal(ufunc(degree_values), ufunc(radian_values))
def test_builtin_sum():
from unyt import km
arr = [1, 2, 3] * km
assert_equal(sum(arr), 6 * km)
def test_initialization_different_registries():
reg1 = UnitRegistry()
reg2 = UnitRegistry()
reg1.add("code_length", 1.0, dimensions.length)
reg2.add("code_length", 3.0, dimensions.length)
l1 = unyt_quantity(1.0, "code_length", registry=reg1)
l2 = unyt_quantity(1.0, "code_length", registry=reg2)
assert_almost_equal(float(l1.in_mks()), 1.0)
assert_almost_equal(float(l2.in_mks()), 3.0)
def test_ones_and_zeros_like():
data = unyt_array([1, 2, 3], "cm")
zd = np.zeros_like(data)
od = np.ones_like(data)
assert_equal(zd, unyt_array([0, 0, 0], "cm"))
assert_equal(zd.units, data.units)
assert_equal(od, unyt_array([1, 1, 1], "cm"))
assert_equal(od.units, data.units)
def test_coerce_iterable():
from unyt import cm, km
a = unyt_array([1, 2, 3], "cm")
b = [1 * cm, 2 * km, 3 * cm]
with pytest.raises(IterableUnitCoercionError):
a + b
with pytest.raises(IterableUnitCoercionError):
b + a
with pytest.raises(IterableUnitCoercionError):
unyt_array(b)
def test_bypass_validation():
from unyt import unyt_array, cm, UnitRegistry
obj = unyt_array(np.array([1.0, 2.0, 3.0]), cm, bypass_validation=True)
assert obj.units is cm
reg = UnitRegistry()
obj = unyt_array(
np.array([1.0, 2.0, 3.0]), cm, registry=reg, bypass_validation=True
)
assert obj.units == cm
assert obj.units.registry is reg
def test_creation():
from unyt import cm, UnitRegistry
data = [1, 2, 3] * cm
new_data = unyt_array(data)
assert new_data.units is cm
assert_array_equal(new_data.v, np.array([1, 2, 3], dtype="float64"))
reg = UnitRegistry()
new_data = unyt_array(data, registry=reg)
assert_array_equal(new_data.v, np.array([1, 2, 3], dtype="float64"))
assert new_data.units is not cm
assert new_data.units == cm
assert new_data.units.registry is reg
new_data = unyt_array([1, 2, 3], cm)
assert_array_equal(new_data.v, np.array([1, 2, 3], dtype="float64"))
assert new_data.units is cm
new_data = unyt_array([1, 2, 3], cm, registry=reg)
assert_array_equal(new_data.v, np.array([1, 2, 3], dtype="float64"))
assert new_data.units is not cm
assert new_data.units == cm
assert new_data.units.registry is reg
with pytest.raises(RuntimeError):
unyt_quantity("hello", "cm")
with pytest.raises(RuntimeError):
unyt_quantity(np.array([1, 2, 3]), "cm")
def test_round():
from unyt import km
assert_equal(round(3.3 * km), 3.0)
assert_equal(round(3.5 * km), 4.0)
assert_equal(round(3 * km), 3)
assert_equal(round(3.7 * km), 4)
with pytest.raises(TypeError):
round([1, 2, 3] * km)
def test_integer_arrays():
from unyt import km, m, mile, ms, s
def integer_semantics(inp):
arr = inp * km
assert arr.dtype == np.int_
arr = np.array(inp, dtype="int32") * km
assert arr.dtype.name == "int32"
ret = arr.in_units("mile")
assert arr.dtype.name == "int32"
answer = (inp * km).astype("int32").to("mile")
assert_array_equal(ret, answer)
assert ret.dtype.name == "float32"
ret = arr.in_units("m")
assert arr.dtype != ret.dtype
assert ret.dtype.name == "float32"
arr.convert_to_units("m")
assert arr.dtype.name == "float32"
arr = inp * km
arr.convert_to_units("mile")
assert arr.dtype.name == | |
<reponame>WagnerNils/MMSplice_MTSplice
# import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Layer
from tensorflow.keras.layers import Conv1D
from tensorflow.keras.regularizers import Regularizer
from tensorflow.keras import initializers
import scipy.interpolate as si
DNA = ["A", "C", "G", "T"]
def normalize_data_format(value):
if value is None:
value = K.image_data_format()
data_format = value.lower()
if data_format not in {'channels_first', 'channels_last'}:
raise ValueError('The `data_format` argument must be one of '
'"channels_first", "channels_last". Received: ' +
str(value))
return data_format
class GlobalAveragePooling1D_Mask0(Layer):
"""
Global average pooling operation for temporal data.
Masking out 0-padded input.
"""
def __init__(self, data_format='channels_last', **kwargs):
super(GlobalAveragePooling1D_Mask0, self).__init__(**kwargs)
self.data_format = normalize_data_format(data_format)
def compute_output_shape(self, input_shape):
input_shape = input_shape[0]
if self.data_format == 'channels_first':
return (input_shape[0], input_shape[1])
else:
return (input_shape[0], input_shape[2])
def call(self, inputs):
inputs, model_inputs = inputs
steps_axis = 1 if self.data_format == 'channels_last' else 2
mask = K.max(model_inputs, axis=2, keepdims=True)
inputs *= mask
return K.sum(inputs, axis=steps_axis) / K.maximum(
K.sum(mask, axis=steps_axis), K.epsilon())
class ConvSequence(Conv1D):
VOCAB = DNA
def __init__(self,
filters,
kernel_size,
strides=1,
padding='valid',
dilation_rate=1,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
seq_length=None,
**kwargs):
# override input shape
if seq_length:
kwargs["input_shape"] = (seq_length, len(self.VOCAB))
kwargs.pop("batch_input_shape", None)
super(ConvSequence, self).__init__(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation_rate=dilation_rate,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
kernel_constraint=kernel_constraint,
bias_constraint=bias_constraint,
**kwargs)
self.seq_length = seq_length
def build(self, input_shape):
if int(input_shape[-1]) != len(self.VOCAB):
raise ValueError("{cls} requires input_shape[-1] == {n}. Given: {s}".
format(cls=self.__class__.__name__, n=len(self.VOCAB), s=input_shape[-1]))
return super(ConvSequence, self).build(input_shape)
def get_config(self):
config = super(ConvSequence, self).get_config()
config["seq_length"] = self.seq_length
return config
class ConvDNA(ConvSequence):
VOCAB = DNA
VOCAB_name = "DNA"
def get_S(n_bases=10, spline_order=3, add_intercept=True):
# mvcv R-code
# S<-diag(object$bs.dim);
# if (m[2]) for (i in 1:m[2]) S <- diff(S)
# object$S <- list(t(S)%*%S) # get penalty
# object$S[[1]] <- (object$S[[1]]+t(object$S[[1]]))/2 # exact symmetry
S = np.identity(n_bases)
m2 = spline_order - 1 # m[2] is the same as m[1] by default
# m2 order differences
for i in range(m2):
S = np.diff(S, axis=0) # same as diff() in R
S = np.dot(S.T, S)
S = (S + S.T) / 2 # exact symmetry
if add_intercept is True:
# S <- cbind(0, rbind(0, S)) # in R
zeros = np.zeros_like(S[:1, :])
S = np.vstack([zeros, S])
zeros = np.zeros_like(S[:, :1])
S = np.hstack([zeros, S])
return S.astype(np.float32)
def get_knots(start, end, n_bases=10, spline_order=3):
"""
Arguments:
x; np.array of dim 1
"""
x_range = end - start
start = start - x_range * 0.001
end = end + x_range * 0.001
# mgcv annotation
m = spline_order - 1
nk = n_bases - m # number of interior knots
dknots = (end - start) / (nk - 1)
knots = np.linspace(start=start - dknots * (m + 1),
stop=end + dknots * (m + 1),
num=nk + 2 * m + 2)
return knots.astype(np.float32)
def get_X_spline(x, knots, n_bases=10, spline_order=3, add_intercept=True):
"""
Returns:
np.array of shape [len(x), n_bases + (add_intercept)]
# BSpline formula
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.BSpline.html#scipy.interpolate.BSpline
Fortran code:
https://github.com/scipy/scipy/blob/v0.19.0/scipy/interpolate/fitpack/splev.f
"""
if len(x.shape) is not 1:
raise ValueError("x has to be 1 dimentional")
tck = [knots, np.zeros(n_bases), spline_order]
X = np.zeros([len(x), n_bases])
for i in range(n_bases):
vec = np.zeros(n_bases)
vec[i] = 1.0
tck[1] = vec
X[:, i] = si.splev(x, tck, der=0)
if add_intercept is True:
ones = np.ones_like(X[:, :1])
X = np.hstack([ones, X])
return X.astype(np.float32)
class BSpline():
"""Class for computing the B-spline funcions b_i(x) and
constructing the penality matrix S.
# Arguments
start: float or int; start of the region
end: float or int; end of the region
n_bases: int; number of spline bases
spline_order: int; spline order
# Methods
- **getS(add_intercept=False)** - Get the penalty matrix S
- Arguments
- **add_intercept**: bool. If true, intercept column is added to the returned matrix.
- Returns
- `np.array`, of shape `(n_bases + add_intercept, n_bases + add_intercept)`
- **predict(x, add_intercept=False)** - For some x, predict the bn(x) for each base
- Arguments
- **x**: np.array; Vector of dimension 1
- **add_intercept**: bool; If True, intercept column is added to the to the final array
- Returns
- `np.array`, of shape `(len(x), n_bases + (add_intercept))`
"""
def __init__(self, start=0, end=1, n_bases=10, spline_order=3):
self.start = start
self.end = end
self.n_bases = n_bases
self.spline_order = spline_order
self.knots = get_knots(self.start, self.end,
self.n_bases, self.spline_order)
self.S = get_S(self.n_bases, self.spline_order, add_intercept=False)
def __repr__(self):
return "BSpline(start={0}, end={1}, n_bases={2}, spline_order={3})".\
format(self.start, self.end, self.n_bases, self.spline_order)
def getS(self, add_intercept=False):
"""Get the penalty matrix S
Returns
np.array, of shape (n_bases + add_intercept, n_bases + add_intercept)
"""
S = self.S
if add_intercept is True:
# S <- cbind(0, rbind(0, S)) # in R
zeros = np.zeros_like(S[:1, :])
S = np.vstack([zeros, S])
zeros = np.zeros_like(S[:, :1])
S = np.hstack([zeros, S])
return S
def predict(self, x, add_intercept=False):
"""For some x, predict the bn(x) for each base
Arguments:
x: np.array; Vector of dimension 1
add_intercept: bool; should we add the intercept to the final array
Returns:
np.array, of shape (len(x), n_bases + (add_intercept))
"""
# sanity check
if x.min() < self.start:
raise Warning("x.min() < self.start")
if x.max() > self.end:
raise Warning("x.max() > self.end")
return get_X_spline(x=x,
knots=self.knots,
n_bases=self.n_bases,
spline_order=self.spline_order,
add_intercept=add_intercept)
def get_config(self):
return {"start": self.start,
"end": self.end,
"n_bases": self.n_bases,
"spline_order": self.spline_order
}
@classmethod
def from_config(cls, config):
return cls(**config)
class GAMRegularizer(Regularizer):
def __init__(self, n_bases=10, spline_order=3, l2_smooth=0., l2=0.):
"""Regularizer for GAM's
# Arguments
n_bases: number of b-spline bases
order: spline order (2 for quadratic, 3 for qubic splines)
l2_smooth: float; Smoothness penalty (penalize w' * S * w)
l2: float; L2 regularization factor - overall weights regularizer
"""
# convert S to numpy-array if it's a list
self.n_bases = n_bases
self.spline_order = spline_order
self.l2_smooth = K.cast_to_floatx(l2_smooth)
self.l2 = K.cast_to_floatx(l2)
# convert to K.constant
self.S = K.constant(
K.cast_to_floatx(
get_S(n_bases, spline_order, add_intercept=False)
))
def __call__(self, x):
# x.shape = (n_bases, n_spline_tracks)
# from conv: (kernel_width=1, n_bases, n_spline_tracks)
from_conv = len(K.int_shape(x)) == 3
if from_conv:
x = K.squeeze(x, 0)
n_spline_tracks = K.cast_to_floatx(K.int_shape(x)[1])
regularization = 0.
if self.l2:
regularization += K.sum(self.l2 * K.square(x)) / n_spline_tracks
if self.l2_smooth:
# https://keras.io/backend/#batch_dot
# equivalent to mean( diag(x' * S * x) )
regularization += self.l2_smooth * \
K.mean(K.batch_dot(x, K.dot(self.S, x), axes=1))
return regularization
def get_config(self):
# convert S to list()
return {'n_bases': self.n_bases,
'spline_order': self.spline_order,
'l2_smooth': float(self.l2_smooth),
'l2': float(self.l2),
}
class SplineWeight1D(Layer):
"""Up- or down-weight positions in the activation array of 1D convolutions:
`x^{out}_{ijk} = x^{in}_{ijk}* (1 + f_S^k(j)) \;,`
where f_S is the spline transformation.
# Arguments
n_bases: int; Number of spline bases used for the positional effect.
l2_smooth: (float) L2 regularization strength for the second
order differences in positional bias' smooth splines. (GAM smoothing regularization)
l2: (float) L2 regularization strength for the spline base coefficients.
use_bias: boolean; should we add a bias to the transition
bias_initializer: bias initializer - from `keras.initializers`
"""
def __name__(self):
return "SplineWeight1D"
def __init__(self,
# spline type
n_bases=10,
spline_degree=3,
share_splines=False,
# regularization
l2_smooth=0,
l2=0,
use_bias=False,
bias_initializer='zeros',
**kwargs):
self.n_bases = n_bases
self.spline_degree = spline_degree
self.share_splines = share_splines
self.l2 = l2
self.l2_smooth = l2_smooth
self.use_bias = use_bias
self.bias_initializer = initializers.get(bias_initializer)
super(SplineWeight1D, self).__init__(**kwargs)
def build(self, input_shape):
# input_shape = (None, steps, filters)
start = 0
end = int(input_shape[1])
filters = int(input_shape[2])
if self.share_splines:
n_spline_tracks = 1
else:
n_spline_tracks = filters
# setup the bspline object
self.bs = BSpline(start, end - 1,
n_bases=self.n_bases,
spline_order=self.spline_degree
)
# create X_spline,
self.positions = np.arange(end)
# shape = (end, self.n_bases)
self.X_spline = self.bs.predict(self.positions, add_intercept=False)
# convert to the right precision and K.constant
self.X_spline_K = K.constant(K.cast_to_floatx(self.X_spline))
# add weights - all set to 0
self.kernel = self.add_weight(shape=(self.n_bases, n_spline_tracks),
initializer='zeros',
name='kernel',
regularizer=GAMRegularizer(self.n_bases, self.spline_degree,
self.l2_smooth, self.l2),
trainable=True)
if self.use_bias:
self.bias = self.add_weight((n_spline_tracks, ),
initializer=self.bias_initializer,
name='bias',
regularizer=None)
# Be sure to call this somewhere!
super(SplineWeight1D, self).build(input_shape)
def call(self, x):
spline_track = K.dot(self.X_spline_K, self.kernel)
if self.use_bias:
spline_track = K.bias_add(spline_track, self.bias)
# if self.spline_exp:
# spline_track = K.exp(spline_track)
# else:
spline_track = spline_track + 1
# multiply together the two coefficients
output = spline_track * x
return output
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
config = {
'n_bases': self.n_bases,
'spline_degree': self.spline_degree,
'share_splines': self.share_splines,
# 'spline_exp': self.spline_exp,
'l2_smooth': self.l2_smooth,
'l2': self.l2,
'use_bias': self.use_bias,
'bias_initializer': initializers.serialize(self.bias_initializer),
}
base_config = super(SplineWeight1D, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def positional_effect(self):
w = self.get_weights()[0]
pos_effect = np.dot(self.X_spline, w)
| |
import os
from os import system as sys
from socket import socket
import idna
from flask import Flask, request, redirect, render_template, jsonify
from backend import vtscan, certcheck, httpscheck,checkReditect,checkTrustedCert
import config
app = Flask(__name__)
app.secret_key = "secret key";
app.config['MAX_CONTENT_LENGTH'] = 350 * 1024 * 1024;
vtscan_bool=False
if config.VTAPIKEY == "YOU_NEED_TO_ENTER_YOUR_API_KEY_HERE_FOR_VIRUSTOTAL_SCAN_TO_WORK":
vtscan_bool=False
else:
vtscan_bool=True
@app.route('/')
def rootdir():
# sys("rm ./templates/result.html")
# return 'test'
# return render_template('main.html')
data="SAMPARK API"
return data
@app.route('/inbuilt')
def alternate():
sys("rm ./templates/result.html")
return render_template('main.html')
@app.route('/legacyport', methods=['POST'])
def legacy():
global urlts
urlts=""
if request.method == 'POST':
# check if the post request has the file part
if 'urlts' not in request.values:
# flash('No file part')
return redirect(request.url)
url = request.values['urlts']
agent=""
if "@shell" in str(url):
agent="shell"
url=str(url)[:-6]
print(request.values['urlts'])
return legacy_processurl(url,agent)
@app.route('/scan', methods=['GET','POST'])
def urlrequest():
# global urlts
# urlts=""
if request.method == 'POST':
# check if the post request has the file part
if 'urlts' not in request.values:
return "MALFORMED Request"
url = request.values['urlts']
# agent=""
# if "@shell" in str(url):
# agent="shell"
# url=str(url)[:-6]
if url[len(url)-1]=='/':
url=url[0:len(url)-1]
print(request.values['urlts'])
data=processurl(url)
return jsonify(data)
if request.method == 'GET':
if 'urlts' not in request.values:
return "MALFORMED Request"
url = request.values['urlts']
if url[len(url)-1]=='/':
url=url[0:len(url)-1]
print(request.values['urlts'])
data=processurl(url)
return jsonify(data)
def processurl(urltsm):
urltsm=httpscheck.rmrf_protocol(urltsm)
#ASSUME NOT SAFE AS DEFAULT
ISWEBSITESAFE = False
CERTSCORE = "DANGER" # THIS WILL MAKE IT NOT SAFE BY DEFAULT
ISHTTPS="NO"
REDIRECTIONSCORE="NA"
REASON = {
'https': "The website uses HTTPS. It's needed to transmit data securely.",
'certtrust': "The certificate for encryption is not provided by trusted Certification Authority. An attacker can forge a certificate and decrypt the data from HTTPS over SSL, making HTTPS insecure.",
'malware': "This website is not reported for malicious scripts.",
'redir': "Redirection is how a website navigates the user to HTTPS even if they try to visit from HTTP on its own.",
'covred': "The website does not contain redirection code.",
'overall': "",
'webstat': "Website Available"
}
if vtscan_bool:
RESULT=vtscan.getResult(config.VTAPIKEY,urltsm)
MALWARESCORE = RESULT['positives']
TRIGGERS=[]
MALHITS=[]
if MALWARESCORE > 0:
REASON['overall']=REASON['overall']+" * MALWARE HIT"
REASON['malware']= "This website is reported to contain malicious scripts or tools, or it is created with malicious intent. BE CAUTIOUS. An adversary can take advantage and steal your data."
ISWEBSITESAFE= False
if MALWARESCORE > 0:
for i in RESULT['scans']:
if RESULT['scans'][i]['detected'] == True:
TRIGGERS.append(i)
MALHITS.append(RESULT['scans'][i]['result'])
else:
TRIGGERS=[]
MALHITS=[]
TRIGGERS.append("--")
MALHITS.append("--")
REASON['malware']="VirusTotal API key not used, skipping malware scan."
hostname_idna = idna.encode(urltsm)
sock = socket()
ERROR404=False
try:
sock.connect((hostname_idna, 80))
MARK =1
except Exception:
MARK=-1
if MARK > 0:
REDIRECTIONSCORE=checkReditect.scan(urltsm)
HTTPSBOOL = httpscheck.scan(urltsm)
HTTPSBOOL = HTTPSBOOL.split(';')
ISHTTPS = HTTPSBOOL[0]
if HTTPSBOOL[1] == 'SR':
REDIRECTSCHEME = "SOFT REDIRECTION TO HTTPS"
elif HTTPSBOOL[1] == 'HR':
REDIRECTSCHEME = "HARD REDIRECTION TO HTTPS"
else:
REDIRECTSCHEME = "NO REDIRECT"
### CHECKING RESULTS
# print("NO" in ISHTTPS)
if "NO" in ISHTTPS:
print("http hit")
REASON['https']="The website do not use HTTPS. It's needed to transmit data securely."
REASON['overall'] = REASON['overall'] + " * HTTP HIT"
ISWEBSITESAFE = False
if REDIRECTIONSCORE:
print("red hit")
REASON['overall'] = REASON['overall'] + " * COVERT REDIRECTION HIT"
REASON['covred'] = "The website contains redirection code. It can redirect to some other page without " \
"user consent. "
ISWEBSITESAFE= False
if "YES" in ISHTTPS:
print("cert check")
CERT = certcheck.getMainScan(urltsm)
CERT = CERT.split(';')
# CHECK TRUSTED CERTS
if checkTrustedCert.scan(CERT[4]) == True:
REASON['certtrust'] = "The certificate for encryption is provided by trusted Certification Authority."
CERTSCORE = "SAFE"
if "SAFE" not in CERTSCORE:
print("cert hit")
REASON['overall'] = REASON['overall'] + " * UNTRUSTED ENCRYPTION CERT"
REASON['certtrust'] = "The certificate for encryption is not provided by trusted Certification Authority. An attacker can forge a certificate and decrypt the data from HTTPS over SSL, making HTTPS insecure."
ISWEBSITESAFE = False
else:
ERROR404=True
REASON['webstat']="Website appears to be unreachable."
### COMPILING THE DATA IN A STRUCTURE
REDIRECTSCHEME="NA"
if ISWEBSITESAFE == True:
TRANRESULT="YES"
else:
TRANRESULT="NO"
WEBUS=urltsm
if vtscan_bool:
if MALWARESCORE > 0:
MALSR="UNSAFE"
TRIGGERS=str(TRIGGERS)
MALHITS=str(MALHITS)
else:
MALSR = "SAFE"
else:
MALSR="N/A"
if "NO" not in ISHTTPS:
HTTPSSCORE="YES"
REDIR=REDIRECTSCHEME
if CERT is not None:
CERT0=CERT[0]
CERT1 = CERT[1]
CERT2 = CERT[2]
CERT3 = str(CERT[3])
CERT4 = CERT[4]
CERT5 = CERT[5]
CERT6 = CERT[6]
else:
CERT0 = "NA"
CERT1 = "NA"
CERT2 = "NA"
CERT3 = "NA"
CERT4 = "NA"
CERT5 = "NA"
CERT6 = "NA"
if checkTrustedCert.scan(CERT[4]) == True:
CERTTRUST="YES"
else:
CERTTRUST = "NO"
else:
HTTPSSCORE = "NO"
REDIR = REDIRECTSCHEME
CERT0 = "NA"
CERT1 = "NA"
CERT2 = "NA"
CERT3 = "NA"
CERT4 = "NA"
CERT5 = "NA"
CERT6 = "NA"
CERTTRUST="NA"
if REDIRECTIONSCORE == True:
COVRED="YES"
else:
COVRED = "NO"
#if agent == "shell":
# return str(str(TRANRESULT)+";"+(WEBUS)+";"+(MALSR)+";"+str(TRIGGERS)+";"+str(MALHITS)+";"+HTTPSSCORE+";"+COVRED+";"+REDIR+";"+CERT0+";"+CERT1+";"+CERT2+";"+CERT3+";"+CERT4+";"+CERT5+";"+CERT6+";"+CERTTRUST+";"+str(ERROR404)+";"+str(REASON))
#return render_template('res.html',TRANRESULT=TRANRESULT,WEBUS=WEBUS,MALSR=MALSR,TRIGGERS=TRIGGERS,MALHITS=MALHITS,
# HTTPSSCORE=HTTPSSCORE,COVRED=COVRED,REDIR=REDIR,CERT0=CERT0,CERT1 = CERT1,CERT2 = CERT2,CERT3 = CERT3,CERT4 = CERT4,CERT5 = CERT5,CERT6 = CERT6,CERTTRUST=CERTTRUST
# ,ERROR404=ERROR404,REASON=REASON)
data={"TRANRESULT":TRANRESULT,"WEBUS":WEBUS,"HTTPSSCORE":HTTPSSCORE,"COVERT":COVRED,"REDIR":REDIR,"CERT0":CERT0,"CERT1":CERT1,"CERT2":CERT2,
"CERT3":CERT3,"CERT4":CERT4,"CERT5":CERT5,"CERT6":CERT6,"ERROR404":str(ERROR404),"REASON":REASON,"MALSR":MALSR,"TRIGGERS":TRIGGERS,"MALHITS":MALHITS,}
return data
def legacy_processurl(urltsm,agent):
urltsm=httpscheck.rmrf_protocol(urltsm)
#ASSUME NOT SAFE AS DEFAULT
ISWEBSITESAFE = True
CERTSCORE = "DANGER" # THIS WILL MAKE IT NOT SAFE BY DEFAULT
ISHTTPS="NO"
REDIRECTIONSCORE="NA"
REASON = {
'https': "The website uses HTTPS. It's needed to transmit data securely.",
'certtrust': "The certificate for encryption is not provided by trusted Certification Authority. An attacker can forge a certificate and decrypt the data from HTTPS over SSL, making HTTPS insecure.",
'malware': "This website is not reported for malicious scripts.",
'redir': "Redirection is how a website navigates the user to HTTPS even if they try to visit from HTTP on its own.",
'covred': "The website does not contain redirection code.",
'overall': "",
'webstat': "Website Available"
}
if vtscan_bool:
RESULT=vtscan.getResult(config.VTAPIKEY,urltsm)
MALWARESCORE = RESULT['positives']
TRIGGERS=[]
MALHITS=[]
if MALWARESCORE > 0:
REASON['overall']=REASON['overall']+" * MALWARE HIT"
REASON['malware']= "This website is reported to contain malicious scripts or tools, or it is created with malicious intent. BE CAUTIOUS. An adversary can take advantage and steal your data."
ISWEBSITESAFE= False
if MALWARESCORE > 0:
for i in RESULT['scans']:
if RESULT['scans'][i]['detected'] == True:
TRIGGERS.append(i)
MALHITS.append(RESULT['scans'][i]['result'])
else:
TRIGGERS=[]
MALHITS=[]
TRIGGERS.append("--")
MALHITS.append("--")
REASON['malware']="VirusTotal API key not used, skipping malware scan."
###### =======================================
hostname_idna = idna.encode(urltsm)
sock = socket()
ERROR404=False
try:
sock.connect((hostname_idna, 80))
MARK =1
except Exception:
MARK=-1
if MARK > 0:
REDIRECTIONSCORE=checkReditect.scan(urltsm)
HTTPSBOOL = httpscheck.scan(urltsm)
HTTPSBOOL = HTTPSBOOL.split(';')
ISHTTPS = HTTPSBOOL[0]
if HTTPSBOOL[1] == 'SR':
REDIRECTSCHEME = "SOFT REDIRECTION TO HTTPS"
elif HTTPSBOOL[1] == 'HR':
REDIRECTSCHEME = "HARD REDIRECTION TO HTTPS"
else:
REDIRECTSCHEME = "NO REDIRECT"
### CHECKING RESULTS
# print("NO" in ISHTTPS)
if "NO" in ISHTTPS:
print("http hit")
REASON['https']="The website do not use HTTPS. It's needed to transmit data securely."
REASON['overall'] = REASON['overall'] + " * HTTP HIT"
ISWEBSITESAFE = False
if REDIRECTIONSCORE:
print("red hit")
REASON['overall'] = REASON['overall'] + " * COVERT REDIRECTION HIT"
REASON['covred'] = "The website contains redirection code. It can redirect to some other page without " \
"user consent. "
ISWEBSITESAFE= False
if "YES" in ISHTTPS:
print("cert check")
CERT = certcheck.getMainScan(urltsm)
CERT = CERT.split(';')
# CHECK TRUSTED CERTS
if checkTrustedCert.scan(CERT[4]) == True:
REASON['certtrust'] = "The certificate for encryption is provided by trusted Certification Authority."
CERTSCORE = "SAFE"
#
if "SAFE" not in CERTSCORE:
print("cert hit")
REASON['overall'] = REASON['overall'] + " * UNTRUSTED ENCRYPTION CERT"
REASON['certtrust'] = "The certificate for encryption is not provided by trusted Certification Authority. An attacker can forge a certificate and decrypt the data from HTTPS over SSL, making HTTPS insecure."
ISWEBSITESAFE = False
else:
ERROR404=True
REASON['webstat']="Website appears to be unreachable."
### COMPILING THE DATA IN A STRUCTURE
REDIRECTSCHEME="NA"
if ISWEBSITESAFE == True:
TRANRESULT="YES"
else:
TRANRESULT="NO"
WEBUS=urltsm
if vtscan_bool:
if MALWARESCORE > 0:
MALSR="UNSAFE"
TRIGGERS=str(TRIGGERS)
MALHITS=str(MALHITS)
else:
MALSR = "SAFE"
else:
MALSR="N/A"
if "NO" not in ISHTTPS:
HTTPSSCORE="YES"
REDIR=REDIRECTSCHEME
if CERT is not None:
CERT0=CERT[0]
CERT1 = CERT[1]
CERT2 = CERT[2]
CERT3 = str(CERT[3])
CERT4 = CERT[4]
CERT5 = CERT[5]
CERT6 = CERT[6]
else:
CERT0 = "NA"
CERT1 = "NA"
CERT2 = "NA"
CERT3 = "NA"
CERT4 = "NA"
CERT5 = "NA"
CERT6 = "NA"
if checkTrustedCert.scan(CERT[4]) == True:
CERTTRUST="YES"
else:
CERTTRUST = "NO"
else:
HTTPSSCORE = "NO"
REDIR = REDIRECTSCHEME
CERT0 = "NA"
CERT1 = "NA"
CERT2 = "NA"
CERT3 = "NA"
CERT4 = "NA"
CERT5 = "NA"
CERT6 = "NA"
CERTTRUST="NA"
if REDIRECTIONSCORE == True:
COVRED="YES"
else:
COVRED = "NO"
if agent == "shell":
return str(str(TRANRESULT)+";"+(WEBUS)+";"+(MALSR)+";"+str(TRIGGERS)+";"+str(MALHITS)+";"+HTTPSSCORE+";"+COVRED+";"+REDIR+";"+CERT0+";"+CERT1+";"+CERT2+";"+CERT3+";"+CERT4+";"+CERT5+";"+CERT6+";"+CERTTRUST+";"+str(ERROR404)+";"+str(REASON))
return render_template('res.html',TRANRESULT=TRANRESULT,WEBUS=WEBUS,MALSR=MALSR,TRIGGERS=TRIGGERS,MALHITS=MALHITS,
HTTPSSCORE=HTTPSSCORE,COVRED=COVRED,REDIR=REDIR,CERT0=CERT0,CERT1 = | |
else:
RiskyDstn = self.RiskyDstn
temp_f = lambda s : -((1.-self.CRRA)**-1)*np.dot((self.Rfree + s*(RiskyDstn.X-self.Rfree))**(1.-self.CRRA), RiskyDstn.pmf)
SharePF = minimize_scalar(temp_f, bounds=(0.0, 1.0), method='bounded').x
self.ShareLimit = SharePF
self.addToTimeInv('ShareLimit')
def getRisky(self):
'''
Sets the attribute RiskyNow as a single draw from a lognormal distribution.
Uses the attributes RiskyAvgTrue and RiskyStdTrue if RiskyAvg is time-varying,
else just uses the single values from RiskyAvg and RiskyStd.
Parameters
----------
None
Returns
-------
None
'''
if 'RiskyDstn' in self.time_vary:
RiskyAvg = self.RiskyAvgTrue
RiskyStd = self.RiskyStdTrue
else:
RiskyAvg = self.RiskyAvg
RiskyStd = self.RiskyStd
RiskyAvgSqrd = RiskyAvg**2
RiskyVar = RiskyStd**2
mu = np.log(RiskyAvg / (np.sqrt(1. + RiskyVar / RiskyAvgSqrd)))
sigma = np.sqrt(np.log(1. + RiskyVar / RiskyAvgSqrd))
self.RiskyNow = Lognormal(mu, sigma).draw(1, seed=self.RNG.randint(0, 2**31-1))
def getAdjust(self):
'''
Sets the attribute AdjustNow as a boolean array of size AgentCount, indicating
whether each agent is able to adjust their risky portfolio share this period.
Uses the attribute AdjustPrb to draw from a Bernoulli distribution.
Parameters
----------
None
Returns
-------
None
'''
self.AdjustNow = Bernoulli(self.AdjustPrb).draw(self.AgentCount, seed=self.RNG.randint(0, 2**31-1))
def getRfree(self):
'''
Calculates realized return factor for each agent, using the attributes Rfree,
RiskyNow, and ShareNow. This method is a bit of a misnomer, as the return
factor is not riskless, but would more accurately be labeled as Rport. However,
this method makes the portfolio model compatible with its parent class.
Parameters
----------
None
Returns
-------
Rport : np.array
Array of size AgentCount with each simulated agent's realized portfolio
return factor. Will be used by getStates() to calculate mNrmNow, where it
will be mislabeled as "Rfree".
'''
Rport = self.ShareNow*self.RiskyNow + (1.-self.ShareNow)*self.Rfree
self.RportNow = Rport
return Rport
def initializeSim(self):
'''
Initialize the state of simulation attributes. Simply calls the same method
for IndShockConsumerType, then sets the type of AdjustNow to bool.
Parameters
----------
None
Returns
-------
None
'''
IndShockConsumerType.initializeSim(self)
self.AdjustNow = self.AdjustNow.astype(bool)
def simBirth(self,which_agents):
'''
Create new agents to replace ones who have recently died; takes draws of
initial aNrm and pLvl, as in ConsIndShockModel, then sets Share and Adjust
to zero as initial values.
Parameters
----------
which_agents : np.array
Boolean array of size AgentCount indicating which agents should be "born".
Returns
-------
None
'''
IndShockConsumerType.simBirth(self,which_agents)
self.ShareNow[which_agents] = 0.
self.AdjustNow[which_agents] = False
def getShocks(self):
'''
Draw idiosyncratic income shocks, just as for IndShockConsumerType, then draw
a single common value for the risky asset return. Also draws whether each
agent is able to update their risky asset share this period.
Parameters
----------
None
Returns
-------
None
'''
IndShockConsumerType.getShocks(self)
self.getRisky()
self.getAdjust()
def getControls(self):
'''
Calculates consumption cNrmNow and risky portfolio share ShareNow using
the policy functions in the attribute solution. These are stored as attributes.
Parameters
----------
None
Returns
-------
None
'''
cNrmNow = np.zeros(self.AgentCount) + np.nan
ShareNow = np.zeros(self.AgentCount) + np.nan
# Loop over each period of the cycle, getting controls separately depending on "age"
for t in range(self.T_cycle):
these = t == self.t_cycle
# Get controls for agents who *can* adjust their portfolio share
those = np.logical_and(these, self.AdjustNow)
cNrmNow[those] = self.solution[t].cFuncAdj(self.mNrmNow[those])
ShareNow[those] = self.solution[t].ShareFuncAdj(self.mNrmNow[those])
# Get Controls for agents who *can't* adjust their portfolio share
those = np.logical_and(these, np.logical_not(self.AdjustNow))
cNrmNow[those] = self.solution[t].cFuncFxd(self.mNrmNow[those], self.ShareNow[those])
ShareNow[those] = self.solution[t].ShareFuncFxd(self.mNrmNow[those], self.ShareNow[those])
# Store controls as attributes of self
self.cNrmNow = cNrmNow
self.ShareNow = ShareNow
# Define a non-object-oriented one period solver
def solveConsPortfolio(solution_next,ShockDstn,IncomeDstn,RiskyDstn,
LivPrb,DiscFac,CRRA,Rfree,PermGroFac,
BoroCnstArt,aXtraGrid,ShareGrid,vFuncBool,AdjustPrb,
DiscreteShareBool,ShareLimit,IndepDstnBool):
'''
Solve the one period problem for a portfolio-choice consumer.
Parameters
----------
solution_next : PortfolioSolution
Solution to next period's problem.
ShockDstn : [np.array]
List with four arrays: discrete probabilities, permanent income shocks,
transitory income shocks, and risky returns. This is only used if the
input IndepDstnBool is False, indicating that income and return distributions
can't be assumed to be independent.
IncomeDstn : [np.array]
List with three arrays: discrete probabilities, permanent income shocks,
and transitory income shocks. This is only used if the input IndepDsntBool
is True, indicating that income and return distributions are independent.
RiskyDstn : [np.array]
List with two arrays: discrete probabilities and risky asset returns. This
is only used if the input IndepDstnBool is True, indicating that income
and return distributions are independent.
LivPrb : float
Survival probability; likelihood of being alive at the beginning of
the succeeding period.
DiscFac : float
Intertemporal discount factor for future utility.
CRRA : float
Coefficient of relative risk aversion.
Rfree : float
Risk free interest factor on end-of-period assets.
PermGroFac : float
Expected permanent income growth factor at the end of this period.
BoroCnstArt: float or None
Borrowing constraint for the minimum allowable assets to end the
period with. In this model, it is *required* to be zero.
aXtraGrid: np.array
Array of "extra" end-of-period asset values-- assets above the
absolute minimum acceptable level.
ShareGrid : np.array
Array of risky portfolio shares on which to define the interpolation
of the consumption function when Share is fixed.
vFuncBool: boolean
An indicator for whether the value function should be computed and
included in the reported solution.
AdjustPrb : float
Probability that the agent will be able to update his portfolio share.
DiscreteShareBool : bool
Indicator for whether risky portfolio share should be optimized on the
continuous [0,1] interval using the FOC (False), or instead only selected
from the discrete set of values in ShareGrid (True). If True, then
vFuncBool must also be True.
ShareLimit : float
Limiting lower bound of risky portfolio share as mNrm approaches infinity.
IndepDstnBool : bool
Indicator for whether the income and risky return distributions are in-
dependent of each other, which can speed up the expectations step.
Returns
-------
solution_now : PortfolioSolution
The solution to the single period consumption-saving with portfolio choice
problem. Includes two consumption and risky share functions: one for when
the agent can adjust his portfolio share (Adj) and when he can't (Fxd).
'''
# Make sure the individual is liquidity constrained. Allowing a consumer to
# borrow *and* invest in an asset with unbounded (negative) returns is a bad mix.
if BoroCnstArt != 0.0:
raise ValueError('PortfolioConsumerType must have BoroCnstArt=0.0!')
# Make sure that if risky portfolio share is optimized only discretely, then
# the value function is also constructed (else this task would be impossible).
if (DiscreteShareBool and (not vFuncBool)):
raise ValueError('PortfolioConsumerType requires vFuncBool to be True when DiscreteShareBool is True!')
# Define temporary functions for utility and its derivative and inverse
u = lambda x : utility(x, CRRA)
uP = lambda x : utilityP(x, CRRA)
uPinv = lambda x : utilityP_inv(x, CRRA)
n = lambda x : utility_inv(x, CRRA)
nP = lambda x : utility_invP(x, CRRA)
# Unpack next period's solution
vPfuncAdj_next = solution_next.vPfuncAdj
dvdmFuncFxd_next = solution_next.dvdmFuncFxd
dvdsFuncFxd_next = solution_next.dvdsFuncFxd
vFuncAdj_next = solution_next.vFuncAdj
vFuncFxd_next = solution_next.vFuncFxd
# Major method fork: (in)dependent risky asset return and income distributions
if IndepDstnBool: # If the distributions ARE independent...
# Unpack the shock distribution
IncPrbs_next = IncomeDstn.pmf
PermShks_next = IncomeDstn.X[0]
TranShks_next = IncomeDstn.X[1]
Rprbs_next = RiskyDstn.pmf
Risky_next = RiskyDstn.X
zero_bound = (np.min(TranShks_next) == 0.) # Flag for whether the natural borrowing constraint is zero
RiskyMax = np.max(Risky_next)
# bNrm represents R*a, balances after asset return shocks but before income.
# This just uses the highest risky return as a rough shifter for the aXtraGrid.
if zero_bound:
aNrmGrid = aXtraGrid
bNrmGrid = np.insert(RiskyMax*aXtraGrid, 0, np.min(Risky_next)*aXtraGrid[0])
else:
aNrmGrid = np.insert(aXtraGrid, 0, 0.0) # Add an asset point at exactly zero
bNrmGrid = RiskyMax*np.insert(aXtraGrid, 0, 0.0)
# Get grid and shock sizes, for easier indexing
aNrm_N = aNrmGrid.size
bNrm_N = bNrmGrid.size
Share_N = ShareGrid.size
Income_N = IncPrbs_next.size
Risky_N = Rprbs_next.size
# Make tiled arrays to calculate future realizations of mNrm and Share when integrating over IncomeDstn
bNrm_tiled = np.tile(np.reshape(bNrmGrid, (bNrm_N,1,1)), (1,Share_N,Income_N))
Share_tiled = np.tile(np.reshape(ShareGrid, (1,Share_N,1)), (bNrm_N,1,Income_N))
IncPrbs_tiled = np.tile(np.reshape(IncPrbs_next, (1,1,Income_N)), (bNrm_N,Share_N,1))
PermShks_tiled = np.tile(np.reshape(PermShks_next, | |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Helper functions/classes for model definition."""
import functools
from typing import Any, Callable
from flax import linen as nn
import jax
from jax import lax
from jax import random
import jax.numpy as jnp
class MLP(nn.Module):
"""A simple MLP."""
net_depth: int = 8 # The depth of the first part of MLP.
net_width: int = 256 # The width of the first part of MLP.
net_depth_condition: int = 1 # The depth of the second part of MLP.
net_width_condition: int = 128 # The width of the second part of MLP.
net_activation: Callable[..., Any] = nn.relu # The activation function.
skip_layer: int = 4 # The layer to add skip layers to.
num_rgb_channels: int = 3 # The number of RGB channels.
num_sigma_channels: int = 1 # The number of sigma channels.
@nn.compact
def __call__(self, x, condition=None):
"""
Evaluate the MLP.
Args:
x: jnp.ndarray(float32), [batch, num_samples, feature], points.
condition: jnp.ndarray(float32), [batch, feature], if not None, this
variable will be part of the input to the second part of the MLP
concatenated with the output vector of the first part of the MLP. If
None, only the first part of the MLP will be used with input x. In the
original paper, this variable is the view direction.
Returns:
raw_rgb: jnp.ndarray(float32), with a shape of
[batch, num_samples, num_rgb_channels].
raw_sigma: jnp.ndarray(float32), with a shape of
[batch, num_samples, num_sigma_channels].
"""
feature_dim = x.shape[-1]
num_samples = x.shape[1]
x = x.reshape([-1, feature_dim])
dense_layer = functools.partial(
nn.Dense, kernel_init=jax.nn.initializers.glorot_uniform())
inputs = x
dtype = x.dtype
for i in range(self.net_depth):
x = dense_layer(self.net_width, dtype = dtype)(x)
x = self.net_activation(x)
if i % self.skip_layer == 0 and i > 0:
x = jnp.concatenate([x, inputs], axis=-1)
raw_sigma = dense_layer(self.num_sigma_channels, dtype = dtype)(x).reshape(
[-1, num_samples, self.num_sigma_channels])
if condition is not None:
# Output of the first part of MLP.
bottleneck = dense_layer(self.net_width, dtype = dtype)(x)
# Broadcast condition from [batch, feature] to
# [batch, num_samples, feature] since all the samples along the same ray
# have the same viewdir.
condition = jnp.tile(condition[:, None, :], (1, num_samples, 1))
# Collapse the [batch, num_samples, feature] tensor to
# [batch * num_samples, feature] so that it can be fed into nn.Dense.
condition = condition.reshape([-1, condition.shape[-1]])
x = jnp.concatenate([bottleneck, condition], axis=-1)
# Here use 1 extra layer to align with the original nerf model.
for i in range(self.net_depth_condition):
x = dense_layer(self.net_width_condition, dtype = dtype)(x)
x = self.net_activation(x)
raw_rgb = dense_layer(self.num_rgb_channels, dtype = dtype)(x).reshape(
[-1, num_samples, self.num_rgb_channels])
return raw_rgb, raw_sigma
def cast_rays(z_vals, origins, directions):
return origins[..., None, :] + z_vals[..., None] * directions[..., None, :]
def sample_along_rays(key, origins, directions, num_samples, near, far,
randomized, lindisp):
"""
Stratified sampling along the rays.
Args:
key: jnp.ndarray, random generator key.
origins: jnp.ndarray(float32), [batch_size, 3], ray origins.
directions: jnp.ndarray(float32), [batch_size, 3], ray directions.
num_samples: int.
near: float, near clip.
far: float, far clip.
randomized: bool, use randomized stratified sampling.
lindisp: bool, sampling linearly in disparity rather than depth.
Returns:
z_vals: jnp.ndarray, [batch_size, num_samples], sampled z values.
points: jnp.ndarray, [batch_size, num_samples, 3], sampled points.
"""
batch_size = origins.shape[0]
dtype = origins.dtype
t_vals = jnp.linspace(0., 1., num_samples, dtype = dtype)
if lindisp:
z_vals = 1. / (1. / near * (1. - t_vals) + 1. / far * t_vals)
else:
z_vals = near * (1. - t_vals) + far * t_vals
if randomized:
mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])
upper = jnp.concatenate([mids, z_vals[..., -1:]], -1)
lower = jnp.concatenate([z_vals[..., :1], mids], -1)
t_rand = random.uniform(key, [batch_size, num_samples])
z_vals = lower + (upper - lower) * t_rand
else:
# Broadcast z_vals to make the returned shape consistent.
z_vals = jnp.broadcast_to(z_vals[None, ...], [batch_size, num_samples]).astype(dtype)
coords = cast_rays(z_vals, origins, directions)
return z_vals, coords
def posenc(x, min_deg, max_deg, legacy_posenc_order=False):
"""
Cat x with a positional encoding of x with scales 2^[min_deg, max_deg-1].
Instead of computing [sin(x), cos(x)], we use the trig identity
cos(x) = sin(x + pi/2) and do one vectorized call to sin([x, x+pi/2]).
Args:
x: jnp.ndarray, variables to be encoded. Note that x should be in [-pi, pi].
min_deg: int, the minimum (inclusive) degree of the encoding.
max_deg: int, the maximum (exclusive) degree of the encoding.
legacy_posenc_order: bool, keep the same ordering as the original tf code.
Returns:
encoded: jnp.ndarray, encoded variables.
"""
if min_deg == max_deg:
return x
dtype = x.dtype
scales = jnp.array([2 ** i for i in range(min_deg, max_deg)], dtype = dtype)
if legacy_posenc_order:
xb = x[..., None, :] * scales[:, None]
four_feat = jnp.reshape(
jnp.sin(jnp.stack([xb, xb + 0.5 * jnp.pi], -2)),
list(x.shape[:-1]) + [-1])
else:
xb = jnp.reshape((x[..., None, :] * scales[:, None]),
list(x.shape[:-1]) + [-1])
four_feat = jnp.sin(jnp.concatenate([xb, xb + 0.5 * jnp.pi], axis=-1))
return jnp.concatenate([x] + [four_feat], axis=-1)
def volumetric_rendering(rgb, sigma, z_vals, dirs, white_bkgd):
"""
Volumetric Rendering Function.
Args:
rgb: jnp.ndarray(float32), color, [batch_size, num_samples, 3]
sigma: jnp.ndarray(float32), density, [batch_size, num_samples, 1].
z_vals: jnp.ndarray(float32), [batch_size, num_samples].
dirs: jnp.ndarray(float32), [batch_size, 3].
white_bkgd: bool.
Returns:
comp_rgb: jnp.ndarray(float32), [batch_size, 3].
disp: jnp.ndarray(float32), [batch_size].
acc: jnp.ndarray(float32), [batch_size].
weights: jnp.ndarray(float32), [batch_size, num_samples]
"""
dtype = rgb.dtype
eps = jnp.array(1e-10, dtype = dtype)
dists = jnp.concatenate([
z_vals[..., 1:] - z_vals[..., :-1],
jnp.broadcast_to(jnp.array([1e10]),#, dtype = dtype),
z_vals[..., :1].shape)
], -1)
dists = dists * jnp.linalg.norm(dirs[..., None, :], axis=-1)
# Note that we're quietly turning sigma from [..., 0] to [...].
alpha = 1.0 - jnp.exp(-sigma[..., 0] * dists)
accum_prod = jnp.concatenate([
jnp.ones_like(alpha[..., :1], alpha.dtype),
jnp.cumprod(1.0 - alpha[..., :-1] + eps, axis=-1)
],
axis=-1)
weights = alpha * accum_prod
weights = weights.astype(dtype)
comp_rgb = (weights[..., None] * rgb).sum(axis=-2)
depth = (weights * z_vals).sum(axis=-1)
acc = weights.sum(axis=-1)
# Equivalent to (but slightly more efficient and stable than):
# disp = 1 / max(eps, where(acc > eps, depth / acc, 0))
inv_eps = 1 / eps
disp = acc / depth
disp = jnp.where((disp > 0) & (disp < inv_eps) & (acc > eps), disp, inv_eps)
if white_bkgd:
comp_rgb = comp_rgb + (1. - acc[..., None])
return comp_rgb, disp, acc, weights
def piecewise_constant_pdf(key, bins, weights, num_samples, randomized):
"""
Piecewise-Constant PDF sampling.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
bins: jnp.ndarray(float32), [batch_size, num_bins + 1].
weights: jnp.ndarray(float32), [batch_size, num_bins].
num_samples: int, the number of samples.
randomized: bool, use randomized samples.
Returns:
z_samples: jnp.ndarray(float32), [batch_size, num_samples].
"""
# Pad each weight vector (only if necessary) to bring its sum to `eps`. This
# avoids NaNs when the input is zeros or small, but has no effect otherwise.
dtype = bins.dtype
eps = 1e-5
weight_sum = jnp.sum(weights, axis=-1, keepdims=True)
padding = jnp.maximum(0, eps - weight_sum)
weights += padding / weights.shape[-1]
weight_sum += padding
# Compute the PDF and CDF for each weight vector, while ensuring that the CDF
# starts with exactly 0 and ends with exactly 1.
pdf = weights / weight_sum
cdf = jnp.minimum(1, jnp.cumsum(pdf[..., :-1], axis=-1))
cdf = jnp.concatenate([
jnp.zeros(list(cdf.shape[:-1]) + [1], dtype = dtype), cdf,
jnp.ones(list(cdf.shape[:-1]) + [1], dtype = dtype)
],
axis=-1)
# Draw uniform samples.
if randomized:
# Note that `u` is in [0, 1) --- it can be zero, but it can never be 1.
u = random.uniform(key, list(cdf.shape[:-1]) + [num_samples])
else:
# Match the behavior of random.uniform() by spanning [0, 1-eps].
u = jnp.linspace(0., 1. - jnp.finfo(dtype).eps, num_samples, dtype = dtype)
u = jnp.broadcast_to(u, list(cdf.shape[:-1]) + [num_samples])
# Identify the location in `cdf` that corresponds to a random sample.
# The final `True` index in `mask` will be the start of the sampled interval.
mask = u[..., None, | |
#!/usr/bin/python
import scipy as sp
import numpy as np
import string
import timeit
import os,sys
# Set other analysis parameters
overlap_length = 15
primer_length = 40
# Get input files
r1_file = sys.argv[1]
r2_file = sys.argv[2]
regions_file = sys.argv[3]
output_file = sys.argv[4]
stats_file = sys.argv[5]
# Make sure that extensions on files are the same, i.e. that they come from the
# same traunch.
#extension = '.'.join(r1_file.split('.')[-2:])
#extension2 = '.'.join(r2_file.split('.')[-2:])
#assert(extension == extension2)
total_time_start = timeit.default_timer()
time_dict = {}
time_dict['align'] = 0
time_dict['trim'] = 0
time_dict['consensus'] = 0
time_dict['read_fastq'] = 0
time_dict['match'] = 0
time_dict['align_compute_scores'] = 0
# Function to compute the reverse complement of a sequence
complement = string.maketrans('ATCGN', 'TAGCN')
def rc(seq):
return seq.upper().translate(complement)[::-1]
# Return the next read from a fastq file
time_get_next_read_from_fastq = 0.0
def get_next_read_from_fastq(f):
start_time = timeit.default_timer()
f.readline()
read = f.readline().strip()
f.readline()
f.readline()
time_dict['read_fastq'] += timeit.default_timer() - start_time
return read
# # Finds the barcode corresponding to each sequence
# def match_barcode(seq, barcodes_dict,search_area=20):
# start_time = timeit.default_timer()
# tag_length = 0
# region = False
# for barcode in barcodes_dict.keys():
# k = seq.find(barcode,0,search_area)
# if k >= 0:
# region = barcodes_dict[barcode]
# tag_length = len(barcode)+k
# #continue
# time_dict['match'] += timeit.default_timer() - start_time
# return (region, tag_length)
def findchar(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
# Performs a gapless alginment of seq1 and seq2. Returns sequences padded with
# dashes as appropriate
def gapless_alignment(seq1, seq2):
start_time = timeit.default_timer()
L1 = len(seq1)
L2 = len(seq2)
dash_val = ord('-')
# Convert sequences to an array of integers
nseq1 = sp.array([ord(c) for c in seq1],dtype='int')
nseq2 = sp.array([ord(c) for c in seq2],dtype='int')
alignment_array_length = 2*L1+L2-2
#positions_to_test = L1+L2-1
# Position nseq2 in the middle of a2
a2 = sp.ones(alignment_array_length,dtype='int')*ord('-')
a2[L1:L1+L2] = nseq2
# Find best alginment position
# First, try finding alignment using heuristics
a2_seq = ''.join([chr(c) for c in a2])
k = -1
i = 0
while k < 0 and i < L1-overlap_length:
k = a2_seq.find(seq1[i:overlap_length+i])-i
i += 1
# If heuristics found a match, use that alignment
if k >= 0:
kbest = k
# Otherwise, do costly alignment
else:
#scores = [sum(nseq1 == a2[k:L1+k]) for k in range(positions_to_test)]
#scores = compute_alignment_scores(nseq1,a2)
#kbest = sp.argmax(scores)
kbest = 0
# Position nseq1 in the optimal place of a1
a1 = sp.ones(alignment_array_length,dtype='int')*ord('-')
a1[kbest:kbest+L1] = nseq1
# Trim excess '-' from ends
indices = (a1 != dash_val) | (a2 != dash_val)
a1_trimmed = a1[indices]
a2_trimmed = a2[indices]
# Convert back to string
seq1_aligned = ''.join([chr(c) for c in a1_trimmed])
seq2_aligned = ''.join([chr(c) for c in a2_trimmed])
time_dict['align'] += timeit.default_timer() - start_time
# Return aligned sequences
return seq1_aligned, seq2_aligned
## Compute alignment scores quickly
def compute_alignment_scores(nseq1,array2):
start_time_2 = timeit.default_timer()
L1 = len(nseq1)
alignment_array_length = len(array2)
positions_to_test = alignment_array_length - L1
scores = sp.zeros(positions_to_test)
for k in range(positions_to_test):
scores[k] = sum(nseq1 == array2[k:L1+k])
time_dict['align_compute_scores'] += timeit.default_timer() - start_time_2
return scores
# Gets consensus sequence of two aligned sequences, using the higher quality
# one for the overlap region
def get_consensus(aligned_seq1,aligned_seq2):
start_time = timeit.default_timer()
# Make sure sequences are the same length
L = len(aligned_seq1)
assert(L==len(aligned_seq2))
# Convert sequences to an array of integers
nseq1 = sp.array([ord(c) for c in aligned_seq1],dtype='int')
nseq2 = sp.array([ord(c) for c in aligned_seq2],dtype='int')
N_val = ord('N')
dash_val = ord('-')
overlap_indices = (nseq1 != dash_val)*(nseq2 != dash_val)
num_Ns_1 = sum(nseq1[overlap_indices] == N_val)
num_Ns_2 = sum(nseq2[overlap_indices] == N_val)
# Compute the three types of overlap region
indices_only1 = (nseq2==dash_val) & (nseq1!=dash_val)
indices_only2 = (nseq1==dash_val) & (nseq2!=dash_val)
indices_overlap = (nseq1!=dash_val) & (nseq2!=dash_val)
# Fill in values for consensus sequence
nconsensus = sp.ones(L,dtype='int')*ord('-')
nconsensus[indices_only1] = nseq1[indices_only1]
nconsensus[indices_only2] = nseq2[indices_only2]
nconsensus[indices_overlap] = nseq1[overlap_indices] if num_Ns_1 <= num_Ns_2 else nseq2[overlap_indices]
# Determine whether to keep sequence
num_overlap_matches = sum(nseq1[overlap_indices] == nseq2[overlap_indices])
num_overlap_positions = sum(overlap_indices)
frac_match = 1.0*num_overlap_matches/(num_overlap_positions + 1E-6)
# Set consensus sequence
if frac_match >= 0.5 or num_overlap_positions < 10:
consensus = ''.join([chr(c) for c in nconsensus])
else:
consensus = ''
time_dict['consensus'] += timeit.default_timer() - start_time
# Return consensus sequence
return consensus
# Trimms 3' junk, assuming the second read has been reverse complemented
def trim_3p_junk(aligned_seq1, aligned_seq2):
start_time = timeit.default_timer()
# Make sure sequences are the same length
L = len(aligned_seq1)
assert(L==len(aligned_seq2))
dash_val = ord('-')
# Convert sequences to an array of integers
nseq1 = sp.array([ord(c) for c in aligned_seq1],dtype='int')
nseq2 = sp.array([ord(c) for c in aligned_seq2],dtype='int')
junk1 = min(sp.where(nseq1!=dash_val)[0])
junk2 = max(sp.where(nseq2!=dash_val)[0])
seq1_trimmed = aligned_seq1[junk1:junk2+1]
seq2_trimmed = aligned_seq2[junk1:junk2+1]
time_dict['trim'] += timeit.default_timer() - start_time
return seq1_trimmed, seq2_trimmed
# # Load barcodes into dictionary
# f = open(barcodes_file)
# barcodes_dict = {}
# lines = f.readlines()
# for line in lines[1:]:
# atoms = line.strip().split()
# if len(atoms) != 2:
# continue
# sample = atoms[0]
# barcode = atoms[1]
# barcodes_dict[barcode] = sample
# f.close()
# Load regions into dictionary
f = open(regions_file)
f.readline() # Skip headder line
region_to_seq_dict = {}
#read_end_to_region_dict = {}
region = ''
for line in f.readlines():
atoms = line.strip().split()
if len(atoms) != 4:
continue
name = atoms[0]
region = name
seq = atoms[3].upper()
# User primers to get sequences of ends
#end_5p = atoms[1][:end_length]
#end_3p = atoms[2][:end_length]
region_to_seq_dict[name] = seq
# read_end_to_region_dict[end_5p] = name+'_5p'
# read_end_to_region_dict[end_3p] = name+'_3p'
# # Load experiment information
# f = open(experiments_file,'r')
# line = f.readline()
# atoms = line.strip().split()
# timepoints = atoms[2:]
# # Load sample information
# f = open(samples_file,'r')
# f.readline() # Skip header line
# num_to_sample_dict = {}
# for line in f.readlines():
# atoms = line.strip().split()
# num = int(atoms[0])
# sample = atoms[1]
# num_to_sample_dict[num] = sample
# output_file = '%s/%s/observed_seqs.%s'(output_dir,sample,extension)
# output_files_by_key = {}
# observed_seq_files = {}
# for line in f.readlines():
# if len(line.strip())==0:
# continue;
# atoms = line.strip().split()
# experiment = atoms[0]
# region = atoms[1]
# barcode_names = atoms[2:]
# for timepoint_num, timepoint_name in enumerate(timepoints):
# barcode_name = barcode_names[timepoint_num]
# key = '%s_%s'%(region,barcode_name)
# output_file_name = '%s/%s/%s/observed_seqs.%s'%(output_dir,experiment,timepoint_name,extension)
# output_files_by_key[key] = open(output_file_name,'w')
# #print 'Creating %s...'%output_file_name
# valid_keys = output_files_by_key.keys()
#
# Process sequences one-by-one: This is where the main processing happens
#
o_f = open(output_file,'w')
r1_f = open(r1_file)
r2_f = open(r2_file)
stop = False
num_successes = 0
num_reads = 0
num_fails_sample = 0
num_fails_region = 0
num_fails_alignment = 0
while not stop:
# Increment number of reads
if num_reads%5000 == 0 and num_reads > 0:
total_time = timeit.default_timer() - total_time_start
successes_pct = 100*num_successes/num_reads
fails_sample_pct = 100*num_fails_sample/num_reads
fails_region_pct = 100*num_fails_region/num_reads
fails_alignment_pct = 100*num_fails_alignment/num_reads
print 'Total time: %d sec, Total reads: %d, Successes: %d%%'%(total_time, num_reads, successes_pct)
#print time_dict
num_reads += 1
# Get reads
read1 = get_next_read_from_fastq(r1_f)
read2 = get_next_read_from_fastq(r2_f)
if len(read1) == 0 or len(read2) == 0:
stop = True
continue
# Determine sequence sample by matching barcode, and clip barcode
#sample1, tag_length1 = match_barcode(read1, barcodes_dict, search_area=15)
#sample2, tag_length2 = match_barcode(read2, barcodes_dict, search_area=15)
#if not (sample1 and sample2):
# num_fails_sample += 1
# continue
#sample = sample1 if sample1 else sample2
#read1_clipped = read1[tag_length1:]
#read2_clipped = read2[tag_length2:]
read1_clipped = read1
read2_clipped = read2
###
### I need a more robust way of determining region.
###
# Determine region by matching front of read1_clipped
region1 = region
region2 = region
region_name = region
region_seq = region_to_seq_dict[region_name]
fwd_seq = region_seq[:primer_length]
rev_seq = rc(region_seq[-primer_length:])
if not ((read1[:primer_length]==fwd_seq or read1[:primer_length]==rev_seq) and (read2[:primer_length]==fwd_seq or read2[:primer_length]==rev_seq)):
continue
#region1, tag_length1 = match_barcode(read1_clipped, read_end_to_region_dict, search_area=15)
#region2, tag_length2 = match_barcode(read2_clipped, read_end_to_region_dict, search_area=15)
#if not region:
#if (not region1) or (not region2) or (region1[-3:] == region2[-3:]):
# num_fails_region += 1
# continue
#region = region1 if region1 else region2
# Clip excess nucleotides from each end
#read1_clipped = read1_clipped[tag_length1-end_length:]
#read2_clipped = read2_clipped[tag_length2-end_length:]
# Test gapless_alignment
aligned1, aligned2 = gapless_alignment(read1_clipped, rc(read2_clipped))
# Test trim_junk
trimmed1, trimmed2 = trim_3p_junk(aligned1, aligned2)
# Gest get_consensus
consensus = get_consensus(trimmed1, trimmed2)
if len(consensus) == 0:
num_fails_alignment += 1
#print '.',
continue
# RC consensus if read1 matches to 3' end of region
#if '_3p' in region1:
# consensus = rc(consensus)
# Verify that first end_length and last end_length positions match region seq
#region_name = region[:-3]
rc_consensus = rc(consensus)
# Test forward sequence
if (region_seq[:primer_length]==consensus[:primer_length]) and \
(region_seq[-primer_length:]==consensus[-primer_length:]):
o_f.write(consensus+'\n')
num_successes += 1
# Test reverse sequence
elif (region_seq[:primer_length]==rc_consensus[:primer_length]) and \
(region_seq[-primer_length:]==rc_consensus[-primer_length:]):
o_f.write(rc_consensus+'\n')
num_successes += 1
# If no success, then fail
else:
num_fails_alignment += 1
#print '---'
#print 'c: | |
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import torch
import torch.autograd as autograd
import torch.optim as optim
from torch.distributions import constraints, transform_to
import sobol_seq
import pyDOE
import pyro
import pyro.contrib.gp as gp
import copy
from torch.distributions.multivariate_normal import MultivariateNormal as normal
import warnings
import numpy as np
from scipy.spatial.distance import cdist
from casadi import *
np.random.seed(0)
torch.seed()
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n'
class BayesOpt(object):
def __init__(self):
print('Start Bayesian Optimization using Torch')
def solve(self, objective, xo=None, bounds=(0,1), maxfun=20, N_initial=4,
select_kernel='Matern32', acquisition='LCB', casadi=False, constraints = None,
probabilistic=False, print_iteration=False):
"""
:param objective: Objective function with numpy inputs
:type objective: Function
:param xo: Initial point, not used at the moment
:type xo: Numpy array
:param bounds: Bounds for the desicion variabls
:type bounds: Tuple of numpy arrays or numpy array
:param maxfun: Maximum number of function evaluations
:type maxfun: Integer
:param N_initial: Number of initial points
:type N_initial: Integer
:param select_kernel: Type of kernel
:type select_kernel: String
:param acquisition: Type of acquitiison functions
:type acquisition: String
:param casadi: Boolean that indicates if casadi is emplyed or not
:type casadi: Boolean
:param constraints: List of the constraints, if there are no constraints then Nana
:type constraints: List of functions
:param probabilistic: Satisfy constraints with probability
:type probabilistic: Boolean
:param print_iteration: Boolean that indicates if the results will be printed per iteration
:type print_iteration: Boolean
:return: (x, objective, maxfun, dictionary with the results)
:rtype: Tuple
"""
if constraints is None:
self.x0 = torch.Tensor(bounds[0])
else:
self.x0 = torch.Tensor(xo)
self.x0 = torch.Tensor(xo)
self.bounds = bounds
self.maxfun = maxfun
self.N_initial = N_initial
self.objective = objective
self.probabilistic = probabilistic
self.print_iter = print_iteration
if constraints is None:
self.constraints = []
else:
self.constraints = constraints
if not(casadi) and acquisition != 'EIC':
casadi = True
warnings.formatwarning = custom_formatwarning
warnings.warn('WARNING: Pytorch optimization cannot handle constraints without EIC. Casadi and ipopt are used instead')
# Append all the functions
self.set_functions = [self.objective]
self.set_functions += [*self.constraints]
self.card_of_funcs = len(self.set_functions)
self.kernel = select_kernel
self.nx = max(self.x0.shape)
self.casadi = casadi
supported_acquisition = ['Mean', 'LCB', 'EI','EIC']
k = 0
for supp in supported_acquisition:
if acquisition == supp:
break
else:
k+=1
if k == len(supported_acquisition):
warnings.formatwarning = custom_formatwarning
warnings.warn('WARNING: Selected acquisition does not exist, Lower Confidence Bound is used instead')
acquisition = 'LCB'
self.acquisition = acquisition
self.X = torch.from_numpy(pyDOE.lhs(self.nx, N_initial))
sol = self.run_main()
return sol
def run_initial(self):
"""
This function computes the initial N_initial points to fit the Gaussian process
:return: Y
:rtype: tensor
"""
Y = torch.zeros([self.N_initial, self.card_of_funcs])
for i in range(self.N_initial):
for j in range(self.card_of_funcs):
Y[i, j] = self.compute_function(self.X[i,:], self.set_functions[j]).reshape(-1,)
return Y
def define_GP(self,i):
"""
This function predefines the Gaussian processes to be trained
:param i: This is the indexed GP to be trained 0 for objective and 1+ for the rest
:type i: integer
:return: Defined GP
:rtype: pyro object
"""
Y_unscaled = self.Y
X_unscaled = self.X
nx = self.nx
# Scale the variables
self.X_mean, self.X_std = X_unscaled.mean(axis=0), X_unscaled.std(axis=0)
self.Y_mean, self.Y_std = Y_unscaled.mean(axis=0), Y_unscaled.std(axis=0)
self.X_norm, self.Y_norm = (X_unscaled - self.X_mean) / self.X_std,\
(Y_unscaled - self.Y_mean) / self.Y_std
X, Y = self.X_norm, self.Y_norm
if self.kernel == 'Matern52':
gpmodel = gp.models.GPRegression(X, Y[:, i], gp.kernels.Matern52(input_dim=nx, lengthscale=torch.ones(nx)),
noise=torch.tensor(0.1), jitter=1.0e-4, )
elif self.kernel == 'Matern32':
gpmodel = gp.models.GPRegression(X, Y[:, i], gp.kernels.Matern32(input_dim=nx,
lengthscale=torch.ones(nx)),
noise=torch.tensor(0.1), jitter=1.0e-4, )
elif self.kernel == 'RBF':
gpmodel = gp.models.GPRegression(X, Y[:, i], gp.kernels.RBF(input_dim=nx,
lengthscale=torch.ones(nx)),
noise=torch.tensor(0.1), jitter=1.0e-4, )
else:
print('NOT IMPLEMENTED KERNEL, USE RBF INSTEAD')
gpmodel = gp.models.GPRegression(X, Y[:, i], gp.kernels.RBF(input_dim=nx,
lengthscale=torch.ones(nx)),
noise=torch.tensor(0.1), jitter=1.0e-4, )
return gpmodel
def training(self):
"""
This function performs the training for the GPs
:return: All GPs
:rtype: list of pyro objects
"""
Y_unscaled = self.Y
X_unscaled = self.X
nx = self.nx
# Scale the variables
self.X_mean, self.X_std = X_unscaled.mean(axis=0), X_unscaled.std( axis=0)
self.Y_mean, self.Y_std = Y_unscaled.mean( axis=0), Y_unscaled.std( axis=0)
self.X_norm, self.Y_norm = (X_unscaled - self.X_mean) / self.X_std,\
(Y_unscaled - self.Y_mean) / self.Y_std
X, Y = self.X_norm, self.Y_norm
# optimizers = []
g = []
for i in range(self.card_of_funcs):
# self.gpmodel[i].set_data(X, Y[:,i])
# # optimize the GP hyperparameters using Adam with lr=0.001
# optimizers= torch.optim.Adam(self.gpmodel[i].parameters(), lr=0.001)
# gp.util.train(self.gpmodel[i], optimizers)
# self.gpmodel[i].requires_grad_(True)
g.append(copy.deepcopy(self.step_train(self.gpmodel[i], X, Y[:,i])))
# self.gpmodel[i].requires_grad_(False)
# if i ==0:
# for j in (g[0].parameters()):
# print(j)
# for k in (g[0].parameters()):
# print(k)
# print('#------#')
return g
def step_train(self, gp_m, X, y):
"""
This function performs the steps for the the training of each gp
:param gp_m: The Gp to be trained
:type gp_m: pyro object
:param X: X input set to for training
:type X: tensor
:param y: Labels for the Gaussian processes
:type y: tensor
:return: trained GP
:rtype: pyro object
"""
gp_m.set_data(X, y)
# optimize the GP hyperparameters using Adam with lr=0.001
pyro.clear_param_store()
optimizers = torch.optim.Adam(gp_m.parameters(), lr=0.001)
s = gp.util.train(gp_m, optimizers)
return gp_m
def acquisition_func(self, X_unscaled):
"""
Given the input the acquisition function is computed FOR THE pytorch optimization
:param X_unscaled: input to be optimized
:type X_unscaled: SX
:return: acquisition as a casadi object
:rtype: SX
"""
acquisition = self.acquisition
X_unscaled = X_unscaled.reshape((1,-1))
x = (X_unscaled - self.X_mean) / self.X_std
gp = copy.deepcopy(self.gpmodel[0])
if acquisition=='Mean':
mu, _ = gp(x, full_cov=False, noiseless=False)
ac = mu
elif acquisition=='LCB':
mu, variance = gp(x, full_cov=False, noiseless=False)
sigma = variance.sqrt()
ac = mu - 2 * sigma
elif acquisition=='EI':
mu, variance = gp(x, full_cov=False, noiseless=False)
fs = self.f_min
# Scale the variables
Y_unscaled = self.Y[:,0]
Y_mean, Y_std = Y_unscaled.mean(), Y_unscaled.std()
fs_norm = (fs - Y_mean) / Y_std
mean = mu
Delta = fs_norm - mean
sigma = torch.sqrt(variance)
Z = (Delta) / (sigma+1e-5)
norm_pdf = torch.exp(-Z**2/2)/torch.sqrt(2*torch.Tensor([np.pi]))
norm_cdf = 0.5 * (1+ torch.erf(Z/sqrt(2)))
ac = -(sigma * norm_pdf + Delta * norm_cdf)
elif acquisition=='EIC':
mu, variance = gp(x, full_cov=False, noiseless=False)
fs = self.f_min
# Scale the variables
Y_unscaled = self.Y[:,0]
Y_mean, Y_std = Y_unscaled.mean(), Y_unscaled.std()
fs_norm = (fs - Y_mean) / Y_std
mean = mu
Delta = fs_norm - mean
sigma = torch.sqrt(variance)
Z = (Delta) / (sigma+1e-5)
norm_pdf = torch.exp(-Z**2/2)/torch.sqrt(2*torch.Tensor([np.pi]))
norm_cdf = 0.5 * (1+ torch.erf(Z/sqrt(2)))
ac = -(sigma * norm_pdf + Delta * norm_cdf)
p = 1
for i in range(1,self.card_of_funcs):
Y_unscaled = self.Y[:, i]
Y_mean, Y_std = Y_unscaled.mean(), Y_unscaled.std()
gp_c = copy.deepcopy(self.gpmodel[i])
mean_norm, var_norm = gp_c(x, full_cov=False, noiseless=False)
mean, var = mean_norm * Y_std + Y_mean, var_norm * Y_std ** 2
Z_p = mean/var#mu/(variance + 1e-5)#(mu-Y_mean)/Y_std
p *= 0.5 * (1+ torch.erf(Z_p/sqrt(2)))
ac = ac * p
else:
print(NotImplementedError)
ac = 0
return ac
def acquisition_func_ca(self, X_unscaled):
"""
Given the input the acquisition function is computed FOR THE CASADI optimization
:param X_unscaled: input to be optimized
:type X_unscaled: SX
:return: acquisition as a casadi object
:rtype: SX
"""
acquisition = self.acquisition
#X_unscaled = X_unscaled.reshape((1,-1))
x = X_unscaled#(X_unscaled - self.X_mean) / self.X_std
gp = copy.deepcopy(self.gpmodel[0])
if acquisition=='Mean':
mu, _ = self.GP_predict_ca(x, gp)
ac = mu
elif acquisition=='LCB':
mu, variance = self.GP_predict_ca(x,gp)
sigma = sqrt(variance)
ac = mu - 2 * sigma
elif acquisition=='EI':
mu, variance = self.GP_predict_ca(x,gp)
fs = self.f_min
Y_unscaled = self.Y[:,0]
Y_mean, Y_std = Y_unscaled.mean(), Y_unscaled.std()
fs_norm = (fs - Y_mean) / (Y_std)
fs_norm_ca = SX(fs_norm.data.numpy())
mean = mu
Delta = fs_norm_ca - mean
sigma = sqrt(variance)
Z = (Delta) / (sigma+1e-5)
norm_pdf = exp(-Z**2/2)/sqrt(2*np.pi)
norm_cdf = 0.5 * (1+ erf(Z/sqrt(2)))
ac = -(sigma * norm_pdf + Delta * norm_cdf)
elif acquisition=='EIC':
mu, variance = self.GP_predict_ca(x,gp)
fs = self.f_min
Y_unscaled = self.Y[:,0]
Y_mean, Y_std = Y_unscaled.mean(), Y_unscaled.std()
fs_norm = (fs - Y_mean) / (Y_std)
fs_norm_ca = SX(fs_norm.data.numpy())
mean = mu
Delta = fs_norm_ca - mean
sigma = sqrt(variance)
Z = (Delta) / (sigma+1e-5)
norm_pdf = exp(-Z**2/2)/sqrt(2*np.pi)
norm_cdf = 0.5 * (1+ erf(Z/sqrt(2)))
ac = -(sigma * norm_pdf + Delta * norm_cdf)
p = 1
for i in range(1,self.card_of_funcs):
Y_unscaled = self.Y[:, i]
Y_mean, Y_std = SX(Y_unscaled.detach().numpy().mean()),\
SX(Y_unscaled.detach().numpy().std())
gp_c = copy.deepcopy(self.gpmodel[i])
mean_norm, var_norm = self.GP_predict_ca(x, gp_c)
mean, var = mean_norm * Y_std + Y_mean, var_norm * Y_std ** 2
Z_p = mean/var#mu/(variance + 1e-5)#(mu-Y_mean)/Y_std
p *= 0.5 * (1+ erf(Z_p/sqrt(2)))
ac = ac * p
else:
print(NotImplementedError)
ac = 0
return ac
def find_a_candidate(self, x_init):
"""
Performs | |
<filename>chroma-manager/chroma_agent_comms/views.py
# Copyright (c) 2017 Intel Corporation. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import Queue
import json
import traceback
import time
from django.db import transaction
from django.http import HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from functools import wraps
import settings
from os import path
from tastypie.http import HttpForbidden
from chroma_core.models import ManagedHost, ClientCertificate, RegistrationToken, ServerProfile, Bundle
from chroma_core.models.copytool import Copytool, CopytoolEvent, CopytoolOperation, log as copytool_log, UNKNOWN_UUID
from chroma_core.models.log import LogMessage, MessageClass
from chroma_core.models.utils import Version
from chroma_core.services import log_register
from chroma_core.services.http_agent.crypto import Crypto
from iml_common.lib.date_time import IMLDateTime
log = log_register('agent_views')
import logging
log.setLevel(logging.WARN)
def log_exception(f):
@wraps(f)
def wrapped(*args, **kwargs):
try:
return f(*args)
except Exception:
log.error(traceback.format_exc())
raise
return wrapped
class ValidatedClientView(View):
@classmethod
def valid_fqdn(cls, request):
"Return fqdn if certificate is valid."
fqdn = cls.valid_certs.get(request.META['HTTP_X_SSL_CLIENT_SERIAL'])
if not fqdn:
log.warning("Rejecting certificate %s" % request.META['HTTP_X_SSL_CLIENT_SERIAL'])
elif fqdn != request.META['HTTP_X_SSL_CLIENT_NAME']:
log.info("Domain name changed %s" % fqdn)
return fqdn
class CopytoolEventView(ValidatedClientView):
@log_exception
def post(self, request):
"""
Receive copytool events from the monitor.
Handle a POST containing events from the monitor
"""
body = json.loads(request.body)
fqdn = self.valid_fqdn(request)
if not fqdn:
copytool_log.error("Invalid client: %s" % request.META)
return HttpForbidden()
copytool_log.debug("Incoming payload: %s" % body)
try:
copytool = Copytool.objects.select_related().get(id = body['copytool'])
events = [CopytoolEvent(**e) for e in body['events']]
except KeyError as e:
return HttpResponseBadRequest("Missing attribute '%s'" % e.args[0])
except Copytool.DoesNotExist:
return HttpResponseBadRequest("Unknown copytool: %s" % body['copytool'])
copytool_log.debug("Received %d events from %s on %s" %
(len(events), copytool, copytool.host))
from chroma_core.services.job_scheduler.job_scheduler_client import JobSchedulerClient
active_operations = {}
for event in sorted(events, key=lambda event: event.timestamp):
copytool_log.debug(event)
# These types aren't associated with active operations
if event.type == 'UNREGISTER':
JobSchedulerClient.unregister_copytool(copytool.id)
continue
elif event.type == 'REGISTER':
JobSchedulerClient.register_copytool(copytool.id, event.uuid)
continue
elif event.type == 'LOG':
LogMessage.objects.create(fqdn = copytool.host.fqdn,
message = event.message,
severity = getattr(logging, event.level),
facility = 4, # daemon
tag = str(copytool),
datetime = event.timestamp,
message_class = MessageClass.COPYTOOL_ERROR if event.level == 'ERROR' else MessageClass.COPYTOOL)
continue
# Fixup for times when the register event was missed
if copytool.state != 'started':
# FIXME: Figure out how to find the uuid after the fact. Maybe
# the solution is to send uuid with every event from the
# copytool, but that seems kludgy.
JobSchedulerClient.register_copytool(copytool.id, UNKNOWN_UUID)
try:
active_operations[event.data_fid] = CopytoolOperation.objects.get(id = event.active_operation)
except AttributeError:
if event.state == 'START':
kwargs = dict(
start_time = event.timestamp,
type = event.type,
path = event.lustre_path,
fid = event.data_fid
)
active_operations[event.data_fid] = copytool.create_operation(**kwargs)
continue
elif event.source_fid in active_operations:
active_operations[event.data_fid] = active_operations.pop(event.source_fid)
else:
copytool_log.error("%s on %s, received malformed non-START event: %s" % (copytool, copytool.host, event))
continue
except CopytoolOperation.DoesNotExist:
copytool_log.error("%s on %s, received event for unknown operation: %s" % (copytool, copytool.host, event))
continue
if event.state in ['FINISH', 'ERROR']:
active_operations[event.data_fid].finish(event.timestamp, event.state, event.error)
del active_operations[event.data_fid]
elif event.state == 'RUNNING':
active_operations[event.data_fid].update(event.timestamp, event.current_bytes, event.total_bytes)
else:
copytool_log.error("%s on %s, received unknown event type: %s" % (copytool, copytool.host, event))
continue
try:
return HttpResponse(json.dumps({'active_operations': dict((fid, op.id) for fid, op in active_operations.items())}), mimetype="application/json")
except AttributeError:
return HttpResponse()
class MessageView(ValidatedClientView):
queues = None
sessions = None
hosts = None
LONG_POLL_TIMEOUT = 30
@log_exception
def post(self, request):
"""
Receive messages FROM the agent.
Handle a POST containing messages from the agent
"""
body = json.loads(request.body)
fqdn = self.valid_fqdn(request)
if not fqdn:
return HttpForbidden()
try:
messages = body['messages']
except KeyError:
return HttpResponseBadRequest("Missing attribute 'messages'")
# Check that the server identifier in each message
# is valid by comparing against the SSL_CLIENT_NAME
# which is cryptographically vouched for at the HTTPS frontend
for message in messages:
if message['fqdn'] != fqdn:
return HttpResponseBadRequest("Incorrect client name")
log.debug("MessageView.post: %s %s messages: %s" % (fqdn, len(messages), body))
for message in messages:
if message['type'] == 'DATA':
try:
self.sessions.get(fqdn, message['plugin'], message['session_id'])
except KeyError:
log.warning("Terminating session because unknown %s/%s/%s" % (fqdn, message['plugin'], message['session_id']))
self.queues.send({
'fqdn': fqdn,
'type': 'SESSION_TERMINATE',
'plugin': message['plugin'],
'session_id': None,
'session_seq': None,
'body': None
})
else:
log.debug("Forwarding valid message %s/%s/%s-%s" % (fqdn, message['plugin'], message['session_id'], message['session_seq']))
self.queues.receive(message)
elif message['type'] == 'SESSION_CREATE_REQUEST':
session = self.sessions.create(fqdn, message['plugin'])
log.info("Creating session %s/%s/%s" % (fqdn, message['plugin'], session.id))
# When creating a session, it may be for a new agent instance. There may be an older
# agent instance with a hanging GET. We need to make sure that messages that we send
# from this point onwards go to the new agent and not any GET handlers that haven't
# caught up yet. Achive this by sending a barrier message with the agent start time, such
# that any GET handler receiving the barrier which has a different agent start time will
# detach itself from the TX queue. NB the barrier only works because there's also a lock,
# so if there was a zombie GET, it will be holding the lock and receive the barrier.
self.queues.send({
'fqdn': fqdn,
'type': 'TX_BARRIER',
'client_start_time': body['client_start_time']
})
self.queues.send({
'fqdn': fqdn,
'type': 'SESSION_CREATE_RESPONSE',
'plugin': session.plugin,
'session_id': session.id,
'session_seq': None,
'body': None
})
return HttpResponse()
def _filter_valid_messages(self, fqdn, messages):
plugin_to_session_id = {}
def is_valid(message):
try:
session_id = plugin_to_session_id[message['plugin']]
except KeyError:
try:
plugin_to_session_id[message['plugin']] = session_id = self.sessions.get(fqdn, message['plugin']).id
except KeyError:
plugin_to_session_id[message['plugin']] = session_id = None
if message['session_id'] != session_id:
log.debug("Dropping message because it has stale session id (current is %s): %s" % (session_id, message))
return False
return True
return [m for m in messages if is_valid(m)]
@log_exception
def get(self, request):
"""
Send messages TO the agent.
Handle a long-polling GET for messages to the agent
"""
fqdn = self.valid_fqdn(request)
if not fqdn:
return HttpForbidden()
server_boot_time = IMLDateTime.parse(request.GET['server_boot_time'])
client_start_time = IMLDateTime.parse(request.GET['client_start_time'])
messages = []
try:
reset_required = self.hosts.update(fqdn, server_boot_time, client_start_time)
except ManagedHost.DoesNotExist:
# This should not happen because the HTTPS frontend should have the
# agent certificate revoked before removing the ManagedHost from the database
log.error("GET from unknown server %s" % fqdn)
return HttpResponseBadRequest("Unknown server '%s'" % fqdn)
if reset_required:
# This is the case where the http_agent service restarts, so
# we have to let the agent know that all open sessions
# are now over.
messages.append({
'fqdn': fqdn,
'type': 'SESSION_TERMINATE_ALL',
'plugin': None,
'session_id': None,
'session_seq': None,
'body': None
})
log.debug("MessageView.get: composing messages for %s" % fqdn)
queues = self.queues.get(fqdn)
# If this handler is sitting on the TX queue, draining messages, then
# when a new session starts, *before* sending any TX messages, we have to
# make sure it has been disconnected, to avoid the TX messages being sent
# to an 'old' session (old session meaning TCP connection from a now-dead agent)
with queues.tx_lock:
try:
first_message = queues.tx.get(block=True, timeout=self.LONG_POLL_TIMEOUT)
if first_message['type'] == 'TX_BARRIER':
if first_message['client_start_time'] != request.GET['client_start_time']:
log.warning("Cancelling GET due to barrier %s %s" % (first_message['client_start_time'], request.GET['client_start_time']))
return HttpResponse(json.dumps({'messages': []}), mimetype="application/json")
else:
messages.append(first_message)
except Queue.Empty:
pass
else:
# TODO: limit number of messages per response
while True:
try:
message = queues.tx.get(block=False)
if message['type'] == 'TX_BARRIER':
if message['client_start_time'] != request.GET['client_start_time']:
log.warning("Cancelling GET due to barrier %s %s" % (message['client_start_time'], request.GET['client_start_time']))
return HttpResponse(json.dumps({'messages': []}), mimetype="application/json")
else:
messages.append(message)
except Queue.Empty:
break
messages = self._filter_valid_messages(fqdn, messages)
log.debug("MessageView.get: responding to %s with %s messages (%s)" % (fqdn, len(messages), client_start_time))
return HttpResponse(json.dumps({'messages': messages}), mimetype = "application/json")
def validate_token(key, credits=1):
"""
Validate that a token is valid to authorize a setup/register operation:
* Check it's not expired
* Check it has some credits
:param credits: number of credits to decrement if valid
:return 2-tuple (<http response if error, else None>, <registration token if valid, else None>)
"""
try:
with transaction.commit_on_success():
token = RegistrationToken.objects.get(secret = key)
if not token.credits:
log.warning("Attempt to register with exhausted token %s" % key)
return HttpForbidden(), None
else:
# Decrement .credits
RegistrationToken.objects.filter(secret = key).update(credits = token.credits - credits)
except RegistrationToken.DoesNotExist:
log.warning("Attempt to register with non-existent token %s" % key)
return HttpForbidden(), None
else:
now = IMLDateTime.utcnow()
if token.expiry < now:
log.warning("Attempt to register with expired token %s (now %s, expired at %s)" % (key, now, token.expiry))
return HttpForbidden(), None
elif token.cancelled:
log.warning("Attempt to register with cancelled token %s" % key)
return HttpForbidden(), None
return None, token
@csrf_exempt
@log_exception
def setup(request, key):
token_error, token = validate_token(key, credits=0)
if token_error:
return token_error
# the minimum repos needed on a storage server now
repos = open("/usr/share/chroma-manager/storage_server.repo").read()
repo_names = token.profile.bundles.values_list('bundle_name', flat=True)
| |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
''' Class for plotting an XZ- , an RZ and an YZ-axis in the same plot.
See PlotterXZ for general info.
'''
# General imports
from matplotlib.figure import Figure
from matplotlib.gridspec import GridSpec
import numpy as np
import logging
# Import from project files
from . import plotterXZ
# Settings
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# DEFINE PLOTTER XYZ #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class PlotterXYRZ(plotterXZ.PlotterXZ):
@classmethod
def _get_opt_float(cls):
opts = super()._get_opt_float()
opts['ymin'] = 'Set y-axis minimum'
opts['ymax'] = 'Set y-axis maximum'
opts['rmin'] = 'Set r-axis minimum'
opts['rmax'] = 'Set r-axis maximum'
opts['yscale'] = 'Set scale of y-axis'
opts['rscale'] = 'Set scale of r-axis'
opts['scale'] = 'Set scale of all axes'
opts['xz_ratio'] = 'Set xz-ratio for all axes'
opts['diffx'] = 'Set offset in x&y&r for each plot'
opts['diffy'] = 'Set offset in y for each plot'
opts['diffr'] = 'Set offset in r for each plot'
opts['diffz'] = 'Set offset in z for each plot'
return opts
@classmethod
def _get_opt_string(cls):
opts = super()._get_opt_string()
opts.pop('fx', None) # not valid
opts['ylabel'] = 'Set y-axis label'
opts['rlabel'] = 'Set r-axis label'
opts['axes_visible'] = 'Choose axes to plot `xyr`'
return opts
def __init__(self,
# control axis
rlabel='R', rscale=1, rmin=None, rmax=None,
ylabel='Y', yscale=1, ymin=None, ymax=None,
diffx=0, diffy=0, diffr=0, diffz=0,
scale=None, axes_visible='xyr', xz_ratio=2.2,
**kwargs):
super().__init__(**kwargs)
# get input / set defaults / sub-class to override if needed
self.rlabel = rlabel
self.ylabel = ylabel
self.rscale = rscale
self.yscale = yscale
if scale is not None:
self.xscale = scale
self.yscale = scale
self.rscale = scale
self.zscale = scale
# plot limits, set by initiation
# leave as 'none' to use plotted data instead
# note: default is to set xy&r-axis equal
self.ymin = ymin
self.ymax = ymax
self.rmin = rmin
self.rmax = rmax
# possibly add offset to plots
self.originx = 0
self.originy = 0
self.originr = 0
self.originz = 0
self.diffx = diffx
self.diffy = diffy or diffx
self.diffr = diffr or diffx
self.diffz = diffz
# plot setup
self.xz_ratio = xz_ratio
self.axes_visible = axes_visible
# plot data
self.pd_y = [] # y-data
self.pd_r = [] # r-data
# add one dict for each plotted data for each axis
self.plotted_data = []
def _set_fig(self):
'''Create figure and add axes.'''
self.reset_mc_cc() # reset colors
self._clear_fig() # clear any present figure
# set-up dummy figure (for unused axes)
self._fig_ghost = Figure()
gs = GridSpec(1, 3, figure=self.fig)
self.ax_xz = self._fig_ghost.add_subplot(gs[0], aspect='equal')
self.ax_yz = self._fig_ghost.add_subplot(gs[1], aspect='equal')
self.ax_rz = self._fig_ghost.add_subplot(gs[2], aspect='equal')
self._axes_ghost = [self.ax_xz, self.ax_yz, self.ax_rz]
# set-up actual figure
self.fig = Figure() # create new figure
self.axes = []
m = len(self.axes_visible)
n = 0
gs = GridSpec(1, m, figure=self.fig)
for key in self.axes_visible:
if key == 'x':
self.ax_xz = self.fig.add_subplot(gs[n], aspect='equal')
self.axes.append(self.ax_xz)
n += 1
if key == 'y':
self.ax_yz = self.fig.add_subplot(gs[n], aspect='equal')
self.axes.append(self.ax_yz)
n += 1
if key == 'r':
self.ax_rz = self.fig.add_subplot(gs[n], aspect='equal')
self.axes.append(self.ax_rz)
n += 1
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Manage data #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def add_data(self, data):
''' Parse data, append data to plot.
Set fpath, llabel, and update origin, as needed.
Parameters
----------
data : dict
loaded simulation data
'''
self.set_fpath(fpath=self.fpath, data=data)
self.set_llabel(data)
# get data
x, y, r, z, t = self.get_xyrzt(data)
x = x * self.xscale
y = y * self.yscale
r = r * self.rscale
z = z * self.zscale
t = t if len(t) == 0 else t * self.tscale
x, y, r, z = self.update_origin(x, y, r, z)
# append data - to be plotted in the end
self.pd_x.append(x)
self.pd_y.append(y)
self.pd_r.append(r)
self.pd_z.append(z)
self.pd_t.append(t)
self.pd_l.append(self.desc['label'])
self.pd_d.append(self.desc.copy())
self.pd_f.append(data['header']['sim_input']['name'])
msg = 'Added {} data points for: {}'
logger.debug(msg.format(x.size, self.desc['label']))
def get_xyrzt(self, data):
'''Get plot data. '''
# this method need to be defined in sub-class
raise NotImplementedError('Plotter need to be sub-classed')
def update_origin(self, x, y, r, z):
''' Offset plot by changing origin. '''
# allow plotting of nothing
# ensures correct legend sequence
if len(x) != 0:
# update positions
x = x + self.originx
y = y + self.originy
r = r + self.originr
z = z + self.originz
# update origin after
self.originx = self.originx + self.diffx
self.originy = self.originy + self.diffy
self.originr = self.originr + self.diffr
self.originz = self.originz + self.diffz
return x, y, r, z
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Manage plotting methods (plot all data) #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def plot_all_pd(self):
''' Plot all data in `self.pd_*` to the axes.
Plot in given order, or sort by legend, as specified.
Remove non-finite elements.
Apply the mask in `pd_m` (used for e.g. plotting movie).
Save the actual plotted data, for dumping later, if specified.
'''
def _argsort(seq):
# return indexes of the sorted sequence.
sbv = sorted((v, i) for (i, v) in enumerate(seq))
return [i for (v, i) in sbv]
# define methods for sorting
# idea: add other ways to sort
# idea: allow user to chose sorting
ksa = list(range(len(self.pd_f))) # added
ksf = _argsort(self.pd_f) # filename
ksl = _argsort(self.pd_l) # legend
# set sorting method (key-index'es)
kis = ksf
if self.legend_sorted:
kis = ksl
# plot in correct order
for ki in kis:
# use masked values, if specified
if self.pd_m:
mask = self.pd_m[ki]
else:
mask = np.isfinite(self.pd_x[ki])
# get the time-series
if sum(len(t) for t in self.pd_t) == 0:
t = []
elif len(self.pd_t[ki]) == 0:
t = []
else:
t = self.pd_t[ki][mask]
# get correct data and plot
x = self.pd_x[ki][mask]
y = self.pd_y[ki][mask]
r = self.pd_r[ki][mask]
z = self.pd_z[ki][mask]
d = self.pd_d[ki]
self.desc.update(d)
label = self.plot_xyrz(x, y, r, z)
self.append_plotted_data(x, y, r, z, t, label)
def append_plotted_data(self, x, y, r, z, t, label):
''' Append the plotted data to a dict as strings. '''
if 'x' in self.axes_visible:
super().append_plotted_data(x, z, t, f'{label}, xz-axis')
if 'y' in self.axes_visible:
super().append_plotted_data(y, z, t, f'{label}, yz-axis')
if 'r' in self.axes_visible:
super().append_plotted_data(r, z, t, f'{label}, rz-axis')
def plot_xyrz(self, x, y, r, z):
''' Actually plot data to the axes, return label.
Update plot description.
Plot legend.
Invoke any/all plotting method(s) specified.
'''
# update descriptions
if self.colors:
self.desc.update(color=next(self.cc)['color'])
if self.markers:
self.scatter_desc.update(marker=next(self.mc)['marker'])
# plot the legend label
desc = self.add_label_to_axes()
label = desc['label']
# plot nothing if nothing is found
# ensures correct legend sequence
if len(x) == 0:
logger.debug('Nothing to plot.')
return
if self.curve_on:
self.curve(x, y, r, z)
if self.scatter_on:
self.scatter(x, y, r, z)
# todo: implement these
if self.lowess_on:
logger.warning(f'`lowess` not implemented')
# self.lowess(x, z)
if self.interpolate_on:
logger.warning(f'`interpolate` not implemented')
# self.interpolate(x, z)
if self.errorbar_on:
logger.warning(f'`errorbar` not implemented')
# self.errorbar(x, z)
if self.minmaxbar_on:
logger.warning(f'`minmaxbar` not implemented')
# self.minmaxbar(x, z)
if self.minmaxfill_on:
logger.warning(f'`minmaxfill` not implemented')
# self.minmaxfill(x, z)
if self.lowess_zx_on:
logger.warning(f'`lowess_zx` not implemented')
# self.lowess_zx(x, z)
if self.interpolate_zx_on:
logger.warning(f'`interpolate_zx` not implemented')
# self.interpolate_zx(x, z)
return label
# # # # # # # # # | |
<reponame>tinyclues/ipython
# -*- coding: utf-8 -*-
"""Classes for handling input/output prompts.
Authors:
* <NAME>
* <NAME>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2010 The IPython Development Team
# Copyright (C) 2001-2007 <NAME> <<EMAIL>>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import re
import socket
import sys
from IPython.core import release
from IPython.external.Itpl import ItplNS
from IPython.utils import coloransi
#-----------------------------------------------------------------------------
# Color schemes for prompts
#-----------------------------------------------------------------------------
PromptColors = coloransi.ColorSchemeTable()
InputColors = coloransi.InputTermColors # just a shorthand
Colors = coloransi.TermColors # just a shorthand
PromptColors.add_scheme(coloransi.ColorScheme(
'NoColor',
in_prompt = InputColors.NoColor, # Input prompt
in_number = InputColors.NoColor, # Input prompt number
in_prompt2 = InputColors.NoColor, # Continuation prompt
in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
out_prompt = Colors.NoColor, # Output prompt
out_number = Colors.NoColor, # Output prompt number
normal = Colors.NoColor # color off (usu. Colors.Normal)
))
# make some schemes as instances so we can copy them for modification easily:
__PColLinux = coloransi.ColorScheme(
'Linux',
in_prompt = InputColors.Green,
in_number = InputColors.LightGreen,
in_prompt2 = InputColors.Green,
in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
out_prompt = Colors.Red,
out_number = Colors.LightRed,
normal = Colors.Normal
)
# Don't forget to enter it into the table!
PromptColors.add_scheme(__PColLinux)
# Slightly modified Linux for light backgrounds
__PColLightBG = __PColLinux.copy('LightBG')
__PColLightBG.colors.update(
in_prompt = InputColors.Blue,
in_number = InputColors.LightBlue,
in_prompt2 = InputColors.Blue
)
PromptColors.add_scheme(__PColLightBG)
del Colors,InputColors
#-----------------------------------------------------------------------------
# Utilities
#-----------------------------------------------------------------------------
def multiple_replace(dict, text):
""" Replace in 'text' all occurences of any key in the given
dictionary by its corresponding value. Returns the new string."""
# Function by <NAME>, originally found at:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
#-----------------------------------------------------------------------------
# Special characters that can be used in prompt templates, mainly bash-like
#-----------------------------------------------------------------------------
# If $HOME isn't defined (Windows), make it an absurd string so that it can
# never be expanded out into '~'. Basically anything which can never be a
# reasonable directory name will do, we just want the $HOME -> '~' operation
# to become a no-op. We pre-compute $HOME here so it's not done on every
# prompt call.
# FIXME:
# - This should be turned into a class which does proper namespace management,
# since the prompt specials need to be evaluated in a certain namespace.
# Currently it's just globals, which need to be managed manually by code
# below.
# - I also need to split up the color schemes from the prompt specials
# somehow. I don't have a clean design for that quite yet.
HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
# We precompute a few more strings here for the prompt_specials, which are
# fixed once ipython starts. This reduces the runtime overhead of computing
# prompt strings.
USER = os.environ.get("USER")
HOSTNAME = socket.gethostname()
HOSTNAME_SHORT = HOSTNAME.split(".")[0]
ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
prompt_specials_color = {
# Prompt/history count
'%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
# Just the prompt counter number, WITHOUT any coloring wrappers, so users
# can get numbers displayed in whatever color they want.
r'\N': '${self.cache.prompt_count}',
# Prompt/history count, with the actual digits replaced by dots. Used
# mainly in continuation prompts (prompt_in2)
#r'\D': '${"."*len(str(self.cache.prompt_count))}',
# More robust form of the above expression, that uses the __builtin__
# module. Note that we can NOT use __builtins__ (note the 's'), because
# that can either be a dict or a module, and can even mutate at runtime,
# depending on the context (Python makes no guarantees on it). In
# contrast, __builtin__ is always a module object, though it must be
# explicitly imported.
r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
# Current working directory
r'\w': '${os.getcwd()}',
# Current time
r'\t' : '${time.strftime("%H:%M:%S")}',
# Basename of current working directory.
# (use os.sep to make this portable across OSes)
r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
# These X<N> are an extension to the normal bash prompts. They return
# N terms of the path, after replacing $HOME with '~'
r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
r'\X1': '${self.cwd_filt(1)}',
r'\X2': '${self.cwd_filt(2)}',
r'\X3': '${self.cwd_filt(3)}',
r'\X4': '${self.cwd_filt(4)}',
r'\X5': '${self.cwd_filt(5)}',
# Y<N> are similar to X<N>, but they show '~' if it's the directory
# N+1 in the list. Somewhat like %cN in tcsh.
r'\Y0': '${self.cwd_filt2(0)}',
r'\Y1': '${self.cwd_filt2(1)}',
r'\Y2': '${self.cwd_filt2(2)}',
r'\Y3': '${self.cwd_filt2(3)}',
r'\Y4': '${self.cwd_filt2(4)}',
r'\Y5': '${self.cwd_filt2(5)}',
# Hostname up to first .
r'\h': HOSTNAME_SHORT,
# Full hostname
r'\H': HOSTNAME,
# Username of current user
r'\u': USER,
# Escaped '\'
'\\\\': '\\',
# Newline
r'\n': '\n',
# Carriage return
r'\r': '\r',
# Release version
r'\v': release.version,
# Root symbol ($ or #)
r'\$': ROOT_SYMBOL,
}
# A copy of the prompt_specials dictionary but with all color escapes removed,
# so we can correctly compute the prompt length for the auto_rewrite method.
prompt_specials_nocolor = prompt_specials_color.copy()
prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
# Add in all the InputTermColors color escapes as valid prompt characters.
# They all get added as \\C_COLORNAME, so that we don't have any conflicts
# with a color name which may begin with a letter used by any other of the
# allowed specials. This of course means that \\C will never be allowed for
# anything else.
input_colors = coloransi.InputTermColors
for _color in dir(input_colors):
if _color[0] != '_':
c_name = r'\C_'+_color
prompt_specials_color[c_name] = getattr(input_colors,_color)
prompt_specials_nocolor[c_name] = ''
# we default to no color for safety. Note that prompt_specials is a global
# variable used by all prompt objects.
prompt_specials = prompt_specials_nocolor
#-----------------------------------------------------------------------------
# More utilities
#-----------------------------------------------------------------------------
def str_safe(arg):
"""Convert to a string, without ever raising an exception.
If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
error message."""
try:
out = str(arg)
except UnicodeError:
try:
out = arg.encode('utf_8','replace')
except Exception,msg:
# let's keep this little duplication here, so that the most common
# case doesn't suffer from a double try wrapping.
out = '<ERROR: %s>' % msg
except Exception,msg:
out = '<ERROR: %s>' % msg
#raise # dbg
return out
#-----------------------------------------------------------------------------
# Prompt classes
#-----------------------------------------------------------------------------
class BasePrompt(object):
"""Interactive prompt similar to Mathematica's."""
def _get_p_template(self):
return self._p_template
def _set_p_template(self,val):
self._p_template = val
self.set_p_str()
p_template = property(_get_p_template,_set_p_template,
doc='Template for prompt string creation')
def __init__(self, cache, sep, prompt, pad_left=False):
# Hack: we access information about the primary prompt through the
# cache argument. We need this, because we want the secondary prompt
# to be aligned with the primary one. Color table info is also shared
# by all prompt classes through the cache. Nice OO spaghetti code!
self.cache = cache
self.sep = sep
# regexp to count the number of spaces at the end of a prompt
# expression, useful for prompt auto-rewriting
self.rspace = re.compile(r'(\s*)$')
# Flag to left-pad prompt strings to match the length of the primary
# prompt
self.pad_left = pad_left
# Set template to create each actual prompt (where numbers change).
# Use a property
self.p_template = prompt
self.set_p_str()
def set_p_str(self):
""" Set the interpolating prompt strings.
This must be called every time the color settings change, because the
prompt_specials global may have changed."""
import os,time # needed in locals for prompt string handling
loc = locals()
try:
self.p_str = ItplNS('%s%s%s' %
('${self.sep}${self.col_p}',
multiple_replace(prompt_specials, self.p_template),
'${self.col_norm}'),self.cache.shell.user_ns,loc)
self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
self.p_template),
self.cache.shell.user_ns,loc)
except:
print "Illegal prompt template (check $ usage!):",self.p_template
self.p_str = self.p_template
self.p_str_nocolor = self.p_template
def write(self, msg):
sys.stdout.write(msg)
return ''
def __str__(self):
"""Return a string form of the prompt.
This for is useful for continuation and output prompts, since it is
left-padded to match lengths with the primary one (if the
self.pad_left attribute is set)."""
out_str = str_safe(self.p_str)
if self.pad_left:
# We must find the amount of padding required to match lengths,
# taking the color escapes (which are invisible on-screen) into
# account.
esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
return format % out_str
else:
return out_str
# these path filters are put in as methods so that we can control the
# namespace where the prompt strings get evaluated
def cwd_filt(self, depth):
"""Return the last depth elements of the current working directory.
$HOME is always replaced with '~'.
If depth==0, the full path is returned."""
cwd = os.getcwd().replace(HOME,"~")
out = os.sep.join(cwd.split(os.sep)[-depth:])
if out:
return out
else:
return os.sep
def cwd_filt2(self, depth):
"""Return the | |
"""
domonic.d3.selection
====================================
https://github.com/d3/d3-selection/tree/main/src/selection
"""
# from domonic.html import *
from domonic.dom import document # bring in the global
from domonic.javascript import *
xhtml = "http://www.w3.org/1999/xhtml"
namespaces = {
"svg": "http://www.w3.org/2000/svg",
"xhtml": xhtml,
"xlink": "http://www.w3.org/1999/xlink",
"xml": "http://www.w3.org/XML/1998/namespace",
"xmlns": "http://www.w3.org/2000/xmlns/",
}
# export {default as namespace} from "./namespace.js";
# export {default as namespaces} from "./namespaces.js";
def namespace(name):
name = str(name)
prefix = name
i = String(prefix).indexOf(":")
if i > 0:
prefix = String(name).slice(0, i)
if i >= 0 and prefix != "xmlns":
name = String(name).slice(i + 1)
return (
{"space": namespaces[prefix], "local": name} if Object(namespaces).hasOwnProperty(prefix) else name
) # eslint-disable-line no-prototype-builtins
def creatorInherit(name):
def anon(this):
# document = this.ownerDocument
from domonic.dom import document
# uri = this.namespaceURI
uri = document.namespaceURI
return (
document.createElement(name)
if uri == xhtml and document.documentElement.namespaceURI == xhtml
else document.createElementNS(uri, name)
)
return anon
def creatorFixed(fullname):
# print('this one')
# return lambda this: print(this[0] , "TESTESTESTE")
# return lambda this: this.ownerDocument.createElementNS(fullname['space'], fullname['local'])
from domonic.dom import document # bring in the global document
return lambda *args: document.ownerDocument.createElementNS(fullname["space"], fullname["local"])
def creator(name):
fullname = namespace(name)
# print(fullname)
func = creatorFixed if isinstance(fullname, dict) else creatorInherit
return func(fullname)
def none():
return {}
def selector(selector):
return None if selector == None else lambda: document.querySelector(selector)
# // Given something array like (or null), returns something that is strictly an
# // array. This is used to ensure that array-like objects passed to d3.selectAll
# // or selection.selectAll are converted into proper arrays when creating a
# // selection; we don’t ever want to create a selection backed by a live
# // HTMLCollection or NodeList. However, note that selection.selectAll will use a
# // static NodeList as a group, since it safely derived from querySelectorAll.
def array(x):
b = x if Array.isArray(x) else Array.from_(x)
return [] if x == None else b
# export {default as window} from "./window.js";
def window(node):
return (node.ownerDocument and node.ownerDocument.defaultView) or (node.document and node) or node.defaultView
defaultView = window
# import selection_select from "./select.js";
# import selection_style from "./style.js";
def styleValue(node, name):
return node.style.getPropertyValue(name) or defaultView(node).getComputedStyle(node, None).getPropertyValue(name)
def sparse(self, update):
return Array(len(update))
class EnterNode:
def __init__(self, parent, datum):
self.ownerDocument = parent.ownerDocument
self.namespaceURI = parent.namespaceURI
self._next = None
self._parent = parent
self.__data__ = datum
def appendChild(self, child):
return self._parent.insertBefore(child, self._next)
def insertBefore(self, child, next):
return self._parent.insertBefore(child, next)
def querySelector(self, selector):
return self._parent.querySelector(selector)
def querySelectorAll(self, selector):
return self._parent.querySelectorAll(selector)
class ClassList:
def __init__(self, node):
# print('class list is in town')
self._node = node
self._names = classArray(node.getAttribute("class") or "")
def add(self, name):
i = String(self._names).indexOf(name)
if i < 0:
self._names.append(name)
self._node.setAttribute("class", " ".join(self._names))
def remove(self, name):
i = self._names.indexOf(name)
if i >= 0:
self._names.splice(i, 1)
self._node.setAttribute("class", " ".join(self._names))
def contains(self, name):
return self._names.indexOf(name) >= 0
def classArray(string):
return String(string).trim().split(r"/^|\s+/")
def classList(node):
# return node.classList or ClassList(node)
return ClassList(node)
def classedAdd(node, names):
mylist = classList(node)
i = -1
n = len(names)
while i < n:
mylist.add(names[i])
i += 1
def classedRemove(node, names):
list = classList(node)
i = -1
n = len(names)
while i < n:
list.remove(names[i])
i += 1
# import selection_append from "./append.js";
root = [None]
class Selection:
def __init__(self, groups, parents, this=None):
self._groups = groups
self._parents = parents
self.this = None
if this is None:
# self.this = root[0]
# self.this = self._groups#[0]
# self.this = self._groups #.__iter__()
pass
else:
self.this = this # context switcher
# unpack groups into a list of nodes
def __iter__(self):
return self._groups.__iter__()
def select(self, select):
if not callable(select):
select = selector(select)
groups = self._groups
m = len(groups)
subgroups = Array(m)
j = 0
for group in groups:
n = len(group)
subgroup = subgroups[j] = Array(n)
for i in range(n):
node = group[i]
if node is None:
print("NODE WAS NONE.err?")
continue
try:
# print(node.__data__)
node.__data__ = None
# print('bipm', select)
subnode = Function(select).call(node, node.__data__, i, group)
except Exception as e:
# print(e)
print("failed. no __data__ on node")
subnode = None
# if subnode is not None:
# if "__data__" in subnode:
# subnode.__data__ = subnode.__data__
# subgroup[i] = subnode
# subnode.__data__ = node.__data__
# subgroup[i] = subnode
# print('super::', node, subnode)
if "__data__" in node:
subnode.__data__ = node.__data__
subgroup[i] = subnode
j += 1
# print("this was set to", self.this)
return Selection(subgroups, self._parents, self.this)
# import selection_selectAll from "./selectAll.js";
# import {Selection} from "./index.js";
# import array from "../array.js";
# import selectorAll from "../selectorAll.js";
def arrayAll(self, select, *args):
return lambda: array(Function(select).apply(self.this, args))
def selectAll(self, select):
if callable(select):
select = self.arrayAll(select)
else:
select = selectorAll(select)
groups = self._groups
m = len(groups)
subgroups = []
parents = []
j = 0
for group in groups:
n = len(group)
for i in range(n):
node = group[i]
if node is None:
print("selectaAll : NODE WAS NONE.err?")
continue
try:
# print(node.__data__)
node.__data__ = None # TODO - only do this if not there
subgroups.append(Function(select).call(node, node.__data__, i, group))
parents.append(node)
except Exception as e:
# print(e)
print("failed. no __data__ on node")
# subgroups.append(Function(select).call(node, node.__data__, i, group))
# parents.append(node)
j += 1
return Selection(subgroups, parents, self.this)
# import selection_selectChild from "./selectChild.js";
# import {childMatcher} from "../matcher.js";
find = Array.prototype.find
def childFind(self, match):
return lambda: find.call(this.children, match)
def childFirst(self):
return this.firstElementChild
def selectChild(self, match):
# return this.select(match == null ? childFirst : childFind(typeof match === "function" ? match : childMatcher(match)))
if callable(match):
match = childFind(match)
else:
match = childMatcher(match)
return this.select(match)
# import selection_selectChildren from "./selectChildren.js";
# def selectChildren: selection_selectChildren,
# import {childMatcher} from "../matcher.js";
# filter = Array.prototype.filter
def children(self):
return Array.from_(self.this.children)
def childrenFilter(self, match):
return lambda: Array.filter.call(self.this.children, match)
def selectChildren(self, match):
# TODO - rewrite this as python
# return this.selectAll(match == None ? children : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
# return self.selectAll(match == None ? self.children : self.childrenFilter(typeof match == "function" ? match : childMatcher(match)))
if match is None:
return self.selectAll(self.this.children)
else:
return self.selectAll(self.childrenFilter(match))
# import selection_filter from "./filter.js";
# def filter: selection_filter,
# import {Selection} from "./index.js";
# import matcher from "../matcher.js"; # TODO - might not be in yet
def filter(self, match):
if callable(match):
match = matcher(match)
# TODO - rewrite this as python
# for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
# for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
# if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
# subgroup.push(node);
# }
# }
# }
groups = self._groups
m = len(groups)
subgroups = []
j = 0
for group in groups:
n = len(group)
for i in range(n):
node = group[i]
if node is None:
continue
if match.call(node, node.__data__, i, group):
subgroups.append(node)
j += 1
return Selection(subgroups, self._parents, self.this)
# import selection_data from "./data.js";
# def data: selection_data, # TODO -------------------------------------- this is a big one
# import selection_enter from "./enter.js";
# def enter: selection_enter,
# import sparse from "./sparse.js";
# import {Selection} from "./index.js";
def enter(self):
return Selection(self._enter or self._groups.map(sparse), self._parents)
# import selection_exit from "./exit.js";
# def exit: selection_exit,
# import sparse from "./sparse.js";
# import {Selection} from "./index.js";
def exit(self):
return Selection(this._exit or self._groups.map(sparse), self._parents)
# import selection_join from "./join.js";
# def join: selection_join,
def join(self, onenter, onupdate, onexit):
enter = this.enter()
update = this
exit = self.exit()
if callable(onenter):
enter = onenter(enter)
if enter:
enter = enter.selection()
else:
enter = enter.append(onenter + "")
if onupdate != None:
update = onupdate(update)
if update:
update = update.selection()
if onexit == None:
exit.remove()
else:
onexit(exit)
return enter.merge(update).order() if enter and update else update
# import selection_merge from "./merge.js";
# def merge: selection_merge,
# import {Selection} from "./index.js";
def merge(self, context):
selection = context.selection() if context.selection else context
# TODO - rewrite this as python
# for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
# for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
# | |
the geo interiors most likely could not be isolated with this tool so we
# abandon the whole isolation for this geo and add this geo to the not_isolated_geo
if nr_pass == 0 and forced_rest is True:
if geo.interiors:
len_interiors = len(geo.interiors)
if len_interiors > 1:
total_poly_len = 1 + len_interiors # one exterior + len_interiors of interiors
if isinstance(temp_geo, Polygon):
# calculate the number of subgeos in the buffered geo
temp_geo_len = len([1] + list(temp_geo.interiors)) # one exterior + interiors
if total_poly_len != temp_geo_len:
# some interiors could not be isolated
break
else:
try:
temp_geo_len = len(temp_geo)
if total_poly_len != temp_geo_len:
# some interiors could not be isolated
break
except TypeError:
# this means that the buffered geo (temp_geo) is not iterable
# (one geo element only) therefore failure:
# we have more interiors but the resulting geo is only one
break
good_pass_iso.append(temp_geo)
if prog_plot == 'progressive':
prog_plot_handler(temp_geo)
if good_pass_iso:
work_geo += good_pass_iso
else:
not_isolated_geo.append(geo)
if invert:
try:
pl = []
for p in work_geo:
if p is not None:
if isinstance(p, Polygon):
pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
elif isinstance(p, LinearRing):
pl.append(Polygon(p.coords[::-1]))
work_geo = MultiPolygon(pl)
except TypeError:
if isinstance(work_geo, Polygon) and work_geo is not None:
work_geo = [Polygon(work_geo.exterior.coords[::-1], work_geo.interiors)]
elif isinstance(work_geo, LinearRing) and work_geo is not None:
work_geo = [Polygon(work_geo.coords[::-1])]
else:
log.debug("ToolIsolation.generate_rest_geometry() Error --> Unexpected Geometry %s" %
type(work_geo))
except Exception as e:
log.debug("ToolIsolation.generate_rest_geometry() Error --> %s" % str(e))
return 'fail', 'fail'
if env_iso_type == 0: # exterior
for geo in work_geo:
isolated_geo.append(geo.exterior)
elif env_iso_type == 1: # interiors
for geo in work_geo:
isolated_geo += [interior for interior in geo.interiors]
else: # exterior + interiors
for geo in work_geo:
isolated_geo += [geo.exterior] + [interior for interior in geo.interiors]
return isolated_geo, not_isolated_geo
@staticmethod
def get_selected_interior(poly: Polygon, point: tuple) -> [Polygon, None]:
try:
ints = [Polygon(x) for x in poly.interiors]
except AttributeError:
return None
for poly in ints:
if poly.contains(Point(point)):
return poly
return None
def find_polygon_ignore_interiors(self, point, geoset=None):
"""
Find an object that object.contains(Point(point)) in
poly, which can can be iterable, contain iterable of, or
be itself an implementer of .contains(). Will test the Polygon as it is full with no interiors.
:param point: See description
:param geoset: a polygon or list of polygons where to find if the param point is contained
:return: Polygon containing point or None.
"""
if geoset is None:
geoset = self.solid_geometry
try: # Iterable
for sub_geo in geoset:
p = self.find_polygon_ignore_interiors(point, geoset=sub_geo)
if p is not None:
return p
except TypeError: # Non-iterable
try: # Implements .contains()
if isinstance(geoset, LinearRing):
geoset = Polygon(geoset)
poly_ext = Polygon(geoset.exterior)
if poly_ext.contains(Point(point)):
return geoset
except AttributeError: # Does not implement .contains()
return None
return None
class IsoUI:
toolName = _("Isolation Tool")
def __init__(self, layout, app):
self.app = app
self.decimals = self.app.decimals
self.layout = layout
self.tools_frame = QtWidgets.QFrame()
self.tools_frame.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.tools_frame)
self.tools_box = QtWidgets.QVBoxLayout()
self.tools_box.setContentsMargins(0, 0, 0, 0)
self.tools_frame.setLayout(self.tools_box)
self.title_box = QtWidgets.QHBoxLayout()
self.tools_box.addLayout(self.title_box)
# ## Title
title_label = FCLabel("%s" % self.toolName)
title_label.setStyleSheet("""
QLabel
{
font-size: 16px;
font-weight: bold;
}
""")
title_label.setToolTip(
_("Create a Geometry object with\n"
"toolpaths to cut around polygons.")
)
self.title_box.addWidget(title_label)
# App Level label
self.level = FCLabel("")
self.level.setToolTip(
_(
"BASIC is suitable for a beginner. Many parameters\n"
"are hidden from the user in this mode.\n"
"ADVANCED mode will make available all parameters.\n\n"
"To change the application LEVEL, go to:\n"
"Edit -> Preferences -> General and check:\n"
"'APP. LEVEL' radio button."
)
)
self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.title_box.addWidget(self.level)
self.obj_combo_label = FCLabel('<b>%s</b>:' % _("GERBER"))
self.obj_combo_label.setToolTip(
_("Gerber object for isolation routing.")
)
self.tools_box.addWidget(self.obj_combo_label)
# ################################################
# ##### The object to be copper cleaned ##########
# ################################################
self.object_combo = FCComboBox()
self.object_combo.setModel(self.app.collection)
self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
# self.object_combo.setCurrentIndex(1)
self.object_combo.is_last = True
self.tools_box.addWidget(self.object_combo)
separator_line = QtWidgets.QFrame()
separator_line.setFrameShape(QtWidgets.QFrame.HLine)
separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.tools_box.addWidget(separator_line)
# ### Tools ## ##
self.tools_table_label = FCLabel('<b>%s</b>' % _('Tools Table'))
self.tools_table_label.setToolTip(
_("Tools pool from which the algorithm\n"
"will pick the ones used for copper clearing.")
)
self.tools_box.addWidget(self.tools_table_label)
self.tools_table = FCTable(drag_drop=True)
self.tools_box.addWidget(self.tools_table)
self.tools_table.setColumnCount(4)
# 3rd column is reserved (and hidden) for the tool ID
self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
self.tools_table.setColumnHidden(3, True)
self.tools_table.setSortingEnabled(False)
# self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tools_table.horizontalHeaderItem(0).setToolTip(
_("This is the Tool Number.\n"
"Isolation routing will start with the tool with the biggest \n"
"diameter, continuing until there are no more tools.\n"
"Only tools that create Isolation geometry will still be present\n"
"in the resulting geometry. This is because with some tools\n"
"this function will not be able to create routing geometry.")
)
self.tools_table.horizontalHeaderItem(1).setToolTip(
_("Tool Diameter. Its value\n"
"is the cut width into the material."))
self.tools_table.horizontalHeaderItem(2).setToolTip(
_("The Tool Type (TT) can be:\n"
"- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
"the cut width in material is exactly the tool diameter.\n"
"- Ball -> informative only and make reference to the Ball type endmill.\n"
"- V-Shape -> it will disable Z-Cut parameter in the resulting geometry UI form\n"
"and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
"V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
"as the cut width into material will be equal with the value in the Tool Diameter\n"
"column of this table.\n"
"Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
"in the resulting geometry as Isolation."))
grid1 = QtWidgets.QGridLayout()
grid1.setColumnStretch(0, 0)
grid1.setColumnStretch(1, 1)
self.tools_box.addLayout(grid1)
# Tool order
self.order_label = FCLabel('%s:' % _('Tool order'))
self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
"'No' --> means that the used order is the one in the tool table\n"
"'Forward' --> means that the tools will be ordered from small to big\n"
"'Reverse' --> means that the tools will ordered from big to small\n\n"
"WARNING: using rest machining will automatically set the order\n"
"in reverse and disable this control."))
self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
{'label': _('Forward'), 'value': 'fwd'},
{'label': _('Reverse'), 'value': 'rev'}])
grid1.addWidget(self.order_label, 1, 0)
grid1.addWidget(self.order_radio, 1, 1)
separator_line = QtWidgets.QFrame()
separator_line.setFrameShape(QtWidgets.QFrame.HLine)
separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
grid1.addWidget(separator_line, 2, 0, 1, 2)
# #############################################################
# ############### Tool selection ##############################
# #############################################################
self.grid3 = QtWidgets.QGridLayout()
self.grid3.setColumnStretch(0, 0)
self.grid3.setColumnStretch(1, 1)
self.tools_box.addLayout(self.grid3)
self.tool_sel_label = FCLabel('<b>%s</b>' % _('Add from DB'))
self.grid3.addWidget(self.tool_sel_label, 0, 0, 1, 2)
# ### Tool Diameter ####
self.new_tooldia_lbl = FCLabel('%s:' % _('Tool Dia'))
self.new_tooldia_lbl.setToolTip(
_("Diameter for the new tool")
)
self.grid3.addWidget(self.new_tooldia_lbl, 2, 0)
new_tool_lay = QtWidgets.QHBoxLayout()
self.new_tooldia_entry = FCDoubleSpinner(callback=self.confirmation_message)
self.new_tooldia_entry.set_precision(self.decimals)
self.new_tooldia_entry.set_range(0.000, 10000.0000)
self.new_tooldia_entry.setObjectName("i_new_tooldia")
new_tool_lay.addWidget(self.new_tooldia_entry)
# Find Optimal Tooldia
self.find_optimal_button = QtWidgets.QToolButton()
self.find_optimal_button.setText(_('Optimal'))
self.find_optimal_button.setIcon(QtGui.QIcon(self.app.resource_location + '/open_excellon32.png'))
self.find_optimal_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.find_optimal_button.setToolTip(
_("Find a tool diameter that is guaranteed\n"
"to do a complete isolation.")
)
new_tool_lay.addWidget(self.find_optimal_button)
self.grid3.addLayout(new_tool_lay, 2, 1)
bhlay = QtWidgets.QHBoxLayout()
self.search_and_add_btn = FCButton(_('Search and Add'))
self.search_and_add_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/plus16.png'))
self.search_and_add_btn.setToolTip(
_("Add a new tool to the Tool Table\n"
"with the diameter specified above.\n"
"This is done by a background search\n"
"in the Tools Database. If nothing is found\n"
"in the Tools DB then a default tool is added.")
)
bhlay.addWidget(self.search_and_add_btn)
self.addtool_from_db_btn = FCButton(_('Pick from DB'))
self.addtool_from_db_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/search_db32.png'))
self.addtool_from_db_btn.setToolTip(
_("Add a new tool to the Tool Table\n"
"from the Tools Database.\n"
"Tools database administration in in:\n"
"Menu: Options -> Tools Database")
)
bhlay.addWidget(self.addtool_from_db_btn)
self.grid3.addLayout(bhlay, 7, 0, 1, 2)
separator_line = QtWidgets.QFrame()
separator_line.setFrameShape(QtWidgets.QFrame.HLine)
separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.grid3.addWidget(separator_line, 8, 0, 1, 2)
self.deltool_btn = FCButton(_('Delete'))
self.deltool_btn.setIcon(QtGui.QIcon(self.app.resource_location + '/trash16.png'))
self.deltool_btn.setToolTip(
_("Delete a selection of tools in the Tool Table\n"
"by first selecting a row in the Tool Table.")
)
self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
# self.grid3.addWidget(FCLabel(''), 10, 0, 1, 2)
separator_line = QtWidgets.QFrame()
separator_line.setFrameShape(QtWidgets.QFrame.HLine)
separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.grid3.addWidget(separator_line, 11, 0, 1, 2)
self.tool_data_label = FCLabel(
"<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
self.tool_data_label.setToolTip(
_(
"The data used for creating GCode.\n"
"Each tool store it's own set of such data."
)
)
self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
# Passes
passlabel = FCLabel('%s:' % _('Passes'))
passlabel.setToolTip(
_("Width of the isolation gap in\n"
"number (integer) of tool widths.")
)
self.passes_entry = FCSpinner(callback=self.confirmation_message_int)
self.passes_entry.set_range(1, 999)
self.passes_entry.setObjectName("i_passes")
self.grid3.addWidget(passlabel, 13, 0)
self.grid3.addWidget(self.passes_entry, 13, 1)
# Overlap Entry
overlabel = FCLabel('%s:' % _('Overlap'))
overlabel.setToolTip(
_("How much (percentage) of the tool width | |
= "none", Rowv = F, Colv = F, margins = c(15,15),
distfun = function(x) dist(x, method = "manhattan"),
hclustfun = function(x) hclust(x, method = "ward.D2"))''')
R["dev.off"]()
#########################################
#########################################
#########################################
@follows(mkdir("pca.dir"))
@jobs_limit(1, "R")
@transform([os.path.join(PARAMS.get("dna_communitiesdir"), "genes.dir/gene_counts.norm.matrix"),
os.path.join(PARAMS.get("rna_communitiesdir"), "genes.dir/gene_counts.norm.matrix"),
os.path.join(PARAMS.get("dna_communitiesdir"), "counts.dir/genus.diamond.aggregated.counts.norm.matrix"),
os.path.join(PARAMS.get("rna_communitiesdir"), "counts.dir/genus.diamond.aggregated.counts.norm.matrix")],
regex("(\S+)/(\S+).matrix"),
r"pca.dir/\2.loadings.tsv")
def buildPCALoadings(infile, outfile):
'''
run PCA and heatmap the loadings
'''
if "RNA" in infile:
suffix = "rna"
else:
suffix = "dna"
if "gene" in infile:
xlim, ylim = 40,40
else:
xlim, ylim = 12,7
outname_plot = P.snip(outfile, ".loadings.tsv").replace("/", "/%s_" % suffix) + ".pca.pdf"
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''rownames(dat) <- dat$taxa''')
R('''dat <- dat[, 1:ncol(dat)-1]''')
R('''pc <- prcomp(t(dat))''')
R('''conds <- unlist(strsplit(colnames(dat), ".R[0-9]"))[seq(1, ncol(dat)*2, 2)]''')
R('''conds <- unlist(strsplit(conds, ".", fixed = T))[seq(2, length(conds)*2, 2)]''')
# plot the principle components
R('''library(ggplot2)''')
R('''pcs <- data.frame(pc$x)''')
R('''pcs$cond <- conds''')
# get variance explained
R('''imps <- c(summary(pc)$importance[2], summary(pc)$importance[5])''')
R('''p <- ggplot(pcs, aes(x = PC1, y = PC2, colour = cond, size = 3)) + geom_point()''')
R('''p2 <- p + xlab(imps[1]) + ylab(imps[2])''')
R('''p3 <- p2 + scale_colour_manual(values = c("slateGrey", "green", "red", "blue"))''')
R('''p3 + xlim(c(-%i, %i)) + ylim(c(-%i, %i))''' % (xlim, xlim, ylim, ylim))
R('''ggsave("%s")''' % outname_plot)
# get the loadings
R('''loads <- data.frame(pc$rotation)''')
R('''loads$taxa <- rownames(loads)''')
# write out data
R('''write.table(loads, file = "%s", sep = "\t", row.names = F, quote = F)''' % outfile.replace("/", "/%s_" % suffix))
P.touch(outfile)
#########################################
#########################################
#########################################
@jobs_limit(1, "R")
@follows(buildPCALoadings)
@transform("pca.dir/*na_*loadings.tsv", suffix(".tsv"), ".pdf")
def plotPCALoadings(infile, outfile):
'''
plot the loadings associated with differentially
expressed genes
'''
R('''library(ggplot2)''')
R('''library(grid)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''top5pc1 <- dat[order(-dat$PC1),][1:5,]''')
R('''bottom5pc1 <- dat[order(dat$PC1),][1:5,]''')
R('''top5pc2 <- dat[order(-dat$PC2),][1:5,]''')
R('''bottom5pc2 <- dat[order(dat$PC2),][1:5,]''')
R('''totext <- data.frame(rbind(top5pc1, bottom5pc1, top5pc2, bottom5pc2))''')
R('''dat$x <- 0''')
R('''dat$y <- 0''')
R('''p <- ggplot(dat, aes(x = x, y = y, xend = PC1, yend = PC2, colour = taxa))''')
R('''p2 <- p + geom_segment(arrow = arrow(length = unit(0.2, "cm")))''')
R('''p2 + geom_text(data = totext, aes(x = PC1, y = PC2, label = totext$taxa, size = 6)) + xlim(c(-0.5,0.5)) + ylim(c(-0.5,0.25))''')
R('''ggsave("%s")''' % outfile)
#########################################
#########################################
#########################################
@follows(mkdir("indicators.dir"))
@jobs_limit(1, "R")
@transform([os.path.join(PARAMS.get("dna_communitiesdir"), "counts.dir/genus.diamond.aggregated.counts.norm.matrix"),
os.path.join(PARAMS.get("rna_communitiesdir"), "counts.dir/genus.diamond.aggregated.counts.norm.matrix")],
regex("(\S+)/(\S+).matrix"),
r"indicators.dir/\2.indicators.pdf")
def plotIndicatorGenera(infile, outfile):
'''
plot genera that load onto PCA
'''
if "RNA" in infile:
suffix = "rna"
else:
suffix = "dna"
R('''library(reshape)''')
R('''library(ggplot2)''')
R('''library(plyr)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''rownames(dat) <- dat$taxa''')
R('''dat <- dat[c("Akkermansia", "Escherichia", "Peptoniphilus"),]''')
R('''dat2 <- melt(dat)''')
R('''conds <- unlist(strsplit(as.character(dat2$variable), ".R[0-9]"))''')
R('''conds <- conds[seq(1,length(conds),2)]''')
R('''dat2$cond <- conds''')
R('''dat2.sum <- ddply(dat2, c("cond", "taxa"), summarize, mean = mean(value), n = length(cond), sd = sd(value), se = sd/sqrt(n))''')
# R('''dat2.sum <- dat2.sum[dat2.sum$cond == "stool.WT" | dat2.sum$cond == "stool.HhaIL10R",]''')
R('''dodge = position_dodge(width=0.9)''')
R('''plot1 <- ggplot(dat2.sum, aes(x = taxa, y = mean, fill = cond))''')
R('''plot2 <- plot1 + geom_bar(stat = "identity", position = dodge)''')
R('''plot3 <- plot2 + geom_errorbar(aes(ymin = mean-se, ymax = mean+se), width = 0.25, position = dodge)''')
R('''plot3 + scale_fill_manual(values = c("grey", "darkGreen","red", "darkBlue")) + theme_bw()''')
outname = P.snip(outfile, ".pdf") + "." + suffix + ".pdf"
R('''ggsave("%s")''' % outname)
#########################################
#########################################
#########################################
@jobs_limit(1, "R")
@transform(buildGenusDiffList,
suffix(".tsv"),
add_inputs([os.path.join(PARAMS.get("dna_communitiesdir"), "counts.dir/genus.diamond.aggregated.counts.norm.matrix"),
os.path.join(PARAMS.get("rna_communitiesdir"), "counts.dir/genus.diamond.aggregated.counts.norm.matrix")]),
".pdf")
def heatMapDiffGenera(infiles, outfile):
'''
heatmap differences between WT and HhaIL10R groups
'''
# we do this for the different combinations to see how the
# DNA and RNA differences compare
R('''diff <- read.csv("%s", header = F, sep = "\t", stringsAsFactors = F)''' % infiles[0])
R('''library(gplots)''')
R('''library(gtools)''')
for mat in infiles[1]:
if "RNA" in mat:
outname = os.path.dirname(outfile) + "/RNA_" + os.path.basename(outfile)
elif "DNA" in mat:
outname = os.path.dirname(outfile) + "/DNA_" + os.path.basename(outfile)
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % mat)
R('''rownames(dat) <- dat$taxa''')
R('''dat <- dat[, 1:ncol(dat)-1]''')
R('''dat <- dat[diff[,1],]''')
R('''dat <- na.omit(dat)''')
R('''colnames(dat) <- unlist(strsplit(colnames(dat), ".diamond_count"))''')
R('''dat <- dat[, mixedsort(colnames(dat))]''')
R('''samples <- colnames(dat)''')
R('''dat <- t(apply(dat, 1, scale))''')
R('''colnames(dat) <- samples''')
R('''cols <- colorRampPalette(c("blue", "white", "red"))''')
R('''pdf("%s")''' % outname)
R('''heatmap.2(as.matrix(dat), col = cols, scale = "row", trace = "none", Rowv = T, Colv = F, margins = c(15,15),
distfun = function(x) dist(x, method = "manhattan"),
hclustfun = function(x) hclust(x, method = "ward.D2"))''')
R["dev.off"]()
@follows(heatMapDiffGenera,heatMapDiffGenes)
def heatmap():
pass
###################################################
###################################################
###################################################
# build ratio of RNA to DNA and see if there is
# a difference between those that are called
# as differentially abundant in RNA analysis
# vs DNA analysis
###################################################
###################################################
###################################################
@follows(mkdir("rna_dna_ratio.dir"))
@merge(glob.glob(os.path.join(PARAMS.get("rna_communitiesdir"), "genes.dir/gene_counts.diff.tsv"))
+ glob.glob(os.path.join(PARAMS.get("dna_communitiesdir"), "genes.dir/gene_counts.diff.tsv")),
"rna_dna_ratio.dir/ratio_genes.tsv")
def buildRNADNARatio(infiles, outfile):
'''
build the ratio between RNA expression
and DNA abundance - from normalised
counts
'''
rna = [x for x in infiles if "RNA" in x][0]
dna = [x for x in infiles if "DNA" in x][0]
R('''rna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % rna)
R('''dna <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % dna)
R('''rna <- rna[rna$group1 == "HhaIL10R" & rna$group2 == "WT",]''')
R('''dna <- dna[dna$group1 == "HhaIL10R" & dna$group2 == "WT",]''')
R('''rownames(rna) <- rna$taxa''')
R('''rownames(dna) <- dna$taxa''')
R('''rna <- rna[,1:ncol(rna)-1]''')
R('''dna <- dna[,1:ncol(dna)-1]''')
# only look at those that are present in both
R('''keep <- intersect(rownames(rna), rownames(dna))''')
R('''rna <- rna[keep,]''')
R('''dna <- dna[keep,]''')
R('''rna.ratio <- rna$logFC''')
R('''dna.ratio <- dna$logFC''')
R('''rna.p <- rna$adj.P.Val''')
R('''dna.p <- dna$adj.P.Val''')
R('''ratio <- data.frame(gene = keep, dna = dna.ratio, rna = rna.ratio, pdna = dna.p, prna = rna.p, ratio = rna.ratio - dna.ratio)''')
R('''write.table(ratio, file = "%s", sep = "\t", row.names = F, quote = F)''' % outfile)
###################################################
###################################################
###################################################
@transform(buildRNADNARatio,
suffix(".tsv"),
add_inputs(buildGeneDiffList),
".annotated.tsv")
def annotateRNADNARatio(infiles, outfile):
'''
annotate the ratio data with how genes look in terms
of DNA and RNA regulation
'''
rna_diff = set([y[:-1] for y in open([x for x in infiles if "RNA" in x][0]).readlines()])
dna_diff = set([y[:-1] for y in open([x for x in infiles if "DNA" in x][0]).readlines()])
inf = IOTools.openFile(infiles[0])
inf.readline()
outf = IOTools.openFile(outfile, "w")
outf.write("gene\tdna\trna\tpdna\tprna\tratio\tstatus\n")
for line in inf.readlines():
gene, dna, rna, pdna, prna, ratio = line[:-1].split("\t")
gene = gene.strip('"')
dna, rna = float(dna), float(rna)
if gene in rna_diff and gene in dna_diff and dna > 0 and rna > 0:
status = "up.both"
elif gene in rna_diff and gene in dna_diff and dna < 0 and rna < 0:
status = "down.both"
elif gene in rna_diff and rna > 0:
status = "up.RNA"
elif gene in rna_diff and rna < 0:
status = "down.RNA"
elif gene in dna_diff and dna > 0:
status = "up.DNA"
elif gene in dna_diff and dna < 0:
status = "down.DNA"
else:
status = "NS"
outf.write("%(gene)s\t%(dna)s\t%(rna)s\t%(pdna)s\t%(prna)s\t%(ratio)s\t%(status)s\n" % locals())
outf.close()
###################################################
###################################################
###################################################
@transform(annotateRNADNARatio, suffix(".tsv"), ".pdf")
def plotSets(infile, outfile):
'''
plot the fold changes in RNA and DNA analyses
and label by how they are regulated in DNA and
RNA analyses
'''
R('''library(ggplot2)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, sep = "\t")''' % infile)
R('''cog2gene <- read.csv("goi.tsv", header = F, stringsAsFactors = F, sep = "\t", row.names = 1)''')
# just get those signficant in either DNA or RNA or both
R('''dat$status[dat$status == "NS"] = "z"''')
R('''genes <- dat$gene''')
# regression model
R('''mod1 <- lm(dat$rna~dat$dna)''')
R('''intercept <- mod1[[1]][1]''')
R('''slope = mod1[[1]][2]''')
# prediction intervals
R('''pred.ints <- predict(mod1, interval = "prediction", level = 0.95)''')
# add to data.frame
R('''dat$lwr <- pred.ints[,2]''')
R('''dat$upr <- pred.ints[,3]''')
# add labels
R('''dat$goi <- cog2gene[dat$gene,]''')
R('''dat$pointsize <- ifelse(!(is.na(dat$goi)), 10, 1)''')
# plot
R('''plot1 <- ggplot(dat, aes(x = dna, y = rna, alpha = 1, colour = status)) + geom_point(shape = 18, aes(size = pointsize)) + scale_size_area() + xlim(c(-5,5))''')
R('''plot2 <- plot1 + scale_colour_manual(values = c("blue", "brown","darkGreen", "orange", "purple", "red", "grey"))''')
R('''plot3 <- plot2 + geom_abline(yintercept = intercept, slope = slope)''')
# prediction intervals
R('''plot4 <- plot3 + geom_line(aes(x = dna, y = lwr), linetype = "dashed", colour = "black")''')
R('''plot5 <- plot4 + geom_line(aes(x = dna, y = upr), linetype = "dashed", colour = "black")''')
R('''plot5 + geom_text(aes(label = goi))''')
# R('''plot6 <- plot5 + geom_vline(xintercept = 0) + geom_vline(xintercept = c(-1,1), linetype = "dashed")''')
# R('''plot6 + geom_hline(yintercept = 0) + geom_hline(yintercept = c(-1,1), linetype = "dashed")''')
R('''ggsave("%s")''' % | |
<filename>ai/Algorithm/influence_map.py<gh_stars>0
# Under MIT License, see LICENSE.txt
from math import ceil, sqrt
import numpy
from RULEngine.Util.constant import *
from RULEngine.Util.Position import Position
from ai.Algorithm.IntelligentModule import IntelligentModule
__author__ = 'RoboCupULaval'
class InfluenceMap(IntelligentModule):
"""
Une classe représentant une influence map d'un terrain de robosoccer. C'est une matrice de cellule représentant le
terrain auquelle on ajoute des points avec des influences qui se propagent sur le reste du terrain.
La matrice et le code respecte le format suivant:
- axe X ou axe 0 est l'axe représentant les rangées / l'axe 0 de la matrice /
la largeur (axe Y) du terrain physique
- axe Y ou axe 1 est l'axe représentant les colonnes / l'axe 1 de la matrice /
la longueur (axe X) du terrain physique
- Le point d'origine (0, 0) se situe au coin supérieur gauche du terrain physique.
- Ce qui veut dire que c'est tableaux sont row-major.
L'algorithm de propagation de l'influence est:
(force appliqué à la case) = (force du point d'origine de l'influence) * ((facteur de réduction) ** (distance))
transfomé en int arrondie vers 0.
"""
def __init__(self, game_state, resolution=100, strength_decay=0.90, strength_peak=100, effect_radius=40,
have_static=False, have_it_executed=False):
"""
Constructeur de la classe InfluenceMap
:param game_state: référence vers le game state
:param resolution: résolution des cases (défaut = 100)
:param strength_decay: facteur de réduction de l'influence par la distance (défaut = 0.8)
:param strength_peak: maximum de la force appliquable par un point (est aussi le min) (défaut = 100)
:param effect_radius: distance qui borne la propagation de l'influence autour de l'origine (défaut = 40)
"""
assert isinstance(resolution, int), "Creation InfluenceMap avec param resolution autre que int"
assert isinstance(strength_decay, float), "Creation InfluenceMap avec param strength_decay autre que int"
assert isinstance(effect_radius, int), "Creation InfluenceMap avec param effect_radius autre que int"
assert isinstance(strength_peak, int), "Creation InfluenceMap avec param strength_peak autre que int"
assert isinstance(have_static, bool), "Creation InfluenceMap avec param have_static autre que bool"
assert isinstance(have_it_executed, bool), "Creation InfluenceMap avec param have_it_executed autre que bool"
assert 0 < resolution, "Creation InfluenceMap avec param resolution <= 0"
assert 0 < strength_decay < 1, "Creation InfluenceMap avec param strength_decay pas dans intervalle ]0, 1["
assert 0 < strength_peak, "Creation InfluenceMap avec param strength_decay <= à 0"
assert 0 < effect_radius, "Creation InfluenceMap avec param effect_radius <= 0"
super().__init__(game_state)
# board parameters
self._resolution = resolution
self._strength_decay = strength_decay
self._strength_peak = strength_peak
self._effect_radius = effect_radius
self._border_strength = - strength_peak * 0.03 # TODO change this variable for something not out of thin air!
# things on the baord parameters
self._ball_position_on_board = ()
self._number_of_rows, self._number_of_columns = self._calculate_rows_and_columns()
if self.state is not None:
self.have_it_executed = have_it_executed
self._last_updated = self.state.get_timestamp()
self._adjust_effect_radius()
# different tableau pour enregistrer les différentes représentation
self._static_boards = None
self._starterboard = self._create_standard_influence_board()
self._board = self._create_standard_influence_board()
# those board are optionnal
self._borders_board = self._create_standard_influence_board()
self._goals_board = self._create_standard_influence_board()
# todo determine how to choose if you want different kinds of static boards (ex: borders, goals, to determine..)
if have_static:
self._create_static_board()
def update(self):
if self.have_it_executed:
if self.state.get_timestamp() - self._last_updated > 1:
# purge the board with a new one (static or not)
if self._static_boards is not None:
self._board = numpy.copy(self._static_boards)
else:
self._board = self._create_standard_influence_board()
self._update_and_draw_robot_position()
self._update_ball_position()
self.state.debug_manager.add_influence_map(self.export_board())
self._last_updated = self.state.timestamp
def export_board(self):
return self._board.tolist()
def find_points_over_strength_square(self, top_left_position, bottom_right_position, strength):
"""
Retourne les points qui se trouve au-dessus ou égale à la force demandé dans le tableau principal(_board)
:param Positon top_left_position: la rangé supérieure
:param Position bottom_right_position: la rangé inférieure
:param int strength: le force à trouvé qui est égale ou au dessus.
:return: un liste de point qui se trouve au dessus ou égale à la force demandé
"""
assert isinstance(top_left_position, Position), "Cette méthode requiert un object Position"
assert isinstance(bottom_right_position, Position), "Cette méthode requiert un object Position"
top_row, left_column = self._transform_field_to_board_position(top_left_position)
bot_row, right_column = self._transform_field_to_board_position(bottom_right_position)
ind_x, ind_y = numpy.where(self._board[top_row:bot_row, left_column:right_column] >= strength)
ind_x = ind_x.tolist()
ind_x = [x+top_row for x in ind_x]
ind_y = ind_y.tolist()
ind_y = [x+left_column for x in ind_y]
indices = zip(ind_x, ind_y)
return list(indices)
def find_points_under_strength_square(self, top_left_position, bottom_right_position, strength):
"""
Retourne les points qui se trouve au-dessous ou égale à la force demandé dans le tableau principal(_board)
:param Positon top_left_position: la rangé supérieure
:param Position bottom_right_position: la rangé inférieure
:param int strength: le force à trouvé qui est égale ou au dessous.
:return: un liste de point qui se trouve au-dessous ou égale à la force demandé
:rtype: une liste de tuple rangée * colonne (int * int) list
"""
assert isinstance(top_left_position, Position), "Cette méthode requiert un object Position"
assert isinstance(bottom_right_position, Position), "Cette méthode requiert un object Position"
top_row, left_column = self._transform_field_to_board_position(top_left_position)
bot_row, right_column = self._transform_field_to_board_position(bottom_right_position)
ind_x, ind_y = numpy.where(self._board[top_row:bot_row, left_column:right_column] <= strength)
ind_x = ind_x.tolist()
ind_x = [x+top_row for x in ind_x]
ind_y = ind_y.tolist()
ind_y = [x+left_column for x in ind_y]
indices = zip(ind_x, ind_y)
return list(indices)
def find_max_value_in_board(self):
"""
Permet de trouver les points du tableau qui ont la plus grande valeur du tableau
:return: la valeur maximale du tableau et la liste de point (rangée * colonne) des point qui ont la valeur max
:rtype: tuple (int * (int * int) list)
"""
uniques = numpy.unique(self._board)
max_in_board = uniques[-1]
x, y = numpy.where(self._board >= max_in_board)
x = x.tolist()
y = y.tolist()
indices = zip(x, y)
return max_in_board, indices
def find_min_value_in_board(self):
"""
Permet de trouver les points du tableau qui ont la plus petite valeur du tableau
:return: la valeur minimale du tableau et la liste de point (rangée * colonne) des point qui ont la valeur min
:rtype: tuple (int * (int * int) list)
"""
uniques = numpy.unique(self._board)
min_in_board = uniques[0]
x, y = numpy.where(self._board <= min_in_board)
x = x.tolist()
y = y.tolist()
indices = zip(x, y)
return min_in_board, indices
def find_max_value_in_circle(self, center, radius):
pass
def get_influence_at_position(self, position):
assert isinstance(position, Position), "accessing this function require a Position object"
row_column_in_board = self._transform_field_to_board_position(position)
return self._board[row_column_in_board[0], row_column_in_board[1]]
def get_ball_influence(self):
return self._board[self._ball_position_on_board[0], self._ball_position_on_board[1]]
def get_number_of_cells(self):
return self._number_of_rows * self._number_of_columns
def print_board_to_file(self):
"""
Create a file in the same running directory with a representation of the current board.
"""
numpy.savetxt("IMBoard", self._board, fmt='%4i')
# todo remove this line while not in debug mode
print(self._starterboard.shape[0], " x ", self._starterboard.shape[1])
def str(self):
# todo comment and make sure this is right! Embelish?
return "Influence Map - ", str(self._number_of_rows), " x ", str(self._number_of_columns)
def _update_and_draw_robot_position(self):
"""
Fetch la position des robots dans le gamestate et les applique sur le tableau principal
"""
robots_position = []
for i in range(self.state.get_count_player()):
try:
friend_position = self._transform_field_to_board_position(self.state.get_player_position(i))
robots_position.append(friend_position)
self._add_point_and_propagate_influence(friend_position[0], friend_position[1], self._board, 100)
except:
pass
try:
enemy_position = self._transform_field_to_board_position(self.state.get_enemy_position(i))
robots_position.append(enemy_position)
self._add_point_and_propagate_influence(enemy_position[0], enemy_position[1], self._board, -100)
except:
pass
self._clamp_board(self._board)
def _update_ball_position(self):
self._ball_position_on_board = self._transform_field_to_board_position(self.state.get_ball_position())
def _calculate_rows_and_columns(self):
"""
Utilise la resolution pour calculer le nombre de rangée(rows) et de colonne(columns) pour le terrain
:return: le nombre de rangées et le nombre de colonnes
:rtype: tuple (int * int)
"""
numberofrow = int(ceil((abs(FIELD_Y_BOTTOM) + FIELD_Y_TOP) / self._resolution))
numberofcolumn = int(ceil((abs(FIELD_X_LEFT) + FIELD_X_RIGHT) / self._resolution))
return numberofrow, numberofcolumn
def _create_standard_influence_board(self):
"""
Crée un objet numpy.ndarray, une liste à 2 dimenson de self._number_of_rows par self._number_of_columns d'int16.
:return: Un numpy.ndarray d'int16 de self._number_of_rows par self._number_of_columns.
:rtype: numpy.ndarray dtype=numpy.int16
"""
return numpy.zeros((self._number_of_rows, self._number_of_columns), numpy.int16)
def _adjust_effect_radius(self):
"""
Permet d'ajuster le rayon d'effet de l'influence (self._effect_radius) si celui-ci éxède la propagation normale.
Si la propagation de l'influence se retrouve à zéro avant d'avoir atteint le rayon d'effet défini à la création
de la classe, cette méthode l'ajuste pour quelle donne exactement le rayon qui permet d'afficher tous les points
qui ne donnent pas zéro.
influence dans les cases:
100 91 86 ... 6 5 4 3 2 1 0 0 0 0 0 0 0 sans effect_radius ajusté (si effect_radius est trop gros)
v
100 91 86 ... 6 5 4 3 2 1 avec effect_radius ajusté
Coupe le nombre d'itérations des boucles de mise en place de l'influence lorsque le calcul donnerait une
influence à 0.
"""
distance_from_center = 0
| |
1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0],
[1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1],
[0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0],
[1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1],
[0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, | |
<filename>_MOM/Selector.py
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# #*** <License> ************************************************************#
# This module is part of the package MOM.
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this module. If not, see <http://www.gnu.org/licenses/>.
# #*** </License> ***********************************************************#
#
#++
# Name
# MOM.Selector
#
# Purpose
# Model entity selector
#
# Revision Dates
# 29-May-2016 (CT) Creation...
# 8-Jun-2016 (CT) ...Finish creation
# 14-Jun-2016 (CT) Use `.sig`, not `.primary`, as `Attr_Selector`
# 14-Jun-2016 (CT) Change `Entity_PS.elements` to iterate over `aq.Atoms`
# ««revision-date»»···
#--
from _MOM import MOM
from _TFL import TFL
from _MOM._Attr import Querier
import _MOM._Meta.M_Entity
import _TFL._Meta.Object
import _TFL._Meta.Property
import _TFL.Decorator
import _TFL.Undef
from _TFL._Meta.Once_Property import Once_Property
from _TFL.Decorator import getattr_safe
from _TFL.I18N import _, _T, _Tn
from _TFL.predicate import first, uniq
from _TFL.pyk import pyk
from _TFL.Regexp import Multi_Regexp, Regexp, re
import logging
### `MOM.Attr.Selector.sig` works right for both Id_Entity and Composite
Attr_Selector = MOM.Attr.Selector.sig
Classes = []
def _selector_type (AQ) :
E_Type = AQ.E_Type
if AQ._polymorphic :
result = Entity_P
elif E_Type.polymorphic_epks :
result = Entity_PS
else :
result = Entity_N
return result
# end def _selector_type
def _lp_ES (f = None, name = "ES") :
if f is None :
return lambda f : _lp_ES (f, name)
else :
return TFL.Meta.Lazy_Property_NI (name, f, f.__doc__)
# end def _lp_ES
@TFL.Add_To_Class ("ES", Querier.Id_Entity, Querier.E_Type, decorator = _lp_ES)
def _entity_selector_AQ_ (AQ) :
"""Entity selector for `AQ.E_Type`"""
T = _selector_type (AQ)
if AQ._attr_selector is not Attr_Selector :
AQ = AQ.Select (Attr_Selector)
return T (AQ)
# end def _entity_selector_AQ_
@TFL.Add_To_Class ("ESW", Querier.Id_Entity, decorator = _lp_ES (name = "ESW"))
def _entity_selector_AQW_ (AQW) :
"""Entity selector for `AQW._attr.E_Type`"""
AQ = AQW._attr.E_Type.AQ
result = AQ.ES
return result.__class__ (AQ, AQW = AQW) if AQ._polymorphic else result
# end def _entity_selector_AQW_
@TFL.Add_To_Class ("ES", MOM.Meta.M_E_Type_Id, decorator = _lp_ES)
def _entity_selector_ET_ (E_Type) :
"""Entity selector for `E_Type`"""
return E_Type.AQ.ES
# end def _entity_selector_ET_
class _Base_ (TFL.Meta.Object) :
"""Base class for selector classes and Instance."""
def level_elements (self, level = 0) :
yield level, self
level += 1
for e in self.elements :
for l, i in e.level_elements (level) :
yield l, i
# end def level_elements
def recursive_repr (self, level = 0) :
return "\n".join \
( "%s%r" % (" " * l, e)
for l, e in self.level_elements (level)
)
# end def recursive_repr
@Once_Property
def _repr_type (self) :
return self.E_Type.type_name
# end def _repr_type
def __repr__ (self) :
return "<Selector.%s for %s>" % \
(self.__class__.__name__, self._repr_tail)
# end def __repr__
# end class _Base_
class _M_Selector_Base_ (TFL.Meta.Object.__class__) :
"""Meta class for atom and entity selector classes."""
macro_name = None
def __init__ (cls, name, bases, dct) :
cls.__m_super.__init__ (name, bases, dct)
if not name.startswith ("_") :
cls.macro_name = "do_%s" % name.lower ()
Classes.append (cls)
# end def __init__
def __call__ (cls, * args, ** kw) :
result = cls.__m_super.__call__ (* args, ** kw)
k = result.AQ._q_name
if k :
result.root._element_map [k] = result
return result
# end def __call__
# end class _M_Selector_Base_
class _Selector_Base_ (_Base_, metaclass = _M_Selector_Base_) :
"""Base class for atom and entity selectors."""
id = TFL.Meta.Alias_Property ("name")
r_name = TFL.Meta.Alias_Property ("name")
@Once_Property
def attr (self) :
return self.AQ._attr
# end def attr
@Once_Property
def Class (self) :
return self.AQ.Class
# end def Class
@Once_Property
def name (self) :
return self.root.elem_prefix + (self.AQ._q_name or "")
# end def name
@property ### depends on currently selected language (I18N/L10N)
def ui_name (self) :
return self.AQ._ui_name_T
# end def ui_name
def instance (self, completer, ** kw) :
return Instance (completer, self, ** kw)
# end def instance
# end class _Selector_Base_
class _Entity_ (_Selector_Base_) :
"""Base class for entity selectors."""
ES = property (lambda s : s)
E_Type = TFL.Meta.Alias_Property ("AQ.E_Type")
E_Type_NP = TFL.Meta.Alias_Property ("root.E_Type")
E_Type_Root = TFL.Meta.Alias_Property ("root.E_Type")
elem_prefix = ""
type_name = TFL.Meta.Alias_Property ("AQ.E_Type.type_name")
ui_name = \
ui_type_name = TFL.Meta.Alias_Property ("AQ.E_Type.ui_name_T")
def __init__ (self, AQ, root = None, AQW = None) :
self.AQ = AQ
self.AQW = AQW
self.root = self if root is None else root
if self.is_root :
self._element_map = {}
# end def __init__
@Once_Property
def atoms (self) :
def _gen (self) :
for e in self.elements :
yield from e.atoms
return tuple (_gen (self))
# end def atoms
@Once_Property
def is_root (self) :
return self.root is self
# end def is_root
@Once_Property
def _repr_tail (self) :
return "%s for %s" % (self.AQ, self._repr_type)
# end def _repr_tail
def completer (self, scope, trigger, values) :
return Completer (self, self, scope, trigger, values)
# end def completer
def Wrapped (self, root) :
return self.__class__ (self.AQ, root)
# end def Wrapped
def __getitem__ (self, key) :
root = self.root
map = root._element_map
if not map :
root.atoms ### materialize all elements
try :
return map [key]
except KeyError :
try :
aq = getattr (root.AQ, key)
except AttributeError :
raise KeyError (key)
else :
### try normalized key
try :
return map [aq._q_name]
except AttributeError :
raise KeyError (key)
# end def __getitem__
def __str__ (self) :
return "<%s.ES>" % (self.E_Type.type_name, )
# end def __str__
# end class _Entity_
class Atom (_Selector_Base_) :
"""Atomic element of an entity selector."""
E_Type = TFL.Meta.Alias_Property ("outer.E_Type")
is_root = False
def __init__ (self, outer, AQ) :
self.outer = outer
self.AQ = AQ
self.root = outer.root
# end def __init__
@Once_Property
def elements (self) :
return ()
# end def elements
@Once_Property
def atoms (self) :
return (self, )
# end def atoms
@Once_Property
def _repr_tail (self) :
return self.AQ._q_name
# end def _repr_tail
# end class Atom
class Entity_N (_Entity_) :
"""Entity selector for non-polymorphic E_Type."""
@Once_Property
def elements (self) :
def _gen (self) :
AQ = self.AQ
for aq in AQ.Atoms :
yield Atom (self, aq)
return tuple (_gen (self))
# end def elements
# end class Entity_N
class Entity_P (_Entity_) :
"""Entity selector for polymorphic E_Type."""
E_Type_NP_field_name = "E_Type_NP"
def __init__ (self, AQ, root = None, AQW = None) :
self.__super.__init__ (AQ, root = root, AQW = AQW)
self._child_map = map = {}
if not self.is_root :
self.E_Type_NP_field_name = "%s/%s" % \
(self.name, self.E_Type_NP_field_name)
if AQW is None :
E_Types_AQ = getattr (AQ, "E_Types_AQ", None)
else :
E_Types_AQ = getattr (AQW, "E_Types_AQ", None)
if E_Types_AQ :
E_Types_AQ = dict \
((k, v.E_Type.AQ) for k, v in pyk.iteritems (E_Types_AQ))
if E_Types_AQ is None :
def _gen (AQ) :
ET = AQ.E_Type
for k, v in pyk.iteritems (ET.children_np_transitive) :
yield k, v.ES
E_Types_AQ = dict (_gen (AQ))
for k, v in pyk.iteritems (E_Types_AQ) :
map [k] = Entity_P_CNP (AQ, self, v)
# end def __init__
@property ### depends on currently selected language (I18N/L10N)
def choices (self) :
return list \
( (v.E_Type_NP.type_name, v.E_Type_NP.ui_name_T)
for v in self.elements
)
# end def choices
@Once_Property
def elements (self) :
children_np = sorted (pyk.iteritems (self._child_map))
return tuple (v for k, v in children_np)
# end def elements
@Once_Property
def selected_type (self) :
return self.E_Type.default_child
# end def selected_type
def completer (self, scope, trigger, values) :
this = self._get_child_np (values)
if values and this is not None :
return Completer (self, this, scope, trigger, values)
else :
return self.__super.choices (scope, trigger, values)
# end def completer
def instance (self, completer, ** kw) :
value = completer.obj if self.is_root else self.AQ.QC (completer.obj)
ikw = dict (kw, selected_type = value.type_name)
return self.__super.instance (completer, ** ikw)
# end def instance
def _get_child_np (self, values) :
rtn = values.get (self.E_Type_NP_field_name)
if not rtn :
return None
try :
return self._child_map [rtn]
except KeyError :
raise ValueError ("Unknown E_Type %s" % rtn)
# end def _get_child_np
def __getitem__ (self, key) :
tr = MOM.Attr.Querier.regexp.type_restriction
| |
= out
else:
out = self.fit_at_z(z=zi[i], templates=t_complex, fitter=fitter)
ci[i], bg, full, coeffs, err = out
# out = self.fit_at_z(z=zi[i], templates=t_complex,
# fitter=fitter)
#
# ci[i], bg, full, coeffs, err = out
if verbose:
print('{0:.4f} - {1:10.1f}'.format(zi[i], ci[i]))
z = np.append(z, zi)
chi2 = np.append(chi2, ci)
so = np.argsort(z)
z = z[so]
chi2 = chi2[so]
# Apply the prior
if prior is not None:
pz = np.interp(z, prior[0], prior[1])
chi2 += pz
# Get the fit with the individual line templates at the best redshift
chi2x, bgz, fullz, coeffs, err = self.fit_at_z(z=z[np.argmin(chi2)], templates=t_i, fitter=fitter, get_uncertainties=True)
# Mask outliers
if outlier_threshold > 0:
resid = self.scif - fullz - bgz
outlier_mask = (resid*self.sivarf < outlier_threshold)
#outlier_mask &= self.fit_mask
#self.sivarf[outlier_mask] = 1/resid[outlier_mask]
#print('Mask {0} pixels with resid > {1} sigma'.format((outlier_mask).sum(), outlier_threshold))
print('Mask {0} pixels with resid > {1} sigma'.format((~outlier_mask & self.fit_mask).sum(), outlier_threshold))
self.fit_mask &= outlier_mask
#self.DoF = self.fit_mask.sum() #(self.ivar > 0).sum()
self.DoF = int((self.fit_mask*self.weightf).sum())
# Table with z, chi-squared
t = utils.GTable()
t['z'] = z
t['chi2'] = chi2
if prior is not None:
t['prior'] = pz
# "area" parameter for redshift quality.
num = np.trapz(np.clip(chi2-chi2.min(), 0, 25), z)
denom = np.trapz(z*0+25, z)
area25 = 1-num/denom
# "best" redshift
zbest = z[np.argmin(chi2)]
# Metadata will be stored as header keywords in the FITS table
t.meta = OrderedDict()
t.meta['ID'] = (self.h0['ID'], 'Object ID')
t.meta['RA'] = (self.h0['RA'], 'Right Ascension')
t.meta['DEC'] = (self.h0['DEC'], 'Declination')
t.meta['Z'] = (zbest, 'Best-fit redshift')
t.meta['CHIMIN'] = (chi2.min(), 'Min Chi2')
t.meta['CHIMAX'] = (chi2.max(), 'Max Chi2')
t.meta['DOF'] = (self.DoF, 'Degrees of freedom')
t.meta['AREA25'] = (area25, 'Area under CHIMIN+25')
t.meta['FITTER'] = (fitter, 'Minimization algorithm')
t.meta['HASPRIOR'] = (prior is not None, 'Was prior specified?')
# Best-fit templates
tc, tl = self.generate_1D_templates(coeffs,
templates_file=templates_file)
# for i, te in enumerate(t_i):
# if i == 0:
# tc = t_i[te].zscale(0, scalar=coeffs[i])
# tl = t_i[te].zscale(0, scalar=coeffs[i])
# else:
# if te.startswith('line'):
# tc += t_i[te].zscale(0, scalar=0.)
# else:
# tc += t_i[te].zscale(0, scalar=coeffs[i])
#
# tl += t_i[te].zscale(0, scalar=coeffs[i])
# Get line fluxes, uncertainties and EWs
il = 0
for i, te in enumerate(t_i):
if te.startswith('line'):
il+=1
if coeffs[i] == 0:
EW = 0.
else:
tn = (t_i[te].zscale(0, scalar=coeffs[i]) +
tc.zscale(0, scalar=1))
td = (t_i[te].zscale(0, scalar=0) +
tc.zscale(0, scalar=1))
clip = (td.wave <= t_i[te].wave.max())
clip &= (td.wave >= t_i[te].wave.min())
EW = np.trapz((tn.flux/td.flux)[clip]-1, td.wave[clip])
if not np.isfinite(EW):
EW = -1000.
t.meta['LINE{0:03d}F'.format(il)] = (coeffs[i],
'{0} line flux'.format(te[5:]))
t.meta['LINE{0:03d}E'.format(il)] = (err[i],
'{0} line flux uncertainty'.format(te[5:]))
#print('xxx EW', EW)
t.meta['LINE{0:03d}W'.format(il)] = (EW,
'{0} line rest EQW'.format(te[5:]))
tfile = self.file.replace('.fits', '.zfit.fits')
if os.path.exists(tfile):
os.remove(tfile)
t.write(tfile)
### Add image HDU and templates
hdu = pyfits.open(tfile, mode='update')
hdu[1].header['EXTNAME'] = 'ZFIT'
# oned_templates = np.array([tc.wave*(1+zbest), tc.flux/(1+zbest),
# tl.flux/(1+zbest)])
header = pyfits.Header()
header['TEMPFILE'] = (templates_file, 'File with stored templates')
hdu.append(pyfits.ImageHDU(data=coeffs, name='COEFFS'))
for i in range(self.N):
E = self.beams[i]
model_i = fullz[self.slices[i]].reshape(E.sh)
bg_i = bgz[self.slices[i]].reshape(E.sh)
model_i[~np.isfinite(model_i)] = 0
bg_i[~np.isfinite(bg_i)] = 0
hdu.append(pyfits.ImageHDU(data=model_i, header=E.header,
name='MODEL'))
hdu.append(pyfits.ImageHDU(data=bg_i, header=E.header,
name='BACKGROUND'))
hdu.flush()
if make_plot:
self.make_fit_plot(hdu)
return hdu
@classmethod
def generate_1D_templates(self, coeffs, templates_file='templates.npy'):
"""
TBD
"""
t_complex, t_i = np.load(templates_file, allow_pickle=True)
# Best-fit templates
for i, te in enumerate(t_i):
if i == 0:
tc = t_i[te].zscale(0, scalar=coeffs[i])
tl = t_i[te].zscale(0, scalar=coeffs[i])
else:
if te.startswith('line'):
tc += t_i[te].zscale(0, scalar=0.)
else:
tc += t_i[te].zscale(0, scalar=coeffs[i])
tl += t_i[te].zscale(0, scalar=coeffs[i])
return tc, tl
def mask_drizzle_overlaps(self, threshold=3, verbose=True):
"""
TBD
mask pixels in beams of a given grism that are greater than
`threshold` sigma times the minimum of all beams of that
grism
"""
min_grism = {}
for grism in self.grisms:
for E in self.beams:
if not E.extver.startswith(grism):
continue
if grism not in min_grism:
min_grism[grism] = E.scif*E.fit_mask
else:
empty = (min_grism[grism] == 0) & E.fit_mask
min_grism[grism][E.fit_mask] = np.minimum(min_grism[grism][E.fit_mask], E.scif[E.fit_mask])
min_grism[grism][empty] = E.scif[empty]
for grism in self.grisms:
for E in self.beams:
if not E.extver.startswith(grism):
continue
new_mask = (E.scif - min_grism[grism]) < threshold/E.sivarf
if verbose:
print('Mask {0} additional pixels for ext {1}'.format((~new_mask & E.fit_mask).sum(), E.extver))
E.fit_mask &= new_mask
def make_fit_plot(self, hdu, scale_pz=True, show_2d=False):
"""Make a plot showing the fit
Parameters
----------
hdu : `~astropy.io.fits.HDUList`
Fit results from `fit_zgrid`.
Returns
-------
fig : `~matplotlib.figure.Figure`
The figure object.
"""
import matplotlib.pyplot as plt
import matplotlib.gridspec
from matplotlib.ticker import MultipleLocator
#import grizli
from . import utils
zfit = utils.GTable.read(hdu[1])
z = zfit['z']
chi2 = zfit['chi2']
# Initialize plot window
Ng = len(self.grisms)
if show_2d:
height_ratios = [0.25]*self.N
height_ratios.append(1)
gs = matplotlib.gridspec.GridSpec(self.N+1,2,
width_ratios=[1,1.5+0.5*(Ng>1)],
height_ratios=height_ratios, hspace=0.)
fig = plt.figure(figsize=[8+4*(Ng>1), 3.5+0.5*self.N])
else:
gs = matplotlib.gridspec.GridSpec(1,2,
width_ratios=[1,1.5+0.5*(Ng>1)],
hspace=0.)
fig = plt.figure(figsize=[8+4*(Ng>1), 3.5])
# Chi-squared
axz = fig.add_subplot(gs[-1,0]) #121)
axz.text(0.95, 0.04, self.file + '\n'+'z={0:.4f}'.format(z[np.argmin(chi2)]), ha='right', va='bottom', transform=axz.transAxes, fontsize=9)
# Scale p(z) to DoF=1.
if scale_pz:
scale_nu = chi2.min()/self.DoF
scl_label = '_s'
else:
scale_nu = 1.
scl_label = ''
axz.plot(z, (chi2-chi2.min())/scale_nu, color='k')
axz.fill_between(z, (chi2-chi2.min())/scale_nu, 27, color='k', alpha=0.5)
axz.set_ylim(-4,27)
axz.set_xlabel(r'$z$')
axz.set_ylabel(r'$\Delta\chi^2{2}$ ({0:.0f}/$\nu$={1:d})'.format(chi2.min(), self.DoF, scl_label))
axz.set_yticks([1,4,9,16,25])
axz.set_xlim(z.min(), z.max())
axz.grid()
# 2D spectra
if show_2d:
twod_axes = []
for i in range(self.N):
ax_i = fig.add_subplot(gs[i,1])
model = hdu['MODEL', self.ext[i]].data
ymax = model[np.isfinite(model)].max()
#print('MAX', ymax)
cmap = 'viridis_r'
cmap = 'cubehelix_r'
clean = self.beams[i].sci - hdu['BACKGROUND', self.ext[i]].data
clean *= self.beams[i].fit_mask.reshape(self.beams[i].sh)
w = self.beams[i].wave/1.e4
ax_i.imshow(clean, vmin=-0.02*ymax, vmax=1.1*ymax, origin='lower',
extent=[w[0], w[-1], 0., 1.], aspect='auto',
cmap=cmap)
ax_i.text(0.04, 0.92, self.ext[i], ha='left', va='top', transform=ax_i.transAxes, fontsize=8)
ax_i.set_xticklabels([]); ax_i.set_yticklabels([])
twod_axes.append(ax_i)
axc = fig.add_subplot(gs[-1,1]) #224)
# 1D Spectra + fit
ymin = 1.e30
ymax = -1.e30
wmin = 1.e30
wmax = -1.e30
for i in range(self.N):
E = self.beams[i]
clean = E.sci - hdu['BACKGROUND', self.ext[i]].data
w, fl, er = E.optimal_extract(clean)
w, flm, erm = E.optimal_extract(hdu['MODEL', self.ext[i]].data)
w = w/1.e4
# Do we need to convert to F-lambda units?
if E.is_flambda:
unit_corr = 1.
clip = (er > 0) & np.isfinite(er) & np.isfinite(flm)
clip[:10] = False
clip[-10:] = False
if clip.sum() == 0:
clip = (er > -1)
else:
unit_corr = 1./E.sens
clip = (E.sens > 0.1*E.sens.max())
clip &= (np.isfinite(flm)) & (er > 0)
if clip.sum() == 0:
continue
# fl *= 100*unit_corr
# er *= 100*unit_corr
# flm *= 100*unit_corr
fl *= unit_corr/1.e-19
er *= unit_corr/1.e-19
flm *= unit_corr/1.e-19
f_alpha = 1./self.Ngrism[E.grism]**0.5 #self.h0['N{0}'.format(E.header['GRISM'])]**0.5
axc.errorbar(w[clip], fl[clip], er[clip], color=GRISM_COLORS[E.grism], alpha=0.3*f_alpha, marker='.', linestyle='None')
#axc.fill_between(w[clip], (fl+er)[clip], (fl-er)[clip], color='k', alpha=0.2)
axc.plot(w[clip], flm[clip], color='r', alpha=0.6*f_alpha, linewidth=2)
# Plot limits
# ymax = np.maximum(ymax, (flm+np.median(er))[clip].max())
# ymin = np.minimum(ymin, (flm-er*0.)[clip].min())
ymax = np.maximum(ymax,
np.percentile((flm+np.median(er))[clip], 98))
ymin = np.minimum(ymin, np.percentile((flm-er*0.)[clip], 2))
wmax = np.maximum(wmax, w.max())
wmin = np.minimum(wmin, w.min())
axc.set_xlim(wmin, wmax)
axc.semilogx(subsx=[wmax])
#axc.set_xticklabels([])
axc.set_xlabel(r'$\lambda$')
axc.set_ylabel(r'$f_\lambda \times 10^{-19}$')
#axc.xaxis.set_major_locator(MultipleLocator(0.1))
axc.set_ylim(ymin-0.2*ymax, 1.2*ymax)
axc.grid()
for ax in [axc]: #[axa, axb, axc]:
labels = np.arange(np.ceil(wmin*10), np.ceil(wmax*10))/10.
ax.set_xticks(labels)
ax.set_xticklabels(labels)
#ax.set_xticklabels([])
#print(labels, wmin, wmax)
if show_2d:
for ax in twod_axes:
ax.set_xlim(wmin, wmax)
gs.tight_layout(fig, pad=0.1, w_pad=0.1)
fig.savefig(self.file.replace('.fits', '.zfit.png'))
return fig
class StackedSpectrum(object):
def __init__(self, file='gnt_18197.stack.G141.285.fits', sys_err=0.02, mask_min=0.1, extver='G141', mask_threshold=7, fcontam=1., min_ivar=0.001, MW_EBV=0.):
import os
#import grizli
from . import GRIZLI_PATH
from . import grismconf
self.sys_err = sys_err
self.mask_min = mask_min
self.extver = extver
self.grism = self.extver.split(',')[0]
self.mask_threshold=mask_threshold
self.MW_EBV = MW_EBV
self.init_galactic_extinction(MW_EBV)
self.file = file
self.hdulist = pyfits.open(file)
self.h0 = self.hdulist[0].header.copy()
self.header = self.hdulist['SCI',extver].header.copy()
self.sh = (self.header['NAXIS2'], self.header['NAXIS1'])
self.wave = self.get_wavelength_from_header(self.header)
self.wavef = np.dot(np.ones((self.sh[0],1)), self.wave[None,:]).flatten()
if 'BEAM' in self.header:
self.beam_name = self.header['BEAM']
else:
self.beam_name = 'A'
# Configuration file
self.is_flambda = self.header['ISFLAM']
self.conf_file = self.header['CONF']
try:
self.conf = grismconf.aXeConf(self.conf_file)
except:
# Try global path
base = os.path.basename(self.conf_file)
localfile = os.path.join(GRIZLI_PATH, 'CONF', base)
self.conf = grismconf.aXeConf(localfile)
self.conf.get_beams()
self.sci = self.hdulist['SCI',extver].data*1.
self.ivar0 = self.hdulist['WHT',extver].data*1
self.size = self.sci.size
self.thumbs | |
#!/usr/bin/env python3
"""Read boot.bin and src.elf and produce debug.bin."""
import os
import sys
import struct
from enum import IntEnum, IntFlag
def printf(fmt, *args, **kwargs):
print(fmt % args, end='', **kwargs)
def readStruct(fmt, file, offset=None):
"""Read struct from file."""
if offset is not None: file.seek(offset)
sLen = struct.calcsize(fmt)
r = struct.unpack(fmt, file.read(sLen))
if len(r) == 1: return r[0] # grumble
return r
class ELF:
"""Represents an ELF file. (Only 32-bit big-endian is supported.)"""
class ProgramHeaderTypes(IntEnum):
PT_NULL = 0x00000000
PT_LOAD = 0x00000001
PT_DYNAMIC = 0x00000002
PT_INTERP = 0x00000003
PT_NOTE = 0x00000004
PT_SHLIB = 0x00000005
PT_PHDR = 0x00000006
PT_TLS = 0x00000007
PT_LOOS = 0x60000000
PT_HIOS = 0x6FFFFFFF
PT_LOPROC = 0x70000000
PT_HIPROC = 0x7FFFFFFF
class SectionHeaderTypes(IntEnum):
SHT_NULL = 0x00000000
SHT_PROGBITS = 0x00000001
SHT_SYMTAB = 0x00000002
SHT_STRTAB = 0x00000003
SHT_RELA = 0x00000004
SHT_HASH = 0x00000005
SHT_DYNAMIC = 0x00000006
SHT_NOTE = 0x00000007
SHT_NOBITS = 0x00000008
SHT_REL = 0x00000009
SHT_SHLIB = 0x0000000A
SHT_DYNSYM = 0x0000000B
SHT_INIT_ARRAY = 0x0000000E
SHT_FINI_ARRAY = 0x0000000F
SHT_PREINIT_ARRAY = 0x00000010
SHT_GROUP = 0x00000011
SHT_SYMTAB_SHNDX = 0x00000012
SHT_NUM = 0x00000013
SHT_LOOS = 0x60000000
class SectionHeaderFlags(IntFlag):
SHF_WRITE = 0x00000001
SHF_ALLOC = 0x00000002
SHF_EXECINSTR = 0x00000004
SHF_MERGE = 0x00000010
SHF_STRINGS = 0x00000020
SHF_INFO_LINK = 0x00000040
SHF_LINK_ORDER = 0x00000080
SHF_OS_NONCONFORMING = 0x00000100
SHF_GROUP = 0x00000200
SHF_TLS = 0x00000400
SHF_MASKOS = 0x0FF00000
SHF_MASKPROC = 0xF0000000
class PPCRelType(IntEnum): # Relocation types
R_PPC_NONE = 0
R_PPC_ADDR32 = 1 # 32bit absolute address
R_PPC_ADDR24 = 2 # 26bit address, 2 bits ignored.
R_PPC_ADDR16 = 3 # 16bit absolute address
R_PPC_ADDR16_LO = 4 # lower 16bit of absolute address
R_PPC_ADDR16_HI = 5 # high 16bit of absolute address
R_PPC_ADDR16_HA = 6 # adjusted high 16bit
R_PPC_ADDR14 = 7 # 16bit address, 2 bits ignored
R_PPC_ADDR14_BRTAKEN = 8
R_PPC_ADDR14_BRNTAKEN = 9
R_PPC_REL24 = 10 # PC relative 26 bit
R_PPC_REL14 = 11 # PC relative 16 bit
R_PPC_REL14_BRTAKEN = 12
R_PPC_REL14_BRNTAKEN = 13
R_PPC_GOT16 = 14
R_PPC_GOT16_LO = 15
R_PPC_GOT16_HI = 16
R_PPC_GOT16_HA = 17
R_PPC_PLTREL24 = 18
R_PPC_COPY = 19
R_PPC_GLOB_DAT = 20
R_PPC_JMP_SLOT = 21
R_PPC_RELATIVE = 22
R_PPC_LOCAL24PC = 23
R_PPC_UADDR32 = 24
R_PPC_UADDR16 = 25
R_PPC_REL32 = 26
R_PPC_PLT32 = 27
R_PPC_PLTREL32 = 28
R_PPC_PLT16_LO = 29
R_PPC_PLT16_HI = 30
R_PPC_PLT16_HA = 31
R_PPC_SDAREL16 = 32
R_PPC_SECTOFF = 33
R_PPC_SECTOFF_LO = 34
R_PPC_SECTOFF_HI = 35
R_PPC_SECTOFF_HA = 36
def __init__(self, file):
self.file = file
self.progHdrs = []
self.sectHdrs = []
self.strTabs = []
self.readHeader()
self.strOffs = None # offset into file for string table
# read program headers
for i in range(self.phNum):
offs = self.phOff + (i * self.phEntSize)
phdr = self.readProgramHeader(offs)
self.progHdrs.append(phdr)
# read section headers
for i in range(self.shNum):
offs = self.shOff + (i * self.shEntSize)
shdr = self.readSectionHeader(offs)
self.sectHdrs.append(shdr)
if shdr['type'] == self.SectionHeaderTypes.SHT_STRTAB:
self.strTabs.append(shdr['offset'])
def getSectionData(self, shdr):
"""Get the raw data of a section header."""
self.file.seek(shdr['offset'])
return self.file.read(shdr['size'])
def readHeader(self):
"""Read ELF header from file and make sure it's correct and supported."""
sig = self.file.read(4)
if sig != b'\x7F' + b'ELF': raise TypeError("Not an ELF file")
cls, endian, version, abi, abiVer = readStruct('>5b', self.file)
ok = (cls == 1) and (endian == 2) and (version == 1)
if not ok:
raise TypeError("Must be 32-bit big-endian ELFv1 (have %s-bit %s-endian ELFv%d)" % (
'32' if cls == 1 else ('64' if cls == 2 else ('?%d?' % cls)),
'little' if endian == 1 else ('big' if endian == 2 else ('?%d?' % endian)),
version))
machine = readStruct('>H', self.file, 0x12)
if machine != 0x14: raise TypeError("Must be PowerPC32 ISA (got 0x%04X)" % machine)
self.entryPoint, self.phOff, self.shOff, self.flags, self.ehSize, \
self.phEntSize, self.phNum, self.shEntSize, self.shNum, self.shStrndx = \
readStruct('>IIIIHHHHHH', self.file, 0x18)
def printHeader(self):
"""Output the header for debugging."""
printf(" Entry Point: 0x%08X\n", self.entryPoint)
printf(" ProgHdr Offset: 0x%08X Size: 0x%08X Count: %d\n",
self.phOff, self.phEntSize, self.phNum)
printf(" SectHdr Offset: 0x%08X Size: 0x%08X Count: %d\n",
self.shOff, self.shEntSize, self.shNum)
printf(" Flags: 0x%08X\n", self.flags)
printf(" Header Size: 0x%08X\n", self.ehSize) # file header
printf(" String Index: 0x%08X\n", self.shStrndx)
def readProgramHeader(self, offset):
"""Read program header from offset."""
pType, offs, vAddr, pAddr, fSize, mSize, flags, align = \
readStruct('>IIIIIIII', self.file, offset)
return {
'headerOffset': offset,
'type': pType,
'offset': offs, # segment offset in file
'vAddr': vAddr, # virtual address
'pAddr': pAddr, # physical address
'fSize': fSize, # size in file
'mSize': mSize, # size in memory
'flags': flags,
'align': align,
}
def printProgramHeader(self, phdr):
"""Output program header for debugging."""
try: typ = self.ProgramHeaderTypes[phdr['type']]
except KeyError: typ = '0x%08X' % phdr['type']
printf(" Type: %s\n", typ)
printf(" File Offs: 0x%08X Size: 0x%08X\n", phdr['offset'], phdr['fSize'])
printf(" Virt Addr: 0x%08X Size: 0x%08X\n", phdr['vAddr'], phdr['mSize'])
printf(" Phys Addr: 0x%08X Algn: 0x%08X\n", phdr['pAddr'], phdr['align'])
printf(" Flags: 0x%08X\n", phdr['flags'])
def readSectionHeader(self, offset):
"""Read section header from offset."""
shName, shType, flags, addr, offs, size, link, info, align, entSize = \
readStruct('>IIIIIIIIII', self.file, offset)
return {
'headerOffset': offset,
'nameOffs': shName,
'type': shType,
'flags': flags,
'addr': addr,
'offset': offs,
'size': size,
'link': link,
'info': info,
'align': align,
'entSize': entSize,
}
def printSectionHeader(self, shdr):
"""Output section header for debugging."""
try: typ = self.SectionHeaderTypes(shdr['type']).name
except KeyError: typ = '0x%08X' % shdr['type']
flags = []
for k, v in self.SectionHeaderFlags.__members__.items():
if shdr['flags'] & v: flags.append(k)
flags = ', '.join(flags)
name = self.getString(shdr['nameOffs'], 1)
if name is None: name = '<none>'
printf(" Type: %s\n", typ)
printf(" Name @ 0x%08X: %s\n", shdr['nameOffs'], name)
printf(" Flags: 0x%08X %s\n", shdr['flags'], flags)
printf(" MemAddr: 0x%08X\n", shdr['addr'])
printf(" FileOffs: 0x%08X Size: 0x%08X\n", shdr['offset'], shdr['size'])
printf(" Link: 0x%08X Info: 0x%08X\n", shdr['link'], shdr['info'])
printf(" Align: 0x%08X EntSz: 0x%08X\n", shdr['align'], shdr['entSize'])
def getString(self, offs, tab=0):
"""Read string from string table."""
if offs == 0: return None
if tab >= len(self.strTabs): return '<no string table>'
self.file.seek(self.strTabs[tab] + offs)
res = b''
while len(res) < 1000:
b = self.file.read(1)
if len(b) < 1 or b == b'\0': break
res += b
return res.decode('utf-8')
def getSymbolTable(self):
"""Retrieve the symbol table data."""
data = None
for shdr in self.sectHdrs:
if shdr['type'] == self.SectionHeaderTypes.SHT_SYMTAB:
data = self.getSectionData(shdr)
break
if data is None: return None
# we have the raw data, now parse it
tbl = []
for i in range(0, len(data), 16):
nameOffs, val, size, info, other, index = \
struct.unpack_from('>IIIBBh', data, i)
tbl.append({
'nameOffs': nameOffs,
'name': self.getString(nameOffs, 0),
'value': val,
'size': size,
'info': info,
'other': other,
'index': index,
})
return tbl
def printSymbolTable(self):
"""Output symbol table for debugging."""
symTab = self.getSymbolTable()
if symTab is None: print("No symbol table")
else:
print("Symbol Table:\n Idx Value Size If Ot Index Name")
for i, sym in enumerate(symTab):
name = sym['name']
if name is None: name = '<none>'
printf("%5d %08X %08X %02X %02X %6d %s\n", i,
sym['value'], sym['size'], sym['info'], sym['other'],
sym['index'], name)
def getRelocationTable(self):
"""Retrieve the relocation table data."""
data = None
for shdr in self.sectHdrs:
if shdr['type'] == self.SectionHeaderTypes.SHT_RELA:
data = self.getSectionData(shdr)
break
if data is None: return None
# we have the raw data, now parse it
tbl = []
for i in range(0, len(data), 12):
offs, unk, symTabIdx, relType, add = \
struct.unpack_from('>IHBBi', data, i)
tbl.append({
'offset': offs,
'unk': unk,
'symTabIdx': symTabIdx,
'relType': relType,
'add': add,
})
return tbl
def printRelocationTable(self):
"""Output relocation table for debugging."""
relTab = self.getRelocationTable()
if relTab is None: print("No relocation table")
else:
symTab = self.getSymbolTable()
print("Relocation data:\n Idx Offset Unk Ix Tp Sym")
for i, entry in enumerate(relTab):
sym = symTab[entry['symTabIdx']]
name = sym['name']
if name is None: name = '<none>'
printf("%5d %08X %04X %02X %02X %16s %+d\n", i,
entry['offset'], entry['unk'], entry['symTabIdx'],
entry['relType'], name, entry['add'])
def main():
args = list(sys.argv[1:])
if len(args) < 2:
print("Usage: elf2bin.py buildDir outPath")
sys.exit(1)
inPath = args.pop(0)
outPath = args.pop(0)
outBin = open(os.path.join(outPath, 'debug.bin'), 'wb')
inBin = open(os.path.join(inPath, 'boot.bin'), 'rb')
inElf = open(os.path.join(inPath, 'src.elf'), 'rb')
elf = ELF(inElf)
# copy bootstrap
while True:
data = inBin.read(1024)
outBin.write(data)
if len(data) < 1024: break
inBin.close()
while outBin.tell() & 0xF: outBin.write(b'\0') # align
outOffs = outBin.tell()
# print headers
#elf.printHeader()
#for i, phdr in enumerate(elf.progHdrs):
# printf("Program Header #%d @ 0x%08X:\n", i, phdr['headerOffset'])
# elf.printProgramHeader(phdr)
#for i, shdr in enumerate(elf.sectHdrs):
# printf("Section Header #%d @ 0x%08X:\n", i, shdr['headerOffset'])
# | |
"""Create lmdb files for [General images (291 images/DIV2K) | Vimeo90K | REDS] training datasets"""
import os, sys
import os.path as osp
import glob
import pickle
from multiprocessing import Pool
import numpy as np
import lmdb
import cv2
import argparse
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
import data.util as data_util # noqa: E402
import utils.util as util # noqa: E402
IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP']
def main_v0(cfgs):
if not osp.exists(cfgs.dst_dir):
os.makedirs(cfgs.dst_dir)
if cfgs.dataset == 'vimeo90k':
vimeo90k(cfgs)
elif cfgs.dataset == 'REDS':
scale = cfgs.scale
img_folder = osp.join(cfgs.src_dir, "X{:.02f}".format(scale))
lmdb_save_path = osp.join(cfgs.dst_dir, "X{:.02f}.lmdb".format(scale))
one_example = osp.join(img_folder, '000', '00000000.png')
im_example = cv2.imread(one_example)
H, W, _ = im_example.shape
REDS(img_folder, lmdb_save_path, H, W, scale)
elif cfgs.dataset == 'general':
opt = {}
opt['img_folder'] = '../../datasets/DIV2K/DIV2K800_sub'
opt['lmdb_save_path'] = '../../datasets/DIV2K/DIV2K800_sub.lmdb'
opt['name'] = 'DIV2K800_sub_GT'
general_image_folder(opt)
elif cfgs.dataset == 'DIV2K_demo':
opt = {}
## GT
opt['img_folder'] = '../../datasets/DIV2K/DIV2K800_sub'
opt['lmdb_save_path'] = '../../datasets/DIV2K/DIV2K800_sub.lmdb'
opt['name'] = 'DIV2K800_sub_GT'
general_image_folder(opt)
## LR
opt['img_folder'] = '../../datasets/DIV2K/DIV2K800_sub_bicLRx4'
opt['lmdb_save_path'] = '../../datasets/DIV2K/DIV2K800_sub_bicLRx4.lmdb'
opt['name'] = 'DIV2K800_sub_bicLRx4'
general_image_folder(opt)
elif cfgs.dataset == 'test':
dataroot = osp.join(cfgs.dst_dir, "X{:.02f}.lmdb".format(cfgs.scale))
test_lmdb(dataroot=dataroot, dataset='REDS')
def main_old():
dataset = 'REDS' # vimeo90K | REDS | general (e.g., DIV2K, 291) | DIV2K_demo |test
mode = 'train_sharp' # used for vimeo90k and REDS datasets
# vimeo90k: GT | LR | flow
# REDS: train_sharp, train_sharp_bicubic, train_blur_bicubic, train_blur, train_blur_comp
# train_sharp_flowx4
if dataset == 'vimeo90k':
vimeo90k(mode)
elif dataset == 'REDS':
REDS(mode)
elif dataset == 'general':
opt = {}
opt['img_folder'] = '../../datasets/DIV2K/DIV2K800_sub'
opt['lmdb_save_path'] = '../../datasets/DIV2K/DIV2K800_sub.lmdb'
opt['name'] = 'DIV2K800_sub_GT'
general_image_folder(opt)
elif dataset == 'DIV2K_demo':
opt = {}
## GT
opt['img_folder'] = '../../datasets/DIV2K/DIV2K800_sub'
opt['lmdb_save_path'] = '../../datasets/DIV2K/DIV2K800_sub.lmdb'
opt['name'] = 'DIV2K800_sub_GT'
general_image_folder(opt)
## LR
opt['img_folder'] = '../../datasets/DIV2K/DIV2K800_sub_bicLRx4'
opt['lmdb_save_path'] = '../../datasets/DIV2K/DIV2K800_sub_bicLRx4.lmdb'
opt['name'] = 'DIV2K800_sub_bicLRx4'
general_image_folder(opt)
elif dataset == 'test':
test_lmdb('../../datasets/REDS/train_sharp_wval.lmdb', 'REDS')
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def get_paths_from_images(path):
"""get image path list from image folder"""
assert os.path.isdir(path), '{:s} is not a valid directory'.format(path)
images = []
for dirpath, _, fnames in sorted(os.walk(path)):
for fname in sorted(fnames):
if is_image_file(fname):
img_path = os.path.join(dirpath, fname)
images.append(img_path)
assert images, '{:s} has no valid image file'.format(path)
return images
def read_image_worker(path, key):
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
return (key, img)
def general_image_folder(opt):
"""Create lmdb for general image folders
Users should define the keys, such as: '0321_s035' for DIV2K sub-images
If all the images have the same resolution, it will only store one copy of resolution info.
Otherwise, it will store every resolution info.
"""
#### configurations
read_all_imgs = False # whether real all images to memory with multiprocessing
# Set False for use limited memory
BATCH = 5000 # After BATCH images, lmdb commits, if read_all_imgs = False
n_thread = 40
########################################################
img_folder = opt['img_folder']
lmdb_save_path = opt['lmdb_save_path']
meta_info = {'name': opt['name']}
if not lmdb_save_path.endswith('.lmdb'):
raise ValueError("lmdb_save_path must end with \'lmdb\'.")
if osp.exists(lmdb_save_path):
print('Folder [{:s}] already exists. Exit...'.format(lmdb_save_path))
sys.exit(1)
#### read all the image paths to a list
print('Reading image path list ...')
all_img_list = sorted(glob.glob(osp.join(img_folder, '*')))
keys = []
for img_path in all_img_list:
keys.append(osp.splitext(osp.basename(img_path))[0])
if read_all_imgs:
#### read all images to memory (multiprocessing)
dataset = {} # store all image data. list cannot keep the order, use dict
print('Read images with multiprocessing, #thread: {} ...'.format(n_thread))
pbar = util.ProgressBar(len(all_img_list))
def mycallback(arg):
'''get the image data and update pbar'''
key = arg[0]
dataset[key] = arg[1]
pbar.update('Reading {}'.format(key))
pool = Pool(n_thread)
for path, key in zip(all_img_list, keys):
pool.apply_async(read_image_worker, args=(path, key), callback=mycallback)
pool.close()
pool.join()
print('Finish reading {} images.\nWrite lmdb...'.format(len(all_img_list)))
#### create lmdb environment
data_size_per_img = cv2.imread(all_img_list[0], cv2.IMREAD_UNCHANGED).nbytes
print('data size per image is: ', data_size_per_img)
data_size = data_size_per_img * len(all_img_list)
env = lmdb.open(lmdb_save_path, map_size=data_size * 10)
#### write data to lmdb
pbar = util.ProgressBar(len(all_img_list))
txn = env.begin(write=True)
resolutions = []
for idx, (path, key) in enumerate(zip(all_img_list, keys)):
pbar.update('Write {}'.format(key))
key_byte = key.encode('ascii')
data = dataset[key] if read_all_imgs else cv2.imread(path, cv2.IMREAD_UNCHANGED)
if data.ndim == 2:
H, W = data.shape
C = 1
else:
H, W, C = data.shape
txn.put(key_byte, data)
resolutions.append('{:d}_{:d}_{:d}'.format(C, H, W))
if not read_all_imgs and idx % BATCH == 0:
txn.commit()
txn = env.begin(write=True)
txn.commit()
env.close()
print('Finish writing lmdb.')
#### create meta information
# check whether all the images are the same size
assert len(keys) == len(resolutions)
if len(set(resolutions)) <= 1:
meta_info['resolution'] = [resolutions[0]]
meta_info['keys'] = keys
print('All images have the same resolution. Simplify the meta info.')
else:
meta_info['resolution'] = resolutions
meta_info['keys'] = keys
print('Not all images have the same resolution. Save meta info for each image.')
pickle.dump(meta_info, open(osp.join(lmdb_save_path, 'meta_info.pkl'), "wb"))
print('Finish creating lmdb meta info.')
def vimeo90k(mode):
"""Create lmdb for the Vimeo90K dataset, each image with a fixed size
GT: [3, 256, 448]
Now only need the 4th frame, e.g., 00001_0001_4
LR: [3, 64, 112]
1st - 7th frames, e.g., 00001_0001_1, ..., 00001_0001_7
key:
Use the folder and subfolder names, w/o the frame index, e.g., 00001_0001
flow: downsampled flow: [3, 360, 320], keys: 00001_0001_4_[p3, p2, p1, n1, n2, n3]
Each flow is calculated with GT images by PWCNet and then downsampled by 1/4
Flow map is quantized by mmcv and saved in png format
"""
#### configurations
read_all_imgs = False # whether real all images to memory with multiprocessing
# Set False for use limited memory
BATCH = 5000 # After BATCH images, lmdb commits, if read_all_imgs = False
if mode == 'GT':
img_folder = '../../datasets/vimeo90k/vimeo_septuplet/sequences'
lmdb_save_path = '../../datasets/vimeo90k/vimeo90k_train_GT.lmdb'
txt_file = '../../datasets/vimeo90k/vimeo_septuplet/sep_trainlist.txt'
H_dst, W_dst = 256, 448
elif mode == 'LR':
img_folder = '../../datasets/vimeo90k/vimeo_septuplet_matlabLRx4/sequences'
lmdb_save_path = '../../datasets/vimeo90k/vimeo90k_train_LR7frames.lmdb'
txt_file = '../../datasets/vimeo90k/vimeo_septuplet/sep_trainlist.txt'
H_dst, W_dst = 64, 112
elif mode == 'flow':
img_folder = '../../datasets/vimeo90k/vimeo_septuplet/sequences_flowx4'
lmdb_save_path = '../../datasets/vimeo90k/vimeo90k_train_flowx4.lmdb'
txt_file = '../../datasets/vimeo90k/vimeo_septuplet/sep_trainlist.txt'
H_dst, W_dst = 128, 112
else:
raise ValueError('Wrong dataset mode: {}'.format(mode))
n_thread = 40
########################################################
if not lmdb_save_path.endswith('.lmdb'):
raise ValueError("lmdb_save_path must end with \'lmdb\'.")
if osp.exists(lmdb_save_path):
print('Folder [{:s}] already exists. Exit...'.format(lmdb_save_path))
sys.exit(1)
#### read all the image paths to a list
print('Reading image path list ...')
with open(txt_file) as f:
train_l = f.readlines()
train_l = [v.strip() for v in train_l]
all_img_list = []
keys = []
for line in train_l:
folder = line.split('/')[0]
sub_folder = line.split('/')[1]
all_img_list.extend(glob.glob(osp.join(img_folder, folder, sub_folder, '*')))
if mode == 'flow':
for j in range(1, 4):
keys.append('{}_{}_4_n{}'.format(folder, sub_folder, j))
keys.append('{}_{}_4_p{}'.format(folder, sub_folder, j))
else:
for j in range(7):
keys.append('{}_{}_{}'.format(folder, sub_folder, j + 1))
all_img_list = sorted(all_img_list)
keys = sorted(keys)
if mode == 'GT': # only read the 4th frame for the GT mode
print('Only keep the 4th frame.')
all_img_list = [v for v in all_img_list if v.endswith('im4.png')]
keys = [v for v in keys if v.endswith('_4')]
if read_all_imgs:
#### read all images to memory (multiprocessing)
dataset = {} # store all image data. list cannot keep the order, use dict
print('Read images with multiprocessing, #thread: {} ...'.format(n_thread))
pbar = util.ProgressBar(len(all_img_list))
def mycallback(arg):
"""get the image data and update pbar"""
key = arg[0]
dataset[key] = arg[1]
pbar.update('Reading {}'.format(key))
pool = Pool(n_thread)
for path, key in zip(all_img_list, keys):
pool.apply_async(read_image_worker, args=(path, key), callback=mycallback)
pool.close()
pool.join()
print('Finish reading {} images.\nWrite lmdb...'.format(len(all_img_list)))
#### write data to lmdb
data_size_per_img = cv2.imread(all_img_list[0], cv2.IMREAD_UNCHANGED).nbytes
print('data size per image is: ', data_size_per_img)
data_size = data_size_per_img * len(all_img_list)
env = lmdb.open(lmdb_save_path, map_size=data_size * 10)
txn = env.begin(write=True)
pbar = util.ProgressBar(len(all_img_list))
for idx, (path, key) in enumerate(zip(all_img_list, keys)):
pbar.update('Write {}'.format(key))
key_byte = key.encode('ascii')
data = dataset[key] if read_all_imgs else cv2.imread(path, cv2.IMREAD_UNCHANGED)
if 'flow' in mode:
H, W = data.shape
assert H == H_dst and W == W_dst, 'different shape.'
else:
H, W, C = data.shape
assert H == H_dst and W == W_dst and C == 3, 'different shape.'
txn.put(key_byte, data)
if not read_all_imgs and idx % BATCH == 0:
txn.commit()
txn = env.begin(write=True)
txn.commit()
env.close()
print('Finish writing lmdb.')
#### create meta information
meta_info = {}
if mode == 'GT':
meta_info['name'] = 'Vimeo90K_train_GT'
elif mode == 'LR':
meta_info['name'] = 'Vimeo90K_train_LR'
elif mode == 'flow':
meta_info['name'] = 'Vimeo90K_train_flowx4'
channel = 1 if 'flow' in mode else 3
meta_info['resolution'] = '{}_{}_{}'.format(channel, H_dst, W_dst)
key_set = set()
for key in keys:
if mode == 'flow':
a, b, _, _ = key.split('_')
else:
a, b, _ = key.split('_')
key_set.add('{}_{}'.format(a, b))
meta_info['keys'] = list(key_set)
pickle.dump(meta_info, open(osp.join(lmdb_save_path, 'meta_info.pkl'), "wb"))
print('Finish creating lmdb meta info.')
def REDS(img_folder, lmdb_save_path, H_dst, W_dst, scale, | |
# -*- coding: utf-8 -*-
u"""
Mayaラッパーオブジェクトの抽象基底クラス。
"""
import sys
import types
from ...common import *
from ..typeinfo import isDerivedNodeType as _isDerivedNodeType
from ..typeregistry import nodetypes
from ._api2mplug import (
_1_mpath, _1_mnode,
makePlugTypeInfo,
)
import maya.api.OpenMaya as _api2
import maya.OpenMaya as _api1
__all__ = [
'BIT_DAGNODE', 'BIT_TRANSFORM', 'BIT_SHAPE',
'CyObject', 'O',
'cyObjects', 'Os',
'ModuleForSel',
]
_MFn = _api2.MFn
_2_MObject = _api2.MObject
_2_MDagPath = _api2.MDagPath
_2_MPlug = _api2.MPlug
_2_MSelectionList = _api2.MSelectionList
_2_MObjectHandle = _api2.MObjectHandle
_2_MFnDagNode = _api2.MFnDagNode
_2_MFnAttribute = _api2.MFnAttribute
_MFn_kDagNode = _MFn.kDagNode
_MFn_kTransform = _MFn.kTransform
_MFn_kShape = _MFn.kShape
_2_getAPathTo = _2_MDagPath.getAPathTo
_2_getAllPathsTo = _2_MDagPath.getAllPathsTo
_2_getActiveSelectionList = _api2.MGlobal.getActiveSelectionList
_2_getSelectionListByName = _api2.MGlobal.getSelectionListByName
_ls = cmds.ls
_decideClass = nodetypes._NodeTypes__decideClass
_relatedNodeTypes = nodetypes.relatedNodeTypes
_object_new = object.__new__
#------------------------------------------------------------------------------
BIT_DAGNODE = 0b0001 #: ノードクラスで dagNode の特徴をサポートしていることを示す。
BIT_TRANSFORM = 0b0010 #: ノードクラスで transform の特徴をサポートしていることを示す。
BIT_SHAPE = 0b0100 #: ノードクラスで shape の特徴をサポートしていることを示す。
#------------------------------------------------------------------------------
class CymelInvalidHandle(Exception):
u"""
`CyObject` が保持している API ハンドルが無効。
"""
__slots__ = tuple()
#------------------------------------------------------------------------------
class CyObject(object):
u"""
Mayaラッパーオブジェクトの抽象基底クラス。
ラッパークラスは、大きく分けて
`.Node` と `.Plug` とがある。
ノードクラスはノードタイプごとに用意されているか自動生成される。
プラグクラスは、システムで用意しているのは1種類だけである。
いずれも、クラスを継承してカスタムクラスを作ることができる。
ノードクラスの場合、
`nodetypes.registerNodeClass <.NodeTypes.registerNodeClass>`
でシステムに登録すると便利である。
プラグクラスの場合、
`CyObject.setGlobalPlugClass <setGlobalPlugClass>`
や
`Node.setPlugClass <.Node_c.setPlugClass>`
を用いて、一時的に使用するクラスを指定すると便利である。
"""
__slots__ = ('__weakref__', '__data', '__ref',)
__glbpcls = None
CLASS_TYPE = 0 #: ラッパークラスの種類を表す (0=CyObject, 1=Node, 2=Plug, -1=ObjectRef)
def __new__(cls, src): #, **kwargs):
# ソースがCyObject派生インスタンスの場合、その複製か参照ラッパーを得る。
if isinstance(src, CyObject):
return _anyClsObjByObj(cls, src)
# ソースが文字列の場合、名前からシーンオブジェクトを検索する。
if isinstance(src, BASESTR):
return _anyClsObjByName(cls, src)
# ソースが API2 MDagPath の場合。
if isinstance(src, _2_MDagPath):
mnode = src.node()
mfn = _mnodeFn(src, mnode)
if not mfn.inModel:
raise ValueError('world (not a model) MDagPath specified')
return _nodeClsObjByAPI2(cls, src, mnode, mfn, src)
# ソースが API2 MObject の場合。
if isinstance(src, _2_MObject):
return _nodeClsObjByMObj(cls, src)
# ソースが API2 MPlug の場合。
if isinstance(src, _2_MPlug):
if src.isNetworked:
raise ValueError('Networked plug is specified')
return _plugClsObjByMPlug(cls, src, src)
# その他の場合、文字列として評価する。
return _anyClsObjByName(cls, str(src))
def __nonzero__(self):
# bool 評価などで __len__ が呼ばれないようにするためにも非常に重要。
return True
def __hash__(self):
return self.__data['hash']
def __repr__(self):
if self.__data['isValid']():
try:
return "%s('%s')" % (type(self).__name__, self.__data['getname']())
except:
return "<%s at %0.16X; unexpected error>" % (type(self).__name__, id(self))
elif self.__data['isAlive']():
return "<%s at %0.16X; invalid handle>" % (type(self).__name__, id(self))
else:
return "<%s at %0.16X; dead internal reference>" % (type(self).__name__, id(self))
def __str__(self):
self.checkValid()
return self.__data['getname']()
def __add__(self, other):
return str(self) + str(other)
def __radd__(self, other):
return str(other) + str(self)
def __unicode__(self):
self.checkValid()
return self.__data['getname']()
def __eq__(self, other):
return self.__data['eq'](self, other)
def __ne__(self, other):
return not self.__eq__(other)
def isValid(self):
u"""
内部ハンドルが正常な状態かどうかを得る。
`isAlive` が真でも、オブジェクトが削除されている場合は無効と判断される。
:rtype: `bool`
"""
return self.__data['isValid']()
def isAlive(self):
u"""
内部ハンドルがメモリ上に存在しているかどうかを得る。
オブジェクトが削除されていても、undo可能な状態で残っていれば真となる。
:rtype: `bool`
"""
return self.__data['isAlive']()
def checkValid(self):
u"""
内部ハンドルの有効性チェック。無効なら `.CymelInvalidHandle` エラーとなる。
"""
if not self.__data['isValid']():
raise CymelInvalidHandle('%s at %0.16X' % (type(self).__name__, id(self)))
def name(self):
u"""
オブジェクトのユニーク名を得る。
オブジェクトの種類に応じて、
ノード名、DAGパーシャルパス名、それらを含むプラグ名などが得られる。
:rtype: `str`
"""
self.checkValid()
return self.__data['getname']()
def name_(self):
u"""
`checkValid` を省略して、オブジェクトのユニーク名を得る。
オブジェクトの種類に応じて、
ノード名、DAGパーシャルパス名、それらを含むプラグ名などが得られる。
:rtype: `str`
"""
return self.__data['getname']()
def node(self):
u"""
ノードを得る。
:rtype: `.Node` 派生クラス
"""
raise NotImplementedError('CyObject.node')
def internalData(self):
u"""
内部データを返す。
派生クラスで内部データを拡張する場合にオーバーライドする。
その場合、 `newObject` クラスメソッドもオーバーライドし、
拡張に対応させる。
内部データはブラックボックスであるものとし、
拡張データでは基底のデータも内包させる必要がある。
"""
return self.__data
@classmethod
def newObject(cls, data):
u"""
内部データとともにインスタンスを生成する。
内部データはブラックボックスであるものとし、
本メソッドをオーバーライドする場合も、
基底メソッドを呼び出して処理を完遂させなければならない。
内部データを拡張する場合は `internalData` も
オーバーライドすること。
:type cls: `type`
:param cls: 生成するインスタンスのクラス。
:param data: インスタンスにセットする内部データ。
:rtype: 指定クラス
"""
obj = _object_new(cls)
obj.__data = data
obj.__ref = None
#trackDestruction(obj)
return obj
@staticmethod
def globalPlugClass():
u"""
グローバル設定のプラグクラスを得る。
これは、 `setGlobalPlugClass` で変更可能。
:rtype: `type`
"""
return CyObject.__glbpcls
@staticmethod
def setGlobalPlugClass(pcls=None):
u"""
グローバル設定のプラグクラスをセットする。
:param `type` cls:
`.Plug` 派生クラス。
None を指定するとクリアする。
"""
global _defaultPlugCls
if _defaultPlugCls is None:
_defaultPlugCls = pcls
CyObject.__glbpcls = pcls or _defaultPlugCls
@classmethod
def ls(cls, *args, **kwargs):
u"""
:mayacmd:`ls` コマンドの結果をクラスに適合するものに限定してオブジェクトとして得る。
:rtype: `list`
"""
isNode = cls.CLASS_TYPE is 1
if isNode:
typs = _relatedNodeTypes(cls)
kwargs['type'] = typs
# o=True が必要なら、オプションで指定されるものとする。
names = _ls(*args, **kwargs)
num = len(names)
if not num:
return names
sel = _2_MSelectionList()
for name in names:
sel.add(name)
num = sel.length()
if isNode:
if hasattr(cls, '_verifyNode'):
return [x for x in [_getNodeObjBySelIdx(sel, i, cls) for i in range(num)] if x]
else:
return [_getNodeObjBySelIdx(sel, i, None) for i in range(num)]
objMap = {} if num > 1 else None
if cls.CLASS_TYPE is 2:
return [x for x in [_getPlugObjBySelIdx(sel, i, cls, objMap) for i in range(num)] if x]
elif cls.CLASS_TYPE is -1:
return [_getObjRefBySelIdx(sel, i, cls, objMap) for i in range(num)]
else:
return [_getObjectBySelIdx(sel, i, objMap) for i in range(num)]
if MAYA_VERSION >= (2016,):
@classmethod
def fromUUID(cls, val):
u"""
UUID からノードリストを得る。
重複も起こり得るので、戻り値はリストである。
:param `str` val:
単一のUUIDかそのリスト。
:rtype: `list`
"""
return [cls(x) for x in (_ls(val) or EMPTY_TUPLE)]
_defaultPlugCls = None #: Plug が import 後にセットされる。
O = CyObject #: `CyObject` の別名。
def cyObjects(val):
u"""
名前リストなどから `CyObject` のリストを得る。
:param iterable val:
ノード名やプラグ名や同等の評価が可能なもののリスト。
単一の名前の場合はそれのみのリスト、
None などの場合は空リストと解釈されるので、
Mayaコマンドの返値をそのまま受けられることが多い。
:rtype: `list`
"""
if not vals:
return []
elif isinstance(val, BASESTR):
return [O(val)]
else:
return [O(v) for v in val]
Os = cyObjects #: `cyObjects` の別名。
#------------------------------------------------------------------------------
def _getObjectRef(*args):
global _getObjectRef, _newNodeRefFromData, _newPlugRefFromData
from .objectref import _getObjectRef, _newNodeRefFromData, _newPlugRefFromData
return _getObjectRef(*args)
def _newNodeRefFromData(*args):
global _getObjectRef, _newNodeRefFromData, _newPlugRefFromData
from .objectref import _getObjectRef, _newNodeRefFromData, _newPlugRefFromData
return _newNodeRefFromData(*args)
def _newPlugRefFromData(*args):
global _getObjectRef, _newNodeRefFromData, _newPlugRefFromData
from .objectref import _getObjectRef, _newNodeRefFromData, _newPlugRefFromData
return _newPlugRefFromData(*args)
#------------------------------------------------------------------------------
def _makeNodeData(mpath, mnode, mfn, dummy=None):
u"""
Node の内部データを構築する。
"""
mhdl = _2_MObjectHandle(mnode)
isAlive = mhdl.isAlive
data = {
'hash': mhdl.hashCode(),
'isAlive': isAlive,
'isValid': mhdl.isValid,
'mnode': mnode,
'mfn': mfn,
'nodetype': mfn.typeName,
'getname': mfn.partialPathName if mpath else mfn.name,
'plugcls': None,
}
if mpath:
data['mpath'] = mpath
if mnode.hasFn(_MFn_kTransform):
data['shape'] = [{}, {}]
elif mnode.hasFn(_MFn_kShape):
data['transform'] = None
def eq(self, other):
if isAlive() and isinstance(other, CyObject) and other._CyObject__data['isAlive']():
if (
(self.refclass() if self.CLASS_TYPE is -1 else self).TYPE_BITS and
(other.refclass() if other.CLASS_TYPE is -1 else other).TYPE_BITS
):
return mpath == other._CyObject__data['mpath']
else:
return mnode == other._CyObject__data['mnode']
return False
else:
def eq(self, other):
return (
isAlive() and isinstance(other, CyObject) and
other._CyObject__data['isAlive']() and
mnode == other._CyObject__data['mnode']
)
data['eq'] = eq
return data
def _makePlugData(noderef, mplug, typeinfo=None, typename=None, attrname=None):
u"""
Plug の内部データを構築する。
"""
# NOTE: システムでは徹底しているのでデバッグ用。通常は、ユーザー指定のチェック用に CyObject.__new__ でのみ行う。
#if mplug.isNetworked:
# raise ValueError('Networked plug is specified')
if not typeinfo:
typeinfo = makePlugTypeInfo(mplug.attribute(), typename)
if not attrname:
attrname = '.' + mplug.partialName(includeNonMandatoryIndices=True, includeInstancedIndices=True)
node_getname = noderef._CyObject__data['getname']
data = {
'hash': hash((noderef._CyObject__data['hash'], attrname)),
'mplug': mplug,
'noderef': noderef,
'attrname': attrname,
'typeinfo': typeinfo,
'getname': lambda: node_getname() + attrname,
'elemIdxAttrs': None,
}
attr_isAlive = typeinfo['isAlive']
if attr_isAlive:
node_isAlive = noderef._CyObject__data['isAlive']
node_isValid = noderef._CyObject__data['isValid']
node_hasAttr = noderef._CyObject__data['mfn'].hasAttribute
shortname = typeinfo['shortname']
data['isValid'] = lambda: attr_isAlive() and node_isValid() and node_hasAttr(shortname)
isAlive = lambda: attr_isAlive() and node_isAlive()
else:
data['isValid'] = noderef._CyObject__data['isValid']
isAlive = noderef._CyObject__data['isAlive']
data['isAlive'] = isAlive
def eq(self, other):
if isAlive() and isinstance(other, CyObject):
dt = other._CyObject__data
return (
'mplug' in dt and dt['isAlive']() and
mplug == dt['mplug'] and attrname == dt['attrname']
)
return False
data['eq'] = eq
return data
def _initAPI1Objects(data):
u"""
API1 オブジェクトを初期化する。
"""
if 'mfn1' in data:
return
if 'mplug' in data:
nodedata = data['noderef']._CyObject__data
_initAPI1Objects(nodedata)
mfnnode = nodedata['mfn1']
# ノードからプラグを得る為に、マルチプラグのインデックスを収集する。
attrTkns = [s.split('[') for s in data['mplug'].info.split('.')[1:]]
ss = attrTkns.pop(-1)
leafName = ss[0]
leafIdx = int(ss[1][:-1]) if len(ss) > 1 else None
ancestorIdxs = [(ss[0], int(ss[1][:-1])) for ss in attrTkns if len(ss) > 1]
# ノードからプラグを取得。
try:
# 末尾のプラグを得る。
mplug1 = mfnnode.findPlug(leafName, False)
# 上位のロジカルインデックスを選択する。
for name, i in ancestorIdxs:
mplug1.selectAncestorLogicalIndex(i, mfnnode.attribute(name))
# 末尾のロジカルインデックスを選択する。
if leafIdx is not None:
mplug1.selectAncestorLogicalIndex(leafIdx)
data['mplug1'] = mplug1
data['mfn1'] = getattr(_api1, type(data['typeinfo']['mfn']).__name__)(mplug1.attribute())
except RuntimeError:
data['mplug1'] = None
data['mfn1'] = None
elif 'mpath' in data:
mpath1 = _1_mpath(data['getname']())
data['mpath1'] = mpath1
data['mnode1'] = mpath1.node()
data['mfn1'] = getattr(_api1, type(data['mfn']).__name__)(mpath1)
else: #if 'mnode' in data:
mnode1 = _1_mnode(data['getname']())
data['mnode1'] = mnode1
data['mfn1'] = getattr(_api1, type(data['mfn']).__name__)(mnode1)
def _setPlugCache(node, plug):
u"""
Node に Plug をキャッシュする。
Plug の後に Node を作った場合に、任意でキャッシュをセットすることができる。
"""
cache = node._Node_c__plugCache.get(plug._CyObject__data['attrname'])
if cache is None:
node._Node_c__plugCache[plug._CyObject__data['attrname']] = {id(type(plug)): plug}
else:
cache[id(type(plug))] = plug
def _newNodePlug(pcls, node, mplug, typeinfo=None, typename=None):
u"""
Node から Plug インスタンスを得る。
Node にキャッシュが作られ、キャッシュがヒットすれば再利用される。
"""
attrname = '.' + mplug.partialName(includeNonMandatoryIndices=True, includeInstancedIndices=True)
key = <KEY>
cache = node._Node_c__plugCache.get(attrname)
if cache:
plug = cache.get(key)
if plug:
return plug
for k in cache:
data = cache[k]._CyObject__data
break
else:
cache = {}
node._Node_c__plugCache[attrname] = cache
data = _makePlugData(_getObjectRef(node), mplug, typeinfo, typename, attrname)
plug = pcls.newObject(data)
cache[key] = plug
return plug
def _newNodeRefPlug(pcls, noderef, mplug, typeinfo=None, typename=None):
u"""
Node の ObjectRef から Plug インスタンスを得る。
Node の参照が生きていれば、Node にキャッシュが作られ、キャッシュがヒットすれば再利用される。
"""
node = noderef.object()
if node:
return _newNodePlug(pcls, node, mplug, typeinfo, typename)
else:
return pcls.newObject(_makePlugData(noderef, mplug, typeinfo, typename))
def _decideNodeClsFromData(data):
u"""
ノード内部データからクラスを決定する。
"""
return _decideClass(data['getname'](), data['mfn'].typeName, lambda: data['mfn'])
#def _newNodeFromData(data):
# u"""
# ノード内部データのみから Node インスタンスを生成する。
# """
# return _decideNodeClsFromData(data).newObject(data)
def _newNodeObjByArgs(args):
u"""
`_makeNodeData` と同じ引数リストから Node インスタンスを生成する。
"""
data = _makeNodeData(*args)
mfn = args[2]
return _decideClass(
args[-1] if len(args) is 4 else data['getname'](),
mfn.typeName, lambda: mfn).newObject(data)
def | |
''' Automate populating element properties for QUAD4M analyses
DESCRIPTION:
This module contains functions that help populate element properties for QUAD4M
analysis, generally adding columns to the dataframe "elems" that then gets
exported to a ".q4r" file.
'''
import llgeo.props_nonlinear.darendeli_2011 as q4m_daran
import numpy as np
import pandas as pd
# ------------------------------------------------------------------------------
# Main Functions
# ------------------------------------------------------------------------------
def elem_stresses(nodes, elems, k = 0.5, unit_w = 21000):
''' add vertical and mean effective stress to elements data frame
Purpose
-------
Given the dataframes "elems" and "nodes" (created by 'geometry' module),
this function adds columns for the vertical stress and the mean stress at
the center of each element.
Parameters
----------
nodes : pandas dataframe
Contains information for elements, usually created by 'geometry.py'
At a *minumum*, must have columns: [node number, x, y]
elems : pandas DataFrame
Contains information for elements, usually created by 'geometry.py'
At a *minumum*, must have columns: [element number, xc, yc]
k : float (defaults = 0.5)
coefficient of lateral earth pressure at rest.
unit_w : float (defaults = 21000)
unit weight for material, *ONLY* used if "elems" does not already
include a 'unit_w' column!!!
Returns
-------
elems : pandas DataFrame
Returns elems DataFrame that was provided, with added columns for effec-
tive and mean stress: ['unit_v', 'unit_m]. CAREFUL WITH UNITS.
Notes
-----
* If unit_w provided is effective, stresses will be effective.
Be careful with units!! unit_w and coordinate units must somehow agree.
* As in 'geometry' module, elements are assumed to be arranged in verti-
cal columns (no slanting).
* Elements and nodes should be numbered bottom-up, and left-to-right
(start at lower left column, move upwards to surface, then one col
to the right).
* Unless provided otherwise, a value of 0.5 is used for lateral earth
pressure coefficient at rest.
* If a unit weight column already exists in elems, this will be used in
calculations. Otherwise, a "unit_w" value will be used, which
defaults to 21000 N/m3. CAREFUL WITH UNITS!!
'''
# If there isn't already a unit_w in elems dataframe, then choose a uniform
# one for all (if none provided, defaults to 21000 N/m3)
if 'unit_w_eff' not in list(elems):
elems['unit_w_eff'] = unit_w * np.ones(len(elems))
# Get the top of each node column (goes left to right)
top_ys_nodes = [col['y'].max() for _, col in nodes.groupby('node_i')]
# Get top of each element col (average of top left and top right nodes)
# (moving average of top_ys_nodes with window of 2; see shorturl.at/iwFLY)
top_ys_elems = np.convolve(top_ys_nodes, [0.5, 0.5], 'valid')
# Initialize space for vertical stress column
elems[['sigma_v', 'sigma_m']] = np.zeros((len(elems), 2))
# Iterate through element soil columns (goes left to right)
for (_, soil_col), y_top in zip(elems.groupby('i'), top_ys_elems):
# Get array of y-coords at center of element and unit weights
# Note that in elems dataframe, elements are ordered from the bot to top
# Here I flip the order so that its easier for stress calc (top down)
ns = np.flip(soil_col['n'].to_numpy())
ys = np.flip(soil_col['yc'].to_numpy())
gs = np.flip(soil_col['unit_w_eff'].to_numpy())
# Get y_diff, the depth intervals between center of elements
y_diff_start = y_top - np.max(ys) # depth to center of top element
y_diff_rest = ys[0:-1] - ys[1:] # depth intervals for rest of elements
y_diff = np.append(y_diff_start, y_diff_rest) # depth intervals for all
# Calculate vertical stress increments, and then vertical stress profile
vert_stress_diff = y_diff * gs
vert_stress_prof = np.cumsum(vert_stress_diff)
# Convet vertical stress to mean effective stress
# (assumes ko = 0.5 unless another value is provided)
mean_stress_prof = (vert_stress_prof + 2 * k * vert_stress_prof) / 3
for n, vert, mean in zip(ns, vert_stress_prof, mean_stress_prof):
elems.loc[elems['n'] == n, 'sigma_v'] = vert
elems.loc[elems['n'] == n, 'sigma_m'] = mean
return(elems)
def add_vs_pfit(nodes, elems, pfits, rf = None, rf_type = 'ratio',
unit_fix = True, unit_w = 21000):
''' Adds shear-wave velocity based on power-fits and possible random field.
Purpose
-------
Given the geometry information of the QUAD4M analysis (nodes and elems), this
function adds Vs based on the following:
1) pfits: which provides the best-fit relationship between depth and vs,
possibly as a function of layering.
2) rf: a random field of residuals to add randomness to Vs.
Parameters
----------
nodes : pandas dataframe
Contains information for elements, usually created by 'geometry.py'
At a *minumum*, must have columns: [node_i]
elems : pandas DataFrame
Contains information for elements, usually created by 'geometry.py'
At a *minumum*, must have columns: [i, xc, yc, layer]
pfits : list of dict
Each elements correspond to a powerfit between depth and vs specific to a
given soil layer.
The number of elements in this list must be equal to the unique number of
layers specified in elems['layer'], where these will be mapped as:
layer number = (index of pfits + 1) since layer number is assumed to
be 1-indexed but python is 0-indexed.
Each dict must, at a minimum, have the keys: 'power', 'const' and 'plus',
with this function assuming a form: vs = plust + const * depth ** power.
rf : bool or numpy array (optional)
If provided, this must be a random field to introduce randomness
in the shear wave velocity measurements. Defaults to None,
so that no randomness is added to the estimated shear wave velocity. Must
be random fields of residuals around shear wave pfit (see rf_type).
rf_type : str (optional)
rf here is assumed to be a random field of residuals that are based on
the powerfit relationship. They can be of two types:
'ratio' : Y = measured / estimated and typ. lognormally distributed
'subs' : R = measured - estimated and typ. normally distributed
unit_fix : bool
If true, Gmax will be divided by 1,000 since QUAD4M works in those units
unit_w : float (optional)
If elems does not already have a 'unit_w' column, then a single value
"unit_w" will be used for all the elements. Defaults to 21,000 N/m3.
Returns
-------
elems : dataframe
Returns same dataframe but with "Vs_mean" column added.
'''
# If there isn't already a unit_w in elems dataframe, then choose a uniform
# one for all (if none provided, defaults to 21000 N/m3)
if 'unit_w' not in list(elems):
elems['unit_w'] = unit_w * np.ones(len(elems))
# Get the top of each node column (goes left to right)
top_ys_nodes = [col['y'].max() for _, col in nodes.groupby('node_i')]
# Get top of each element col (average of top left and top right nodes)
# (moving average of top_ys_nodes with window of 2; see shorturl.at/iwFLY)
top_ys_elems = np.convolve(top_ys_nodes, [0.5, 0.5], 'valid')
# Add required columns if there is randomness
if (rf is not None):
elems = map_rf(elems, 'rf', rf)
elems['vs_mean'] = np.empty(len(elems))
# Initalize new columns in dataframe
elems['vs'] = np.empty(len(elems))
elems['Gmax'] = np.empty(len(elems))
elems['depth'] = np.empty(len(elems))
# Iterate through element soil columns (goes left to right)
for (i, soil_col), y_top in zip(elems.groupby('i'), top_ys_elems):
# Get array of y-coords at center of element and unit weights
# Note that in elems dataframe, elements are ordered from the bot to top
# Here I flip the order so that its easier for stress calc (top down)
ys = soil_col['yc'].values
gs = soil_col['unit_w'].values
ds = y_top - ys
# Determine power and constant as function of depth (based on layer)
layers = soil_col['layer'].values
powers = [pfits[int(L)]['power'] for L in layers]
consts = [pfits[int(L)]['const'] for L in layers]
pluss = [pfits[int(L)]['plus'] for L in layers]
# Calculate vs and Gmax
vs_mean = np.array([c * d**power + plus for c, d, power, plus in
zip(consts, ds, powers, pluss)])
# Add depth values to elements table
elems.loc[elems['i'] == i, 'depth'] = ds
# If there is no random field, then vs_final = vs_mean
if rf is None:
vs_final = vs_mean
# If random field type is ratio, then multiply rf and | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import print_function
import nose
from datetime import datetime
from pandas import date_range
from pandas.core.index import MultiIndex
from pandas.core.api import DataFrame
from pandas.core.series import Series
from pandas.util.testing import (assert_frame_equal, assert_series_equal
)
from pandas.core.groupby import (SpecificationError)
from pandas.compat import (lmap, OrderedDict)
from pandas.formats.printing import pprint_thing
from pandas import compat
import pandas.core.common as com
import numpy as np
import pandas.util.testing as tm
import pandas as pd
class TestGroupByAggregate(tm.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
self.ts = tm.makeTimeSeries()
self.seriesd = tm.getSeriesData()
self.tsd = tm.getTimeSeriesData()
self.frame = DataFrame(self.seriesd)
self.tsframe = DataFrame(self.tsd)
self.df = DataFrame(
{'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})
self.df_mixed_floats = DataFrame(
{'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.array(
np.random.randn(8), dtype='float32')})
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two',
'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
self.mframe = DataFrame(np.random.randn(10, 3), index=index,
columns=['A', 'B', 'C'])
self.three_group = DataFrame(
{'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two', 'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull', 'dull', 'shiny', 'shiny',
'dull', 'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
def test_agg_api(self):
# GH 6337
# http://stackoverflow.com/questions/21706030/pandas-groupby-agg-function-column-dtype-error
# different api for agg when passed custom function with mixed frame
df = DataFrame({'data1': np.random.randn(5),
'data2': np.random.randn(5),
'key1': ['a', 'a', 'b', 'b', 'a'],
'key2': ['one', 'two', 'one', 'two', 'one']})
grouped = df.groupby('key1')
def peak_to_peak(arr):
return arr.max() - arr.min()
expected = grouped.agg([peak_to_peak])
expected.columns = ['data1', 'data2']
result = grouped.agg(peak_to_peak)
assert_frame_equal(result, expected)
def test_agg_regression1(self):
grouped = self.tsframe.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.mean)
expected = grouped.mean()
assert_frame_equal(result, expected)
def test_agg_datetimes_mixed(self):
data = [[1, '2012-01-01', 1.0], [2, '2012-01-02', 2.0], [3, None, 3.0]]
df1 = DataFrame({'key': [x[0] for x in data],
'date': [x[1] for x in data],
'value': [x[2] for x in data]})
data = [[row[0], datetime.strptime(row[1], '%Y-%m-%d').date() if row[1]
else None, row[2]] for row in data]
df2 = DataFrame({'key': [x[0] for x in data],
'date': [x[1] for x in data],
'value': [x[2] for x in data]})
df1['weights'] = df1['value'] / df1['value'].sum()
gb1 = df1.groupby('date').aggregate(np.sum)
df2['weights'] = df1['value'] / df1['value'].sum()
gb2 = df2.groupby('date').aggregate(np.sum)
assert (len(gb1) == len(gb2))
def test_agg_period_index(self):
from pandas import period_range, PeriodIndex
prng = period_range('2012-1-1', freq='M', periods=3)
df = DataFrame(np.random.randn(3, 2), index=prng)
rs = df.groupby(level=0).sum()
tm.assertIsInstance(rs.index, PeriodIndex)
# GH 3579
index = period_range(start='1999-01', periods=5, freq='M')
s1 = Series(np.random.rand(len(index)), index=index)
s2 = Series(np.random.rand(len(index)), index=index)
series = [('s1', s1), ('s2', s2)]
df = DataFrame.from_items(series)
grouped = df.groupby(df.index.month)
list(grouped)
def test_agg_dict_parameter_cast_result_dtypes(self):
# GH 12821
df = DataFrame(
{'class': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],
'time': date_range('1/1/2011', periods=8, freq='H')})
df.loc[[0, 1, 2, 5], 'time'] = None
# test for `first` function
exp = df.loc[[0, 3, 4, 6]].set_index('class')
grouped = df.groupby('class')
assert_frame_equal(grouped.first(), exp)
assert_frame_equal(grouped.agg('first'), exp)
assert_frame_equal(grouped.agg({'time': 'first'}), exp)
assert_series_equal(grouped.time.first(), exp['time'])
assert_series_equal(grouped.time.agg('first'), exp['time'])
# test for `last` function
exp = df.loc[[0, 3, 4, 7]].set_index('class')
grouped = df.groupby('class')
assert_frame_equal(grouped.last(), exp)
assert_frame_equal(grouped.agg('last'), exp)
assert_frame_equal(grouped.agg({'time': 'last'}), exp)
assert_series_equal(grouped.time.last(), exp['time'])
assert_series_equal(grouped.time.agg('last'), exp['time'])
def test_agg_must_agg(self):
grouped = self.df.groupby('A')['C']
self.assertRaises(Exception, grouped.agg, lambda x: x.describe())
self.assertRaises(Exception, grouped.agg, lambda x: x.index[:2])
def test_agg_ser_multi_key(self):
# TODO(wesm): unused
ser = self.df.C # noqa
f = lambda x: x.sum()
results = self.df.C.groupby([self.df.A, self.df.B]).aggregate(f)
expected = self.df.groupby(['A', 'B']).sum()['C']
assert_series_equal(results, expected)
def test_agg_apply_corner(self):
# nothing to group, all NA
grouped = self.ts.groupby(self.ts * np.nan)
self.assertEqual(self.ts.dtype, np.float64)
# groupby float64 values results in Float64Index
exp = Series([], dtype=np.float64, index=pd.Index(
[], dtype=np.float64))
assert_series_equal(grouped.sum(), exp)
assert_series_equal(grouped.agg(np.sum), exp)
assert_series_equal(grouped.apply(np.sum), exp, check_index_type=False)
# DataFrame
grouped = self.tsframe.groupby(self.tsframe['A'] * np.nan)
exp_df = DataFrame(columns=self.tsframe.columns, dtype=float,
index=pd.Index([], dtype=np.float64))
assert_frame_equal(grouped.sum(), exp_df, check_names=False)
assert_frame_equal(grouped.agg(np.sum), exp_df, check_names=False)
assert_frame_equal(grouped.apply(np.sum), exp_df.iloc[:, :0],
check_names=False)
def test_agg_grouping_is_list_tuple(self):
from pandas.core.groupby import Grouping
df = tm.makeTimeDataFrame()
grouped = df.groupby(lambda x: x.year)
grouper = grouped.grouper.groupings[0].grouper
grouped.grouper.groupings[0] = Grouping(self.ts.index, list(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
grouped.grouper.groupings[0] = Grouping(self.ts.index, tuple(grouper))
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_aggregate_api_consistency(self):
# GH 9052
# make sure that the aggregates via dict
# are consistent
df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two',
'two', 'two', 'one', 'two'],
'C': np.random.randn(8) + 1.0,
'D': np.arange(8)})
grouped = df.groupby(['A', 'B'])
c_mean = grouped['C'].mean()
c_sum = grouped['C'].sum()
d_mean = grouped['D'].mean()
d_sum = grouped['D'].sum()
result = grouped['D'].agg(['sum', 'mean'])
expected = pd.concat([d_sum, d_mean],
axis=1)
expected.columns = ['sum', 'mean']
assert_frame_equal(result, expected, check_like=True)
result = grouped.agg([np.sum, np.mean])
expected = pd.concat([c_sum,
c_mean,
d_sum,
d_mean],
axis=1)
expected.columns = MultiIndex.from_product([['C', 'D'],
['sum', 'mean']])
assert_frame_equal(result, expected, check_like=True)
result = grouped[['D', 'C']].agg([np.sum, np.mean])
expected = pd.concat([d_sum,
d_mean,
c_sum,
c_mean],
axis=1)
expected.columns = MultiIndex.from_product([['D', 'C'],
['sum', 'mean']])
assert_frame_equal(result, expected, check_like=True)
result = grouped.agg({'C': 'mean', 'D': 'sum'})
expected = pd.concat([d_sum,
c_mean],
axis=1)
assert_frame_equal(result, expected, check_like=True)
result = grouped.agg({'C': ['mean', 'sum'],
'D': ['mean', 'sum']})
expected = pd.concat([c_mean,
c_sum,
d_mean,
d_sum],
axis=1)
expected.columns = MultiIndex.from_product([['C', 'D'],
['mean', 'sum']])
result = grouped[['D', 'C']].agg({'r': np.sum,
'r2': np.mean})
expected = pd.concat([d_sum,
c_sum,
d_mean,
c_mean],
axis=1)
expected.columns = MultiIndex.from_product([['r', 'r2'],
['D', 'C']])
assert_frame_equal(result, expected, check_like=True)
def test_agg_compat(self):
# GH 12334
df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two',
'two', 'two', 'one', 'two'],
'C': np.random.randn(8) + 1.0,
'D': np.arange(8)})
g = df.groupby(['A', 'B'])
expected = pd.concat([g['D'].sum(),
g['D'].std()],
axis=1)
expected.columns = MultiIndex.from_tuples([('C', 'sum'),
('C', 'std')])
result = g['D'].agg({'C': ['sum', 'std']})
assert_frame_equal(result, expected, check_like=True)
expected = pd.concat([g['D'].sum(),
g['D'].std()],
axis=1)
expected.columns = ['C', 'D']
result = g['D'].agg({'C': 'sum', 'D': 'std'})
assert_frame_equal(result, expected, check_like=True)
def test_agg_nested_dicts(self):
# API change for disallowing these types of nested dicts
df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two',
'two', 'two', 'one', 'two'],
'C': np.random.randn(8) + 1.0,
'D': np.arange(8)})
g = df.groupby(['A', 'B'])
def f():
g.aggregate({'r1': {'C': ['mean', 'sum']},
'r2': {'D': ['mean', 'sum']}})
self.assertRaises(SpecificationError, f)
result = g.agg({'C': {'ra': ['mean', 'std']},
'D': {'rb': ['mean', 'std']}})
expected = pd.concat([g['C'].mean(), g['C'].std(), g['D'].mean(),
g['D'].std()], axis=1)
expected.columns = pd.MultiIndex.from_tuples([('ra', 'mean'), (
'ra', 'std'), ('rb', 'mean'), ('rb', 'std')])
assert_frame_equal(result, expected, check_like=True)
# same name as the original column
# GH9052
expected = g['D'].agg({'result1': np.sum, 'result2': np.mean})
expected = expected.rename(columns={'result1': 'D'})
result = g['D'].agg({'D': np.sum, 'result2': np.mean})
assert_frame_equal(result, expected, check_like=True)
def test_agg_python_multiindex(self):
grouped = self.mframe.groupby(['A', 'B'])
result = grouped.agg(np.mean)
expected = grouped.mean()
tm.assert_frame_equal(result, expected)
def test_aggregate_str_func(self):
def _check_results(grouped):
# single series
result = grouped['A'].agg('std')
expected = grouped['A'].std()
assert_series_equal(result, expected)
# group frame by function name
result = grouped.aggregate('var')
expected = grouped.var()
assert_frame_equal(result, expected)
# group frame by function dict
result = grouped.agg(OrderedDict([['A', 'var'], ['B', 'std'],
['C', 'mean'], ['D', 'sem']]))
expected = DataFrame(OrderedDict([['A', grouped['A'].var(
)], ['B', grouped['B'].std()], ['C', grouped['C'].mean()],
['D', grouped['D'].sem()]]))
assert_frame_equal(result, expected)
by_weekday = self.tsframe.groupby(lambda x: x.weekday())
_check_results(by_weekday)
by_mwkday = self.tsframe.groupby([lambda x: x.month,
lambda x: x.weekday()])
_check_results(by_mwkday)
def test_aggregate_item_by_item(self):
df = self.df.copy()
df['E'] = ['a'] * len(self.df)
grouped = self.df.groupby('A')
# API change in 0.11
# def aggfun(ser):
# return len(ser + 'a')
# result = grouped.agg(aggfun)
# self.assertEqual(len(result.columns), 1)
aggfun = lambda ser: ser.size
result = grouped.agg(aggfun)
foo = (self.df.A == 'foo').sum()
bar = (self.df.A == 'bar').sum()
K = len(result.columns)
# GH5782
# odd comparisons can result here, so cast to make easy
exp = pd.Series(np.array([foo] * K), index=list('BCD'),
dtype=np.float64, name='foo')
tm.assert_series_equal(result.xs('foo'), exp)
exp = pd.Series(np.array([bar] * K), index=list('BCD'),
dtype=np.float64, name='bar')
tm.assert_almost_equal(result.xs('bar'), exp)
def aggfun(ser):
return ser.size
result = DataFrame().groupby(self.df.A).agg(aggfun)
tm.assertIsInstance(result, DataFrame)
self.assertEqual(len(result), 0)
def test_agg_item_by_item_raise_typeerror(self):
from numpy.random import randint
df = DataFrame(randint(10, size=(20, 10)))
def raiseException(df):
pprint_thing('----------------------------------------')
pprint_thing(df.to_string())
raise TypeError
self.assertRaises(TypeError, df.groupby(0).agg, raiseException)
def test_series_agg_multikey(self):
ts = tm.makeTimeSeries()
grouped = ts.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.sum)
expected = grouped.sum()
assert_series_equal(result, expected)
def test_series_agg_multi_pure_python(self):
data = DataFrame(
{'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar',
'foo', 'foo', 'foo'],
'B': ['one', 'one', 'one', 'two', 'one', 'one', 'one', 'two',
'two', 'two', 'one'],
'C': ['dull', 'dull', 'shiny', 'dull', 'dull', 'shiny', 'shiny',
'dull', 'shiny', 'shiny', 'shiny'],
'D': np.random.randn(11),
'E': np.random.randn(11),
'F': np.random.randn(11)})
def bad(x):
assert (len(x.base) > 0)
| |
<reponame>khramtsova/federated<gh_stars>1-10
# Lint as: python3
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build a model for EMNIST classification."""
import functools
import tensorflow as tf
def create_conv_dropout_model(only_digits=True):
"""Recommended model to use for EMNIST experiments.
When `only_digits=True`, the summary of returned model is
```
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
reshape (Reshape) (None, 28, 28, 1) 0
_________________________________________________________________
conv2d (Conv2D) (None, 26, 26, 32) 320
_________________________________________________________________
conv2d_1 (Conv2D) (None, 24, 24, 64) 18496
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 12, 12, 64) 0
_________________________________________________________________
dropout (Dropout) (None, 12, 12, 64) 0
_________________________________________________________________
flatten (Flatten) (None, 9216) 0
_________________________________________________________________
dense (Dense) (None, 128) 1179776
_________________________________________________________________
dropout_1 (Dropout) (None, 128) 0
_________________________________________________________________
dense_1 (Dense) (None, 10) 1290
=================================================================
Total params: 1,199,882
Trainable params: 1,199,882
Non-trainable params: 0
```
For `only_digits=False`, the last dense layer is slightly larger.
Args:
only_digits: If True, uses a final layer with 10 outputs, for use with the
digits only EMNIST dataset. If False, uses 62 outputs for the larger
dataset.
Returns:
A `tf.keras.Model`.
"""
data_format = 'channels_last'
input_shape = [28, 28, 1]
model = tf.keras.models.Sequential([
tf.keras.layers.Reshape(input_shape=(28 * 28,), target_shape=input_shape),
tf.keras.layers.Conv2D(
32,
kernel_size=(3, 3),
activation='relu',
input_shape=input_shape,
data_format=data_format),
tf.keras.layers.Conv2D(
64, kernel_size=(3, 3), activation='relu', data_format=data_format),
tf.keras.layers.MaxPool2D(pool_size=(2, 2), data_format=data_format),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(
10 if only_digits else 62, activation=tf.nn.softmax),
])
return model
def create_original_fedavg_cnn_model(only_digits=True):
"""The CNN model used in https://arxiv.org/abs/1602.05629.
The number of parameters when `only_digits=True` is (1,663,370), which matches
what is reported in the paper.
When `only_digits=True`, the summary of returned model is
```
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
reshape (Reshape) (None, 28, 28, 1) 0
_________________________________________________________________
conv2d (Conv2D) (None, 28, 28, 32) 832
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 14, 14, 32) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 14, 14, 64) 51264
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 7, 7, 64) 0
_________________________________________________________________
flatten (Flatten) (None, 3136) 0
_________________________________________________________________
dense (Dense) (None, 512) 1606144
_________________________________________________________________
dense_1 (Dense) (None, 10) 5130
=================================================================
Total params: 1,663,370
Trainable params: 1,663,370
Non-trainable params: 0
```
For `only_digits=False`, the last dense layer is slightly larger.
Args:
only_digits: If True, uses a final layer with 10 outputs, for use with the
digits only EMNIST dataset. If False, uses 62 outputs for the larger
dataset.
Returns:
A `tf.keras.Model`.
"""
data_format = 'channels_last'
input_shape = [28, 28, 1]
max_pool = functools.partial(
tf.keras.layers.MaxPooling2D,
pool_size=(2, 2),
padding='same',
data_format=data_format)
conv2d = functools.partial(
tf.keras.layers.Conv2D,
kernel_size=5,
padding='same',
data_format=data_format,
activation=tf.nn.relu)
model = tf.keras.models.Sequential([
tf.keras.layers.Reshape(input_shape=(28 * 28,), target_shape=input_shape),
conv2d(filters=32, input_shape=input_shape),
max_pool(),
conv2d(filters=64),
max_pool(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dense(
10 if only_digits else 62, activation=tf.nn.softmax),
])
return model
def create_two_hidden_layer_model(only_digits=True, hidden_units=200):
"""Create a two hidden-layer fully connected neural network.
Args:
only_digits: A boolean that determines whether to only use the digits in
EMNIST, or the full EMNIST-62 dataset. If True, uses a final layer with 10
outputs, for use with the digit-only EMNIST dataset. If False, uses 62
outputs for the larger dataset.
hidden_units: An integer specifying the number of units in the hidden layer.
Returns:
A `tf.keras.Model`.
"""
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(
hidden_units, activation=tf.nn.relu, input_shape=(28 * 28,)),
tf.keras.layers.Dense(hidden_units, activation=tf.nn.relu),
tf.keras.layers.Dense(
10 if only_digits else 62, activation=tf.nn.softmax),
])
return model
# Defining global constants for ResNet model
L2_WEIGHT_DECAY = 2e-4
def _residual_block(input_tensor, kernel_size, filters, base_name):
"""A block of two conv layers with an identity residual connection.
Args:
input_tensor: The input tensor for the residual block.
kernel_size: An integer specifying the kernel size of the convolutional
layers in the residual blocks.
filters: A list of two integers specifying the filters of the conv layers in
the residual blocks. The first integer specifies the number of filters on
the first conv layer within each residual block, the second applies to the
remaining conv layers within each block.
base_name: A string used to generate layer names.
Returns:
The output tensor of the residual block evaluated at the input tensor.
"""
filters1, filters2 = filters
x = tf.keras.layers.Conv2D(
filters1,
kernel_size,
padding='same',
use_bias=False,
name='{}_conv_1'.format(base_name))(
input_tensor)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(
filters2,
kernel_size,
padding='same',
use_bias=False,
name='{}_conv_2'.format(base_name))(
x)
x = tf.keras.layers.add([x, input_tensor])
x = tf.keras.layers.Activation('relu')(x)
return x
def _conv_residual_block(input_tensor,
kernel_size,
filters,
base_name,
strides=(2, 2)):
"""A block of two conv layers with a convolutional residual connection.
Args:
input_tensor: The input tensor for the residual block.
kernel_size: An integer specifying the kernel size of the convolutional
layers in the residual blocks.
filters: A list of two integers specifying the filters of the conv layers in
the residual blocks. The first integer specifies the number of filters on
the first conv layer within each residual block, the second applies to the
remaining conv layers within each block.
base_name: A string used to generate layer names.
strides: A tuple of integers specifying the strides lengths in the first
conv layer in the block.
Returns:
The output tensor of the residual block evaluated at the input tensor.
"""
filters1, filters2 = filters
x = tf.keras.layers.Conv2D(
filters1,
kernel_size,
strides=strides,
padding='same',
use_bias=False,
name='{}_conv_1'.format(base_name))(
input_tensor)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(
filters2,
kernel_size,
padding='same',
use_bias=False,
name='{}_conv_2'.format(base_name))(
x)
shortcut = tf.keras.layers.Conv2D(
filters2, (1, 1),
strides=strides,
use_bias=False,
name='{}_conv_shortcut'.format(base_name))(
input_tensor)
x = tf.keras.layers.add([x, shortcut])
x = tf.keras.layers.Activation('relu')(x)
return x
def _resnet_block(input_tensor,
size,
kernel_size,
filters,
stage,
conv_strides=(2, 2)):
"""A block which applies multiple residual blocks to a given input.
The resnet block applies a single conv residual block followed by multiple
identity residual blocks to a given input.
Args:
input_tensor: The input tensor for the resnet block.
size: An integer specifying the number of residual blocks. A conv residual
block is applied once, followed by (size - 1) identity residual blocks.
kernel_size: An integer specifying the kernel size of the convolutional
layers in the residual blocks.
filters: A list of two integers specifying the filters of the conv layers in
the residual blocks. The first integer specifies the number of filters on
the first conv layer within each residual block, the second applies to the
remaining conv layers within each block.
stage: An integer representing the the position of the resnet block within
the resnet. Used for generating layer names.
conv_strides: A tuple of integers specifying the strides in the first conv
layer within each conv residual block.
Returns:
The output tensor of the resnet block evaluated at the input tensor.
"""
x = _conv_residual_block(
input_tensor,
kernel_size,
filters,
base_name='res_{}_block_0'.format(stage),
strides=conv_strides)
for i in range(size - 1):
x = _residual_block(
x,
kernel_size,
filters,
base_name='res_{}_block_{}'.format(stage, i + 1))
return x
def create_resnet(num_blocks=5, only_digits=True):
"""Instantiates a ResNet model for EMNIST classification.
Instantiates the ResNet architecture from https://arxiv.org/abs/1512.03385.
The ResNet contains 3 stages of ResNet blocks with each block containing one
conv residual block followed by (num_blocks - 1) idenity residual blocks. Each
residual block has 2 convolutional layers. With the input convolutional
layer and the final dense layer, this brings the total number of trainable
layers in the network to (6*num_blocks + 2). This number is often used to
identify the ResNet, so for example ResNet56 has num_blocks = 9.
Args:
num_blocks: An integer representing the number of residual blocks within
each ResNet block.
only_digits: A boolean that determines whether to only use the digits in
EMNIST, or the full EMNIST-62 dataset. If True, uses a final layer with 10
outputs, for use with the digit-only EMNIST dataset. If False, uses 62
outputs for the larger dataset.
Returns:
A `tf.keras.Model`.
"""
num_classes = 10 if only_digits else 62
target_shape = (28, 28, 1)
img_input = tf.keras.layers.Input(shape=(28 * 28,))
x = img_input
x = tf.keras.layers.Reshape(
target_shape=target_shape, input_shape=(28 * 28,))(
x)
x = | |
Test that second iteration is possible
act_values_list2 = list(act_values)
# Test __contained__() of the returned view
for value in act_values_list:
assert value in act_values
# Ensure that exceptions raised in the remainder of this function
# are not mistaken as expected exceptions
assert testcase.exp_exc_types is None
assert isinstance(act_values, ValuesView)
exp_values = [item[1] for item in exp_items]
assert act_values_list == exp_values
assert act_values_list2 == exp_values
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_DICTVIEW_ITEMS)
@simplified_test_function
def test_DictView_viewitems(testcase, obj, exp_items):
"""
Test function for DictView.viewitems()
"""
if not DICT_SUPPORTS_ITER_VIEW:
pytest.skip("Test dictionary does not support viewitems() method")
assert PY2
# The code to be tested
act_items = obj.viewitems()
# Also test iterating through the result
act_items_list = list(act_items)
# Test that second iteration is possible
act_items_list2 = list(act_items)
# Test __contained__() of the returned view
for item in act_items_list:
assert item in act_items
# Ensure that exceptions raised in the remainder of this function
# are not mistaken as expected exceptions
assert testcase.exp_exc_types is None
assert isinstance(act_items, ItemsView)
assert act_items_list == exp_items
assert act_items_list2 == exp_items
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_DICTVIEW_ITEMS)
@simplified_test_function
def test_DictView_iter(testcase, obj, exp_items):
"""
Test function for DictView.__iter__() / for key in ncd
"""
# The code to be tested
act_keys = []
for key in obj:
act_keys.append(key)
# Ensure that exceptions raised in the remainder of this function
# are not mistaken as expected exceptions
assert testcase.exp_exc_types is None
exp_keys = [item[0] for item in exp_items]
assert act_keys == exp_keys
TESTCASES_DICTVIEW_REPR = [
# Testcases for DictView.__repr__() / repr(ncd)
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * obj: DictView object to be used for the test.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
(
"Empty dict",
dict(
obj=DictView({}),
),
None, None, True
),
(
"Dict with two items",
dict(
obj=DictView(OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')])),
),
None, None, True
),
]
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_DICTVIEW_REPR)
@simplified_test_function
def test_DictView_repr(testcase, obj):
"""
Test function for DictView.__repr__() / repr(ncd)
"""
# The code to be tested
result = repr(obj)
# Ensure that exceptions raised in the remainder of this function
# are not mistaken as expected exceptions
assert testcase.exp_exc_types is None
assert re.match(r'^DictView\(.*\)$', result)
# Note: This only tests for existence of each item, not for excess items
# or representing the correct order.
for item in obj.items():
exp_item_result1 = "{0!r}: {1!r}".format(*item)
exp_item_result2 = "({0!r}, {1!r})".format(*item)
assert exp_item_result1 in result or exp_item_result2 in result
TESTCASES_DICTVIEW_COPY = [
# Testcases for DictView.copy()
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * dictview: DictView object to be used for the test.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
(
"DictView with empty dict",
dict(
dictview=DictView({}),
),
None, None, True
),
(
"DictView with dict with two items",
dict(
dictview=DictView(
dict([('Dog', 'Cat'), ('Budgie', 'Fish')])),
),
None, None, True
),
(
"DictView with OrderedDict with two items",
dict(
dictview=DictView(
OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')])),
),
None, None, True
),
]
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_DICTVIEW_COPY)
@simplified_test_function
def test_DictView_copy(testcase, dictview):
"""
Test function for DictView.copy()
"""
dictview_dict = dictview.dict
# The code to be tested
dictview_copy = dictview.copy()
dictview_copy_dict = dictview_copy.dict
# Ensure that exceptions raised in the remainder of this function
# are not mistaken as expected exceptions
assert testcase.exp_exc_types is None
# Verify the result type
# pylint: disable=unidiomatic-typecheck
assert type(dictview_copy) is DictView
# Verify the result is a different object than the DictView
assert id(dictview_copy) != id(dictview)
# Verify the new dictionary is a different object than the underlying
# dictionary, if mutable
if isinstance(dictview_dict, MutableMapping):
assert id(dictview_copy_dict) != id(dictview_dict)
# Verify the new dictionary has the same type as the underlying dictionary
# pylint: disable=unidiomatic-typecheck
assert type(dictview_copy_dict) == type(dictview_dict)
# Verify the new dictionary is equal to the underlying dictionary
assert dictview_copy_dict == dictview_dict
TESTCASES_DICTVIEW_EQUAL = [
# Testcases for DictView.__eq__(), __ne__()
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * obj1: DictView object #1 to use.
# * obj2: DictView object #2 to use.
# * exp_obj_equal: Expected equality of the objects.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
(
"Empty dictionary",
dict(
obj1=DictView({}),
obj2=DictView({}),
exp_obj_equal=True,
),
None, None, True
),
(
"One item, keys and values equal",
dict(
obj1=DictView(OrderedDict([('k1', 'v1')])),
obj2=DictView(OrderedDict([('k1', 'v1')])),
exp_obj_equal=True,
),
None, None, True
),
(
"One item, keys equal, values different",
dict(
obj1=DictView(OrderedDict([('k1', 'v1')])),
obj2=DictView(OrderedDict([('k1', 'v1_x')])),
exp_obj_equal=False,
),
None, None, True
),
(
"One item, keys different, values equal",
dict(
obj1=DictView(OrderedDict([('k1', 'v1')])),
obj2=DictView(OrderedDict([('k2', 'v1')])),
exp_obj_equal=False,
),
None, None, True
),
(
"One item, keys equal, values both None",
dict(
obj1=DictView(OrderedDict([('k1', None)])),
obj2=DictView(OrderedDict([('k1', None)])),
exp_obj_equal=True,
),
None, None, True
),
(
"Two equal items, in same order",
dict(
obj1=DictView(OrderedDict([('k1', 'v1'), ('k2', 'v2')])),
obj2=DictView(OrderedDict([('k1', 'v1'), ('k2', 'v2')])),
exp_obj_equal=True,
),
None, None, True
),
(
"Two equal items in ordered dict, in different order",
dict(
obj1=DictView(OrderedDict([('k1', 'v1'), ('k2', 'v2')])),
obj2=DictView(OrderedDict([('k2', 'v2'), ('k1', 'v1')])),
exp_obj_equal=False,
),
None, None, False
),
(
"Two equal items in standard dict, in different order",
dict(
obj1=DictView(dict([('k1', 'v1'), ('k2', 'v2')])),
obj2=DictView(dict([('k2', 'v2'), ('k1', 'v1')])),
exp_obj_equal=not DICT_IS_ORDERED,
),
None, None, False
),
(
"Comparing unicode value with bytes value",
dict(
obj1=DictView(OrderedDict([('k1', b'v1')])),
obj2=DictView(OrderedDict([('k2', u'v2')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Matching unicode key with string key",
dict(
obj1=DictView(OrderedDict([('k1', 'v1')])),
obj2=DictView(OrderedDict([(u'k2', 'v2')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Higher key missing",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Budgie', 'Fish')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Lower key missing",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Dog', 'Cat')])),
exp_obj_equal=False,
),
None, None, True
),
(
"First non-matching key is less. But longer size!",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([
('Budgie', 'Fish'), ('Curly', 'Snake'), ('Cozy', 'Dog'),
])),
exp_obj_equal=False,
),
None, None, True
),
(
"Only non-matching keys that are less. But longer size!",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict(
[('Alf', 'F'), ('Anton', 'S'), ('Aussie', 'D')])),
exp_obj_equal=False,
),
None, None, True
),
(
"First non-matching key is greater. But shorter size!",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Budgio', 'Fish')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Only non-matching keys that are greater. But shorter size!",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Zoe', 'F')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size. First non-matching key is less",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict(
[('Budgie', 'Fish'), ('Curly', 'Snake')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size. Only non-matching keys that are less",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Alf', 'F'), ('Anton', 'S')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size. Only non-matching keys that are greater",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Zoe', 'F'), ('Zulu', 'S')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size, only matching keys. First non-matching value is less",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Car')])),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size, only matching keys. First non-matching value is greater",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Caz')])),
exp_obj_equal=False,
),
None, None, True
),
(
"A value raises TypeError when compared (and equal still succeeds)",
dict(
obj1=DictView(OrderedDict([('Budgie', 'Fish'), ('Dog', 'Cat')])),
obj2=DictView(OrderedDict(
[('Budgie', NonEquatable()), ('Dog', 'Cat')])),
exp_obj_equal=False,
),
TypeError, None, True
),
(
"Mixing types: DictView of dict and dict",
dict(
obj1=DictView(dict({'Dog': 'Cat'})),
obj2=dict({'Dog': 'Cat'}),
exp_obj_equal=True,
),
None, None, True
),
(
"Mixing types: dict and DictView of dict",
dict(
obj1=dict({'Dog': 'Cat'}),
obj2=DictView(dict({'Dog': 'Cat'})),
exp_obj_equal=True,
),
| |
<filename>S4_FaceRecognition/models/utils/detect_face.py
mport torch
from torch.nn.functional import interpolate
from torchvision.transforms import functional as F
from torchvision.ops.boxes import batched_nms
from PIL import Image
import numpy as np
import os
import math
# OpenCV is optional, but required if using numpy arrays instead of PIL
try:
import cv2
except:
pass
def fixed_batch_process(im_data, model):
batch_size = 512
out = []
for i in range(0, len(im_data), batch_size):
batch = im_data[i:(i+batch_size)]
out.append(model(batch))
return tuple(torch.cat(v, dim=0) for v in zip(*out))
def detect_face(imgs, minsize, pnet, rnet, onet, threshold, factor, device):
if isinstance(imgs, (np.ndarray, torch.Tensor)):
if isinstance(imgs,np.ndarray):
imgs = torch.as_tensor(imgs.copy(), device=device)
if isinstance(imgs,torch.Tensor):
imgs = torch.as_tensor(imgs, device=device)
if len(imgs.shape) == 3:
imgs = imgs.unsqueeze(0)
else:
if not isinstance(imgs, (list, tuple)):
imgs = [imgs]
if any(img.size != imgs[0].size for img in imgs):
raise Exception("MTCNN batch processing only compatible with equal-dimension images.")
imgs = np.stack([np.uint8(img) for img in imgs])
imgs = torch.as_tensor(imgs.copy(), device=device)
model_dtype = next(pnet.parameters()).dtype
imgs = imgs.permute(0, 3, 1, 2).type(model_dtype)
batch_size = len(imgs)
h, w = imgs.shape[2:4]
m = 12.0 / minsize
minl = min(h, w)
minl = minl * m
# Create scale pyramid
scale_i = m
scales = []
while minl >= 12:
scales.append(scale_i)
scale_i = scale_i * factor
minl = minl * factor
# First stage
boxes = []
image_inds = []
scale_picks = []
all_i = 0
offset = 0
for scale in scales:
im_data = imresample(imgs, (int(h * scale + 1), int(w * scale + 1)))
im_data = (im_data - 127.5) * 0.0078125
reg, probs = pnet(im_data)
boxes_scale, image_inds_scale = generateBoundingBox(reg, probs[:, 1], scale, threshold[0])
boxes.append(boxes_scale)
image_inds.append(image_inds_scale)
pick = batched_nms(boxes_scale[:, :4], boxes_scale[:, 4], image_inds_scale, 0.5)
scale_picks.append(pick + offset)
offset += boxes_scale.shape[0]
boxes = torch.cat(boxes, dim=0)
image_inds = torch.cat(image_inds, dim=0)
scale_picks = torch.cat(scale_picks, dim=0)
# NMS within each scale + image
boxes, image_inds = boxes[scale_picks], image_inds[scale_picks]
# NMS within each image
pick = batched_nms(boxes[:, :4], boxes[:, 4], image_inds, 0.7)
boxes, image_inds = boxes[pick], image_inds[pick]
regw = boxes[:, 2] - boxes[:, 0]
regh = boxes[:, 3] - boxes[:, 1]
qq1 = boxes[:, 0] + boxes[:, 5] * regw
qq2 = boxes[:, 1] + boxes[:, 6] * regh
qq3 = boxes[:, 2] + boxes[:, 7] * regw
qq4 = boxes[:, 3] + boxes[:, 8] * regh
boxes = torch.stack([qq1, qq2, qq3, qq4, boxes[:, 4]]).permute(1, 0)
boxes = rerec(boxes)
y, ey, x, ex = pad(boxes, w, h)
# Second stage
if len(boxes) > 0:
im_data = []
for k in range(len(y)):
if ey[k] > (y[k] - 1) and ex[k] > (x[k] - 1):
img_k = imgs[image_inds[k], :, (y[k] - 1):ey[k], (x[k] - 1):ex[k]].unsqueeze(0)
im_data.append(imresample(img_k, (24, 24)))
im_data = torch.cat(im_data, dim=0)
im_data = (im_data - 127.5) * 0.0078125
# This is equivalent to out = rnet(im_data) to avoid GPU out of memory.
out = fixed_batch_process(im_data, rnet)
out0 = out[0].permute(1, 0)
out1 = out[1].permute(1, 0)
score = out1[1, :]
ipass = score > threshold[1]
boxes = torch.cat((boxes[ipass, :4], score[ipass].unsqueeze(1)), dim=1)
image_inds = image_inds[ipass]
mv = out0[:, ipass].permute(1, 0)
# NMS within each image
pick = batched_nms(boxes[:, :4], boxes[:, 4], image_inds, 0.7)
boxes, image_inds, mv = boxes[pick], image_inds[pick], mv[pick]
boxes = bbreg(boxes, mv)
boxes = rerec(boxes)
# Third stage
points = torch.zeros(0, 5, 2, device=device)
if len(boxes) > 0:
y, ey, x, ex = pad(boxes, w, h)
im_data = []
for k in range(len(y)):
if ey[k] > (y[k] - 1) and ex[k] > (x[k] - 1):
img_k = imgs[image_inds[k], :, (y[k] - 1):ey[k], (x[k] - 1):ex[k]].unsqueeze(0)
im_data.append(imresample(img_k, (48, 48)))
im_data = torch.cat(im_data, dim=0)
im_data = (im_data - 127.5) * 0.0078125
# This is equivalent to out = onet(im_data) to avoid GPU out of memory.
out = fixed_batch_process(im_data, onet)
out0 = out[0].permute(1, 0)
out1 = out[1].permute(1, 0)
out2 = out[2].permute(1, 0)
score = out2[1, :]
points = out1
ipass = score > threshold[2]
points = points[:, ipass]
boxes = torch.cat((boxes[ipass, :4], score[ipass].unsqueeze(1)), dim=1)
image_inds = image_inds[ipass]
mv = out0[:, ipass].permute(1, 0)
w_i = boxes[:, 2] - boxes[:, 0] + 1
h_i = boxes[:, 3] - boxes[:, 1] + 1
points_x = w_i.repeat(5, 1) * points[:5, :] + boxes[:, 0].repeat(5, 1) - 1
points_y = h_i.repeat(5, 1) * points[5:10, :] + boxes[:, 1].repeat(5, 1) - 1
points = torch.stack((points_x, points_y)).permute(2, 1, 0)
boxes = bbreg(boxes, mv)
# NMS within each image using "Min" strategy
# pick = batched_nms(boxes[:, :4], boxes[:, 4], image_inds, 0.7)
pick = batched_nms_numpy(boxes[:, :4], boxes[:, 4], image_inds, 0.7, 'Min')
boxes, image_inds, points = boxes[pick], image_inds[pick], points[pick]
boxes = boxes.cpu().numpy()
points = points.cpu().numpy()
image_inds = image_inds.cpu()
batch_boxes = []
batch_points = []
for b_i in range(batch_size):
b_i_inds = np.where(image_inds == b_i)
batch_boxes.append(boxes[b_i_inds].copy())
batch_points.append(points[b_i_inds].copy())
batch_boxes, batch_points = np.array(batch_boxes), np.array(batch_points)
return batch_boxes, batch_points
def bbreg(boundingbox, reg):
if reg.shape[1] == 1:
reg = torch.reshape(reg, (reg.shape[2], reg.shape[3]))
w = boundingbox[:, 2] - boundingbox[:, 0] + 1
h = boundingbox[:, 3] - boundingbox[:, 1] + 1
b1 = boundingbox[:, 0] + reg[:, 0] * w
b2 = boundingbox[:, 1] + reg[:, 1] * h
b3 = boundingbox[:, 2] + reg[:, 2] * w
b4 = boundingbox[:, 3] + reg[:, 3] * h
boundingbox[:, :4] = torch.stack([b1, b2, b3, b4]).permute(1, 0)
return boundingbox
def generateBoundingBox(reg, probs, scale, thresh):
stride = 2
cellsize = 12
reg = reg.permute(1, 0, 2, 3)
mask = probs >= thresh
mask_inds = mask.nonzero()
image_inds = mask_inds[:, 0]
score = probs[mask]
reg = reg[:, mask].permute(1, 0)
bb = mask_inds[:, 1:].type(reg.dtype).flip(1)
q1 = ((stride * bb + 1) / scale).floor()
q2 = ((stride * bb + cellsize - 1 + 1) / scale).floor()
boundingbox = torch.cat([q1, q2, score.unsqueeze(1), reg], dim=1)
return boundingbox, image_inds
def nms_numpy(boxes, scores, threshold, method):
if boxes.size == 0:
return np.empty((0, 3))
x1 = boxes[:, 0].copy()
y1 = boxes[:, 1].copy()
x2 = boxes[:, 2].copy()
y2 = boxes[:, 3].copy()
s = scores
area = (x2 - x1 + 1) * (y2 - y1 + 1)
I = np.argsort(s)
pick = np.zeros_like(s, dtype=np.int16)
counter = 0
while I.size > 0:
i = I[-1]
pick[counter] = i
counter += 1
idx = I[0:-1]
xx1 = np.maximum(x1[i], x1[idx]).copy()
yy1 = np.maximum(y1[i], y1[idx]).copy()
xx2 = np.minimum(x2[i], x2[idx]).copy()
yy2 = np.minimum(y2[i], y2[idx]).copy()
w = np.maximum(0.0, xx2 - xx1 + 1).copy()
h = np.maximum(0.0, yy2 - yy1 + 1).copy()
inter = w * h
if method is "Min":
o = inter / np.minimum(area[i], area[idx])
else:
o = inter / (area[i] + area[idx] - inter)
I = I[np.where(o <= threshold)]
pick = pick[:counter].copy()
return pick
def batched_nms_numpy(boxes, scores, idxs, threshold, method):
device = boxes.device
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=device)
# strategy: in order to perform NMS independently per class.
# we add an offset to all the boxes. The offset is dependent
# only on the class idx, and is large enough so that boxes
# from different classes do not overlap
max_coordinate = boxes.max()
offsets = idxs.to(boxes) * (max_coordinate + 1)
boxes_for_nms = boxes + offsets[:, None]
boxes_for_nms = boxes_for_nms.cpu().numpy()
scores = scores.cpu().numpy()
keep = nms_numpy(boxes_for_nms, scores, threshold, method)
return torch.as_tensor(keep, dtype=torch.long, device=device)
def pad(boxes, w, h):
boxes = boxes.trunc().int().cpu().numpy()
x = boxes[:, 0]
y = boxes[:, 1]
ex = boxes[:, 2]
ey = boxes[:, 3]
x[x < 1] = 1
y[y < 1] = 1
ex[ex > w] = w
ey[ey > h] = h
return y, ey, x, ex
def rerec(bboxA):
h = bboxA[:, 3] - bboxA[:, 1]
w = bboxA[:, 2] - bboxA[:, 0]
l = torch.max(w, h)
bboxA[:, 0] = bboxA[:, 0] + w * 0.5 - l * 0.5
bboxA[:, 1] = bboxA[:, 1] + h * 0.5 - l * 0.5
bboxA[:, 2:4] = bboxA[:, :2] + l.repeat(2, 1).permute(1, 0)
return bboxA
def imresample(img, sz):
im_data = interpolate(img, size=sz, mode="area")
return im_data
def crop_resize(img, box, image_size):
if isinstance(img, np.ndarray):
out = cv2.resize(
img[box[1]:box[3], box[0]:box[2]],
(image_size, image_size),
interpolation=cv2.INTER_AREA
).copy()
else:
out = img.crop(box).copy().resize((image_size, image_size), Image.BILINEAR)
return out
def save_img(img, path):
if isinstance(img, np.ndarray):
cv2.imwrite(path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
else:
img.save(path)
def get_size(img):
if isinstance(img, np.ndarray):
return img.shape[1::-1]
else:
return img.size
def extract_face(img, box, image_size=160, margin=0, save_path=None):
"""Extract face + margin from | |
<reponame>jtyuan/racetrack<filename>src/arch/isa_parser.py
# Copyright (c) 2003-2005 The Regents of The University of Michigan
# Copyright (c) 2013 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: <NAME>
from __future__ import with_statement
import os
import sys
import re
import string
import inspect, traceback
# get type names
from types import *
from m5.util.grammar import Grammar
debug=False
###################
# Utility functions
#
# Indent every line in string 's' by two spaces
# (except preprocessor directives).
# Used to make nested code blocks look pretty.
#
def indent(s):
return re.sub(r'(?m)^(?!#)', ' ', s)
#
# Munge a somewhat arbitrarily formatted piece of Python code
# (e.g. from a format 'let' block) into something whose indentation
# will get by the Python parser.
#
# The two keys here are that Python will give a syntax error if
# there's any whitespace at the beginning of the first line, and that
# all lines at the same lexical nesting level must have identical
# indentation. Unfortunately the way code literals work, an entire
# let block tends to have some initial indentation. Rather than
# trying to figure out what that is and strip it off, we prepend 'if
# 1:' to make the let code the nested block inside the if (and have
# the parser automatically deal with the indentation for us).
#
# We don't want to do this if (1) the code block is empty or (2) the
# first line of the block doesn't have any whitespace at the front.
def fixPythonIndentation(s):
# get rid of blank lines first
s = re.sub(r'(?m)^\s*\n', '', s);
if (s != '' and re.match(r'[ \t]', s[0])):
s = 'if 1:\n' + s
return s
class ISAParserError(Exception):
"""Error handler for parser errors"""
def __init__(self, first, second=None):
if second is None:
self.lineno = 0
self.string = first
else:
if hasattr(first, 'lexer'):
first = first.lexer.lineno
self.lineno = first
self.string = second
def display(self, filename_stack, print_traceback=debug):
# Output formatted to work under Emacs compile-mode. Optional
# 'print_traceback' arg, if set to True, prints a Python stack
# backtrace too (can be handy when trying to debug the parser
# itself).
spaces = ""
for (filename, line) in filename_stack[:-1]:
print "%sIn file included from %s:" % (spaces, filename)
spaces += " "
# Print a Python stack backtrace if requested.
if print_traceback or not self.lineno:
traceback.print_exc()
line_str = "%s:" % (filename_stack[-1][0], )
if self.lineno:
line_str += "%d:" % (self.lineno, )
return "%s%s %s" % (spaces, line_str, self.string)
def exit(self, filename_stack, print_traceback=debug):
# Just call exit.
sys.exit(self.display(filename_stack, print_traceback))
def error(*args):
raise ISAParserError(*args)
####################
# Template objects.
#
# Template objects are format strings that allow substitution from
# the attribute spaces of other objects (e.g. InstObjParams instances).
labelRE = re.compile(r'(?<!%)%\(([^\)]+)\)[sd]')
class Template(object):
def __init__(self, parser, t):
self.parser = parser
self.template = t
def subst(self, d):
myDict = None
# Protect non-Python-dict substitutions (e.g. if there's a printf
# in the templated C++ code)
template = self.parser.protectNonSubstPercents(self.template)
# CPU-model-specific substitutions are handled later (in GenCode).
template = self.parser.protectCpuSymbols(template)
# Build a dict ('myDict') to use for the template substitution.
# Start with the template namespace. Make a copy since we're
# going to modify it.
myDict = self.parser.templateMap.copy()
if isinstance(d, InstObjParams):
# If we're dealing with an InstObjParams object, we need
# to be a little more sophisticated. The instruction-wide
# parameters are already formed, but the parameters which
# are only function wide still need to be generated.
compositeCode = ''
myDict.update(d.__dict__)
# The "operands" and "snippets" attributes of the InstObjParams
# objects are for internal use and not substitution.
del myDict['operands']
del myDict['snippets']
snippetLabels = [l for l in labelRE.findall(template)
if d.snippets.has_key(l)]
snippets = dict([(s, self.parser.mungeSnippet(d.snippets[s]))
for s in snippetLabels])
myDict.update(snippets)
compositeCode = ' '.join(map(str, snippets.values()))
# Add in template itself in case it references any
# operands explicitly (like Mem)
compositeCode += ' ' + template
operands = SubOperandList(self.parser, compositeCode, d.operands)
myDict['op_decl'] = operands.concatAttrStrings('op_decl')
if operands.readPC or operands.setPC:
myDict['op_decl'] += 'TheISA::PCState __parserAutoPCState;\n'
# In case there are predicated register reads and write, declare
# the variables for register indicies. It is being assumed that
# all the operands in the OperandList are also in the
# SubOperandList and in the same order. Otherwise, it is
# expected that predication would not be used for the operands.
if operands.predRead:
myDict['op_decl'] += 'uint8_t _sourceIndex = 0;\n'
if operands.predWrite:
myDict['op_decl'] += 'uint8_t M5_VAR_USED _destIndex = 0;\n'
is_src = lambda op: op.is_src
is_dest = lambda op: op.is_dest
myDict['op_src_decl'] = \
operands.concatSomeAttrStrings(is_src, 'op_src_decl')
myDict['op_dest_decl'] = \
operands.concatSomeAttrStrings(is_dest, 'op_dest_decl')
if operands.readPC:
myDict['op_src_decl'] += \
'TheISA::PCState __parserAutoPCState;\n'
if operands.setPC:
myDict['op_dest_decl'] += \
'TheISA::PCState __parserAutoPCState;\n'
myDict['op_rd'] = operands.concatAttrStrings('op_rd')
if operands.readPC:
myDict['op_rd'] = '__parserAutoPCState = xc->pcState();\n' + \
myDict['op_rd']
# Compose the op_wb string. If we're going to write back the
# PC state because we changed some of its elements, we'll need to
# do that as early as possible. That allows later uncoordinated
# modifications to the PC to layer appropriately.
reordered = list(operands.items)
reordered.reverse()
op_wb_str = ''
pcWbStr = 'xc->pcState(__parserAutoPCState);\n'
for op_desc in reordered:
if op_desc.isPCPart() and op_desc.is_dest:
op_wb_str = op_desc.op_wb + pcWbStr + op_wb_str
pcWbStr = ''
else:
op_wb_str = op_desc.op_wb + op_wb_str
myDict['op_wb'] = op_wb_str
elif isinstance(d, dict):
# if the argument is a dictionary, we just use it.
myDict.update(d)
elif hasattr(d, '__dict__'):
# if the argument is an object, we use its attribute map.
myDict.update(d.__dict__)
else:
raise TypeError, "Template.subst() arg must be or have dictionary"
return template % myDict
# Convert to string. This handles the case when a template with a
# CPU-specific term gets interpolated into another template or into
# an output block.
def __str__(self):
return self.parser.expandCpuSymbolsToString(self.template)
################
# Format object.
#
# A format object encapsulates an instruction format. It must provide
# a defineInst() method that generates the code for an instruction
# definition.
class Format(object):
def __init__(self, id, params, code):
self.id = id
self.params = params
label = 'def format ' + id
self.user_code = compile(fixPythonIndentation(code), label, 'exec')
param_list = string.join(params, ", ")
f = '''def defInst(_code, _context, %s):
my_locals = vars().copy()
exec _code in _context, my_locals
return my_locals\n''' % param_list
c = compile(f, label + ' wrapper', 'exec')
exec c
self.func = defInst
def defineInst(self, parser, name, args, lineno):
parser.updateExportContext()
context = parser.exportContext.copy()
if len(name):
Name = name[0].upper()
if len(name) > 1:
Name += name[1:]
context.update({ 'name' : name, 'Name' : Name })
try:
vars = self.func(self.user_code, context, *args[0], **args[1])
except Exception, exc:
if debug:
raise
error(lineno, 'error defining "%s": %s.' % (name, exc))
for k in vars.keys():
if k not in ('header_output', 'decoder_output',
'exec_output', 'decode_block'):
del vars[k]
return GenCode(parser, **vars)
# Special null format to catch an implicit-format instruction
# definition outside of any format block.
class NoFormat(object):
def __init__(self):
self.defaultInst = ''
def defineInst(self, parser, name, args, lineno):
error(lineno,
'instruction definition "%s" with no active | |
AssertionError is raised in this scenario.
Why is this so important? The ``DropoutLayer`` and ``PoolLayer`` (in
the case of stochastic pooling) are sensitive to this parameter and
results are very different for the two settings.
:param shuffle: bool.
If set to True, shuffle the training data every epoch. The test data
is not shuffled. Default: False.
"""
if net is not None:
from barrista import net as _net
assert isinstance(net, _net.Net), (
'net must be an instance of barrista.net.Net')
self._Update_net(net)
assert self._net is not None, (
'neither the solver was initialized with a net nor',
'the fit function was called with one')
assert self._net._mode == _Phase.TRAIN or allow_test_phase_for_train, (
'The network must be in TRAIN phase for fitting! If you really '
'want to, you can override this requirement by setting '
'the optional parameter `allow_test_phase_for_train` to True.'
)
train_callbacks = self._Assert_callbacks(self._net,
train_callbacks,
'train')
testnet = self._Init_testnet(test_interval,
use_fit_phase_for_validation)
if testnet is not None:
test_callbacks = self._Assert_callbacks(testnet,
test_callbacks,
'test')
else:
test_callbacks = []
batch_size, test_iterations = self._Get_batch_size(
self._net,
testnet,
test_interval,
test_iterations,
X_val,
read_input_batch_size_from_blob_name)
self._Assert_iterations(
batch_size,
iterations,
test_interval,
test_iterations,
self._parameter_dict.get('stepvalue')
)
if self._parameter_dict.get('stepvalue') is not None:
self._parameter_dict['stepvalue'] = [
val / batch_size for val in self._parameter_dict['stepvalue']]
self._Init_cycling_monitor(X,
X_val,
input_processing_flags,
batch_size,
test_interval,
train_callbacks,
test_callbacks,
shuffle)
run_pre = True
iteration = 0
cbparams = dict()
cbparams['max_iter'] = iterations
cbparams['batch_size'] = batch_size
cbparams['iter'] = 0
cbparams['net'] = self._net
cbparams['testnet'] = testnet
cbparams['solver'] = self
cbparams['X'] = X
cbparams['X_val'] = X_val
cbparams['test_iterations'] = test_iterations
cbparams['test_interval'] = test_interval
cbparams['train_callbacks'] = train_callbacks
cbparams['test_callbacks'] = test_callbacks
cbparams['callback_signal'] = 'initialize_train'
for cb in train_callbacks:
cb(cbparams)
if test_interval > 0:
cbparams['callback_signal'] = 'initialize_test'
for cb in test_callbacks:
cb(cbparams)
try:
_parallel.init_prebatch(
self,
self._net,
train_callbacks,
True)
if test_interval > 0:
_parallel.init_prebatch(
self,
testnet,
test_callbacks,
False)
while iteration <= iterations:
cbparams['iter'] = iteration
# Check whether to test the net.
if (( # pylint: disable=too-many-boolean-expressions
test_interval > 0 and
iteration % test_interval == 0 and iteration > 0
) or (
iteration == 0 and test_initialization
) or (
test_interval > 0 and iteration + batch_size > iterations
)
):
###############################################################
# testing loop
###############################################################
test_iter = 0
run_pre = True
# Pretest gets called if necessary in `run_prebatch`.
while test_iter < test_iterations:
cbparams['callback_signal'] = 'pre_test_batch'
_parallel.run_prebatch(
self,
test_callbacks,
cbparams,
False,
cbparams['iter'],
run_pre)
# pylint: disable=W0212
testnet._forward(0, len(testnet.layers) - 1)
cbparams['callback_signal'] = 'post_test_batch'
for cb in test_callbacks:
cb(cbparams)
test_iter += batch_size
run_pre = False
cbparams['callback_signal'] = 'post_test'
for cb in test_callbacks:
cb(cbparams)
run_pre = True
if iteration == iterations:
break
###################################################################
# training loop
###################################################################
# `pre_fit` gets called if necessary in `run_prebatch`.
PRETRBATCH_BEGINPOINT = _time.time()
cbparams['callback_signal'] = 'pre_train_batch'
_parallel.run_prebatch(
self,
train_callbacks,
cbparams,
True,
cbparams['iter'] + batch_size,
run_pre)
run_pre = False
PRETRBATCH_DURATION = _time.time() - PRETRBATCH_BEGINPOINT
_LOGGER.debug("Pre-batch preparation time: %03.3fs.",
PRETRBATCH_DURATION)
TRBATCH_BEGINPOINT = _time.time()
self.step(1)
TRBATCH_DURATION = _time.time() - TRBATCH_BEGINPOINT
_LOGGER.debug("Batch processing time: %03.3fs.",
TRBATCH_DURATION)
POSTTRBATCH_BEGINPOINT = _time.time()
cbparams['callback_signal'] = 'post_train_batch'
for cb in train_callbacks:
cb(cbparams)
POSTTRBATCH_DURATION = _time.time() - POSTTRBATCH_BEGINPOINT
_LOGGER.debug("Post-batch processing time: %03.3fs.",
POSTTRBATCH_DURATION)
iteration += batch_size
finally:
for cb in set(train_callbacks + test_callbacks):
if not isinstance(cb, _monitoring.ParallelMonitor):
try:
cb.finalize(cbparams)
except Exception as ex: # pylint: disable=broad-except
_LOGGER.fatal(str(ex))
continue
_parallel.finalize_prebatch(self, cbparams)
if self._parameter_dict.get('stepvalue') is not None:
self._parameter_dict['stepvalue'] = [
val * batch_size for val in self._parameter_dict['stepvalue']]
def step(self, number_of_batches):
"""Run ``number_of_batches`` solver steps."""
tmp_hash = self.Get_parameter_hash(self.Get_parameter_dict())
if self._parameter_hash != tmp_hash:
if self._print_warning: # pragma: no cover
_LOGGER.warn('WARNING: ---------------------------------------------')
_LOGGER.warn('you are re-initializing a new solver which will delete')
_LOGGER.warn('the weight history of the solver.')
_LOGGER.warn('Only use this option if you know what you are doing!')
self._print_warning = False
self._Update_solver()
return self._solver.step(number_of_batches)
def Get_parameter_dict(self):
"""Get the solver describing parameters in a dictionary."""
# work our stack of assertions followed by a weak copy of the dict
for Tmp_assert in self._asserts:
assert Tmp_assert()
return copy.copy(self._parameter_dict)
def Assert_iter_size(self):
"""Enforce the parameter constraints."""
return self._parameter_dict['iter_size'] > 0
def Assert_regularization_types(self):
"""Enforce the parameter constraints."""
return self._parameter_dict['regularization_type'] in ['L1', 'L2']
def Assert_policy(self): # pylint: disable=R0911
"""Enforce the parameter constraints."""
# although redundant this allows to have a quick check
# of what is really required without loading the actuall net which
# might take a bit of time
if self._parameter_dict['lr_policy'] == 'fixed':
return 'base_lr' in self._parameter_dict
if self._parameter_dict['lr_policy'] == 'step':
return 'gamma' in self._parameter_dict
if self._parameter_dict['lr_policy'] == 'exp':
return 'gamma' in self._parameter_dict
if self._parameter_dict['lr_policy'] == 'inv':
return ('gamma' in self._parameter_dict and
'power' in self._parameter_dict)
if self._parameter_dict['lr_policy'] == 'multistep':
return ('stepvalue' in self._parameter_dict and
'base_lr' in self._parameter_dict and
'gamma' in self._parameter_dict)
if self._parameter_dict['lr_policy'] == 'poly':
return 'power' in self._parameter_dict
if self._parameter_dict['lr_policy'] == 'sigmoid':
return 'stepsize' in self._parameter_dict
return False
@classmethod
def Get_parameter_hash(cls, solver_parameter_dict):
"""Get a has of the parameter dict."""
hash_obj = hashlib.md5()
for key in sorted(solver_parameter_dict.keys()):
hash_obj.update(str(key).encode('utf-8'))
hash_obj.update(str(solver_parameter_dict[key]).encode('utf-8'))
return str(hash_obj.hexdigest())
@classmethod
def Get_caffe_solver_instance(cls, solver_parameter_dict, net):
"""Get a caffe solver object."""
# now we actually create a instance of the solver
solver_message = _caffe_pb2.SolverParameter(**solver_parameter_dict)
messagestr = _gprototext.MessageToString(solver_message)
with _NamedTemporaryFile(mode='w+b', suffix='.prototxt') as tmpfile:
tmpfile.write(bytes(messagestr.encode('utf-8')))
tmpfile.flush()
try:
# Newer version of caffe with full solver init support.
return cls.Get_caffe_solver_class(
solver_parameter_dict['solver_type'])._caffe_solver_class(
tmpfile.name, net, _caffe._caffe.NetVec(), True)
except TypeError:
# Fallback for older, patched versions.
return cls.Get_caffe_solver_class(
solver_parameter_dict['solver_type'])._caffe_solver_class(
tmpfile.name, net)
raise Exception('could not initialize solver class')
@classmethod
def Get_solver_class(cls, solver_type):
"""Get the solver class as string."""
return cls._solver_types[solver_type]
@classmethod
def Get_caffe_solver_class(cls, caffe_solver_type):
"""Get the solver class as ``caffe_solver_type``."""
return cls._solver_types[caffe_solver_type]
@classmethod
def Register_solver(cls, solver_class):
"""Register a solver class."""
assert issubclass(solver_class, Solver)
if solver_class._solver_type in cls._solver_types:
raise Exception(
' '.join('solver',
solver_class._solver_type,
'already defined'))
if solver_class._caffe_solver_type in cls._solver_types:
raise Exception(
' '.join('solver',
solver_class._solver_type,
'already defined'))
# we register with both access types
cls._solver_types[solver_class._caffe_solver_type] = solver_class
cls._solver_types[solver_class._solver_type] = solver_class
def _Update_solver(self):
"""Re-initialize the solver."""
# we (re-)initialize the solver
self._solver = self.Get_caffe_solver_instance(
self.Get_parameter_dict(),
self._net)
self._parameter_hash = self.Get_parameter_hash(
self.Get_parameter_dict())
# we only want to see the warning once
self._print_warning = True
def update_parameters(self, **kwargs):
"""Update the solver parameters."""
# adding the default keys if they are not yet set
for argument, default in list(self.Get_optional_arguments().items()):
if argument not in self._parameter_dict and default is not None:
self._parameter_dict[argument] = default
# first add all parameters which are actually required
for arg_key, arg_value in list(kwargs.items()):
if arg_key in self.Get_required_arguments():
self._parameter_dict[arg_key] = arg_value
# make sure that all required arguments are set
tmp_required_arguments = set(self.Get_required_arguments())
intersection = tmp_required_arguments.intersection(set(kwargs.keys()))
if intersection != tmp_required_arguments:
raise Exception(' '.join(
['we are missing required arguments',
str(list(kwargs.keys())),
'vs',
str(self.Get_required_arguments())]))
for arg_key, arg_value in list(kwargs.items()):
# the very special case of passing the net
# this will not be passed as a parameter to the parameter dict
# but we will ensure that the net is always the same
# as the one used for initialization
if arg_key == 'net':
self._Update_net(arg_value)
continue
if arg_key in list(self.Get_optional_arguments().keys()):
self._parameter_dict[arg_key] = arg_value
# we make sure that there is no spelling mistake in the kwargs
total_arguments = set(self.Get_required_arguments())
total_arguments = total_arguments.union(
list(self.Get_optional_arguments().keys()))
for argument in list(kwargs.keys()):
if argument not in total_arguments:
raise Exception(' '.join(
['argument', argument, 'is not supported']))
def _Update_net(self, net):
"""Check that the net remains the same."""
# since the user could potentially provide two different nets to
# the solver, which is not supported, thus we check that the net
# has not changed
if net is None:
return
if self._net is not None:
if id(self._net) != id(net):
raise Exception(' '.join(
['a solver works only with one network',
'the network has to remain the same']))
self._net = net
def _Get_batch_size(self, # pylint: disable=R0201
net,
testnet,
test_interval,
test_iterations,
X_val,
read_input_batch_size_from_blob_name):
"""Get the batch size and the test iterations."""
if len(net.inputs) > 0:
# Otherwise, a DB backend is used.
batch_size = net.blobs[net.inputs[0]].data.shape[0]
if testnet is not None:
assert (testnet.blobs[net.inputs[0]].data.shape[0] ==
batch_size), ("Validation and fit network batch size "
"must agree!")
if (test_interval != 0 and
test_iterations == 0 and
X_val is not None):
if isinstance(X_val, dict):
if len(X_val.values()[0]) % batch_size != 0:
_LOGGER.warn(
"The number of test samples is not a multiple "
"of the batch size. Test performance estimates "
"will | |
from __future__ import division
from datetime import datetime
import collect_ncs_files
import cPickle as pickle
import unittest
import get_mtz
import shutil
import sys
import os
__author__ = 'Youval'
# control if temp folder will be deleted after test
DEBUG_MODE = False
class TestNCSDataCollection(unittest.TestCase):
def setUp(self):
""" Create temporary folder for temp files produced during test """
self.current_dir = os.getcwd()
now = datetime.now().strftime("%I%p_%m_%d_%Y")
test_name = self.__class__.__name__
self.tempdir = os.path.join(self.current_dir,'{}_{}'.format(test_name,now))
if not os.path.isdir(self.tempdir):
os.mkdir(self.tempdir)
os.chdir(self.tempdir)
def test_look_at_file_summary(self):
""" look at __repr__ results """
obj = collect_ncs_files.File_records()
obj.data_completeness = 10
obj.r_free_header = 0.4
r = collect_ncs_files.Refinement_results()
r.r_free_final = 0.1
r.clashscore = 10
obj.refinement_records['init'] = r
print obj
def test_getting_file_info(self):
""" making sure MTRIX records are handled correctly """
pdbs = [test_pdb_1,test_pdb_2,test_pdb_3,test_pdb_4]
fns = ['test_pdb_1','test_pdb_2','test_pdb_3','test_pdb_4']
n_ncs = [2,None,3,None]
for fn,s,n in zip(fns,pdbs,n_ncs):
open(fn+'.pdb','w').write(s)
collect = collect_ncs_files.ncs_paper_data_collection()
a = collect.get_pdb_file_info(fn)
if a:
n_ncs_copies = a.n_ncs_copies
else:
n_ncs_copies = None
self.assertEqual(n_ncs_copies,n)
# clean test pdb files from pdb folder
files_to_delete = [
'test_pdb_1.pdb','test_pdb_2.pdb','test_pdb_3.pdb','test_pdb_4.pdb']
for fn in files_to_delete:
full_path = os.path.join(collect.asu_dir,fn)
if os.path.isfile(full_path):
os.remove(full_path)
def test_reading_processing_pdb_file(self):
""" test processing a pdb file """
collect = collect_ncs_files.ncs_paper_data_collection()
a = collect.get_pdb_file_info('1vcr')
self.assertEqual(a.n_ncs_copies,5)
def test_command_line(self):
""" Test the command line call """
osType = sys.platform
if osType.startswith('win'):
pass
else:
sources = os.environ["workfolder"]
com_path = sources + '/NCS/ncs_paper/get_file_ncs_info.py'
cmd = 'python {} 1vcr > log_test'.format(com_path)
os.system(cmd)
def test_reading_results(self):
""" make sure we can read the results """
sources = os.environ["workfolder"]
path = sources + '/NCS/ncs_paper/ncs_queue_results'
fn = os.path.join(path,'log_1vcr')
if os.path.isfile(fn):
pdb_info = pickle.load(open(fn,'rb'))
print pdb_info
else:
print 'Could not find log_vcr'
def test_records_update(self):
""" test that we reformat the file records object
attribute names correctly """
class Old_File_records(object):
def __init__(self):
self.pdb_id = ''
self.n_ncs_copies = None
self.year = None
self.resolution = None
self.data_completeness = None
self.solvent = None
self.only_master_in_pdb = None
self.ncs_reported_in_pdb = None
# data_to_param_ratio: f_obs.size / atom_number
self.data_to_param_ration = None
# refinement_records contains Refinement_results objects
# for example refinement_records['using cartesian NCS']
self.refinement_records = {}
f = Old_File_records()
f.solvent = 7
f.n_ncs_copies = 10
f.refinement_records['xray'] = [1,2,3]
n = get_mtz.fix_pdb_info(f)
self.assertEqual(n.solvent_fraction,7)
self.assertEqual(n.n_ncs_copies,10)
self.assertEqual(n.refinement_records['xray'],[1,2,3])
def test_get_mtz(self):
""" make sure get_mtz works """
get_mtz.run(['1vcr'])
def test_make_csv_file(self):
""" check csv file creation, with all data """
c = collect_ncs_files.ncs_paper_data_collection()
all_records = c.collect_all_file_records()
table = c.make_csv_file(file_name='temp.csv',out_path=self.tempdir)
table = c.make_csv_file()
print table
def test_collect_refinement_results(self):
""" test collection of refinement results """
c = collect_ncs_files.ncs_paper_data_collection()
c.collect_refinement_results()
print 'Done'
def test_collect_refine_data(self):
""" test collecting data from refinement log """
c = collect_ncs_files.ncs_paper_data_collection()
fn = os.path.join(c.refine_no_ncs_dir,'1a0d')
data = collect_ncs_files.collect_refine_data(fn)
print data
print 'Done'
def test_running_refienemt(self):
""" make sure the commands are called properly """
from run_refinement_test import run
run(['1vcr','-no_ncs'])
def test_table_headers(self):
headers, table_pos_map = collect_ncs_files.table_headers()
a = headers.__repr__().splitlines()
self.assertEqual(len(a),len(table_pos_map))
print 'Done'
def tearDown(self):
""" remove temp files and folder
When DEBUG_MODE = True, the temporary folder will not be deleted """
os.chdir(self.current_dir)
try:
if not DEBUG_MODE:
shutil.rmtree(self.tempdir)
except:
pass
test_pdb_1 = '''\
CRYST1 577.812 448.715 468.790 90.00 90.00 90.00 P 1
SCALE1 0.001731 0.000000 0.000000 0.00000
SCALE2 0.000000 0.002229 0.000000 0.00000
SCALE3 0.000000 0.000000 0.002133 0.00000
ATOM 1 CA LYS A 151 10.766 9.333 12.905 1.00 44.22 C
ATOM 2 CA LYS A 152 10.117 9.159 11.610 1.00 49.42 C
ATOM 3 CA LYS A 153 9.099 8.000 11.562 1.00 46.15 C
ATOM 4 CA LYS A 154 8.000 8.202 11.065 1.00 52.97 C
ATOM 5 CA LYS A 155 11.146 9.065 10.474 1.00 41.68 C
ATOM 6 CA LYS A 156 10.547 9.007 9.084 1.00 55.55 C
ATOM 7 CA LYS A 157 11.545 9.413 8.000 1.00 72.27 C
ATOM 8 CA LYS A 158 12.277 10.718 8.343 1.00 75.78 C
ATOM 9 CA LYS A 159 11.349 11.791 8.809 1.00 75.88 C
TER
ATOM 222 CA LEU X 40 94.618 -5.253 91.582 1.00 87.10 C
ATOM 223 CA ARG X 41 62.395 51.344 80.786 1.00107.25 C
ATOM 224 CA ARG X 42 62.395 41.344 80.786 1.00107.25 C
TER
ATOM 1 CA THR D 1 8.111 11.080 10.645 1.00 20.00 C
ATOM 2 CA THR D 2 8.000 9.722 10.125 1.00 20.00 C
ATOM 3 CA THR D 3 8.075 8.694 11.249 1.00 20.00 C
ATOM 4 CA THR D 4 8.890 8.818 12.163 1.00 20.00 C
ATOM 5 CA THR D 5 9.101 9.421 9.092 1.00 20.00 C
ATOM 6 CA THR D 6 9.001 10.343 8.000 1.00 20.00 C
ATOM 7 CA THR D 7 8.964 8.000 8.565 1.00 20.00 C
TER
ATOM 1 CA LYS B 151 6.855 8.667 15.730 1.00 44.22 C
ATOM 2 CA LYS B 152 5.891 8.459 14.655 1.00 49.42 C
ATOM 3 CA LYS B 153 6.103 7.155 13.858 1.00 46.15 C
ATOM 4 CA LYS B 154 5.138 6.438 13.633 1.00 52.97 C
ATOM 5 CA LYS B 155 5.801 9.685 13.736 1.00 41.68 C
ATOM 6 CA LYS B 156 4.731 9.594 12.667 1.00 55.55 C
ATOM 7 CA LYS B 157 4.334 10.965 12.119 1.00 72.27 C
ATOM 8 CA LYS B 158 4.057 11.980 13.238 1.00 75.78 C
ATOM 9 CA LYS B 159 3.177 11.427 14.310 1.00 75.88 C
END
'''
test_pdb_2 = '''\
CRYST1 577.812 448.715 468.790 90.00 90.00 90.00 P 1
SCALE1 0.001731 0.000000 0.000000 0.00000
SCALE2 0.000000 0.002229 0.000000 0.00000
SCALE3 0.000000 0.000000 0.002133 0.00000
ATOM 1 CA LYS A 151 10.766 9.333 12.905 1.00 44.22 C
ATOM 2 CA LYS A 152 10.117 9.159 11.610 1.00 49.42 C
ATOM 3 CA LYS A 153 9.099 8.000 11.562 1.00 46.15 C
ATOM 4 CA LYS A 154 8.000 8.202 11.065 1.00 52.97 C
ATOM 5 CA LYS A 155 11.146 9.065 10.474 1.00 41.68 C
ATOM 6 CA LYS A 156 10.547 9.007 9.084 1.00 55.55 C
ATOM 7 CA LYS A 157 11.545 9.413 8.000 1.00 72.27 C
ATOM 8 CA LYS A 158 12.277 10.718 8.343 1.00 75.78 C
ATOM 9 CA LYS A 159 11.349 11.791 8.809 1.00 75.88 C
TER
ATOM 222 CA LEU X 40 94.618 -5.253 91.582 1.00 87.10 C
ATOM 223 CA ARG X 41 62.395 51.344 80.786 1.00107.25 C
ATOM 224 CA ARG X 42 62.395 41.344 80.786 1.00107.25 C
END
'''
test_pdb_3 = """\
CRYST1 577.812 448.715 468.790 90.00 90.00 90.00 P 1
MTRIX1 1 1.000000 0.000000 0.000000 0.00000 1
MTRIX2 1 0.000000 1.000000 0.000000 0.00000 1
MTRIX3 1 0.000000 0.000000 1.000000 0.00000 1
MTRIX1 2 0.496590 -0.643597 0.582393 0.00000
MTRIX2 2 0.867925 0.376088 -0.324443 0.00000
MTRIX3 2 -0.010221 0.666588 0.745356 0.00000
MTRIX1 3 -0.317946 -0.173437 0.932111 0.00000
MTRIX2 3 0.760735 -0.633422 0.141629 0.00000
MTRIX3 3 0.565855 0.754120 0.333333 0.00000
ATOM 757 N ASP A 247 16.068 -20.882 -28.984 1.00 35.93 N
ATOM 758 CA ASP A 247 15.914 -22.265 -28.600 1.00 47.90 C
ATOM 759 C ASP A 247 17.130 -23.042 -29.116 1.00 42.32 C
ATOM 760 O ASP A 247 17.461 -22.986 -30.301 1.00 47.25 O
ATOM 761 CB ASP A 247 14.621 -22.814 -29.198 1.00 47.22 C
ATOM 762 CG ASP A 247 14.068 -23.974 -28.412 1.00 61.15 C
ATOM 763 OD1 ASP A 247 14.359 -24.061 -27.196 1.00 63.66 O
ATOM 764 OD2 ASP A 247 13.341 -24.798 -29.012 1.00 77.01 O
ATOM 765 N VAL A 248 17.808 -23.746 -28.218 1.00 44.08 N
ATOM 766 CA VAL A 248 19.008 -24.503 -28.584 1.00 46.18 C
ATOM 767 C VAL A 248 18.668 -25.988 -28.583 1.00 53.97 C
ATOM 768 O VAL A 248 18.049 -26.478 -27.638 1.00 51.48 O
ATOM 769 CB VAL A 248 20.185 -24.226 -27.608 1.00 47.55 C
ATOM 770 CG1 VAL A 248 21.414 -25.015 -28.012 1.00 41.43 C
ATOM 771 CG2 VAL A 248 20.513 -22.743 -27.567 1.00 41.64 C
ATOM 772 N VAL A 249 19.057 -26.697 -29.641 1.00 54.29 N
ATOM 773 CA VAL A 249 18.662 -28.097 -29.810 1.00 60.17 C
ATOM 774 C VAL A 249 19.859 -29.041 -29.982 1.00 57.98 C
ATOM 775 O VAL A 249 20.731 -28.827 -30.828 1.00 58.31 O
ATOM 776 CB VAL A 249 17.671 -28.280 -30.997 1.00 60.85 C
ATOM 777 CG1 VAL A 249 16.500 -27.300 -30.884 1.00 48.00 C
ATOM 778 CG2 VAL A 249 18.386 -28.110 -32.337 1.00 59.99 C
TER
ATOM 780 N LYS D 151 4.045 -6.858 -32.823 1.00 45.22 N
ATOM 781 CA LYS D 151 4.686 -6.715 -34.123 1.00 50.40 C
ATOM 782 C LYS D 151 5.707 -5.554 -34.172 1.00 47.13 C
ATOM 783 O LYS D 151 6.820 -5.764 -34.625 1.00 52.91 O
ATOM 784 CB LYS D 151 3.657 -6.646 -35.268 | |
self.domain_name = kwargs.get('domain_name', None)
self.organization_unit = kwargs.get('organization_unit', None)
self.domain_username = kwargs.get('domain_username', None)
self.domain_password = kwargs.get('domain_password', None)
class NetworkConnectionUpdateProperties(msrest.serialization.Model):
"""Properties of network connection. These properties can be updated after the resource has been created.
:param subnet_id: The subnet to attach Virtual Machines to.
:type subnet_id: str
:param domain_name: Active Directory domain name.
:type domain_name: str
:param organization_unit: Active Directory domain Organization Unit (OU).
:type organization_unit: str
:param domain_username: The username of an Active Directory account (user or service account)
that has permissions to create computer objects in Active Directory. Required format:
<EMAIL>.
:type domain_username: str
:param domain_password: The password for the account used to join domain.
:type domain_password: str
"""
_attribute_map = {
'subnet_id': {'key': 'subnetId', 'type': 'str'},
'domain_name': {'key': 'domainName', 'type': 'str'},
'organization_unit': {'key': 'organizationUnit', 'type': 'str'},
'domain_username': {'key': 'domainUsername', 'type': 'str'},
'domain_password': {'key': 'domainPassword', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkConnectionUpdateProperties, self).__init__(**kwargs)
self.subnet_id = kwargs.get('subnet_id', None)
self.domain_name = kwargs.get('domain_name', None)
self.organization_unit = kwargs.get('organization_unit', None)
self.domain_username = kwargs.get('domain_username', None)
self.domain_password = kwargs.get('domain_password', None)
class NetworkProperties(NetworkConnectionUpdateProperties):
"""Network properties.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param subnet_id: The subnet to attach Virtual Machines to.
:type subnet_id: str
:param domain_name: Active Directory domain name.
:type domain_name: str
:param organization_unit: Active Directory domain Organization Unit (OU).
:type organization_unit: str
:param domain_username: The username of an Active Directory account (user or service account)
that has permissions to create computer objects in Active Directory. Required format:
<EMAIL>.
:type domain_username: str
:param domain_password: The password for the account used to join domain.
:type domain_password: str
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
:ivar health_check_status: Overall health status of the network connection. Health checks are
run on creation, update, and periodically to validate the network connection. Possible values
include: "Pending", "Running", "Passed", "Failed", "Warning", "Unknown".
:vartype health_check_status: str or ~dev_center.models.HealthCheckStatus
:param networking_resource_group_name: The name for resource group where NICs will be placed.
:type networking_resource_group_name: str
:param domain_join_type: Required. AAD Join type. Possible values include: "HybridAzureADJoin",
"AzureADJoin".
:type domain_join_type: str or ~dev_center.models.DomainJoinType
"""
_validation = {
'provisioning_state': {'readonly': True},
'health_check_status': {'readonly': True},
'domain_join_type': {'required': True},
}
_attribute_map = {
'subnet_id': {'key': 'subnetId', 'type': 'str'},
'domain_name': {'key': 'domainName', 'type': 'str'},
'organization_unit': {'key': 'organizationUnit', 'type': 'str'},
'domain_username': {'key': 'domainUsername', 'type': 'str'},
'domain_password': {'key': 'domainPassword', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'health_check_status': {'key': 'healthCheckStatus', 'type': 'str'},
'networking_resource_group_name': {'key': 'networkingResourceGroupName', 'type': 'str'},
'domain_join_type': {'key': 'domainJoinType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkProperties, self).__init__(**kwargs)
self.provisioning_state = None
self.health_check_status = None
self.networking_resource_group_name = kwargs.get('networking_resource_group_name', None)
self.domain_join_type = kwargs['domain_join_type']
class Operation(msrest.serialization.Model):
"""Details of a REST API operation, returned from the Resource Provider Operations API.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples:
"Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action".
:vartype name: str
:ivar is_data_action: Whether the operation applies to data-plane. This is "true" for data-
plane operations and "false" for ARM/control-plane operations.
:vartype is_data_action: bool
:param display: Localized display information for this particular operation.
:type display: ~dev_center.models.OperationDisplay
:ivar origin: The intended executor of the operation; as in Resource Based Access Control
(RBAC) and audit logs UX. Default value is "user,system". Possible values include: "user",
"system", "user,system".
:vartype origin: str or ~dev_center.models.Origin
:ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for
internal only APIs. Possible values include: "Internal".
:vartype action_type: str or ~dev_center.models.ActionType
"""
_validation = {
'name': {'readonly': True},
'is_data_action': {'readonly': True},
'origin': {'readonly': True},
'action_type': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'is_data_action': {'key': 'isDataAction', 'type': 'bool'},
'display': {'key': 'display', 'type': 'OperationDisplay'},
'origin': {'key': 'origin', 'type': 'str'},
'action_type': {'key': 'actionType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Operation, self).__init__(**kwargs)
self.name = None
self.is_data_action = None
self.display = kwargs.get('display', None)
self.origin = None
self.action_type = None
class OperationDisplay(msrest.serialization.Model):
"""Localized display information for this particular operation.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft
Monitoring Insights" or "Microsoft Compute".
:vartype provider: str
:ivar resource: The localized friendly name of the resource type related to this operation.
E.g. "Virtual Machines" or "Job Schedule Collections".
:vartype resource: str
:ivar operation: The concise, localized friendly name for the operation; suitable for
dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine".
:vartype operation: str
:ivar description: The short, localized friendly description of the operation; suitable for
tool tips and detailed views.
:vartype description: str
"""
_validation = {
'provider': {'readonly': True},
'resource': {'readonly': True},
'operation': {'readonly': True},
'description': {'readonly': True},
}
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationDisplay, self).__init__(**kwargs)
self.provider = None
self.resource = None
self.operation = None
self.description = None
class OperationListResult(msrest.serialization.Model):
"""A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: List of operations supported by the resource provider.
:vartype value: list[~dev_center.models.Operation]
:ivar next_link: URL to get the next set of operation list results (if there are any).
:vartype next_link: str
"""
_validation = {
'value': {'readonly': True},
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[Operation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationListResult, self).__init__(**kwargs)
self.value = None
self.next_link = None
class OperationStatus(msrest.serialization.Model):
"""The current status of an async operation.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified ID for the operation status.
:vartype id: str
:ivar name: The operation id name.
:vartype name: str
:ivar status: Provisioning state of the resource.
:vartype status: str
:ivar start_time: The start time of the operation.
:vartype start_time: ~datetime.datetime
:ivar end_time: The end time of the operation.
:vartype end_time: ~datetime.datetime
:ivar percent_complete: Percent of the operation that is complete.
:vartype percent_complete: float
:ivar properties: Custom operation properties, populated only for a successful operation.
:vartype properties: object
:param error: Operation Error message.
:type error: ~dev_center.models.OperationStatusError
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'status': {'readonly': True},
'start_time': {'readonly': True},
'end_time': {'readonly': True},
'percent_complete': {'readonly': True, 'maximum': 100, 'minimum': 0},
'properties': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
'percent_complete': {'key': 'percentComplete', 'type': 'float'},
'properties': {'key': 'properties', 'type': 'object'},
'error': {'key': 'error', 'type': 'OperationStatusError'},
}
def __init__(
self,
**kwargs
):
super(OperationStatus, self).__init__(**kwargs)
self.id = None
self.name = None
self.status = None
self.start_time = None
self.end_time = None
self.percent_complete = None
self.properties = None
self.error = kwargs.get('error', None)
class OperationStatusError(msrest.serialization.Model):
"""Operation Error message.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: The error code.
:vartype code: str
:ivar message: The error message.
:vartype message: str
"""
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationStatusError, self).__init__(**kwargs)
self.code = None
self.message = None
class Pool(TrackedResource):
"""A pool of Virtual Machines.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. | |
item, and provide the user with feedback if it's not. The possible cases
# are captured by this next enumeration, and the following helper function
# assesses the current status and returns additional info (as multiple values).
class Status(Enum):
NOT_READY = auto() # Item.ready is False
NO_COPIES_LEFT = auto() # No copies left to loan
LOANED_BY_USER = auto() # Already loaned by user
TOO_SOON = auto() # Too soon after user's last loan of this
USER_HAS_OTHER = auto() # User has another active loan
AVAILABLE = auto() # Available to this user
UNKNOWN_ITEM = auto() # Barcode is not in the DIBS database.
def loan_availability(user, barcode):
'''Return multiple values: (item, status, explanation, when_available).'''
item = Item.get_or_none(Item.barcode == barcode)
if not item:
log(f'unknown barcode {barcode}')
status = Status.UNKNOWN_ITEM
explanation = 'This item is not known to DIBS.'
return None, status, explanation, None
if not item.ready:
log(f'{barcode} is not ready for loans')
status = Status.NOT_READY
explanation = 'This item is not available for borrowing at this time.'
return item, status, explanation, None
# Start by checking if the user has any active or recent loans.
explanation = ''
when_available = None
loan = Loan.get_or_none(Loan.user == user, Loan.item == item)
who = anon(user)
if loan:
if loan.state == 'active':
log(f'{who} already has {barcode} on loan')
status = Status.LOANED_BY_USER
explanation = 'This item is currently on digital loan to you.'
else:
log(f'{who} had a loan on {barcode} too recently')
status = Status.TOO_SOON
explanation = ('Your loan period has ended and it is too soon '
'after the last time you borrowed it.')
when_available = loan.reloan_time
else:
loan = Loan.get_or_none(Loan.user == user, Loan.state == 'active')
if loan:
other = loan.item
log(f'{who} has a loan on {other.barcode} that ends at {loan.end_time}')
status = Status.USER_HAS_OTHER
author = shorten(other.author, width = 50, placeholder = ' …')
explanation = ('You have another item currently on loan'
+ f' ("{other.title}" by {author}).')
when_available = loan.end_time
else:
# The user may be allowed to loan this, but are there any copies left?
loans = list(Loan.select().where(Loan.item == item, Loan.state == 'active'))
if len(loans) == item.num_copies:
log(f'all copies of {barcode} are currently loaned')
status = Status.NO_COPIES_LEFT
explanation = 'All available copies are currently on loan.'
when_available = min(loan.end_time for loan in loans)
else:
log(f'{who} is allowed to borrow {barcode}')
status = Status.AVAILABLE
return item, status, explanation, when_available
@dibs.get('/')
@dibs.get('/<name:re:(info|about|thankyou)>')
def general_page(name = '/'):
'''Display the welcome page.'''
if name and name in ['info', 'about', 'thankyou']:
return page(f'{name}')
else:
return page('info')
# Next one is used by the item page to update itself w/o reloading whole page.
@dibs.get('/item-status/<barcode:int>', apply = AddPersonArgument())
def item_status(barcode, person):
'''Returns an item summary status as a JSON string'''
item, status, explanation, when_available = loan_availability(person.uname, barcode)
return json.dumps({'available' : (status == Status.AVAILABLE),
'loaned_by_user': (status == Status.LOANED_BY_USER),
'explanation' : explanation,
'when_available': human_datetime(when_available)})
@dibs.get('/item/<barcode:int>', apply = AddPersonArgument())
def show_item_info(barcode, person):
'''Display information about the given item.'''
item, status, explanation, when_available = loan_availability(person.uname, barcode)
# Users can put ?viewer=0 to avoid being sent to the viewer if they have
# the item on loan. This is useful mainly for developers and staff.
show_viewer = str2bool(request.query.get('viewer', '1'))
if status == Status.LOANED_BY_USER and show_viewer:
log(f'redirecting {user(person)} to uv for {barcode}')
redirect(f'{dibs.base_url}/view/{barcode}')
return
return page('item', browser_no_cache = True, item = item,
available = (status == Status.AVAILABLE),
when_available = human_datetime(when_available),
explanation = explanation, thumbnails_dir = _THUMBNAILS_DIR)
@dibs.post('/loan', apply = AddPersonArgument())
def loan_item(person):
'''Handle http post request to loan out an item, from the item info page.'''
barcode = request.POST.barcode.strip()
# Checking if the item is available requires steps, and we have to be sure
# that two users don't do them concurrently, or else we might make 2 loans.
log(f'locking db')
with database.atomic('immediate'):
item, status, explanation, when_available = loan_availability(person.uname, barcode)
if status == Status.NOT_READY:
# Normally we shouldn't see a loan request through this form if the
# item is not ready, so either staff changed the status after the
# item was made available or someone got here accidentally.
log(f'redirecting {user(person)} back to item page for {barcode}')
redirect(f'{dibs.base_url}/item/{barcode}')
return
if status == Status.LOANED_BY_USER:
# Shouldn't be able to reach this point b/c the item page
# shouldn't make a loan available for this user & item combo.
# But if something weird happens, we might.
log(f'redirecting {user(person)} to {dibs.base_url}/view/{barcode}')
redirect(f'{dibs.base_url}/view/{barcode}')
return
if status == Status.USER_HAS_OTHER:
return page('error', summary = 'only one loan at a time',
message = ('Our policy currently prevents users from '
'borrowing more than one item at a time.'))
if status == Status.TOO_SOON:
loan = Loan.get_or_none(Loan.user == person.uname, Loan.item == item)
return page('error', summary = 'too soon',
message = ('We ask that you wait at least '
f'{naturaldelta(_RELOAN_WAIT_TIME)} before '
'requesting the same item again. Please try '
f'after {human_datetime(when_available)}'))
if status == Status.NO_COPIES_LEFT:
# The loan button shouldn't have been clickable in this case, but
# someone else might have gotten the loan between the last status
# check and the user clicking it.
log(f'redirecting {user(person)} to {dibs.base_url}/view/{barcode}')
redirect(f'{dibs.base_url}/view/{barcode}')
return
# OK, the user is allowed to loan out this item. Round up the time to
# the next minute to avoid loan times ending in the middle of a minute.
time = delta(minutes = 1) if debug_mode() else delta(hours = item.duration)
start = time_now()
end = round_minutes(start + time, 'up')
reloan = end + _RELOAN_WAIT_TIME
log(f'creating new loan for {barcode} for {user(person)}')
Loan.create(item = item, state = 'active', user = person.uname,
start_time = start, end_time = end, reloan_time = reloan)
send_email(person.uname, item, start, end, dibs.base_url)
redirect(f'{dibs.base_url}/view/{barcode}')
@dibs.post('/return/<barcode:int>', apply = AddPersonArgument())
def end_loan(barcode, person):
'''Handle http post request to return the given item early.'''
# Sometimes, for unknown reasons, the end-loan button sends a post without
# the barcode data. The following are compensatory mechanisms.
post_barcode = request.POST.get('barcode')
if not post_barcode:
log(f'missing post barcode in /return by user {user(person)}')
if barcode:
log(f'using barcode {barcode} from post address instead')
else:
log(f'/return invoked by user {user(person)} but we have no barcode')
return
else:
barcode = post_barcode
item = Item.get(Item.barcode == barcode)
loan = Loan.get_or_none(Loan.item == item, Loan.user == person.uname)
if loan and loan.state == 'active':
# Normal case: user has loaned a copy of item. Update to 'recent'.
log(f'locking db to change {barcode} loan state by user {user(person)}')
with database.atomic('immediate'):
now = time_now()
loan.state = 'recent'
loan.end_time = now
loan.reloan_time = round_minutes(now + _RELOAN_WAIT_TIME, 'down')
loan.save(only = [Loan.state, Loan.end_time, Loan.reloan_time])
if not staff_user(loan.user) or debug_mode():
# Don't count staff users in loan stats except in debug mode.
History.create(type = 'loan', what = loan.item.barcode,
start_time = loan.start_time,
end_time = loan.end_time)
redirect(f'{dibs.base_url}/thankyou')
else:
log(f'{user(person)} does not have {barcode} loaned out')
redirect(f'{dibs.base_url}/item/{barcode}')
@dibs.get('/view/<barcode:int>', apply = AddPersonArgument())
def send_item_to_viewer(barcode, person):
'''Redirect to the viewer.'''
item = Item.get(Item.barcode == barcode)
loan = Loan.get_or_none(Loan.item == item, Loan.user == person.uname)
if loan and loan.state == 'active':
log(f'redirecting to viewer for {barcode} for {user(person)}')
wait_time = _RELOAN_WAIT_TIME
return page('uv', browser_no_cache = True, barcode = barcode,
title = shorten(item.title, width = 100, placeholder = ' …'),
end_time = human_datetime(loan.end_time, '%I:%M %p (%b %d, %Z)'),
js_end_time = human_datetime(loan.end_time, '%m/%d/%Y %H:%M:%S'),
wait_time = naturaldelta(wait_time))
else:
log(f'{user(person)} does not have {barcode} loaned out')
redirect(f'{dibs.base_url}/item/{barcode}')
@dibs.get('/manifests/<barcode:int>', apply = AddPersonArgument())
def return_iiif_manifest(barcode, person):
'''Return the manifest file for a given item.'''
item = Item.get(Item.barcode == barcode)
loan = Loan.get_or_none(Loan.item == item, Loan.user == person.uname)
if loan and loan.state == 'active':
manifest_file = join(_MANIFEST_DIR, f'{barcode}-manifest.json')
if not exists(manifest_file):
log(f'{manifest_file} does not exist')
return
record_request(barcode)
with open(manifest_file, 'r', encoding = 'utf-8') as mf:
adjusted_content = urls_rerouted(mf.read(), barcode)
encoded_content = adjusted_content.encode()
data = BytesIO(encoded_content)
size = len(encoded_content)
log(f'returning manifest for {barcode} for {user(person)}')
return send_file(data, ctype = 'application/json', size = size)
else:
log(f'{user(person)} does not have {barcode} loaned out')
redirect(f'{dibs.base_url}/notallowed')
return
@dibs.get('/iiif/<barcode>/<rest:re:.+>', apply = AddPersonArgument())
def return_iiif_content(barcode, rest, person):
'''Return the manifest file for a given item.'''
item = Item.get(Item.barcode == barcode)
loan = Loan.get_or_none(Loan.item == item, Loan.user == person.uname)
if loan and loan.state == 'active':
record_request(barcode)
url = _IIIF_BASE_URL + '/' + | |
from_dict(cls, _dict: Dict) -> 'Rule':
"""Initialize a Rule object from a json dictionary."""
args = {}
if 'account_id' in _dict:
args['account_id'] = _dict.get('account_id')
if 'name' in _dict:
args['name'] = _dict.get('name')
else:
raise ValueError('Required property \'name\' not present in Rule JSON')
if 'description' in _dict:
args['description'] = _dict.get('description')
else:
raise ValueError('Required property \'description\' not present in Rule JSON')
if 'rule_type' in _dict:
args['rule_type'] = _dict.get('rule_type')
if 'target' in _dict:
args['target'] = TargetResource.from_dict(_dict.get('target'))
else:
raise ValueError('Required property \'target\' not present in Rule JSON')
if 'required_config' in _dict:
args['required_config'] = _dict.get('required_config')
else:
raise ValueError('Required property \'required_config\' not present in Rule JSON')
if 'enforcement_actions' in _dict:
args['enforcement_actions'] = [EnforcementAction.from_dict(x) for x in _dict.get('enforcement_actions')]
else:
raise ValueError('Required property \'enforcement_actions\' not present in Rule JSON')
if 'labels' in _dict:
args['labels'] = _dict.get('labels')
if 'rule_id' in _dict:
args['rule_id'] = _dict.get('rule_id')
if 'creation_date' in _dict:
args['creation_date'] = string_to_datetime(_dict.get('creation_date'))
if 'created_by' in _dict:
args['created_by'] = _dict.get('created_by')
if 'modification_date' in _dict:
args['modification_date'] = string_to_datetime(_dict.get('modification_date'))
if 'modified_by' in _dict:
args['modified_by'] = _dict.get('modified_by')
if 'number_of_attachments' in _dict:
args['number_of_attachments'] = _dict.get('number_of_attachments')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a Rule object from a json dictionary."""
return cls.from_dict(_dict)
def to_dict(self) -> Dict:
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'account_id') and self.account_id is not None:
_dict['account_id'] = self.account_id
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'description') and self.description is not None:
_dict['description'] = self.description
if hasattr(self, 'rule_type') and self.rule_type is not None:
_dict['rule_type'] = self.rule_type
if hasattr(self, 'target') and self.target is not None:
_dict['target'] = self.target.to_dict()
if hasattr(self, 'required_config') and self.required_config is not None:
if isinstance(self.required_config, dict):
_dict['required_config'] = self.required_config
else:
_dict['required_config'] = self.required_config.to_dict()
if hasattr(self, 'enforcement_actions') and self.enforcement_actions is not None:
_dict['enforcement_actions'] = [x.to_dict() for x in self.enforcement_actions]
if hasattr(self, 'labels') and self.labels is not None:
_dict['labels'] = self.labels
if hasattr(self, 'rule_id') and getattr(self, 'rule_id') is not None:
_dict['rule_id'] = getattr(self, 'rule_id')
if hasattr(self, 'creation_date') and getattr(self, 'creation_date') is not None:
_dict['creation_date'] = datetime_to_string(getattr(self, 'creation_date'))
if hasattr(self, 'created_by') and getattr(self, 'created_by') is not None:
_dict['created_by'] = getattr(self, 'created_by')
if hasattr(self, 'modification_date') and getattr(self, 'modification_date') is not None:
_dict['modification_date'] = datetime_to_string(getattr(self, 'modification_date'))
if hasattr(self, 'modified_by') and getattr(self, 'modified_by') is not None:
_dict['modified_by'] = getattr(self, 'modified_by')
if hasattr(self, 'number_of_attachments') and getattr(self, 'number_of_attachments') is not None:
_dict['number_of_attachments'] = getattr(self, 'number_of_attachments')
return _dict
def _to_dict(self):
"""Return a json dictionary representing this model."""
return self.to_dict()
def __str__(self) -> str:
"""Return a `str` version of this Rule object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'Rule') -> bool:
"""Return `true` when self and other are equal, false otherwise."""
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other: 'Rule') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class RuleTypeEnum(str, Enum):
"""
The type of rule. Rules that you create are `user_defined`.
"""
USER_DEFINED = 'user_defined'
class RuleCondition():
"""
RuleCondition.
"""
def __init__(self) -> None:
"""
Initialize a RuleCondition object.
"""
msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format(
", ".join(['RuleConditionSingleProperty', 'RuleConditionOrLvl2', 'RuleConditionAndLvl2']))
raise Exception(msg)
class RuleList():
"""
A list of rules.
:attr int offset: The requested offset for the returned items.
:attr int limit: The requested limit for the returned items.
:attr int total_count: The total number of available items.
:attr Link first: The first page of available items.
:attr Link last: The last page of available items.
:attr List[Rule] rules: An array of rules.
"""
def __init__(self,
offset: int,
limit: int,
total_count: int,
first: 'Link',
last: 'Link',
rules: List['Rule']) -> None:
"""
Initialize a RuleList object.
:param int offset: The requested offset for the returned items.
:param int limit: The requested limit for the returned items.
:param int total_count: The total number of available items.
:param Link first: The first page of available items.
:param Link last: The last page of available items.
:param List[Rule] rules: An array of rules.
"""
self.offset = offset
self.limit = limit
self.total_count = total_count
self.first = first
self.last = last
self.rules = rules
@classmethod
def from_dict(cls, _dict: Dict) -> 'RuleList':
"""Initialize a RuleList object from a json dictionary."""
args = {}
if 'offset' in _dict:
args['offset'] = _dict.get('offset')
else:
raise ValueError('Required property \'offset\' not present in RuleList JSON')
if 'limit' in _dict:
args['limit'] = _dict.get('limit')
else:
raise ValueError('Required property \'limit\' not present in RuleList JSON')
if 'total_count' in _dict:
args['total_count'] = _dict.get('total_count')
else:
raise ValueError('Required property \'total_count\' not present in RuleList JSON')
if 'first' in _dict:
args['first'] = Link.from_dict(_dict.get('first'))
else:
raise ValueError('Required property \'first\' not present in RuleList JSON')
if 'last' in _dict:
args['last'] = Link.from_dict(_dict.get('last'))
else:
raise ValueError('Required property \'last\' not present in RuleList JSON')
if 'rules' in _dict:
args['rules'] = [Rule.from_dict(x) for x in _dict.get('rules')]
else:
raise ValueError('Required property \'rules\' not present in RuleList JSON')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a RuleList object from a json dictionary."""
return cls.from_dict(_dict)
def to_dict(self) -> Dict:
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'offset') and self.offset is not None:
_dict['offset'] = self.offset
if hasattr(self, 'limit') and self.limit is not None:
_dict['limit'] = self.limit
if hasattr(self, 'total_count') and self.total_count is not None:
_dict['total_count'] = self.total_count
if hasattr(self, 'first') and self.first is not None:
_dict['first'] = self.first.to_dict()
if hasattr(self, 'last') and self.last is not None:
_dict['last'] = self.last.to_dict()
if hasattr(self, 'rules') and self.rules is not None:
_dict['rules'] = [x.to_dict() for x in self.rules]
return _dict
def _to_dict(self):
"""Return a json dictionary representing this model."""
return self.to_dict()
def __str__(self) -> str:
"""Return a `str` version of this RuleList object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'RuleList') -> bool:
"""Return `true` when self and other are equal, false otherwise."""
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other: 'RuleList') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class RuleRequest():
"""
User-settable properties associated with a rule to be created or updated.
:attr str account_id: (optional) Your IBM Cloud account ID.
:attr str name: A human-readable alias to assign to your rule.
:attr str description: An extended description of your rule.
:attr str rule_type: (optional) The type of rule. Rules that you create are
`user_defined`.
:attr TargetResource target: The properties that describe the resource that you
want to target
with the rule.
:attr RuleRequiredConfig required_config:
:attr List[EnforcementAction] enforcement_actions: The actions that the service
must run on your behalf when a request to create or modify the target resource
does not comply with your conditions.
:attr List[str] labels: (optional) Labels that you can use to group and search
for similar rules, such as those that help you to meet a specific organization
guideline.
"""
def __init__(self,
name: str,
description: str,
target: 'TargetResource',
required_config: 'RuleRequiredConfig',
enforcement_actions: List['EnforcementAction'],
*,
account_id: str = None,
rule_type: str = None,
labels: List[str] = None) -> None:
"""
Initialize a RuleRequest object.
:param str name: A human-readable alias to assign to your rule.
:param str description: An extended description of your rule.
:param TargetResource target: The properties that describe the resource
that you want to target
with the rule.
:param RuleRequiredConfig required_config:
:param List[EnforcementAction] enforcement_actions: The actions that the
service must run on your behalf when a request to create or modify the
target resource does not comply with your conditions.
:param str account_id: (optional) Your IBM Cloud account ID.
:param str rule_type: (optional) The type of rule. Rules that you create
are `user_defined`.
:param List[str] labels: (optional) Labels that you can use to group and
search for similar rules, such as those that help you to meet a specific
organization guideline.
"""
self.account_id = account_id
self.name = name
self.description = description
self.rule_type = rule_type
self.target = target
self.required_config = required_config
self.enforcement_actions = enforcement_actions
self.labels = labels
@classmethod
def from_dict(cls, _dict: Dict) -> 'RuleRequest':
"""Initialize a RuleRequest object | |
mask[2, 2] = True
mask_resized = mask.resized_mask_from(new_shape=(3, 3))
mask_resized_manual = np.full(fill_value=False, shape=(3, 3))
mask_resized_manual[1, 1] = True
assert (mask_resized == mask_resized_manual).all()
def test__rescaled_mask_from__compare_to_manual_mask(self):
mask = aa.Mask2D.unmasked(shape_native=(5, 5), pixel_scales=1.0)
mask[2, 2] = True
mask_rescaled = mask.rescaled_mask_from(rescale_factor=2.0)
mask_rescaled_manual = np.full(fill_value=False, shape=(3, 3))
mask_rescaled_manual[1, 1] = True
mask_rescaled_manual = aa.util.mask_2d.rescaled_mask_2d_from(
mask_2d=mask, rescale_factor=2.0
)
assert (mask_rescaled == mask_rescaled_manual).all()
def test__edged_buffed_mask__compare_to_manual_mask(self):
mask = aa.Mask2D.unmasked(shape_native=(5, 5), pixel_scales=1.0)
mask[2, 2] = True
edge_buffed_mask_manual = aa.util.mask_2d.buffed_mask_2d_from(
mask_2d=mask
).astype("bool")
assert (mask.edge_buffed_mask == edge_buffed_mask_manual).all()
class TestRegions:
def test__sub_native_index_for_sub_slim_index__compare_to_array_util(self):
mask = aa.Mask2D.manual(
mask=[[True, True, True], [True, False, False], [True, True, False]],
pixel_scales=1.0,
)
sub_native_index_for_sub_slim_index_2d = aa.util.mask_2d.native_index_for_slim_index_2d_from(
mask_2d=mask, sub_size=1
)
assert mask.native_index_for_slim_index == pytest.approx(
sub_native_index_for_sub_slim_index_2d, 1e-4
)
def test__unmasked_mask(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
assert (mask.unmasked_mask == np.full(fill_value=False, shape=(9, 9))).all()
def test__blurring_mask_for_psf_shape__compare_to_array_util(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True],
[True, False, True, True, True, False, True, True],
[True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True],
[True, False, True, True, True, False, True, True],
[True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
blurring_mask_via_util = aa.util.mask_2d.blurring_mask_2d_from(
mask_2d=mask, kernel_shape_native=(3, 3)
)
blurring_mask = mask.blurring_mask_from(kernel_shape_native=(3, 3))
assert (blurring_mask == blurring_mask_via_util).all()
def test__edge_image_pixels__compare_to_array_util(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
edge_pixels_util = aa.util.mask_2d.edge_1d_indexes_from(mask_2d=mask)
assert mask.edge_1d_indexes == pytest.approx(edge_pixels_util, 1e-4)
assert mask.edge_2d_indexes[0] == pytest.approx(np.array([1, 1]), 1e-4)
assert mask.edge_2d_indexes[10] == pytest.approx(np.array([3, 3]), 1e-4)
assert mask.edge_1d_indexes.shape[0] == mask.edge_2d_indexes.shape[0]
def test__edge_mask(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
assert (
mask.edge_mask
== np.array(
[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
]
)
).all()
def test__border_image_pixels__compare_to_array_util(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
border_pixels_util = aa.util.mask_2d.border_slim_indexes_from(mask_2d=mask)
assert mask.border_1d_indexes == pytest.approx(border_pixels_util, 1e-4)
assert mask.border_2d_indexes[0] == pytest.approx(np.array([1, 1]), 1e-4)
assert mask.border_2d_indexes[10] == pytest.approx(np.array([3, 7]), 1e-4)
assert mask.border_1d_indexes.shape[0] == mask.border_2d_indexes.shape[0]
def test__border_mask(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
assert (
mask.border_mask
== np.array(
[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
]
)
).all()
def test__sub_border_flat_indexes__compare_to_array_util_and_numerics(self):
mask = aa.Mask2D.manual(
mask=[
[False, False, False, False, False, False, False, True],
[False, True, True, True, True, True, False, True],
[False, True, False, False, False, True, False, True],
[False, True, False, True, False, True, False, True],
[False, True, False, False, False, True, False, True],
[False, True, True, True, True, True, False, True],
[False, False, False, False, False, False, False, True],
],
pixel_scales=1.0,
sub_size=2,
)
sub_border_pixels_util = aa.util.mask_2d.sub_border_pixel_slim_indexes_from(
mask_2d=mask, sub_size=2
)
assert mask.sub_border_flat_indexes == pytest.approx(
sub_border_pixels_util, 1e-4
)
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True],
[True, True, True, True, True, True, True],
[True, True, False, False, False, True, True],
[True, True, False, False, False, True, True],
[True, True, False, False, False, True, True],
[True, True, True, True, True, True, True],
[True, True, True, True, True, True, True],
],
pixel_scales=1.0,
sub_size=2,
)
assert (
mask.sub_border_flat_indexes == np.array([0, 5, 9, 14, 23, 26, 31, 35])
).all()
def test__slim_index_for_sub_slim_index__compare_to_util(self):
mask = aa.Mask2D.manual(
mask=[[True, False, True], [False, False, False], [True, False, False]],
pixel_scales=1.0,
sub_size=2,
)
slim_index_for_sub_slim_index_util = aa.util.mask_2d.slim_index_for_sub_slim_index_via_mask_2d_from(
mask_2d=mask, sub_size=2
)
assert (
mask.slim_index_for_sub_slim_index == slim_index_for_sub_slim_index_util
).all()
def test__sub_mask_index_for_sub_mask_1d_index__compare_to_array_util(self):
mask = aa.Mask2D.manual(
mask=[[True, True, True], [True, False, False], [True, True, False]],
pixel_scales=1.0,
sub_size=2,
)
sub_mask_index_for_sub_mask_1d_index = aa.util.mask_2d.native_index_for_slim_index_2d_from(
mask_2d=mask, sub_size=2
)
assert mask.sub_mask_index_for_sub_mask_1d_index == pytest.approx(
sub_mask_index_for_sub_mask_1d_index, 1e-4
)
def test__shape_masked_pixels(self):
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, True],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
assert mask.shape_native_masked_pixels == (7, 7)
mask = aa.Mask2D.manual(
mask=[
[True, True, True, True, True, True, True, True, False],
[True, False, False, False, False, False, False, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, False, True, False, True, False, True],
[True, False, True, False, False, False, True, False, True],
[True, False, True, True, True, True, True, False, True],
[True, False, False, False, False, False, False, False, True],
[True, True, True, True, True, True, True, True, True],
],
pixel_scales=1.0,
)
assert mask.shape_native_masked_pixels == (8, 8)
| |
from concat.level0.lex import to_tokens
# The newlines in each example are important.
examples = {
'None\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('NONE', 'None', (1, 0), (1, 4)),
('NEWLINE', '\n', (1, 4), (1, 5)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'NotImplemented\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('NOTIMPL', 'NotImplemented', (1, 0), (1, 14)),
('NEWLINE', '\n', (1, 14), (1, 15)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'... Ellipsis\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('ELLIPSIS', '...', (1, 0), (1, 3)),
('ELLIPSIS', 'Ellipsis', (1, 4), (1, 12)),
('NEWLINE', '\n', (1, 12), (1, 13)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'[9]\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LSQB', '[', (1, 0), (1, 1)),
('NUMBER', '9', (1, 1), (1, 2)),
('RSQB', ']', (1, 2), (1, 3)),
('NEWLINE', '\n', (1, 3), (1, 4)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'[7:8]\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LSQB', '[', (1, 0), (1, 1)),
('NUMBER', '7', (1, 1), (1, 2)),
('COLON', ':', (1, 2), (1, 3)),
('NUMBER', '8', (1, 3), (1, 4)),
('RSQB', ']', (1, 4), (1, 5)),
('NEWLINE', '\n', (1, 5), (1, 6)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'[::0 1 -]\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LSQB', '[', (1, 0), (1, 1)),
('COLON', ':', (1, 1), (1, 2)),
('COLON', ':', (1, 2), (1, 3)),
('NUMBER', '0', (1, 3), (1, 4)),
('NUMBER', '1', (1, 5), (1, 6)),
('MINUS', '-', (1, 7), (1, 8)),
('RSQB', ']', (1, 8), (1, 9)),
('NEWLINE', '\n', (1, 9), (1, 10)),
('ENDMARKER', '', (2, 0), (2, 0))
),
"b'bytes'\n": to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('BYTES', "b'bytes'", (1, 0), (1, 8)),
('NEWLINE', '\n', (1, 8), (1, 9)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'(5,)\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LPAR', '(', (1, 0), (1, 1)),
('NUMBER', '5', (1, 1), (1, 2)),
('COMMA', ',', (1, 2), (1, 3)),
('RPAR', ')', (1, 3), (1, 4)),
('NEWLINE', '\n', (1, 4), (1, 5)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'[,]\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LSQB', '[', (1, 0), (1, 1)),
('COMMA', ',', (1, 1), (1, 2)),
('RSQB', ']', (1, 2), (1, 3)),
('NEWLINE', '\n', (1, 3), (1, 4)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'(1,2,3)\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LPAR', '(', (1, 0), (1, 1)),
('NUMBER', '1', (1, 1), (1, 2)),
('COMMA', ',', (1, 2), (1, 3)),
('NUMBER', '2', (1, 3), (1, 4)),
('COMMA', ',', (1, 4), (1, 5)),
('NUMBER', '3', (1, 5), (1, 6)),
('RPAR', ')', (1, 6), (1, 7)),
('NEWLINE', '\n', (1, 7), (1, 8)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'(1,2,)\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LPAR', '(', (1, 0), (1, 1)),
('NUMBER', '1', (1, 1), (1, 2)),
('COMMA', ',', (1, 2), (1, 3)),
('NUMBER', '2', (1, 3), (1, 4)),
('COMMA', ',', (1, 4), (1, 5)),
('RPAR', ')', (1, 5), (1, 6)),
('NEWLINE', '\n', (1, 6), (1, 7)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'del .attr\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('DEL', 'del', (1, 0), (1, 3)),
('DOT', '.', (1, 4), (1, 5)),
('NAME', 'attr', (1, 5), (1, 9)),
('NEWLINE', '\n', (1, 9), (1, 10)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'{1,2,3,}\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LBRACE', '{', (1, 0), (1, 1)),
('NUMBER', '1', (1, 1), (1, 2)),
('COMMA', ',', (1, 2), (1, 3)),
('NUMBER', '2', (1, 3), (1, 4)),
('COMMA', ',', (1, 4), (1, 5)),
('NUMBER', '3', (1, 5), (1, 6)),
('COMMA', ',', (1, 6), (1, 7)),
('RBRACE', '}', (1, 7), (1, 8)),
('NEWLINE', '\n', (1, 8), (1, 9)),
('ENDMARKER', '', (2, 0), (2, 0))
),
"{'a':1,'b':2}\n": to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('LBRACE', '{', (1, 0), (1, 1)),
('STRING', "'a'", (1, 1), (1, 4)),
('COLON', ':', (1, 4), (1, 5)),
('NUMBER', '1', (1, 5), (1, 6)),
('COMMA', ',', (1, 6), (1, 7)),
('STRING', "'b'", (1, 7), (1, 10)),
('COLON', ':', (1, 10), (1, 11)),
('NUMBER', '2', (1, 11), (1, 12)),
('RBRACE', '}', (1, 12), (1, 13)),
('NEWLINE', '\n', (1, 13), (1, 14)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'word yield\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('NAME', 'word', (1, 0), (1, 4)),
('YIELD', 'yield', (1, 5), (1, 10)),
('NEWLINE', '\n', (1, 10), (1, 11)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'async def fun: 5\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('ASYNC', 'async', (1, 0), (1, 5)),
('DEF', 'def', (1, 6), (1, 9)),
('NAME', 'fun', (1, 10), (1, 13)),
('COLON', ':', (1, 13), (1, 14)),
('NUMBER', '5', (1, 15), (1, 16)),
('NEWLINE', '\n', (1, 16), (1, 17)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'word await\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('NAME', 'word', (1, 0), (1, 4)),
('AWAIT', 'await', (1, 5), (1, 10)),
('NEWLINE', '\n', (1, 10), (1, 11)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'import a.submodule\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('IMPORT', 'import', (1, 0), (1, 6)),
('NAME', 'a', (1, 7), (1, 8)),
('DOT', '.', (1, 8), (1, 9)),
('NAME', 'submodule', (1, 9), (1, 18)),
('NEWLINE', '\n', (1, 18), (1, 19)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'import a as b\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('IMPORT', 'import', (1, 0), (1, 6)),
('NAME', 'a', (1, 7), (1, 8)),
('AS', 'as', (1, 9), (1, 11)),
('NAME', 'b', (1, 12), (1, 13)),
('NEWLINE', '\n', (1, 13), (1, 14)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'from .a import b\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('FROM', 'from', (1, 0), (1, 4)),
('DOT', '.', (1, 5), (1, 6)),
('NAME', 'a', (1, 6), (1, 7)),
('IMPORT', 'import', (1, 8), (1, 14)),
('NAME', 'b', (1, 15), (1, 16)),
('NEWLINE', '\n', (1, 16), (1, 17)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'from .a import b as c\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('FROM', 'from', (1, 0), (1, 4)),
('DOT', '.', (1, 5), (1, 6)),
('NAME', 'a', (1, 6), (1, 7)),
('IMPORT', 'import', (1, 8), (1, 14)),
('NAME', 'b', (1, 15), (1, 16)),
('AS', 'as', (1, 17), (1, 19)),
('NAME', 'c', (1, 20), (1, 21)),
('NEWLINE', '\n', (1, 21), (1, 22)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'from a import *\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('FROM', 'from', (1, 0), (1, 4)),
('NAME', 'a', (1, 5), (1, 6)),
('IMPORT', 'import', (1, 7), (1, 13)),
('STAR', '*', (1, 14), (1, 15)),
('NEWLINE', '\n', (1, 15), (1, 16)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'class A: pass\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('CLASS', 'class', (1, 0), (1, 5)),
('NAME', 'A', (1, 6), (1, 7)),
('COLON', ':', (1, 7), (1, 8)),
('NAME', 'pass', (1, 9), (1, 13)),
('NEWLINE', '\n', (1, 13), (1, 14)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'class A @decorator: pass\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('CLASS', 'class', (1, 0), (1, 5)),
('NAME', 'A', (1, 6), (1, 7)),
('AT', '@', (1, 8), (1, 9)),
('NAME', 'decorator', (1, 9), (1, 18)),
('COLON', ':', (1, 18), (1, 19)),
('NAME', 'pass', (1, 20), (1, 24)),
('NEWLINE', '\n', (1, 24), (1, 25)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'class A($B,): pass\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('CLASS', 'class', (1, 0), (1, 5)),
('NAME', 'A', (1, 6), (1, 7)),
('LPAR', '(', (1, 7), (1, 8)),
('DOLLARSIGN', '$', (1, 8), (1, 9)),
('NAME', 'B', (1, 9), (1, 10)),
('COMMA', ',', (1, 10), (1, 11)),
('RPAR', ')', (1, 11), (1, 12)),
('COLON', ':', (1, 12), (1, 13)),
('NAME', 'pass', (1, 14), (1, 18)),
('NEWLINE', '\n', (1, 18), (1, 19)),
('ENDMARKER', '', (2, 0), (2, 0))
),
'def test: pass\n': to_tokens(
('ENCODING', 'utf-8', (0, 0), (0, 0)),
('DEF', 'def', (1, 0), (1, 3)),
('NAME', 'test', (1, 4), (1, 8)),
('COLON', ':', (1, 8), (1, 9)),
('NAME', 'pass', (1, 10), (1, 14)),
('NEWLINE', '\n', (1, 14), (1, | |
#!/usr/bin/env python3
r"""Full workflow that converts RetroPath2.0 output to a list of pathways.
Copyright (C) 2017 <NAME> research group, INRA
Use of this source code is governed by the MIT license that can be found in the
LICENSE.txt file.
Command line example:
python RP2paths.py all results.csv --outdir pathways
"""
import os
import argparse
import signal
import subprocess
from rp2paths.rp2erxn import compute as rp2erxn_compute
from rp2paths.Scope import compute as Scope_compute
from rp2paths.EFMHandler import EFMHandler
from rp2paths.ImgHandler import ImgHandler
from rp2paths.DotHandler import DotHandler
from rp2paths.PathFilter import PathFilter
class NoScopeMatrix(Exception):
"""Raised when no scope matrix was produced"""
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
if self.message:
return 'NoScopeMatrix, {0} '.format(self.message)
else:
return 'NoScopeMatrix has been raised'
class GeneralTask(object):
"""Generic class for handling the execution of task."""
def _launch_external_program(self, command, baselog, timeout,
use_shell=False):
"""Make a system call to an external program."""
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=False,
preexec_fn=os.setsid)
try:
fout = open(baselog+'.log', 'w')
ferr = open(baselog+'.err', 'w')
out, err = p.communicate(timeout=timeout)
fout.write(' '.join(command) + '\n')
fout.write(out.decode('UTF-8'))
ferr.write(err.decode('UTF-8'))
except (subprocess.TimeoutExpired):
fout.write(' '.join(command) + '\n')
print('TIMEOUT:' + ' '.join(command) + '\n')
ferr.write('TIMEOUT')
os.killpg(p.pid, signal.SIGKILL)
fout.close()
ferr.close()
def _check_args(self):
"""Make some checking on arguments."""
raise NotImplementedError("baseclass")
def compute(self, timeout):
"""Make some computation."""
raise NotImplementedError("baseclass")
class TaskConvert(GeneralTask):
"""Handling the execution of the conversion task."""
def __init__(self, infile, cmpdfile, reacfile, sinkfile, reverse):
"""Initializing."""
self.infile = infile
self.cmpdfile = cmpdfile
self.reacfile = reacfile
self.sinkfile = sinkfile
self.reverse = reverse
self._check_args()
def _check_args(self):
"""Checking that arguments are usable."""
if not os.path.exists(self.infile):
raise IOError(self.infile)
def compute(self, timeout):
"""Process the conversion."""
rp2erxn_compute(self.infile, self.cmpdfile,
self.reacfile, self.sinkfile,
self.reverse)
def set_absolute_infile_path(self):
"""Change the path of the infile."""
self.infile = os.path.abspath(self.infile)
class TaskScope(GeneralTask):
"""Handling the execution of the scope task."""
def __init__(self, reacfile, sinkfile, target, minDepth=False,
customsinkfile=None):
"""Initialize."""
self.outdir = '.'
self.reacfile = reacfile
self.sinkfile = sinkfile
self.target = target
self.minDepth = minDepth
# Custom sink? If yes, replace sinkfile
if customsinkfile is not None:
self.sinkfile = customsinkfile
self.sinkfile = os.path.abspath(self.sinkfile)
def _check_args(self):
"""Check the validity of some arguments."""
for f in [self.outdir, self.reacfile, self.sinkfile]:
if not os.path.exists(f):
raise FileNotFoundError(f)
def _check_output(self):
"""Check whether the outputted scope is empty."""
if not os.path.exists('out_mat'):
raise NoScopeMatrix("*** Scope Task: no scope matrix was produced, exit")
def compute(self, timeout):
"""Process the conversion."""
Scope_compute(out_folder=self.outdir, sink_file=self.sinkfile,
reaction_file=self.reacfile, target=self.target,
minDepth=self.minDepth)
self._check_output()
class TaskEfm(GeneralTask):
"""Handling the execution of the efm task."""
def __init__(self, ebin, basename):
"""Initialize."""
self.ebin = ebin
self.basename = basename
def _check_args(self):
if not os.path.exists(self.ebin):
raise IOError(self.ebin)
def compute(self, timeout):
"""Enumerate EFMs."""
if not os.path.exists(self.basename + '_mat'):
raise IOError('No stoichiometry matrix found: ' + self.basename + '_mat')
command = [self.ebin, self.basename, self.basename]
self._launch_external_program(command=command, baselog='efm',
timeout=timeout, use_shell=True)
class TaskPath(object):
"""Handling result generated by the EFM enumeration tool."""
def __init__(self, basename, outfile,
unfold_stoichio=False, unfold_compounds=False,
maxsteps=0, maxpaths=150):
"""Initialization."""
self.basename = basename
self.full_react_file = basename + '_full_react'
self.react_file = basename + '_react'
self.efm_file = basename + '_efm'
self.outfile = outfile
self.unfold_stoichio = unfold_stoichio
self.unfold_compounds = unfold_compounds
self.maxsteps = maxsteps if maxsteps != 0 else float('+inf')
self.maxpaths = maxpaths
def _check_args(self):
"""Perform some checking on arguments."""
assert type(self.unfold_stoichio) is bool
assert type(self.unfold_compounds) is bool
assert self.maxsteps > 0
assert type(self.maxpaths) is int and self.maxpaths >= 0
for filepath in (self.full_react_file, self.react_file, self.efm_file):
if not os.path.exists(filepath):
raise IOError(filepath)
def compute(self, timeout):
"""Generate pathways from EFM enumerations."""
efmh = EFMHandler(
full_react_file=self.full_react_file,
react_file=self.react_file,
efm_file=self.efm_file,
outfile=self.outfile,
unfold_stoichio=self.unfold_stoichio,
unfold_compounds=self.unfold_compounds,
maxsteps=self.maxsteps,
maxpaths=self.maxpaths
)
efmh.ParseEFMs()
efmh.WriteCsv()
class TaskFilter(GeneralTask):
"""Filter out unwanted pathways."""
def __init__(self, pathfile, sinkfile,
customsinkfile=None,
onlyPathsStartingBy=None,
notPathsStartingBy=None):
"""Initialize."""
self.pathfile = pathfile
self.sinkfile = sinkfile
# Custom sink? If yes, replace sinkfile
if customsinkfile is not None:
self.sinkfile = customsinkfile
self.sinkfile = os.path.abspath(self.sinkfile)
# Only keep paths starting by specified compound(s)?
self.onlyPathsStartingBy = onlyPathsStartingBy
# Filter out paths starting by specified compound(s)?
self.notPathsStartingBy = notPathsStartingBy
def _check_args(self):
for f in [self.pathfile, self.sinkfile]:
if not os.path.exists(f):
raise IOError(f)
def compute(self, timeout):
"""Filter pathways."""
pf = PathFilter(
pathfile=self.pathfile,
sinkfile=self.sinkfile,
filter_bootstraps=True,
filter_inconsistentsubstrates=True,
onlyPathsStartingBy=self.onlyPathsStartingBy,
notPathsStartingBy=self.notPathsStartingBy
)
pf.GetPathwaysFromFile()
pf.GetSinkCompoundsFromFile()
pf.FilterOutPathways()
pf.RewritePathFile()
class TaskImg(GeneralTask):
"""Handling computation of pictures."""
def __init__(self, pathsfile, cmpdfile, imgdir, cmpdnamefile=None):
"""Initialize."""
self.pathsfile = pathsfile
self.cmpdfile = cmpdfile
self.imgdir = imgdir
self.cmpdnamefile = cmpdnamefile
self.tryCairo = True
self.width = 400
self.height = 200
self.kekulize = True
def _check_args(self):
if not os.path.isdir(self.imgdir):
os.mkdir(self.imgdir)
if not os.path.exists(self.pathsfile):
raise IOError(self.pathsfile)
if self.cmpdnamefile is not None:
if not os.path.exists(self.cmpdnamefile):
self.cmpdnamefile = None
print('Warning: --cmpdnamefile is not a valid path, name of compounds will be not available.')
def compute(self, timeout):
"""Compute pictures."""
imgh = ImgHandler(
pathsfile=self.pathsfile,
cmpdfile=self.cmpdfile,
imgdir=self.imgdir,
cmpdnamefile=self.cmpdnamefile,
width=self.width,
height=self.height,
tryCairo=self.tryCairo,
kekulize=self.kekulize
)
imgh.GetInvolvedCompoundsFromFile()
imgh.GetSmilesOfCompoundsFromFile()
imgh.GetCompoundsNameFromFile()
imgh.MakeAllImg()
class TaskDot(object):
"""Generating pathways as dot files."""
def __init__(self, pathsfile, chassisfile, target, outbasename,
imgdir=None, cmpdnamefile=None, customchassisfile=None):
"""Initialization."""
self.pathsfile = pathsfile
self.chassisfile = chassisfile
self.target = target
self.outbasename = outbasename
self.imgdir = imgdir
self.cmpdnamefile = cmpdnamefile
# Custom sink? If yes, replace chassisfile
if customchassisfile is not None:
self.chassisfile = customchassisfile
self.chassisfile = os.path.abspath(self.chassisfile)
def _check_args(self):
"""Perform some checking on arguments."""
for filepath in (self.pathsfile, self.chassisfile):
if not os.path.exists(filepath):
raise IOError(filepath)
if self.cmpdnamefile is not None:
if not os.path.exists(self.cmpdnamefile):
self.cmpdnamefile = None
print('Warning: --cmpdnamefile is not a valid path, name of compounds will be not available.')
def compute(self, timeout):
"""Generate all dot files."""
doth = DotHandler(
pathsfile=self.pathsfile,
chassisfile=self.chassisfile,
target=self.target,
outbasename=self.outbasename,
imgdir=self.imgdir,
cmpdnamefile=self.cmpdnamefile)
doth.GetPathwaysFromFile()
doth.GetChassisCompoundsFromFile()
doth.GetCompoundsNameFromFile()
doth.MakeAllDot(dot=True, svg=True, png=False)
def launch(tasks, outdir, timeout):
"""Launch the computation of one or several tasks.
tasks: list, *Task object
..
"""
# Checking output folder
dir_handler(outdir)
# Switch the
base_dir = os.getcwd()
os.chdir(os.path.join(outdir))
# Compute each task
for t in tasks:
t._check_args()
t.compute(timeout=timeout)
# Back to initial folder
os.chdir(os.path.join(base_dir))
def dir_handler(outdir):
"""Handling paths to the output folder."""
# Create the out folder if it does not exist
if not os.path.exists(os.path.join(outdir)):
os.mkdir(os.path.join(outdir))
def convert(args):
"""Convert output from RetroPath2.0 workflow."""
task = TaskConvert(infile=args.infile, cmpdfile=args.cmpdfile,
reacfile=args.reacfile, sinkfile=args.sinkfile,
reverse=args.reverse)
task.set_absolute_infile_path()
launch(tasks=[task], outdir=args.outdir, timeout=None)
def scope(args):
"""Compute the scope using new version."""
task = TaskScope(reacfile=args.reacfile, sinkfile=args.sinkfile,
target=args.target, minDepth=args.minDepth,
customsinkfile=args.customsinkfile)
launch(tasks=[task], outdir=args.outdir, timeout=None)
def efm(args):
"""Enumerate EFMs."""
task = TaskEfm(ebin=args.ebin, basename=args.basename)
launch(tasks=[task], outdir=args.outdir, timeout=args.timeout)
def paths(args):
"""Compute possible heterologous pathways."""
task = TaskPath(basename=args.basename, outfile=args.pathsfile,
unfold_stoichio=args.unfold_stoichio,
unfold_compounds=args.unfold_compounds,
maxsteps=args.maxsteps, maxpaths=args.maxpaths)
launch(tasks=[task], outdir=args.outdir, timeout=None)
def filter(args):
"""Filter out some paths according to some criteria."""
task = TaskFilter(pathfile=args.pathsfile, sinkfile=args.sinkfile,
customsinkfile=args.customsinkfile,
onlyPathsStartingBy=args.onlyPathsStartingBy,
notPathsStartingBy=args.notPathsStartingBy)
launch(tasks=[task], outdir=args.outdir, timeout=None)
def img(args):
"""Compute compound and pathway pictures."""
task = TaskImg(pathsfile=args.pathsfile, cmpdfile=args.cmpdfile,
imgdir=args.imgdir, cmpdnamefile=args.cmpdnamefile)
launch(tasks=[task], outdir=args.outdir, timeout=None)
def dot(args):
"""Compute dot files of pathways."""
task = TaskDot(pathsfile=args.pathsfile, chassisfile=args.sinkfile,
target=args.target, outbasename=args.dotfilebase,
imgdir=args.imgdir, cmpdnamefile=args.cmpdnamefile,
customchassisfile=args.customsinkfile)
launch(tasks=[task], outdir=args.outdir, timeout=None)
def doall(args):
"""Compute all the tasks at once."""
c_task = TaskConvert(
infile=args.infile, cmpdfile=args.cmpdfile,
reacfile=args.reacfile, sinkfile=args.sinkfile,
reverse=args.reverse)
c_task.set_absolute_infile_path()
s_task = TaskScope(
reacfile=args.reacfile, sinkfile=args.sinkfile,
target=args.target, minDepth=args.minDepth,
customsinkfile=args.customsinkfile)
e_task = TaskEfm(
ebin=args.ebin, basename=args.basename)
p_task = TaskPath(
basename=args.basename, outfile=args.pathsfile,
unfold_stoichio=args.unfold_stoichio,
unfold_compounds=args.unfold_compounds,
maxsteps=args.maxsteps, maxpaths=args.maxpaths)
f_task = TaskFilter(
pathfile=args.pathsfile, sinkfile=args.sinkfile,
customsinkfile=args.customsinkfile,
onlyPathsStartingBy=args.onlyPathsStartingBy,
notPathsStartingBy=args.notPathsStartingBy)
i_task = TaskImg(
pathsfile=args.pathsfile, cmpdfile=args.cmpdfile,
imgdir=args.imgdir, cmpdnamefile=args.cmpdnamefile)
d_task = TaskDot(
pathsfile=args.pathsfile, chassisfile=args.sinkfile,
target=args.target, outbasename=args.dotfilebase,
imgdir=args.imgdir, cmpdnamefile=args.cmpdnamefile,
customchassisfile=args.customsinkfile)
launch(
tasks=[c_task, s_task, e_task, p_task, f_task, i_task, d_task],
outdir=args.outdir, timeout=args.timeout)
def build_args_parser(prog='rp2paths'):
script_path = os.path.dirname(os.path.realpath(__file__))
# Args: converting the EMS from RetroPath2.0 Knime workflow
c_args = argparse.ArgumentParser(prog='rp2paths', add_help=False)
c_args.add_argument(
dest='infile',
help='File outputed by the RetroPath2.0 Knime workflow',
type=str)
c_args.add_argument(
'--outdir', dest='outdir',
help='Folder to put all results',
type=str, required=False,
default=os.getcwd()+'/')
c_args.add_argument(
'--reverse', '-r', dest='reverse',
help='Consider reactions in the reverse direction',
required=False, action='store_false',
default=True)
# Args: computing the scope
s_args = argparse.ArgumentParser(prog='rp2paths', add_help=False)
s_args.add_argument(
'--outdir', dest='outdir',
help='Folder to put all results',
type=str, required=False,
default=os.getcwd()+'/')
s_args.add_argument(
'--minDepth', action='store_true', default=False,
help='Use minimal depth scope, i.e. stop the scope computation as \
as soon an a first minimal path linking target to sink is found \
(default: False).')
s_args.add_argument(
'--target',
help='Target compound internal ID. This internal ID specifies \
which compound should be considered as the targeted compound. The \
default behavior is to consider as the target the first compound \
used as a source compound in a first iteration of a metabolic \
exploration. Let this value as it is except if you know what you \
are doing.',
type=str, required=False,
default='TARGET_0000000001')
s_args.add_argument(
'--customsinkfile', dest='customsinkfile',
help='User-defined sink file, i.e. file listing compounds to \
consider as sink compounds. Sink compounds should be provided by \
their IDs, as used in the reaction.erxn file. If no file is \
provided | |
train_test_switch == "test":
#DEFINING TEST DATA LOADER FOR TESTINGs
testDatasetSaveplace = FileParentPath + "/Datasets/test"
testDataset = self.Dataset(testDatasetSaveplace)
testDataLoader = DataLoader(testDataset, batch_size=opt.batch_size, shuffle=True, num_workers=opt.n_cpu, drop_last=True )
#This will create batches of your data that you can access as:
testiter= iter(testDataLoader)
testDataset = testiter.next()
testDataset = transforms.ToTensor()
dataset = testDataset
dataloader = testDataLoader
except:
PrintException()
print("Did you rebuild the train test data? Please check")
input("")
pass
#####################################################################################################################
# DATA COMPLETE -> NOW MACHINE LEARNING PART
assert dataset is not None
#else: input("Dataset is None")
return dataset, dataloader
# opt.verbosity = False
#INIT BoxcountNetParams as empty Dict
#The BoxCountEncoder takes the image and calculates the boxcountratios and the Lakcountmaps for each iteration and passes all the arrays(iteration) and returns it.
previous_Best_Loss = None
Loss_Now = None
def TrainSpacialBoxcount_with(self,HyperparameterAndENCODERCLASS):
HyperParameterspace, BoxCountEncoder = HyperparameterAndENCODERCLASS
global previous_Best_Loss, Loss_Now
#BoxCountEncoder = None
#INIT VARIABLES
opt.n_epochs = HyperParameterspace['n_epochs']
opt.batch_size = HyperParameterspace['batch_size']
opt.lr = HyperParameterspace['lr']
opt.b1 = HyperParameterspace['b1']
opt.b2 = HyperParameterspace['b2']
#BoxCountLayerDiscription
#self.BoxcountRatioConv = nn.Conv2d(3, 16, (self.BoxsizeX,BoxsizeY), (len(self.BoxsizeX), len(self.BoxsizeY) ), padding=0)
#self.LACcountConv = nn.Conv2d(3, 16, (self.BoxsizeX,self.BoxsizeY), (len(self.BoxsizeX), len(self.BoxsizeY) ), padding=0)
Boxsize=[2,4,8,16,32,64,128,256,512,1024]
#Channles
IN, OUTCOM = 1 , 2 #Channels 2, cause output is BCRmap and LAKmap, one is derived from the other
Inter1, Inter2, Inter3 = HyperParameterspace['Inter1'], HyperParameterspace['Inter2'], HyperParameterspace['Inter3'] # Hyperoptimization here
#Kernelsize in X/Y resprective layer is 2, cause...
Kx1, Kx2, Kx3, Kx4 = 2,2,2,2
Ky1, Ky2, Ky3, Ky4 = 2,2,2,2
# ...with a stride of 2 the picture is getting halfed in size, exacly like the boxcounting with bigger boxsizes , but in cpu version the ori bz overlap one pixel, which here is not checkk
Sx1, Sx2, Sx3, Sx4 = 2, 2, 2, 2
Sy1, Sy2, Sy3, Sy4 = 2, 2, 2, 2
#padding should be 0, cause every picture is same size and all the kernels fit perfectly
Px1, Px2, Px3, Px4 = 0,0,0,0
Py1, Py2, Py3, Py4 = 0,0,0,0
#Batchnorm is not needed, causewe want to focus just on the convolution calculation and dont want to alter the image/ entry arrays in any unknown form... EVALUATE and CHECK
BN1, BN2, BN3, BN4 = 0,0,0,0
#Intermediate OutputLayer ... Cause every Filter of a Convulution is described within the Channels in the hidden layers and we want to output the BCR and LAK like like the cpu version...
# we have to generate an output with a 1x1 = KxS conv with x Chan input and 2 Chan Output for calcing the loss
BoxCountLayerDiscription = [ [IN, Inter1,Kx1, Ky1,Sx1,Sy1,Px1,Py1,BN1], #input layer
[Inter1,OUTCOM ,1, 1,1,1,0,0,0], # output layer for first iteration (Boxsize 2)
[Inter1,Inter2,Kx2, Ky2,Sx2,Sy2,Px2,Py2,BN2],
[Inter2,OUTCOM ,1, 1,1,1,0,0,0], # output layer for second iteration (Boxsize 4)
[Inter2,Inter3,Kx3, Ky3,Sx3,Sy3,Px3,Py3,BN3],
[Inter3,OUTCOM ,1, 1,1,1,0,0,0], # output layer for third iteration (Boxsize 8)
[Inter3,OUTCOM,Kx4, Ky4,Sx4,Sy4,Px4,Py4,BN4], #last ouput layer
] # [Inter3,OUTCOM ,1, 1,1,1,0,0,0], # output layer for 4th iteration (Boxsize 16)
input_shape = (opt.batch_size,1, ChunkLenght,ChunkLenght)
OutputLayerIndexList = [2,6,10,12] # Cause the intermediate output layers are branched out from the main flowchart
BoxCountNetParameters = {'BoxCountLayerDiscription': BoxCountLayerDiscription, 'input_shape': input_shape, 'OutputLayerIndexList': OutputLayerIndexList}
Modelname = "n_epochs_" + str(round(opt.n_epochs,3))
Modelname += "_batch-size_" + str(round(opt.batch_size,3))
Modelname += "_learning-rate_" + str(round(opt.lr,3))
Modelname += "_beta-decay_" + str(round(opt.b1,3)) +"_" + str(round(opt.b2,3))
#Modelname += "_Scalefactors_" + str(round(Scalefactor_2,3)) +"_" + str(round(Scalefactor_4,3)) +"_" + str(round(Scalefactor_8,3))
# -----------------
# Train_BoxcountingCONV
# -----------------
#define Loss
pixelwise_loss = torch.nn.L1Loss()
#Init BoxcountEncoder
BoxCountEncoder = BoxCountEncoder(BoxCountNetParameters)
BoxCountEncoder.to(device)
pixelwise_loss.to(device)
# Optimizers
optimizer_BC = torch.optim.Adam(BoxCountEncoder.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
if device=="cuda":
Tensor = torch.cuda.FloatTensor
else:
Tensor = torch.FloatTensor
#from tqdm import tqdm
# ----------
# Training
# ----------
epochs =range(opt.n_epochs)
print("Model: ",Modelname)
for epoch in epochs:
if opt.verbosity: print("epoch ",str(epoch), "of", str(opt.n_epochs) )
for i, (images, labels_2, labels_4, labels_8, labels_16 ) in enumerate(self.trainDataloader):
#real_labels_2, real_labels_4, real_labels_8, real_labels_16 = labels
if opt.verbosity: print("Nr",str(i) ,"of", str(len(self.trainDataloader)))
real_labels_2 = Variable(labels_2.type(Tensor))
real_labels_2.to(device)
real_labels_4 = Variable(labels_4.type(Tensor))
real_labels_4.to(device)
real_labels_8 = Variable(labels_8.type(Tensor))
real_labels_8.to(device)
real_labels_16 = Variable(labels_16.type(Tensor))
real_labels_16.to(device)
# Configure input
real_imgs = Variable(images.type(Tensor))
real_imgs.to(device)
optimizer_BC.zero_grad()
BCR_LAK_map_2 , BCR_LAK_map_4 , BCR_LAK_map_8 , BCR_LAK_map_16 = BoxCountEncoder(real_imgs)
BCR_LAK_map_2_loss = pixelwise_loss(BCR_LAK_map_2, real_labels_2)
BCR_LAK_map_4_loss = pixelwise_loss(BCR_LAK_map_4, real_labels_4)
BCR_LAK_map_8_loss = pixelwise_loss(BCR_LAK_map_8, real_labels_8)
BCR_LAK_map_16_loss = pixelwise_loss(BCR_LAK_map_16, real_labels_16)
Scalefactor_2 , Scalefactor_4 , Scalefactor_8 , Scalefactor_16 = 0.25, 0.25, 0.25 , 0.25 # maybe optimiziing usage?!
BCR_LAK_loss = Scalefactor_2 * BCR_LAK_map_2_loss + Scalefactor_4 * BCR_LAK_map_4_loss + Scalefactor_8 * BCR_LAK_map_8_loss + Scalefactor_16 * BCR_LAK_map_16_loss
if opt.verbosity: print("loss: BCR_LAK_loss",BCR_LAK_loss)
#input()
BCR_LAK_loss.backward()
optimizer_BC.step()
'''
print(
"[Epoch %d/%d] [Batch %d/%d] [BC loss: %f] "
% (epoch, opt.n_epochs, i, len(trainDataloader), BCR_LAK_loss.item() )
)
'''
### SAVE MODEL IF its better than 0something
if previous_Best_Loss == None:
previous_Best_Loss = BCR_LAK_loss.item()
else:
pass
Loss_Now = BCR_LAK_loss.item()
print("Best loss so far :", previous_Best_Loss)
print("loss of this model:", Loss_Now)
if Loss_Now <= previous_Best_Loss:
#<= to save first model always and then just, when better model was found with LOWER LOSS
saveplace = FileParentPath
saveplace +="/models/"
saveplace += "Loss" + str(round(BCR_LAK_loss.item(),3)) +"---"
saveplace += Modelname
NetParametersSaveplace = saveplace +".netparams"
with open(NetParametersSaveplace, "wb") as f:
pickle.dump(BoxCountNetParameters, f)
saveplace += ".model"
torch.save(BoxCountEncoder.state_dict(), saveplace)
#only update, when it was higher
print("Model Saved")
previous_Best_Loss = Loss_Now
else:
print("Loss was higher/worse than previous best model")
return {'loss': BCR_LAK_loss.item(), 'status': STATUS_OK}
def begin_training(self, trainDataset, trainDataloader):
#global trainDataset, trainDataloader
self.trainDataset = trainDataset
self.trainDataloader = trainDataloader
#Source: https://github.com/hyperopt/hyperopt/issues/267
#To save trials object to pick up where you left
def run_trials(HyperParameterspace, Modelname):
#ATTENTION: If you want to begin training anew, then you have to delete the .hyperopt file
TrialsSaveplace = FileParentPath
TrialsSaveplace += "/"+ str(Modelname) +".hyperopt"
trials_step = 1 # how many additional trials to do after loading saved trials. 1 = save after iteration
max_trials = 3 # initial max_trials. put something small to not have to wait
try: # try to load an already saved trials object, and increase the max
trials = pickle.load(open(TrialsSaveplace, "rb"))
print("Found saved Trials! Loading...")
max_trials = len(trials.trials) + trials_step
print("Rerunning from {} trials to {} (+{}) trials".format(len(trials.trials), max_trials, trials_step))
except: # create a new trials object and start searching
trials = Trials()
lowest_loss = fmin(self.TrainSpacialBoxcount_with, HyperparameterAndENCODERCLASS, algo=tpe.suggest, max_evals=max_trials, trials=trials)
print("Lowest achieved loss so far:", lowest_loss)
# save the trials object
with open(TrialsSaveplace, "wb") as f:
pickle.dump(trials, f)
HyperParameterspace = {
'n_epochs':hp.choice('opt.n_epochs', range(5,150,5) ),
'batch_size':hp.choice('opt.batch_size', [2,4,8,16,32,64,128,256,512] ),
'lr':hp.uniform('lr', 0.0000001 , 0.1 ),
'b1':hp.uniform('b1', 0.01 , 1.0 ),
'b2':hp.uniform('b2', 0.01 , 1.0 ),
'Inter1':hp.choice('Inter1', range(1,512) ),
'Inter2':hp.choice('Inter2', range(1,512) ),
'Inter3':hp.choice('Inter3', range(1,512) ),
#'Scalefactor_2':hp.uniform('Scalefactor_2', 0.4, 0.5 ),
#'Scalefactor_4':hp.uniform('Scalefactor_4', 0.15, 0.25 ),
#'Scalefactor_8':hp.uniform('Scalefactor_8', 0.1, 0.15 ),
}
HyperparameterAndENCODERCLASS = HyperParameterspace, BoxCountEncoder
print("Begin HyperparameterOptimization")
# loop indefinitely and stop whenever you like by setting MaxTrys
#TotalTrials = 0
MaxTrys = 100
for TotalTrials in range(MaxTrys):
Modelname = "SpacialBoxcountEncoder"+"_trialsOBJ"
run_trials(HyperparameterAndENCODERCLASS, "BoxcountEncoder")
def validation(self,testDataset, testDataLoader):
if self.ModelnameList == None:
# -------------------------------------------------------------------------------------------------------
# Testing BoxcountEncoder
# -------------------------------------------------------------------------------------------------------
self.ModelnameList = []
#Pretrained Networks-----------------------
self.ModelnameList.append("Loss0.01---n_epochs_135_batch-size_4_learning-rate_0.001_beta-decay_0.671_0.362")
self.ModelnameList.append("Loss0.01---n_epochs_85_batch-size_512_learning-rate_0.001_beta-decay_0.681_0.876")
self.ModelnameList.append("Loss0.014---n_epochs_5_batch-size_128_learning-rate_0.001_beta-decay_0.501_0.945")
self.ModelnameList.append("Loss0.506---n_epochs_25_batch-size_512_learning-rate_0.071_beta-decay_0.26_0.248")
self.ModelnameList.append("Loss0.735---n_epochs_95_batch-size_4_learning-rate_0.062_beta-decay_0.311_0.194")
self.ModelnameList.append("Loss0.012---n_epochs_135_batch-size_4_learning-rate_0.015_beta-decay_0.808_0.762")
showitem = None
whereTObreakIteration = 100 #at batch the test will break the testloop to continue
#To render the network output set verbosity to True
opt.verbosity = True
opt.n_cpu = 8 #for every thread of my quadcore -> adjust as you like
def TestSpacialBoxcount_with(Modelname, BoxCountEncoder,showitem, device):
#global showitem
NetParametersSaveplace =FileParentPath+ "/models/"+ Modelname +".netparams"
BoxCountNetParameters = pickle.load(open(NetParametersSaveplace, "rb"))
saveplace = FileParentPath+ "/models/"+Modelname +".model"
__, parameter = Modelname.split('---') #extracting parameter to generate option object
__, __, n_epochs, __, batch_size, __, learning_rate, __ , betadecay1, betadecay2 = parameter.split('_')
#should not be nessecary, except the changing batchsize #self, n_epochs, batch_size, img_size, channels, learning_rate, b1, b2
#opt = OptionObject(int(n_epochs), int(batch_size), ChunkLenght, 1 , float(learning_rate), float(betadecay1), float(betadecay2))
#device = "cuda"
#device = "cpu"
#load and init the BCencoder
BoxCountEncoder = BoxCountEncoder(BoxCountNetParameters)
BoxCountEncoder.load_state_dict(torch.load(saveplace, map_location=device))
BoxCountEncoder.eval() #to disable backpropagation, so don't adjust any weights and biases
#define Loss
pixelwise_loss = torch.nn.L1Loss()
#Init BoxcountEncoder
BoxCountEncoder.to(device)
pixelwise_loss.to(device)
# Optimizers
optimizer_BC = torch.optim.Adam(BoxCountEncoder.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))
if device=="cuda":
Tensor = torch.cuda.FloatTensor
else:
Tensor = torch.FloatTensor
totaltime |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.