input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
multiplies them by `P` and
compositions.
Returns
-------
fugacities : list[float]
Fugacities, [Pa]
'''
P = self.P
lnphis = self.lnphis_at_zs(zs)
return [P*zs[i]*trunc_exp(lnphis[i]) for i in range(len(zs))]
def lnphi(self):
r'''Method to calculate and return the log of fugacity coefficient of
the phase; provided the phase is 1 component.
Returns
-------
lnphi : list[float]
Log fugacity coefficient, [-]
'''
if self.N != 1:
raise ValueError("Property not supported for multicomponent phases")
return self.lnphis()[0]
def phi(self):
r'''Method to calculate and return the fugacity coefficient of
the phase; provided the phase is 1 component.
Returns
-------
phi : list[float]
Fugacity coefficient, [-]
'''
if self.N != 1:
raise ValueError("Property not supported for multicomponent phases")
return self.phis()[0]
def fugacity(self):
r'''Method to calculate and return the fugacity of
the phase; provided the phase is 1 component.
Returns
-------
fugacity : list[float]
Fugacity, [Pa]
'''
if self.N != 1:
raise ValueError("Property not supported for multicomponent phases")
return self.fugacities()[0]
def dfugacity_dT(self):
r'''Method to calculate and return the temperature derivative of
fugacity of the phase; provided the phase is 1 component.
Returns
-------
dfugacity_dT : list[float]
Fugacity first temperature derivative, [Pa/K]
'''
if self.N != 1:
raise ValueError("Property not supported for multicomponent phases")
return self.dfugacities_dT()[0]
def dfugacity_dP(self):
r'''Method to calculate and return the pressure derivative of
fugacity of the phase; provided the phase is 1 component.
Returns
-------
dfugacity_dP : list[float]
Fugacity first pressure derivative, [-]
'''
if self.N != 1:
raise ValueError("Property not supported for multicomponent phases")
return self.dfugacities_dP()[0]
def fugacities(self):
r'''Method to calculate and return the fugacities of the phase.
.. math::
f_i = P z_i \exp(\ln \phi_i)
Returns
-------
fugacities : list[float]
Fugacities, [Pa]
'''
P = self.P
zs = self.zs
lnphis = self.lnphis()
return [P*zs[i]*trunc_exp(lnphis[i]) for i in range(len(zs))]
def lnfugacities(self):
r'''Method to calculate and return the log of fugacities of the phase.
.. math::
\ln f_i = \ln\left( P z_i \exp(\ln \phi_i)\right)
= \log(P) + \log(z_i) + \ln \phi_i
Returns
-------
lnfugacities : list[float]
Log fugacities, [log(Pa)]
'''
P = self.P
zs = self.zs
lnphis = self.lnphis()
logP = log(P)
log_zs = self.log_zs()
return [logP + log_zs[i] + lnphis[i] for i in range(self.N)]
fugacities_lowest_Gibbs = fugacities
def dfugacities_dT(self):
r'''Method to calculate and return the temperature derivative of fugacities
of the phase.
.. math::
\frac{\partial f_i}{\partial T} = P z_i \frac{\partial
\log \phi_i}{\partial T}
Returns
-------
dfugacities_dT : list[float]
Temperature derivative of fugacities of all components
in the phase, [Pa/K]
Notes
-----
'''
dphis_dT = self.dphis_dT()
P, zs = self.P, self.zs
return [P*zs[i]*dphis_dT[i] for i in range(len(zs))]
def lnphis_G_min(self):
r'''Method to calculate and return the log fugacity coefficients of the
phase. If the phase can have multiple solutions at its `T` and `P`,
this method should return those with the lowest Gibbs energy. This
needs to be implemented on phases with that criteria like cubic EOSs.
Returns
-------
lnphis : list[float]
Log fugacity coefficients, [-]
'''
return self.lnphis()
def phis(self):
r'''Method to calculate and return the fugacity coefficients of the
phase.
.. math::
\phi_i = \exp (\ln \phi_i)
Returns
-------
phis : list[float]
Fugacity coefficients, [-]
'''
return [trunc_exp(i) for i in self.lnphis()]
def dphis_dT(self):
r'''Method to calculate and return the temperature derivative of fugacity
coefficients of the phase.
.. math::
\frac{\partial \phi_i}{\partial T} = \phi_i \frac{\partial
\log \phi_i}{\partial T}
Returns
-------
dphis_dT : list[float]
Temperature derivative of fugacity coefficients of all components
in the phase, [1/K]
Notes
-----
'''
try:
return self._dphis_dT
except AttributeError:
pass
try:
dlnphis_dT = self._dlnphis_dT
except AttributeError:
dlnphis_dT = self.dlnphis_dT()
try:
phis = self._phis
except AttributeError:
phis = self.phis()
self._dphis_dT = [dlnphis_dT[i]*phis[i] for i in range(self.N)]
return self._dphis_dT
def dphis_dP(self):
r'''Method to calculate and return the pressure derivative of fugacity
coefficients of the phase.
.. math::
\frac{\partial \phi_i}{\partial P} = \phi_i \frac{\partial
\log \phi_i}{\partial P}
Returns
-------
dphis_dP : list[float]
Pressure derivative of fugacity coefficients of all components
in the phase, [1/Pa]
Notes
-----
'''
try:
return self._dphis_dP
except AttributeError:
pass
try:
dlnphis_dP = self._dlnphis_dP
except AttributeError:
dlnphis_dP = self.dlnphis_dP()
try:
phis = self._phis
except AttributeError:
phis = self.phis()
self._dphis_dP = [dlnphis_dP[i]*phis[i] for i in range(self.N)]
return self._dphis_dP
def dfugacities_dP(self):
r'''Method to calculate and return the pressure derivative of the
fugacities of the components in the phase.
.. math::
\frac{\partial f_i}{\partial P} = z_i \left(P \frac{\partial
\phi_i}{\partial P} + \phi_i \right)
Returns
-------
dfugacities_dP : list[float]
Pressure derivative of fugacities of all components
in the phase, [-]
Notes
-----
For models without pressure dependence of fugacity, the returned result
may not be exactly zero due to inaccuracy in floating point results;
results are likely on the order of 1e-14 or lower in that case.
'''
try:
dphis_dP = self._dphis_dP
except AttributeError:
dphis_dP = self.dphis_dP()
try:
phis = self._phis
except AttributeError:
phis = self.phis()
P, zs = self.P, self.zs
return [zs[i]*(P*dphis_dP[i] + phis[i]) for i in range(self.N)]
def dfugacities_dns(self):
r'''Method to calculate and return the mole number derivative of the
fugacities of the components in the phase.
if i != j:
.. math::
\frac{\partial f_i}{\partial n_j} = P\phi_i z_i \left(
\frac{\partial \ln \phi_i}{\partial n_j} - 1
\right)
if i == j:
.. math::
\frac{\partial f_i}{\partial n_j} = P\phi_i z_i \left(
\frac{\partial \ln \phi_i}{\partial n_j} - 1
\right) + P\phi_i
Returns
-------
dfugacities_dns : list[list[float]]
Mole number derivatives of the fugacities of all components
in the phase, [Pa/mol]
Notes
-----
'''
phis = self.phis()
dlnphis_dns = self.dlnphis_dns()
P, zs, cmps = self.P, self.zs, range(self.N)
matrix = []
for i in cmps:
phi_P = P*phis[i]
ziPphi = phi_P*zs[i]
r = dlnphis_dns[i]
row = [ziPphi*(r[j] - 1.0) for j in cmps]
row[i] += phi_P
matrix.append(row)
return matrix
def dlnfugacities_dns(self):
r'''Method to calculate and return the mole number derivative of the
log of fugacities of the components in the phase.
.. math::
\frac{\partial \ln f_i}{\partial n_j} = \frac{1}{f_i}
\frac{\partial f_i}{\partial n_j}
Returns
-------
dlnfugacities_dns : list[list[float]]
Mole number derivatives of the log of fugacities of all components
in the phase, [log(Pa)/mol]
Notes
-----
'''
zs, cmps = self.zs, range(self.N)
fugacities = self.fugacities()
dlnfugacities_dns = [list(i) for i in self.dfugacities_dns()]
fugacities_inv = [1.0/fi for fi in fugacities]
for i in cmps:
r = dlnfugacities_dns[i]
for j in cmps:
r[j]*= fugacities_inv[i]
return dlnfugacities_dns
def dlnfugacities_dzs(self):
r'''Method to calculate and return the mole fraction derivative of the
log of fugacities of the components in the phase.
.. math::
\frac{\partial \ln f_i}{\partial z_j} = \frac{1}{f_i}
\frac{\partial f_i}{\partial z_j}
Returns
-------
dlnfugacities_dzs : list[list[float]]
Mole fraction derivatives of the log of fugacities of all components
in the phase, [log(Pa)]
Notes
-----
'''
zs, cmps = self.zs, range(self.N)
fugacities = self.fugacities()
dlnfugacities_dzs = [list(i) for i in self.dfugacities_dzs()]
fugacities_inv = [1.0/fi for fi in fugacities]
for i in cmps:
r = dlnfugacities_dzs[i]
for j in cmps:
r[j]*= fugacities_inv[i]
return dlnfugacities_dzs
def log_zs(self):
r'''Method to calculate and return the log of mole fractions specified.
These are used in calculating entropy and in many other formulas.
.. math::
\ln z_i
Returns
-------
log_zs : list[float]
Log of mole fractions, [-]
Notes
-----
'''
try:
return self._log_zs
except AttributeError:
pass
try:
self._log_zs = [log(zi) for zi in self.zs]
except ValueError:
self._log_zs = _log_zs = []
for zi in self.zs:
try:
_log_zs.append(log(zi))
except ValueError:
_log_zs.append(-690.7755278982137) # log(1e-300)
return self._log_zs
def V_iter(self, force=False):
r'''Method to calculate and return the volume of the phase in a way
suitable for a TV resolution to converge on the same pressure. This
often means the return value of this method is an mpmath `mpf`.
This dummy method simply returns the implemented V method.
Returns
-------
V : float or mpf
Molar volume, [m^3/mol]
Notes
-----
'''
return self.V()
def G(self):
r'''Method to calculate and return the Gibbs free energy of the phase.
.. math::
G = H - TS
Returns
-------
G : float
Gibbs free energy, [J/mol]
Notes
-----
'''
try:
return self._G
except AttributeError:
pass
G = self.H() - | |
[3393, 80.10075151],
[3394, 80.10445042],
[3394, 79.74884672],
[3396, 80.39176952],
[3397, 79.75273925],
[3398, 79.80364796],
[3398, 79.77673955],
[3399, 79.96147169],
[3401, 79.81509581],
[3402, 79.2488253],
[3402, 79.29367556],
[3403, 79.33729744],
[3405, 78.84174034],
[3406, 78.66886552],
[3407, 78.90415785],
[3407, 79.0215944],
[3409, 78.52220681],
[3410, 78.35466777],
[3411, 79.05167563],
[3411, 79.08194765],
[3412, 78.25791126],
[3414, 78.87148158],
[3415, 77.75834009],
[3415, 78.36108412],
[3416, 78.17041183],
[3418, 79.1857855],
[3419, 78.61018714],
[3420, 78.80534914],
[3420, 78.25723389],
[3421, 77.37628059],
[3423, 78.40534116],
[3424, 77.36122972],
[3424, 77.3710975],
[3425, 77.33776774],
[3427, 77.27279761],
[3428, 76.9392119],
[3429, 77.12644391],
[3429, 77.40309095],
[3431, 77.04725468],
[3432, 76.00030027],
[3433, 76.7135549],
[3433, 76.41920576],
[3434, 76.16943277],
[3436, 76.27259729],
[3437, 76.81895927],
[3437, 76.15380371],
[3438, 75.53200818],
[3440, 75.77416666],
[3441, 75.88039086],
[3442, 76.07201734],
[3442, 74.98287997],
[3443, 75.12764414],
[3445, 74.80373429],
[3446, 74.70056876],
[3446, 75.40658679],
[3447, 74.96624684],
[3449, 75.27221935],
[3450, 74.82028497],
[3451, 74.19246367],
[3451, 73.96032092],
[3452, 74.16682957],
[3454, 74.9240053],
[3455, 74.42470546],
[3455, 73.55285398],
[3456, 74.17574307],
[3458, 72.92726376],
[3459, 73.41975511],
[3460, 73.32805485],
[3460, 72.84579525],
[3461, 72.81208029],
[3463, 72.42976944],
[3464, 73.0795714],
[3464, 72.12997236],
[3465, 71.94642057],
[3467, 72.09872737],
[3468, 71.99211337],
[3469, 71.33869366],
[3469, 71.80386029],
[3470, 70.79336589],
[3472, 71.67670578],
[3473, 70.8827888],
[3474, 70.07514309],
[3474, 71.01048778],
[3475, 70.54699408],
[3477, 69.57941081],
[3478, 69.92401216],
[3478, 69.65876432],
[3479, 69.94440945],
[3481, 69.68860239],
[3482, 69.0561305],
[3483, 68.66080942],
[3483, 67.85457496],
[3484, 67.96395914],
[3486, 68.22064937],
[3487, 67.9444337],
[3487, 68.20902943],
[3488, 67.59228952],
[3489, 66.80767169],
[3491, 66.3572184],
[3492, 66.84686205],
[3492, 66.1549701],
[3493, 65.9788566],
[3495, 65.60594505],
[3496, 65.27407057],
[3497, 65.11461551],
[3497, 65.70523436],
[3498, 65.61234474],
[3500, 64.94171586],
[3501, 64.72196805],
[3502, 64.24591865],
[3502, 63.83491553],
[3503, 64.24736442],
[3505, 63.28964372],
[3506, 62.8385987],
[3506, 62.83798125],
[3507, 63.08602102],
[3508, 63.10014435],
[3510, 63.03745938],
[3511, 62.13955931],
[3511, 62.50803285],
[3512, 61.1593637],
[3513, 62.04079249],
[3515, 61.24272688],
[3516, 60.64974683],
[3516, 61.38670986],
[3517, 60.02405638],
[3518, 60.48783358],
[3520, 60.24445564],
[3521, 59.15045314],
[3521, 59.79385128],
[3522, 58.70447332],
[3524, 58.88799896],
[3525, 59.58988042],
[3526, 58.01146976],
[3526, 57.81691589],
[3527, 57.88871325],
[3529, 57.7269786],
[3530, 58.16333051],
[3531, 57.96225803],
[3531, 57.3111987],
[3532, 57.40856687],
[3534, 56.44646595],
[3535, 56.46265469],
[3535, 56.31927988],
[3536, 56.23791661],
[3537, 55.88042285],
[3539, 55.01980625],
[3540, 55.61083118],
[3540, 54.55119218],
[3541, 55.21360869],
[3542, 54.01438494],
[3544, 54.2736441],
[3545, 54.09764322],
[3545, 54.50863756],
[3546, 53.52333271],
[3547, 52.87751211],
[3549, 52.87519432],
[3550, 52.75129611],
[3550, 52.35592189],
[3551, 52.99042896],
[3552, 51.84448228],
[3554, 52.33306403],
[3555, 52.18053829],
[3555, 51.95829278],
[3556, 51.4400288],
[3557, 51.10887973],
[3559, 51.27979189],
[3560, 50.97019623],
[3561, 50.00289388],
[3561, 50.09342101],
[3562, 50.17990382],
[3564, 49.62375046],
[3565, 49.94653513],
[3566, 50.04049098],
[3566, 49.40176108],
[3567, 49.95061647],
[3568, 49.76533694],
[3570, 49.07004276],
[3571, 48.9365708],
[3571, 48.48090766],
[3572, 49.20351418],
[3573, 48.33505168],
[3575, 48.64812392],
[3576, 47.52916926],
[3576, 47.71539871],
[3577, 48.4537783],
[3578, 47.68627534],
[3580, 46.67489285],
[3581, 47.13918847],
[3581, 46.86848945],
[3582, 47.22938689],
[3583, 46.67807574],
[3585, 46.61604325],
[3586, 45.78756474],
[3586, 46.82031634],
[3587, 46.37569545],
[3588, 45.94853378],
[3589, 46.30407907],
[3591, 45.64909999],
[3592, 45.7016687],
[3592, 45.4126314],
[3593, 45.53011556],
[3594, 45.44852869],
[3596, 45.22070051],
[3597, 44.48586132],
[3597, 45.28417178],
[3598, 44.5176413],
[3599, 43.70141511],
[3601, 43.69966157],
[3602, 44.20024814],
[3602, 43.13660936],
[3603, 44.60508504],
[3604, 43.2063875],
[3605, 43.69034774],
[3607, 43.6561129],
[3608, 44.60196007],
[3608, 43.55328551],
[3609, 43.63926054],
[3610, 42.74741456],
[3612, 42.60058236],
[3613, 42.72540282],
[3613, 42.64739288],
[3614, 42.59743533],
[3615, 42.0024744],
[3616, 42.39481247],
[3618, 42.44744968],
[3619, 41.62954469],
[3619, 41.86823521],
[3620, 41.77847448],
[3621, 41.8996526],
[3623, 40.55472097],
[3624, 41.65212661],
[3624, 40.91097388],
[3625, 40.08077244],
[3626, 39.62750609],
[3627, 40.68738157],
[3629, 39.76251885],
[3630, 39.79055815],
[3630, 39.82385596],
[3631, 39.81486929],
[3632, 38.63853228],
[3634, 39.16468987],
[3635, 38.78663331],
[3635, 38.08779804],
[3636, 38.27628448],
[3637, 36.80284439],
[3638, 37.40287429],
[3640, 38.02065601],
[3641, 37.25869466],
[3641, 36.77999629],
[3642, 37.01112536],
[3643, 36.45597293],
[3644, 36.93591755],
[3646, 35.55406432],
[3646, 35.98907287],
[3647, 35.91198354],
[3648, 34.96898591],
[3649, 35.71059676],
[3651, 34.95286657],
[3652, 35.42477249],
[3652, 34.46347777],
[3653, 33.68613204],
[3654, 33.56939441],
[3655, 35.0532849],
[3657, 33.92022404],
[3658, 33.84954436],
[3658, 32.90212472],
[3659, 32.50711276],
[3660, 32.57543097],
[3661, 32.1333154],
[3663, 31.99120616],
[3664, 31.76130032],
[3664, 31.90916819],
[3665, 30.88823747],
[3666, 31.41290126],
[3667, 30.88487844],
[3669, 30.48995777],
[3670, 30.56408648],
[3670, 29.87209057],
[3671, 28.76869416],
[3672, 30.3332205],
[3673, 29.58544016],
[3675, 27.98217199],
[3675, 28.71235058],
[3676, 27.99744921],
[3677, 27.92111736],
[3678, 27.7006241],
[3679, 27.59774435],
[3681, 27.69898781],
[3681, 27.59238585],
[3682, 26.82530587],
[3683, 26.93011041],
[3684, 26.51656312],
[3685, 25.47822799],
[3687, 26.7076944],
[3687, 26.83395047],
[3688, 25.40703374],
[3689, 24.92858396],
[3690, 25.57227567],
[3691, 24.44576237],
[3693, 25.02260022],
[3694, 25.0343156],
[3694, 24.35168934],
[3695, 23.71521814],
[3696, 24.83934439],
[3697, 23.8819051],
[3699, 23.69765668],
[3700, 23.32458008],
[3700, 22.87960994],
[3701, 24.00058184],
[3702, 22.51068887],
[3703, 22.19091004],
[3705, 21.60172174],
[3706, 22.76525333],
[3706, 21.83112078],
[3707, 22.98902296],
[3708, 21.73093551],
[3709, 21.75372838],
[3710, 21.45225508],
[3712, 21.48800435],
[3712, 20.55368501],
[3713, 20.97110873],
[3714, 21.07622153],
[3715, 20.48719602],
[3716, 20.07226672],
[3718, 19.61574238],
[3718, 21.58565333],
[3719, 20.18490047],
[3720, 19.99494473],
[3721, 19.11881238],
[3722, 19.41821298],
[3724, 19.92271372],
[3725, 19.09172368],
[3725, 19.01321193],
[3726, 17.98318764],
[3727, 18.57421116],
[3728, 18.77489469],
[3729, 18.77967356],
[3731, 19.23397581],
[3731, 18.60187531],
[3732, 18.67067436],
[3733, 19.02625629],
[3734, 18.97290307],
[3735, 18.66775156],
[3737, 18.94479997],
[3738, 17.70285096],
[3738, 18.01825792],
[3739, 17.90705001],
[3740, 16.98627563],
[3741, 17.76178566],
[3742, 18.75158871],
[3744, 17.95243963],
[3744, 17.77321675],
[3745, 18.32081755],
[3746, 18.21800445],
[3747, 17.95116315],
[3748, 17.12022336],
[3749, 17.2412566],
[3751, 17.27361788],
[3751, 17.71180459],
[3752, 17.10644583],
[3753, 17.1165269],
[3754, 16.27767823],
[3755, 16.38002234],
[3756, 16.74448322],
[3758, 16.73111659],
[3758, 16.76811212],
[3759, 16.20930461],
[3760, 16.4338053],
[3761, 17.40681909],
[3762, 17.81992955],
[3764, 17.16566348],
[3765, 17.58325458],
[3765, 17.85061773],
[3766, 16.57451193],
[3767, 16.86825163],
[3768, 17.29749312],
[3769, 16.28788872],
[3771, 16.91339678],
[3771, 16.43776349],
[3772, 17.1464364],
[3773, 16.76932165],
[3774, 16.89941231],
[3775, 16.48398543],
[3776, 17.33985407],
[3778, 15.87700727],
[3778, 15.94023713],
[3779, 17.23467878],
[3780, 17.4507685],
[3781, 16.61874052],
[3782, 16.63394824],
[3783, 16.53181308],
[3784, 17.73480115],
[3786, 17.23783621],
[3786, 17.34962391],
[3787, 17.06857367],
[3788, 17.1038818],
[3789, 17.59130907],
[3790, 17.81402222],
[3791, 16.84552355],
[3793, 17.3728943],
[3793, 17.21662119],
[3794, 17.79542366],
[3795, 18.11417815],
[3796, 16.86020571],
[3797, 17.72113429],
[3798, 17.51943249],
[3800, 17.21356302],
[3800, 17.92014663],
[3801, 18.32580152],
[3802, 17.4817213],
[3803, 17.65528376],
[3804, 17.60190131],
[3805, 16.582116],
[3806, 17.43090277],
[3807, 16.63836584],
[3808, 17.3643345],
[3809, 17.41756604],
[3810, 17.93731788],
[3811, 17.17832179],
[3812, 16.48281137],
[3813, 17.02678087],
[3815, 17.65343413],
[3815, 17.10338592],
[3816, 17.70924826],
[3817, 17.89370464],
[3818, 18.01138309],
[3819, 17.76432756],
[3820, 17.82494416],
[3821, 18.09784513],
[3823, 17.22427911],
[3823, 16.63646305],
[3824, 17.48327991],
[3825, 17.58172451],
[3826, 17.8439615],
[3827, 18.37200513],
[3828, 17.88564265],
[3829, 18.08361745],
[3830, 17.62548923],
[3831, 17.60822618],
[3832, 17.63512135],
[3833, 17.61101609],
[3834, 18.42700417],
[3835, 17.2890354],
[3836, 17.08105976],
[3837, 17.11597859],
[3838, 17.76308739],
[3839, 18.11310265],
[3840, 17.93927982],
[3841, 18.04094043],
[3842, 17.49669091],
[3843, 17.36704546],
[3844, 18.38078902],
[3845, 18.14502538],
[3846, 18.32064302],
[3847, 17.61325609],
[3848, 17.31227665],
[3849, 17.2758437],
[3850, 17.52970881],
[3851, 18.61328697],
[3852, 17.21611148],
[3853, 18.37929909],
[3854, 17.03165877],
[3855, 17.1977765],
[3856, 18.68766959],
[3857, 17.55741443],
[3858, 17.55902932],
[3859, 17.69425155],
[3860, 18.25423328],
[3861, 18.38273337],
[3863, 16.90640852],
[3863, 17.12662152],
[3864, 17.88606878],
[3865, 16.92263876],
[3866, 17.99783285],
[3867, 17.36752277],
[3868, 17.22952843],
[3869, 17.2166966],
[3870, 17.58460591],
[3871, 17.09075612],
[3872, 17.09686161],
[3873, 17.82855751],
[3874, 17.92676472],
[3875, 17.19895797],
[3876, 16.42488351],
[3877, 17.20272696],
[3878, 17.76866033],
[3879, 16.54184784],
[3880, 17.10711302],
[3881, 16.17083032],
[3882, 17.07555344],
[3883, 18.58059724],
[3884, 18.15787158],
[3885, 18.13682846],
[3886, 17.04335907],
[3887, 17.67001209],
[3888, 16.13791955],
[3889, 16.47029351],
[3890, 16.94550301],
[3891, 16.84644965],
[3892, 16.57517706],
[3893, 17.58521847],
[3894, 16.060953],
[3895, 17.51320394],
[3896, 18.28909937],
[3897, 17.74357226],
[3898, 17.62594831],
[3899, 17.08900098],
[3900, 16.5967001],
[3901, 16.5984533],
[3902, 17.20239803],
[3903, 16.5775758],
[3904, 16.67775355],
[3905, 16.25009392],
[3906, 16.66095195],
[3907, 16.75331994],
[3908, 16.15636432],
[3909, 17.57227222],
[3910, 17.19136219],
[3911, 17.40434134],
[3912, 16.4684595],
[3913, 15.41843549],
[3914, 15.89886117],
[3915, 15.44515584],
[3916, 15.88030576],
[3917, 17.2678042],
[3918, 16.74730185],
[3919, 16.80818415],
[3920, 16.74866059],
[3921, 16.86177245],
[3922, 16.83409188],
[3923, 16.56898877],
[3924, 16.83951259],
[3925, 16.59868021],
[3926, 16.23178431],
[3927, 15.2909303],
[3928, 16.32448473],
[3929, 16.56932032],
[3930, 16.82010314],
[3931, 16.10976749],
[3932, 15.60649708],
[3933, 15.83392327],
[3934, 15.69618528],
[3935, 15.61663923],
[3936, 14.99168727],
[3937, 15.55394449],
[3938, 16.47032651],
[3939, 15.13392984],
[3940, 17.16246477],
[3941, 16.07770893],
[3942, 16.44991532],
[3943, 16.0482158],
[3944, 15.33583335],
[3945, 15.25748862],
[3946, 15.24587614],
[3947, 15.83265868],
[3948, 15.82614364],
[3949, 15.18838107],
[3950, 15.7433733],
[3951, 15.69190246],
[3952, 16.25947403],
[3953, 14.54133291],
[3954, 15.34363512],
[3955, 15.89114124],
[3956, 14.87102477],
[3957, 14.27797995],
[3958, 14.46394882],
[3959, 15.73512943],
[3960, 14.9983306],
[3961, 15.42948689],
[3962, 15.72435571],
[3963, 14.62835572],
[3964, 14.73070059],
[3965, 16.19477796],
[3966, 14.16133282],
[3967, 15.147421],
[3968, 14.80590317],
[3969, 15.17193746],
[3970, 14.17912097],
[3971, 14.01850157],
[3972, 14.17840643],
[3973, 13.89139839],
[3974, 14.66850475],
[3975, 14.4629228],
[3976, 14.35186674],
[3977, 13.67826976],
[3978, 13.90885999],
[3979, 13.75234134],
[3980, 14.87072829],
[3981, 14.85228323],
[3982, 14.51467681],
[3983, 13.98441275],
[3984, 14.06927972],
[3985, 15.28957234],
[3986, 14.70719772],
[3987, 13.81552024],
[3988, 14.13436071],
[3989, 14.05085857],
[3990, 13.37758274],
[3991, 12.78665249],
[3992, 13.19896886],
[3993, 12.99716],
[3994, 13.60334263],
[3995, 13.43799497],
[3996, 14.26876624],
[3997, 13.10772999],
[3998, 11.80488694],
[3999, 13.00488871],
[4000, 13.09360649],
[4001, 13.5897509],
[4002, 12.35124708],
[4003, 11.97994307],
[4004, 11.75243337],
[4005, 11.8241933],
[4006, 13.37785631],
[4007, 12.24056535],
[4008, 10.73210867],
[4009, 11.57986049],
[4010, 11.89480357],
[4011, 12.55699049],
[4012, 11.80283396],
[4013, 10.91609377],
[4014, 12.38302381],
[4015, 11.54835433],
[4016, 12.46284918],
[4017, 11.78892429],
[4018, 11.89424823],
[4019, 11.29582404],
[4020, 10.71563274],
[4021, 12.6356735],
[4022, 11.29591596],
[4023, 11.04827715],
[4024, 10.86469357],
[4025, 10.64144329],
[4026, 10.91119667],
[4027, 10.12278603],
[4028, 10.00664076],
[4029, 10.34620057],
[4030, 11.20259983],
[4031, 10.31059972],
| |
<reponame>noisyoscillator/qiskit-aqua
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Line search with Gaussian-smoothed samples on a sphere."""
from typing import Dict, Optional, Tuple, List, Callable
import logging
import numpy as np
from qiskit.aqua import aqua_globals
from .optimizer import Optimizer
logger = logging.getLogger(__name__)
class GSLS(Optimizer):
"""Gaussian-smoothed Line Search.
An implementation of the line search algorithm described in
https://arxiv.org/pdf/1905.01332.pdf, using gradient approximation
based on Gaussian-smoothed samples on a sphere.
"""
_OPTIONS = ['max_iter', 'max_eval', 'disp', 'sampling_radius',
'sample_size_factor', 'initial_step_size', 'min_step_size',
'step_size_multiplier', 'armijo_parameter',
'min_gradient_norm', 'max_failed_rejection_sampling']
# pylint:disable=unused-argument
def __init__(self,
max_iter: int = 10000,
max_eval: int = 10000,
disp: bool = False,
sampling_radius: float = 1.0e-6,
sample_size_factor: int = 1,
initial_step_size: float = 1.0e-2,
min_step_size: float = 1.0e-10,
step_size_multiplier: float = 0.4,
armijo_parameter: float = 1.0e-1,
min_gradient_norm: float = 1e-8,
max_failed_rejection_sampling: int = 50) -> None:
"""
Args:
max_iter: Maximum number of iterations.
max_eval: Maximum number of evaluations.
disp: Set to True to display convergence messages.
sampling_radius: Sampling radius to determine gradient estimate.
sample_size_factor: The size of the sample set at each iteration is this number
multiplied by the dimension of the problem, rounded to the nearest integer.
initial_step_size: Initial step size for the descent algorithm.
min_step_size: Minimum step size for the descent algorithm.
step_size_multiplier: Step size reduction after unsuccessful steps, in the
interval (0, 1).
armijo_parameter: Armijo parameter for sufficient decrease criterion, in the
interval (0, 1).
min_gradient_norm: If the gradient norm is below this threshold, the algorithm stops.
max_failed_rejection_sampling: Maximum number of attempts to sample points within
bounds.
"""
super().__init__()
for k, v in locals().items():
if k in self._OPTIONS:
self._options[k] = v
def get_support_level(self) -> Dict[str, int]:
"""Return support level dictionary.
Returns:
A dictionary containing the support levels for different options.
"""
return {
'gradient': Optimizer.SupportLevel.ignored,
'bounds': Optimizer.SupportLevel.supported,
'initial_point': Optimizer.SupportLevel.required
}
def optimize(self, num_vars: int,
objective_function: Callable,
gradient_function: Optional[Callable] = None,
variable_bounds: Optional[List[Tuple[float, float]]] = None,
initial_point: Optional[np.ndarray] = None) -> Tuple[np.ndarray, float, int]:
super().optimize(num_vars, objective_function, gradient_function,
variable_bounds, initial_point)
if initial_point is None:
initial_point = aqua_globals.random.normal(size=num_vars)
else:
initial_point = np.array(initial_point)
if variable_bounds is None:
var_lb = np.array([-np.inf] * num_vars)
var_ub = np.array([np.inf] * num_vars)
else:
var_lb = np.array([l for (l, _) in variable_bounds])
var_ub = np.array([u for (_, u) in variable_bounds])
x, x_value, n_evals, _ = self.ls_optimize(
num_vars, objective_function, initial_point, var_lb, var_ub
)
return x, x_value, n_evals
def ls_optimize(self, n: int, obj_fun: Callable, initial_point: np.ndarray, var_lb: np.ndarray,
var_ub: np.ndarray) -> Tuple[np.ndarray, float, int, float]:
"""Run the line search optimization.
Args:
n: Dimension of the problem.
obj_fun: Objective function.
initial_point: Initial point.
var_lb: Vector of lower bounds on the decision variables. Vector elements can be -np.inf
if the corresponding variable is unbounded from below.
var_ub: Vector of upper bounds on the decision variables. Vector elements can be np.inf
if the corresponding variable is unbounded from below.
Returns:
Final iterate as a vector, corresponding objective function value,
number of evaluations, and norm of the gradient estimate.
Raises:
ValueError: If the number of dimensions mismatches the size of the initial point or
the length of the lower or upper bound.
"""
if len(initial_point) != n:
raise ValueError('Size of the initial point mismatches the number of dimensions.')
if len(var_lb) != n:
raise ValueError('Length of the lower bound mismatches the number of dimensions.')
if len(var_ub) != n:
raise ValueError('Length of the upper bound mismatches the number of dimensions.')
# Initialize counters and data
iter_count = 0
n_evals = 0
prev_iter_successful = True
prev_directions, prev_sample_set_x, prev_sample_set_y = None, None, None
consecutive_fail_iter = 0
alpha = self._options['initial_step_size']
grad_norm = np.inf
sample_set_size = int(round(self._options['sample_size_factor'] * n))
# Initial point
x = initial_point
x_value = obj_fun(x)
n_evals += 1
while iter_count < self._options['max_iter'] \
and n_evals < self._options['max_eval']:
# Determine set of sample points
directions, sample_set_x = self.sample_set(n, x, var_lb, var_ub, sample_set_size)
if n_evals + len(sample_set_x) + 1 >= self._options['max_eval']:
# The evaluation budget is too small to allow for
# another full iteration; we therefore exit now
break
sample_set_y = np.array([obj_fun(point) for point in sample_set_x])
n_evals += len(sample_set_x)
# Expand sample set if we could not improve
if not prev_iter_successful:
directions = np.vstack((prev_directions, directions))
sample_set_x = np.vstack((prev_sample_set_x, sample_set_x))
sample_set_y = np.hstack((prev_sample_set_y, sample_set_y))
# Find gradient approximation and candidate point
grad = self.gradient_approximation(n, x, x_value, directions, sample_set_x,
sample_set_y)
grad_norm = np.linalg.norm(grad)
new_x = np.clip(x - alpha * grad, var_lb, var_ub)
new_x_value = obj_fun(new_x)
n_evals += 1
# Print information
if self._options['disp']:
print('Iter {:d}'.format(iter_count))
print('Point {} obj {}'.format(x, x_value))
print('Gradient {}'.format(grad))
print('Grad norm {} new_x_value {} step_size {}'.format(grad_norm, new_x_value,
alpha))
print('Direction {}'.format(directions))
# Test Armijo condition for sufficient decrease
if new_x_value <= x_value - self._options['armijo_parameter'] * alpha * grad_norm:
# Accept point
x, x_value = new_x, new_x_value
alpha /= 2 * self._options['step_size_multiplier']
prev_iter_successful = True
consecutive_fail_iter = 0
# Reset sample set
prev_directions = None
prev_sample_set_x = None
prev_sample_set_y = None
else:
# Do not accept point
alpha *= self._options['step_size_multiplier']
prev_iter_successful = False
consecutive_fail_iter += 1
# Store sample set to enlarge it
prev_directions = directions
prev_sample_set_x, prev_sample_set_y = sample_set_x, sample_set_y
iter_count += 1
# Check termination criterion
if grad_norm <= self._options['min_gradient_norm'] \
or alpha <= self._options['min_step_size']:
break
return x, x_value, n_evals, grad_norm
def sample_points(self, n: int, x: np.ndarray, num_points: int
) -> Tuple[np.ndarray, np.ndarray]:
"""Sample ``num_points`` points around ``x`` on the ``n``-sphere of specified radius.
The radius of the sphere is ``self._options['sampling_radius']``.
Args:
n: Dimension of the problem.
x: Point around which the sample set is constructed.
num_points: Number of points in the sample set.
Returns:
A tuple containing the sampling points and the directions.
"""
normal_samples = aqua_globals.random.normal(size=(num_points, n))
row_norms = np.linalg.norm(normal_samples, axis=1, keepdims=True)
directions = normal_samples / row_norms
points = x + self._options['sampling_radius'] * directions
return points, directions
def sample_set(self, n: int, x: np.ndarray, var_lb: np.ndarray, var_ub: np.ndarray,
num_points: int) -> Tuple[np.ndarray, np.ndarray]:
"""Construct sample set of given size.
Args:
n: Dimension of the problem.
x: Point around which the sample set is constructed.
var_lb: Vector of lower bounds on the decision variables. Vector elements can be -np.inf
if the corresponding variable is unbounded from below.
var_ub: Vector of lower bounds on the decision variables. Vector elements can be np.inf
if the corresponding variable is unbounded from above.
num_points: Number of points in the sample set.
Returns:
Matrices of (unit-norm) sample directions and sample points, one per row.
Both matrices are 2D arrays of floats.
Raises:
RuntimeError: If not enough samples could be generated within the bounds.
"""
# Generate points uniformly on the sphere
points, directions = self.sample_points(n, x, num_points)
# Check bounds
if (points >= var_lb).all() and (points <= var_ub).all():
# If all points are within bounds, return them
return directions, (x + self._options['sampling_radius'] * directions)
else:
# Otherwise we perform rejection sampling until we have
# enough points that satisfy the bounds
indices = np.where((points >= var_lb).all(axis=1) & (points <= var_ub).all(axis=1))[0]
accepted = directions[indices]
num_trials = 0
while len(accepted) < num_points \
and num_trials < self._options['max_failed_rejection_sampling']:
# Generate points uniformly on the sphere
points, directions = self.sample_points(n, x, num_points)
indices = np.where((points >= var_lb).all(axis=1) &
(points <= var_ub).all(axis=1))[0]
accepted = np.vstack((accepted, directions[indices]))
num_trials += 1
# When we are at a corner point, the expected fraction of acceptable points may be
# exponential small in the dimension of the problem. Thus, if we keep failing and
# do not have enough points by now, we switch to a different method that guarantees
# finding enough points, but they may not be uniformly distributed.
if len(accepted) < num_points:
points, directions = self.sample_points(n, x, num_points)
to_be_flipped = | |
<gh_stars>0
# Copyright 2018 Brocade Communications Systems LLC. 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.
# You may also 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.
"""
:mod:`pyfos_brocade_fibrechannel_switch` - PyFOS module to provide REST \
support for an FC switch.
*********************************************************************************************************
The :mod:`pyfos_brocade_fibrechannel_switch` provides a REST support for \
an FC switch.
"""
from pyfos import pyfos_rest_util
from pyfos.pyfos_type import pyfos_type
import pyfos.pyfos_version as version
UNDEFINED = 0
ENABLE = 2
DISABLE = 3
TESTING = 7
class fibrechannel_switch(pyfos_rest_util.rest_object):
"""Class of FC Switch
Important Class Members:
+-------------------------------+-------------------------------+------------------------------------------------------+
| Attribute Name | Description |Frequently Used Methods |
+===============================+===============================+======================================================+
| name | The WWN name of switch. |:meth:`set_name` |
| | |:meth:`peek_name` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| domain-id | The domain ID of the switch. |:meth:`peek_domain_id` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| user-friendly-name | The user friendly name of |:meth:`set_user_friendly_name` |
| | the switch. |:meth:`peek_user_friendly_name` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| fcid | The FCID of the switch. |:meth:`peek_fcid` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| vf-id | The VFID of the switch. |:meth:`peek_vf_id` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| principal | Whether principal or not. |:meth:`peek_principal` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| enabled-state | Enabled or disabled state. |:meth:`set_enabled_state` |
| | |:meth:`peek_enabled_state` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| up-time | The uptime of the switch. |:meth:`peek_up_time` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| model | The model of the switch. |:meth:`peek_model` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| firmware-version |The FOS version of the switch. |:meth:`peek_firmware_version` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| ip-address/ip-address | A list of IPv4/IPv6 |:meth:`set_ip_address_ip_address` |
| | addresses. |:meth:`peek_ip_address_ip_address` |
| | | |
+-------------------------------+-------------------------------+------------------------------------------------------+
| ip-static-gateway-list/ | IPv4 and IPv6 static gateway |:meth:`set_ip_static_gateway_list_ip_static_gateway` |
| ip-static-gateway | addresses for the switch IP. |:meth:`peek_ip_static_gateway_list_ip_static_gateway` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| subnet-mask | IPv4 subnet mask of the |:meth:`set_subnet_mask` |
| | switch IP network. |:meth:`peek_subnet_mask` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| domain-name |The DNS domain name of switch. |:meth:`set_domain_name` |
| | |:meth:`peek_domain_name` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| dns-servers/dns-server | A list of addresses of DNS |:meth:`set_dns_servers_dns_server` |
| | servers containing the map |:meth:`peek_dns_servers_dns_server` |
| | of switch domain names to | |
| | IPv4/IPv6 addresses. | |
+-------------------------------+-------------------------------+------------------------------------------------------+
| fabric-user-friendly-name | The user friendly name of |:meth:`set_fabric_user_friendly_name` |
| | the fabric. |:meth:`peek_fabric_user_friendly_name` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| ag-mode | Enables or disables AG mode. |:meth:`set_ag_mode` |
| | |:meth:`peek_ag_mode` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| banner | The login banner message. |:meth:`set_banner` |
| | |:meth:`peek_banner` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| is-enabled-state | Enabled or disabled state. |:meth:`set_enabled_state` |
| | |:meth:`peek_enabled_state` |
+-------------------------------+-------------------------------+------------------------------------------------------+
| operational-status | Current state of the switch. |:meth:`peek_operational_status` |
+-------------------------------+-------------------------------+------------------------------------------------------+
.. method:: get(session, name=None)
Returns a :class:`fibrechannel_switch` object or a list of
objects with attributes gathered from the switch. \
If an optional name is given, returns either an object
matching the WWN of the switch or an empty object.
Each object can be printed using :func:`pyfos_util.response_print`,
and individual attributes can be accessed through peek methods.
:param session: The session handler returned by
:func:`pyfos_auth.login`.
:rtype: A :class:`fibrechannel_switch` object if there
is only one switch within the fabric or a list of
objects if there is more than one switch.
.. method:: patch(session)
Applies configurable attribute(s) within the object to the switch.
*Below Is an Example Using Individual Sets:*
.. code-block:: python
# initialize the switch object
switch = pyfos_switch.fibrechannel_switch()
# set the enabled-state attribute to enable the switch
switch.set_enabled_state(pyfos_switch.ENABLE)
# execute HTTP patch command to apply the object to the
# switch connected through session
switch.patch(session)
*Below Is an Example of Combining Object \
Initialization and Attribute Sets:*
.. code-block:: python
# initialize the switch object and
# set the enable-state attribute
switch = pyfos_switch.fibrechannel_switch(
{"enabled-state" : pyfos_switch.ENABLE})
# execute HTTP patch command to apply the object to the
# switch connected through session
switch.patch(session)
:param session: The session handler returned by
:func:`pyfos_auth.login`.
:rtype: A dictionary of errors or success information.
*Attribute Methods*
.. method:: set_name(name)
Sets the name in the object.
:param name: The WWN of the switch to be set within the object.
:rtype: None or a dictionary of error information.
.. method:: peek_name()
Reads the name in the object.
:rtype: None or the WWN of the switch.
.. method:: set_domain_id(did)
Sets the domain ID in the object.
:param name: The DID of the switch to be set within the object.
:rtype: None or a dictionary of error information.
.. method:: peek_domain_id()
Reads the domain ID in the object.
:rtype: None or the domain ID of the switch.
.. method:: set_user_friendly_name(name)
Sets the user friendly name in the object.
:rtype: None or a dictionary of error information.
.. method:: peek_user_friendly_name()
Reads the user friendly name in the object.
:rtype: None or the user friendly name of the switch.
.. method:: peek_fcid()
Reads the FCID in the object.
:rtype: None or the FCID of the switch.
.. method:: peek_vf_id()
Reads the VFID in the object.
:rtype: None or the VFID of the switch.
.. method:: peek_principal()
Reads the boolean value to determine if the switch is
the principal switch or not in the object.
:rtype: None, True, or False.
.. method:: set_enabled_state(newstate)
Sets the enabled state to :data:`ENABLE` or
:data:`DISABLE` in the object.
:rtype: None or a dictionary of error information.
.. method:: peek_enabled_state()
Reads the enabled state of the switch in the object.
:rtype: None or an enabled state of :data:`ENABLE`,
:data:`DISABLE`, :data:`UNDEFINED`, or :data:`TESTING`.
.. method:: peek_up_time()
Reads the uptime of the switch in the object.
:rtype: None or the uptime of the switch.
.. method:: peek_model()
Reads the model of the switch in the object.
:rtype: None or the model of the switch.
.. method:: peek_firmware_version()
Reads the FOS firmware version of the switch in the object.
:rtype: None or the FOS firmware version of the switch.
.. method:: set_ip_address_ip_address(ipaddress)
Sets using a new list of IP addresses.
:rtype: None or a dictionary of error information.
.. method:: peek_ip_address_ip_address()
Reads a list of IP addresses of the switch in the object.
:rtype: None or a list of IP addresses.
.. method:: set_ip_static_gateway_list_ip_static_gateway \
(ip-static-gateway-list)
Sets the new IPv4/IPv6 static gateway addresses for the switch.
:rtype: None or a dictionary of error information.
.. method:: peek_ip_static_gateway_list_ip_static_gateway()
Reads the static gateway IP addresses set for the switch.
:rtype: None or a list of IPv4 and IPv6 static gateway addresses.
.. method:: set_subnet_mask(subnet_mask)
Sets the new subnet mask of the switch.
:rtype: None or a dictionary of error information.
.. method:: peek_subnet_mask()
Reads the subnet mask of the switch.
:rtype: None or the subnet mask.
.. method:: set_domain_name(domain_name)
Sets the domain name of the switch in DNS.
:rtype: None or a dictionary of error information.
.. method:: peek_domain_name()
Reads the DNS domain name of the switch in the object.
:rtype: None or the domain name.
.. method:: set_dns_servers_dns_server(dns-servers)
Sets the DNS servers for the switch with their \
IPv4/IPv6 addresses.
:rtype: None or a dictionary of error information.
.. method:: peek_dns_servers_dns_server()
Reads the IP address of the DNS servers set for the switch.
:rtype: None or a list of IP addresses.
.. method:: set_fabric_user_friendly_name(name)
Sets the fabric user friendly name in the object.
:rtype: None or a dictionary of error information.
.. method:: peek_fabric_user_friendly_name()
Reads the fabric user friendly name in the object.
:rtype: None or the fabric user friendly name of the switch.
.. method:: set_ag_mode(value)
Sets the AG mode enabled state of the switch.
:rtype: None or a dictionary of error information.
.. method:: peek_ag_mode()
Reads the Access Gateway mode in the object.
:rtype: None or the AG mode of the switch.
.. method:: set_banner(value)
Sets the banner message displayed during login.
:rtype: None or a dictionary of error | |
<reponame>ShenhanQian/SpeechDrivesTemplates
import os
from datetime import datetime
import logging
import time
from abc import abstractmethod
import matplotlib as mpl
import numpy as np
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from core.datasets import get_dataset
from core.networks import get_model
from core.utils.video_processing import VideoWriter
class Trainer(object):
def __init__(self, cfg) -> None:
self.cfg = cfg
self.model = None
self.optimizers = {}
self.schedulers = {}
self.train_dataloader = None
self.test_dataloader = None
torch.cuda.set_device(self.get_rank())
def get_rank(self):
if torch.distributed.is_initialized():
return torch.distributed.get_rank()
else:
return 0
def get_world_size(self):
if torch.distributed.is_initialized():
return torch.distributed.get_world_size()
else:
return 1
def is_master_process(self):
if not torch.distributed.is_initialized():
return True
else:
return not self.get_rank()
def setup_logger(self, base_path, exp_name):
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.INFO)
logFormatter = logging.Formatter("%(asctime)s [%(levelname)-0.5s] %(message)s")
log_path = "{0}/{1}.log".format(base_path, exp_name)
fileHandler = logging.FileHandler(log_path)
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
logging.info('log path: %s' % log_path)
def setup_dataset(self, cfg, split, demo_input=None):
if self.is_master_process():
print('Setting up dataset...')
if split == 'train':
self.train_dataset = get_dataset(cfg.DATASET.NAME)(self.cfg.DATASET.ROOT_DIR, self.cfg.DATASET.SPEAKER, 'train', self.cfg)
if self.cfg.SYS.DISTRIBUTED:
self.train_sampler = torch.utils.data.distributed.DistributedSampler(self.train_dataset)
else:
self.train_sampler = None
self.train_dataloader = DataLoader(self.train_dataset,
batch_size=self.cfg.TRAIN.BATCH_SIZE // self.get_world_size(),
shuffle=(self.train_sampler is None),
num_workers=self.cfg.SYS.NUM_WORKERS // self.get_world_size(),
sampler=self.train_sampler, drop_last=True)
self.num_train_samples = len(self.train_dataset)
self.num_train_batches = len(self.train_dataloader)
self.result_saving_interval_train = self.num_train_batches // self.cfg.TRAIN.NUM_RESULT_SAMPLE \
if self.num_train_batches // self.cfg.TRAIN.NUM_RESULT_SAMPLE > 0 else 1
if self.is_master_process():
print('num_train_samples: %d' % self.num_train_samples)
if self.cfg.TRAIN.VALIDATE:
self.test_dataset = get_dataset(cfg.DATASET.NAME)(self.cfg.DATASET.ROOT_DIR, self.cfg.DATASET.SPEAKER, 'val', self.cfg)
if self.cfg.SYS.DISTRIBUTED:
self.val_sampler = torch.utils.data.distributed.DistributedSampler(self.test_dataset, shuffle=False)
else:
self.val_sampler = None
self.test_dataloader = DataLoader(self.test_dataset,
batch_size=self.cfg.TEST.BATCH_SIZE // self.get_world_size(),
shuffle=False,
num_workers=self.cfg.SYS.NUM_WORKERS // self.get_world_size(),
sampler=self.val_sampler)
self.num_test_samples = len(self.test_dataset)
self.num_test_batches = len(self.test_dataloader)
self.result_saving_interval_test = self.num_test_batches // self.cfg.TEST.NUM_RESULT_SAMPLE \
if self.num_test_batches // self.cfg.TEST.NUM_RESULT_SAMPLE > 0 else 1
if self.is_master_process():
print('num_val_samples: %d' % self.num_test_samples)
elif split == 'test':
self.num_train_samples = None
self.test_dataset = get_dataset(cfg.DATASET.NAME)(self.cfg.DATASET.ROOT_DIR, self.cfg.DATASET.SPEAKER, 'val', self.cfg)
if self.cfg.SYS.DISTRIBUTED:
self.test_sampler = torch.utils.data.distributed.DistributedSampler(self.test_dataset, shuffle=False)
else:
self.test_sampler = None
self.test_dataloader = DataLoader(self.test_dataset,
batch_size=self.cfg.TEST.BATCH_SIZE // self.get_world_size(),
shuffle=False,
num_workers=self.cfg.SYS.NUM_WORKERS // self.get_world_size(),
sampler=self.test_sampler, drop_last=False)
self.num_test_samples = len(self.test_dataset)
self.num_test_batches = len(self.test_dataloader)
self.result_saving_interval_test = self.num_test_batches // self.cfg.TEST.NUM_RESULT_SAMPLE \
if self.num_test_batches // self.cfg.TEST.NUM_RESULT_SAMPLE > 0 else 1
if self.is_master_process():
print('num_test_samples: %d' % self.num_test_samples)
elif split == 'demo':
self.num_train_samples = None
self.test_dataset = get_dataset(cfg.DATASET.NAME)(self.cfg.DATASET.ROOT_DIR, self.cfg.DATASET.SPEAKER, 'demo', self.cfg, demo_input=demo_input)
if self.cfg.SYS.DISTRIBUTED:
self.test_sampler = torch.utils.data.distributed.DistributedSampler(self.test_dataset, shuffle=False)
else:
self.test_sampler = None
self.test_dataloader = DataLoader(self.test_dataset,
batch_size=1,
shuffle=False,
num_workers=self.cfg.SYS.NUM_WORKERS // self.get_world_size(),
sampler=self.test_sampler)
self.num_test_samples = len(self.test_dataset)
self.num_test_batches = len(self.test_dataloader)
self.result_saving_interval_test = self.num_test_batches // self.cfg.TEST.NUM_RESULT_SAMPLE \
if self.num_test_batches // self.cfg.TEST.NUM_RESULT_SAMPLE > 0 else 1
if self.is_master_process():
print('num_test_samples: %d' % self.num_test_samples)
else:
raise Exception('Unknown data split.')
@abstractmethod
def setup_model(self, cfg, state_dict=None):
pass
def setup_optimizer(self, checkpoint=None, last_epoch=-1):
learning_rate = self.cfg.TRAIN.LR
self.optimizers['optimizer'] = torch.optim.Adam(self.model.parameters(), lr=learning_rate)
if checkpoint is not None:
self.optimizers['optimizer'].load_state_dict(checkpoint['optimizer_state_dict'])
if self.cfg.TRAIN.LR_SCHEDULER:
self.schedulers['scheduler'] = torch.optim.lr_scheduler.MultiStepLR(
self.optimizers['optimizer'], [90, 98], gamma=0.1, last_epoch=last_epoch)
def setup_experiment(self, is_training, exp_tag, resume_from=None, checkpoint=None, demo_input=None):
map_location = {'cuda:0' : 'cuda:%d' % self.get_rank()}
if self.is_master_process():
print('Setting up base directory...')
dt = str(datetime.now()).replace('.', '-').replace(':', '-').replace(' ', '_')
exp_tag = '_'.join([dt, exp_tag])
if is_training:
self.setup_dataset(self.cfg, 'train')
if resume_from is not None:
assert resume_from.split('.')[-1]=='pth', 'file type not supported: %s' % resume_from
assert os.path.exists(resume_from), 'file not exists: %s' % resume_from
if self.is_master_process():
print('Resuming from checkpoint: %s' % resume_from)
checkpoint = torch.load(resume_from, map_location=map_location)
epoch = checkpoint['epoch']
global_step = checkpoint['step']
base_path = os.path.split(resume_from)[0]
self.setup_model(self.cfg, state_dict=checkpoint['model_state_dict'])
self.setup_optimizer(checkpoint=checkpoint, last_epoch=epoch)
else:
epoch = 0
global_step = 0
base_path = os.path.join(self.cfg.SYS.OUTPUT_DIR, exp_tag)
if self.is_master_process():
os.makedirs(base_path)
if self.cfg.TRAIN.PRETRAIN_FROM is not None:
pretrain_from = self.cfg.TRAIN.PRETRAIN_FROM
assert pretrain_from.split('.')[-1]=='pth', 'file type not supported: %s' % pretrain_from
assert os.path.exists(pretrain_from), 'file not exists: %s' % pretrain_from
if self.is_master_process():
print('Loading from pretrained model: %s' % pretrain_from)
checkpoint = torch.load(pretrain_from, map_location=map_location)
self.setup_model(self.cfg, state_dict=checkpoint['model_state_dict'])
else:
self.setup_model(self.cfg)
self.setup_optimizer()
return base_path, epoch, global_step
else:
if demo_input is None:
self.setup_dataset(self.cfg, 'test')
else:
self.setup_dataset(self.cfg, 'demo', demo_input=demo_input)
base_path = os.path.join(self.cfg.SYS.OUTPUT_DIR, exp_tag)
if self.is_master_process():
os.makedirs(base_path)
if checkpoint is not None:
print('Loading from checkpoint: %s' % checkpoint)
assert checkpoint.split('.')[-1]=='pth', 'file type not supported: %s' % checkpoint
assert os.path.exists(checkpoint), 'file not exists: %s' % checkpoint
checkpoint = torch.load(checkpoint)
self.setup_model(self.cfg, state_dict=checkpoint['model_state_dict'])
else:
raise Exception('Checkpoint file is not provided.')
return base_path
@abstractmethod
def draw_figure_epoch(self):
fig_dict = {}
mpl.use('Agg')
mpl.rcParams['agg.path.chunksize'] = 10000
return fig_dict
@abstractmethod
def evaluate_epoch(self, results_dict):
tic = time.time()
metrics_dict = {}
toc = time.time() - tic
logging.info('Compelte epoch evaluation in %.2f min' % (toc/60))
return metrics_dict
def logger_writer_step(self, tag, losses, step, epoch=None, global_step=None):
step_toc = (time.time() - self.step_tic) / self.cfg.SYS.LOG_INTERVAL
self.step_tic = time.time()
if tag == 'TRAIN':
msg = '[%s] epoch: %d/%d step: %d/%d global_step: %d time: %.3f '% (
tag, epoch, self.cfg.TRAIN.NUM_EPOCHS, step, self.num_train_batches, global_step, step_toc)
# learning rate
for k, v in self.optimizers.items():
lr_values = list(map(lambda x: x['lr'], v.param_groups))
for i, lr in enumerate(lr_values):
if i == 0:
msg += 'lr_%s: %.1e ' % (k, lr)
self.tb_writer.add_scalar('train/lr_%s' % k, lr, global_step)
else:
msg += 'lr_%s_%d: %.1e ' % (k, i, lr)
self.tb_writer.add_scalar('train/lr_%s_%d' % (k, i), lr, global_step)
# losses
for k, v in losses.items():
loss = v.detach().cpu().numpy()
msg += '%s: %.5f ' % (k, v)
self.tb_writer.add_scalar('train/%s' % (k), loss, global_step)
elif tag == 'VAL' or tag == 'TEST': # testing or validation
msg = '[%s] epoch: %d/%d step: %d/%d time: %.3f ' % (
tag, epoch, self.cfg.TRAIN.NUM_EPOCHS, step, self.num_test_batches, step_toc)
# losses
msg += ''.join(['%s: %.5f ' % (k, v) for k, v in losses.items()])
else:
raise Exception('Unknown tag:', tag)
logging.info(msg)
def logger_writer_epoch(self, tag, epoch_toc, losses=None, figures=None, epoch=0, ETA=None):
if tag == 'TRAIN':
msg = '[TRAIN] epoch_time: %.2f hours ETA: %.2f hours' % (epoch_toc, ETA)
self.tb_writer.add_scalar('train/epoch_time', epoch_toc, global_step=epoch)
self.tb_writer.add_scalar('train/ETA', ETA, global_step=epoch)
# figures
for k, v in figures.items():
self.tb_writer.add_figure('%s/%s' % (tag.lower(), k), v, global_step=epoch)
elif tag == 'VAL' or tag == 'TEST': # testing or validation
epoch_counter = 'epoch: %d/%d ' %(epoch, self.cfg.TRAIN.NUM_EPOCHS, ) \
if tag == 'VAL' else ''
msg = '[%s] %sval_time: %.1f min num_samples: %d ' % (
tag, epoch_counter, epoch_toc, self.num_test_samples)
# losses
for k, v in losses.items():
loss = v.detach().cpu().numpy()
msg += '%s: %.5f ' % (k, v)
self.tb_writer.add_scalar('%s/%s' % (tag.lower(), k), loss, global_step=epoch)
elif tag == 'DEMO': # demo
msg = '[%s] time: %.1f min num_samples: %d ' % (
tag, epoch_toc, self.num_test_samples)
else:
raise Exception('Unknown tag:', tag)
logging.info(msg)
def save_checkpoint(self, epoch, global_step):
checkpoint_dir = os.path.join(self.base_path, 'checkpoints')
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
checkpoint_path = os.path.join(checkpoint_dir,
'checkpoint_epoch-%d_step-%d.pth' % (epoch, global_step))
logging.info('Saving checkpoint to: %s' % checkpoint_path)
ckpt_dict = {
'epoch': epoch,
'step': global_step,
'model_state_dict': self.model.state_dict(),
}
for k, v in self.optimizers.items():
ckpt_dict['%s_state_dict' % k] = v.state_dict()
torch.save(ckpt_dict, checkpoint_path)
def reduce_tensor_dict(self, tensor_dict):
for k, v in tensor_dict.items():
torch.distributed.reduce(v, 0)
if self.is_master_process():
v /= self.get_world_size()
def concat_tensor_dict(self, input_dict, collection_dict):
for k, v in input_dict.items():
assert isinstance(v, np.ndarray) or isinstance(v, torch.Tensor)
if k not in collection_dict:
collection_dict[k] = v
else:
if isinstance(v, np.ndarray):
collection_dict[k] = np.concatenate([collection_dict[k], v], axis=0)
elif isinstance(v, torch.Tensor):
collection_dict[k] = torch.cat([collection_dict[k], v], dim=0)
else:
raise NotImplementedError
return collection_dict
def mutiply_batch(self, batch, multiple):
if isinstance(batch, dict):
for k, v in batch.items():
batch[k] = self.mutiply_batch(v, multiple)
return batch
elif isinstance(batch, list):
return batch * multiple
elif isinstance(batch, torch.Tensor):
return batch.unsqueeze(0).repeat_interleave(multiple, dim=0).reshape(multiple*batch.shape[0], *batch.shape[1:])
else:
raise NotImplementedError
@abstractmethod
def train_step(self, batch, t_step, global_step, epoch):
pass
@abstractmethod
def test_step(self, batch, t_step, epoch=0):
pass
@abstractmethod
def demo_step(self, batch, t_step, epoch=0, extra_id=None, interpolation_coeff=None):
pass
def train(self, cfg, exp_tag, resume_from):
self.base_path, epoch, global_step = self.setup_experiment(True, exp_tag, resume_from=resume_from)
if self.is_master_process():
print('Setting up logger and summary writer...')
self.setup_logger(self.base_path, exp_tag)
self.tb_writer = SummaryWriter(log_dir=self.base_path)
self.video_writer = VideoWriter(self.cfg)
logging.info('\n====== Configurations ======\n' + str(cfg) + '\n============\n')
logging.info('Training begins!')
while epoch < cfg.TRAIN.NUM_EPOCHS:
epoch += 1
epoch_tic = time.time()
epoch_toc_list = []
self.step_tic = time.time()
self.model.train()
if self.cfg.SYS.DISTRIBUTED:
self.train_sampler.set_epoch(epoch)
for t_step, batch in enumerate(self.train_dataloader):
global_step += 1
self.train_step(batch, t_step+1, global_step, epoch)
if epoch % cfg.TRAIN.CHECKPOINT_INTERVAL == 0:
if self.get_rank() == 0:
self.save_checkpoint(epoch, global_step)
if cfg.TRAIN.VALIDATE:
self.validate(self.test_dataloader, epoch)
if self.cfg.TRAIN.LR_SCHEDULER:
for _, v in self.schedulers.items():
v.step()
epoch_toc = (time.time() - epoch_tic) / 3600
epoch_toc_list.append(epoch_toc)
epoch_toc_mean = sum(epoch_toc_list) / len(epoch_toc_list) if len(epoch_toc_list) < 10 else sum(epoch_toc_list[-10:]) / 10
ETA = (self.cfg.TRAIN.NUM_EPOCHS - epoch) * epoch_toc_mean
if self.is_master_process():
fig_dict = self.draw_figure_epoch()
self.logger_writer_epoch('TRAIN', epoch_toc, epoch=epoch, ETA=ETA, figures=fig_dict)
def validate(self, test_dataloader, epoch):
if self.is_master_process():
| |
'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'count',
'variable_value': 999,
'variable_type': 'integer',
'source_info': {},
},
)
mock_client_logger.info.reset_mock()
# String
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(None, None, enums.DecisionSources.ROLLOUT), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger, mock.patch(
'optimizely.notification_center.NotificationCenter.send_notifications'
) as mock_broadcast_decision:
self.assertEqual(
'devel', opt_obj.get_feature_variable_string('test_feature_in_experiment', 'environment', 'test_user'),
)
mock_client_logger.info.assert_called_once_with(
'User "test_user" is not in any variation or rollout rule. '
'Returning default value for variable "environment" of feature flag "test_feature_in_experiment".'
)
mock_broadcast_decision.assert_called_once_with(
enums.NotificationTypes.DECISION,
'feature-variable',
'test_user',
{},
{
'feature_key': 'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'environment',
'variable_value': 'devel',
'variable_type': 'string',
'source_info': {},
},
)
mock_client_logger.info.reset_mock()
# JSON
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(None, None, enums.DecisionSources.ROLLOUT), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger, mock.patch(
'optimizely.notification_center.NotificationCenter.send_notifications'
) as mock_broadcast_decision:
self.assertEqual(
{"test": 12}, opt_obj.get_feature_variable_json('test_feature_in_experiment', 'object', 'test_user'),
)
mock_client_logger.info.assert_called_once_with(
'User "test_user" is not in any variation or rollout rule. '
'Returning default value for variable "object" of feature flag "test_feature_in_experiment".'
)
mock_broadcast_decision.assert_called_once_with(
enums.NotificationTypes.DECISION,
'feature-variable',
'test_user',
{},
{
'feature_key': 'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'object',
'variable_value': {"test": 12},
'variable_type': 'json',
'source_info': {},
},
)
mock_client_logger.info.reset_mock()
# Non-typed
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(None, None, enums.DecisionSources.ROLLOUT), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger, mock.patch(
'optimizely.notification_center.NotificationCenter.send_notifications'
) as mock_broadcast_decision:
self.assertTrue(opt_obj.get_feature_variable('test_feature_in_experiment', 'is_working', 'test_user'))
mock_client_logger.info.assert_called_once_with(
'User "test_user" is not in any variation or rollout rule. '
'Returning default value for variable "is_working" of feature flag "test_feature_in_experiment".'
)
mock_broadcast_decision.assert_called_once_with(
enums.NotificationTypes.DECISION,
'feature-variable',
'test_user',
{},
{
'feature_key': 'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'is_working',
'variable_value': True,
'variable_type': 'boolean',
'source_info': {},
},
)
mock_client_logger.info.reset_mock()
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(None, None, enums.DecisionSources.ROLLOUT), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger, mock.patch(
'optimizely.notification_center.NotificationCenter.send_notifications'
) as mock_broadcast_decision:
self.assertEqual(
10.99, opt_obj.get_feature_variable('test_feature_in_experiment', 'cost', 'test_user'),
)
mock_client_logger.info.assert_called_once_with(
'User "test_user" is not in any variation or rollout rule. '
'Returning default value for variable "cost" of feature flag "test_feature_in_experiment".'
)
mock_broadcast_decision.assert_called_once_with(
enums.NotificationTypes.DECISION,
'feature-variable',
'test_user',
{},
{
'feature_key': 'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'cost',
'variable_value': 10.99,
'variable_type': 'double',
'source_info': {},
},
)
mock_client_logger.info.reset_mock()
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(None, None, enums.DecisionSources.ROLLOUT), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger, mock.patch(
'optimizely.notification_center.NotificationCenter.send_notifications'
) as mock_broadcast_decision:
self.assertEqual(
999, opt_obj.get_feature_variable('test_feature_in_experiment', 'count', 'test_user'),
)
mock_client_logger.info.assert_called_once_with(
'User "test_user" is not in any variation or rollout rule. '
'Returning default value for variable "count" of feature flag "test_feature_in_experiment".'
)
mock_broadcast_decision.assert_called_once_with(
enums.NotificationTypes.DECISION,
'feature-variable',
'test_user',
{},
{
'feature_key': 'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'count',
'variable_value': 999,
'variable_type': 'integer',
'source_info': {},
},
)
mock_client_logger.info.reset_mock()
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(None, None, enums.DecisionSources.ROLLOUT), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger, mock.patch(
'optimizely.notification_center.NotificationCenter.send_notifications'
) as mock_broadcast_decision:
self.assertEqual(
'devel', opt_obj.get_feature_variable('test_feature_in_experiment', 'environment', 'test_user'),
)
mock_client_logger.info.assert_called_once_with(
'User "test_user" is not in any variation or rollout rule. '
'Returning default value for variable "environment" of feature flag "test_feature_in_experiment".'
)
mock_broadcast_decision.assert_called_once_with(
enums.NotificationTypes.DECISION,
'feature-variable',
'test_user',
{},
{
'feature_key': 'test_feature_in_experiment',
'feature_enabled': False,
'source': 'rollout',
'variable_key': 'environment',
'variable_value': 'devel',
'variable_type': 'string',
'source_info': {},
},
)
def test_get_feature_variable__returns_none_if_none_feature_key(self):
""" Test that get_feature_variable_* returns None for None feature key. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
with mock.patch.object(opt_obj, 'logger') as mock_client_logger:
# Check for booleans
self.assertIsNone(opt_obj.get_feature_variable_boolean(None, 'variable_key', 'test_user'))
mock_client_logger.error.assert_called_with('Provided "feature_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for doubles
self.assertIsNone(opt_obj.get_feature_variable_double(None, 'variable_key', 'test_user'))
mock_client_logger.error.assert_called_with('Provided "feature_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for integers
self.assertIsNone(opt_obj.get_feature_variable_integer(None, 'variable_key', 'test_user'))
mock_client_logger.error.assert_called_with('Provided "feature_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for strings
self.assertIsNone(opt_obj.get_feature_variable_string(None, 'variable_key', 'test_user'))
mock_client_logger.error.assert_called_with('Provided "feature_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for json
self.assertIsNone(opt_obj.get_feature_variable_json(None, 'variable_key', 'test_user'))
mock_client_logger.error.assert_called_with('Provided "feature_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for non-typed
self.assertIsNone(opt_obj.get_feature_variable(None, 'variable_key', 'test_user'))
mock_client_logger.error.assert_called_with('Provided "feature_key" is in an invalid format.')
mock_client_logger.reset_mock()
def test_get_feature_variable__returns_none_if_none_variable_key(self):
""" Test that get_feature_variable_* returns None for None variable key. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
with mock.patch.object(opt_obj, 'logger') as mock_client_logger:
# Check for booleans
self.assertIsNone(opt_obj.get_feature_variable_boolean('feature_key', None, 'test_user'))
mock_client_logger.error.assert_called_with('Provided "variable_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for doubles
self.assertIsNone(opt_obj.get_feature_variable_double('feature_key', None, 'test_user'))
mock_client_logger.error.assert_called_with('Provided "variable_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for integers
self.assertIsNone(opt_obj.get_feature_variable_integer('feature_key', None, 'test_user'))
mock_client_logger.error.assert_called_with('Provided "variable_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for strings
self.assertIsNone(opt_obj.get_feature_variable_string('feature_key', None, 'test-User'))
mock_client_logger.error.assert_called_with('Provided "variable_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for json
self.assertIsNone(opt_obj.get_feature_variable_json('feature_key', None, 'test-User'))
mock_client_logger.error.assert_called_with('Provided "variable_key" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for non-typed
self.assertIsNone(opt_obj.get_feature_variable('feature_key', None, 'test-User'))
mock_client_logger.error.assert_called_with('Provided "variable_key" is in an invalid format.')
mock_client_logger.reset_mock()
def test_get_feature_variable__returns_none_if_none_user_id(self):
""" Test that get_feature_variable_* returns None for None user ID. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
with mock.patch.object(opt_obj, 'logger') as mock_client_logger:
# Check for booleans
self.assertIsNone(opt_obj.get_feature_variable_boolean('feature_key', 'variable_key', None))
mock_client_logger.error.assert_called_with('Provided "user_id" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for doubles
self.assertIsNone(opt_obj.get_feature_variable_double('feature_key', 'variable_key', None))
mock_client_logger.error.assert_called_with('Provided "user_id" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for integers
self.assertIsNone(opt_obj.get_feature_variable_integer('feature_key', 'variable_key', None))
mock_client_logger.error.assert_called_with('Provided "user_id" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for strings
self.assertIsNone(opt_obj.get_feature_variable_string('feature_key', 'variable_key', None))
mock_client_logger.error.assert_called_with('Provided "user_id" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for json
self.assertIsNone(opt_obj.get_feature_variable_json('feature_key', 'variable_key', None))
mock_client_logger.error.assert_called_with('Provided "user_id" is in an invalid format.')
mock_client_logger.reset_mock()
# Check for non-typed
self.assertIsNone(opt_obj.get_feature_variable('feature_key', 'variable_key', None))
mock_client_logger.error.assert_called_with('Provided "user_id" is in an invalid format.')
mock_client_logger.reset_mock()
def test_get_feature_variable__invalid_attributes(self):
""" Test that get_feature_variable_* returns None for invalid attributes. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
with mock.patch.object(opt_obj, 'logger') as mock_client_logging, mock.patch(
'optimizely.helpers.validator.are_attributes_valid', return_value=False
) as mock_validator:
# get_feature_variable_boolean
self.assertIsNone(
opt_obj.get_feature_variable_boolean(
'test_feature_in_experiment', 'is_working', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
# get_feature_variable_double
self.assertIsNone(
opt_obj.get_feature_variable_double(
'test_feature_in_experiment', 'cost', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
# get_feature_variable_integer
self.assertIsNone(
opt_obj.get_feature_variable_integer(
'test_feature_in_experiment', 'count', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
# get_feature_variable_string
self.assertIsNone(
opt_obj.get_feature_variable_string(
'test_feature_in_experiment', 'environment', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
# get_feature_variable_json
self.assertIsNone(
opt_obj.get_feature_variable_json(
'test_feature_in_experiment', 'object', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
# get_feature_variable
self.assertIsNone(
opt_obj.get_feature_variable(
'test_feature_in_experiment', 'is_working', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
self.assertIsNone(
opt_obj.get_feature_variable('test_feature_in_experiment', 'cost', 'test_user', attributes='invalid',)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
self.assertIsNone(
opt_obj.get_feature_variable('test_feature_in_experiment', 'count', 'test_user', attributes='invalid',)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
self.assertIsNone(
opt_obj.get_feature_variable(
'test_feature_in_experiment', 'environment', 'test_user', attributes='invalid',
)
)
mock_validator.assert_called_once_with('invalid')
mock_client_logging.error.assert_called_once_with('Provided attributes are in an invalid format.')
mock_validator.reset_mock()
mock_client_logging.reset_mock()
def test_get_feature_variable__returns_none_if_invalid_feature_key(self):
""" Test that get_feature_variable_* returns None for invalid feature key. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
with mock.patch.object(opt_obj.config_manager.get_config(), 'logger') as mock_config_logger:
self.assertIsNone(opt_obj.get_feature_variable_boolean('invalid_feature', 'is_working', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable_double('invalid_feature', 'cost', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable_integer('invalid_feature', 'count', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable_string('invalid_feature', 'environment', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable_json('invalid_feature', 'object', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable('invalid_feature', 'is_working', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable('invalid_feature', 'cost', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable('invalid_feature', 'count', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable('invalid_feature', 'environment', 'test_user'))
self.assertIsNone(opt_obj.get_feature_variable('invalid_feature', 'object', 'test_user'))
self.assertEqual(10, mock_config_logger.error.call_count)
mock_config_logger.error.assert_has_calls(
[
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
mock.call('Feature "invalid_feature" is not in datafile.'),
]
)
def test_get_feature_variable__returns_none_if_invalid_variable_key(self):
""" Test that get_feature_variable_* returns None for invalid variable key. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
with mock.patch.object(opt_obj.config_manager.get_config(), 'logger') as mock_config_logger:
self.assertIsNone(
opt_obj.get_feature_variable_boolean('test_feature_in_experiment', 'invalid_variable', 'test_user')
)
self.assertIsNone(
opt_obj.get_feature_variable_double('test_feature_in_experiment', 'invalid_variable', 'test_user')
)
self.assertIsNone(
opt_obj.get_feature_variable_integer('test_feature_in_experiment', 'invalid_variable', 'test_user')
)
self.assertIsNone(
opt_obj.get_feature_variable_string('test_feature_in_experiment', 'invalid_variable', 'test_user')
)
self.assertIsNone(
opt_obj.get_feature_variable_json('test_feature_in_experiment', 'invalid_variable', 'test_user')
)
self.assertIsNone(
opt_obj.get_feature_variable('test_feature_in_experiment', 'invalid_variable', 'test_user')
)
self.assertEqual(6, mock_config_logger.error.call_count)
mock_config_logger.error.assert_has_calls(
[
mock.call('Variable with key "invalid_variable" not found in the datafile.'),
mock.call('Variable with key "invalid_variable" not found in the datafile.'),
mock.call('Variable with key "invalid_variable" not found in the datafile.'),
mock.call('Variable with key "invalid_variable" not found in the datafile.'),
mock.call('Variable with key "invalid_variable" not found in the datafile.'),
mock.call('Variable with key "invalid_variable" not found in the datafile.'),
]
)
def test_get_feature_variable__returns_default_value_if_feature_not_enabled(self):
""" Test that get_feature_variable_* returns default value if feature is not enabled for the user. """
opt_obj = optimizely.Optimizely(json.dumps(self.config_dict_with_features))
mock_experiment = opt_obj.config_manager.get_config().get_experiment_from_key('test_experiment')
mock_variation = opt_obj.config_manager.get_config().get_variation_from_id('test_experiment', '111128')
# Boolean
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(mock_experiment,
mock_variation, enums.DecisionSources.FEATURE_TEST), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger:
self.assertTrue(
opt_obj.get_feature_variable_boolean('test_feature_in_experiment', 'is_working', 'test_user')
)
mock_client_logger.info.assert_called_once_with(
'Feature "test_feature_in_experiment" is not enabled for user "test_user". '
'Returning the default variable value "true".'
)
# Double
with mock.patch(
'optimizely.decision_service.DecisionService.get_variation_for_feature',
return_value=(decision_service.Decision(mock_experiment,
mock_variation, enums.DecisionSources.FEATURE_TEST), []),
), mock.patch.object(opt_obj, 'logger') as mock_client_logger:
self.assertEqual(
10.99, opt_obj.get_feature_variable_double('test_feature_in_experiment', 'cost', 'test_user'),
)
mock_client_logger.info.assert_called_once_with(
'Feature "test_feature_in_experiment" is not | |
<reponame>chris-angeli-rft/cloud-custodian
# Copyright 2019 Capital One Services, LLC
#
# 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 time import sleep
from gcp_common import BaseTest, event_data
class LoadBalancingAddressTest(BaseTest):
def test_loadbalancer_address_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-addresses-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-addresses',
'resource': 'gcp.loadbalancer-address'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#address')
self.assertEqual(resources[0]['address'], '192.168.127.12')
def test_loadbalancer_address_get(self):
factory = self.replay_flight_data('lb-addresses-get')
p = self.load_policy(
{'name': 'one-region-address',
'resource': 'gcp.loadbalancer-address',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-addresses-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#address')
self.assertEqual(instances[0]['address'], '192.168.127.12')
def test_loadbalancer_address_delete(self):
region = 'us-central1'
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-addresses-delete',
project_id=project_id)
policy = self.load_policy(
{'name': 'delete-address',
'resource': 'gcp.loadbalancer-address',
'actions': ['delete']
}, session_factory=factory)
resources = policy.run()
self.assertEqual(resources[0]['name'], 'new322')
client = policy.resource_manager.get_client()
result = client.execute_query(
'list', {'project': project_id,
'region': region})
self.assertEqual(len(result['items']["regions/{}".format(region)]['addresses']), 0)
class LoadBalancingUrlMapTest(BaseTest):
def test_loadbalancer_url_map_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-url-maps-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-url-maps',
'resource': 'gcp.loadbalancer-url-map'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#urlMap')
self.assertEqual(resources[0]['fingerprint'], 'GMqHBoGzLDY=')
def test_loadbalancer_url_map_get(self):
factory = self.replay_flight_data('lb-url-maps-get')
p = self.load_policy(
{'name': 'one-lb-url-map',
'resource': 'gcp.loadbalancer-url-map',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-url-maps-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#urlMap')
self.assertEqual(instances[0]['fingerprint'], 'oA9r95u1zRI=')
self.assertEqual(instances[0]['name'], 'custodian-load-balancer-0')
class LoadBalancingTargetTcpProxyTest(BaseTest):
def test_loadbalancer_target_tcp_proxy_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-target-tcp-proxies-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-target-tcp-proxies',
'resource': 'gcp.loadbalancer-target-tcp-proxy'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#targetTcpProxy')
self.assertEqual(resources[0]['name'], 'newlb1-target-proxy')
def test_loadbalancer_target_tcp_proxy_get(self):
factory = self.replay_flight_data('lb-target-tcp-proxies-get')
p = self.load_policy(
{'name': 'one-lb-target-tcp-proxy',
'resource': 'gcp.loadbalancer-target-tcp-proxy',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-target-tcp-proxy-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#targetTcpProxy')
self.assertEqual(instances[0]['name'], 'target-tcp-proxy')
class LoadBalancingTargetSslProxyTest(BaseTest):
def test_loadbalancer_target_ssl_proxy_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-target-ssl-proxies-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-target-ssl-proxies',
'resource': 'gcp.loadbalancer-target-ssl-proxy'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#targetSslProxy')
self.assertEqual(resources[0]['name'], 'lb2-target-proxy')
def test_loadbalancer_target_ssl_proxy_get(self):
factory = self.replay_flight_data('lb-target-ssl-proxies-get')
p = self.load_policy(
{'name': 'one-lb-target-ssl-proxy',
'resource': 'gcp.loadbalancer-target-ssl-proxy',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-target-ssl-proxy-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#targetSslProxy')
self.assertEqual(instances[0]['name'], 'target-ssl-proxy')
class LoadBalancingSslPolicyTest(BaseTest):
def test_loadbalancer_ssl_policy_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-ssl-policies-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-ssl-policies',
'resource': 'gcp.loadbalancer-ssl-policy'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#sslPolicy')
self.assertEqual(resources[0]['name'], 'newpolicy')
def test_loadbalancer_ssl_policy_get(self):
factory = self.replay_flight_data('lb-ssl-policies-get')
p = self.load_policy(
{'name': 'one-lb-ssl-policies',
'resource': 'gcp.loadbalancer-ssl-policy',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-ssl-policy-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#sslPolicy')
self.assertEqual(instances[0]['name'], 'custodian-ssl-policiy-0')
def test_loadbalancer_ssl_policy_delete(self):
project_id = 'custodian-test-project-0'
session_factory = self.replay_flight_data('lb-ssl-policy-delete',
project_id=project_id)
base_policy = {'name': 'lb-ssl-policy-delete',
'resource': 'gcp.loadbalancer-ssl-policy'}
policy = self.load_policy(
dict(base_policy,
filters=[{'type': 'value',
'key': 'minTlsVersion',
'op': 'ne',
'value': 'TLS_1_2'}],
actions=[{'type': 'delete'}]),
session_factory=session_factory)
resources = policy.run()
self.assertEqual(2, len(resources))
self.assertIsNot('TLS_1_2', resources[0]['minTlsVersion'])
self.assertIsNot('TLS_1_2', resources[1]['minTlsVersion'])
if self.recording:
sleep(1)
client = policy.resource_manager.get_client()
result = client.execute_query(
'list', {'project': project_id})
items = result['items']
self.assertEqual(1, len(items))
self.assertEqual('TLS_1_2', items[0]['minTlsVersion'])
class LoadBalancingSslCertificateTest(BaseTest):
def test_loadbalancer_ssl_certificate_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-ssl-certificates-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-ssl-certificates',
'resource': 'gcp.loadbalancer-ssl-certificate'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#sslCertificate')
self.assertEqual(resources[0]['name'], 'testcert')
def test_loadbalancer_ssl_certificate_get(self):
factory = self.replay_flight_data('lb-ssl-certificates-get')
p = self.load_policy(
{'name': 'one-lb-ssl-certificates',
'resource': 'gcp.loadbalancer-ssl-certificate',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-ssl-certificate-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#sslCertificate')
self.assertEqual(instances[0]['name'], 'comelfo-com-google-certificate')
class LoadBalancingTargetHttpsProxyTest(BaseTest):
def test_loadbalancer_target_https_proxy_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-target-https-proxies-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-target-https-proxies',
'resource': 'gcp.loadbalancer-target-https-proxy'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#targetHttpsProxy')
self.assertEqual(resources[0]['name'], 'newhttpslb-target-proxy')
def test_loadbalancer_target_https_proxy_get(self):
factory = self.replay_flight_data('lb-target-https-proxies-get')
p = self.load_policy(
{'name': 'one-lb-target-https-proxies',
'resource': 'gcp.loadbalancer-target-https-proxy',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-target-https-proxy-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#targetHttpsProxy')
self.assertEqual(instances[0]['name'], 'custodian-https-target-proxy-0')
class LoadBalancingBackendBucketTest(BaseTest):
def test_loadbalancer_backend_bucket_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-backend-buckets-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-backend-buckets',
'resource': 'gcp.loadbalancer-backend-bucket'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#backendBucket')
self.assertEqual(resources[0]['name'], 'newbucket')
def test_loadbalancer_backend_bucket_get(self):
factory = self.replay_flight_data('lb-backend-buckets-get')
p = self.load_policy(
{'name': 'one-lb-backend-buckets',
'resource': 'gcp.loadbalancer-backend-bucket',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-backend-bucket-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#backendBucket')
self.assertEqual(instances[0]['name'], 'custodian-backend-bucket-0')
def test_loadbalancer_backend_bucket_delete(self):
project_id = 'custodian-test-project-0'
session_factory = self.replay_flight_data('lb-backend-buckets-delete',
project_id=project_id)
base_policy = {'name': 'lb-addresses-delete',
'resource': 'gcp.loadbalancer-backend-bucket'}
policy = self.load_policy(
dict(base_policy,
filters=[{'type': 'value',
'key': 'bucketName',
'op': 'eq',
'value': 'custodian-bucket-0'}],
actions=[{'type': 'delete'}]),
session_factory=session_factory)
resources = policy.run()
self.assertEqual(2, len(resources))
self.assertEqual('custodian-bucket-0', resources[0]['bucketName'])
self.assertEqual('custodian-bucket-0', resources[1]['bucketName'])
self.assertEqual('custodian-backend-bucket-1', resources[0]['name'])
self.assertEqual('custodian-backend-bucket-3', resources[1]['name'])
if self.recording:
sleep(5)
client = policy.resource_manager.get_client()
result = client.execute_query(
'list', {'project': project_id})
items = result['items']
self.assertEqual(1, len(items))
self.assertIsNot('custodian-bucket-0', items[0]['bucketName'])
self.assertEqual('custodian-backend-bucket-2', items[0]['name'])
class LoadBalancingHttpsHealthCheckTest(BaseTest):
def test_loadbalancer_https_health_check_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-https-health-checks-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-https-health-checks',
'resource': 'gcp.loadbalancer-https-health-check'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#httpsHealthCheck')
self.assertEqual(resources[0]['name'], 'newhealthcheck')
def test_loadbalancer_https_health_check_get(self):
factory = self.replay_flight_data('lb-https-health-checks-get')
p = self.load_policy(
{'name': 'one-lb-https-health-checks',
'resource': 'gcp.loadbalancer-https-health-check',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-https-health-checks-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#httpsHealthCheck')
self.assertEqual(instances[0]['name'], 'custodian-https-health-check')
class LoadBalancingHttpHealthCheckTest(BaseTest):
def test_loadbalancer_http_health_check_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-http-health-checks-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-http-health-checks',
'resource': 'gcp.loadbalancer-http-health-check'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#httpHealthCheck')
self.assertEqual(resources[0]['name'], 'newhttphealthcheck')
def test_loadbalancer_http_health_check_get(self):
factory = self.replay_flight_data('lb-http-health-checks-get')
p = self.load_policy(
{'name': 'one-lb-http-health-checks',
'resource': 'gcp.loadbalancer-http-health-check',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-http-health-checks-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#httpHealthCheck')
self.assertEqual(instances[0]['name'], 'custodian-http-health-check')
class LoadBalancingHealthCheckTest(BaseTest):
def test_loadbalancer_health_check_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-health-checks-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-health-checks',
'resource': 'gcp.loadbalancer-health-check'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#healthCheck')
self.assertEqual(resources[0]['name'], 'new-tcp-health-check')
def test_loadbalancer_health_check_get(self):
factory = self.replay_flight_data('lb-health-checks-get')
p = self.load_policy(
{'name': 'one-lb-health-checks',
'resource': 'gcp.loadbalancer-health-check',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-health-checks-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#healthCheck')
self.assertEqual(instances[0]['name'], 'custodain-health-check')
class LoadBalancingTargetHttpProxyTest(BaseTest):
def test_loadbalancer_target_http_proxy_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-target-http-proxies-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-target-http-proxies',
'resource': 'gcp.loadbalancer-target-http-proxy'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#targetHttpProxy')
self.assertEqual(resources[0]['name'], 'new-proxy')
def test_loadbalancer_target_http_proxy_get(self):
factory = self.replay_flight_data('lb-target-http-proxies-get')
p = self.load_policy(
{'name': 'one-lb-target-http-proxies',
'resource': 'gcp.loadbalancer-target-http-proxy',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-target-http-proxies-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#targetHttpProxy')
self.assertEqual(instances[0]['name'], 'custodian-load-balancer-0-target-proxy')
class LoadBalancingBackendServiceTest(BaseTest):
def test_loadbalancer_backend_service_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-backend-services-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-backend-services',
'resource': 'gcp.loadbalancer-backend-service'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#backendService')
self.assertEqual(resources[0]['name'], 'new-backend-service')
def test_loadbalancer_backend_service_get(self):
factory = self.replay_flight_data('lb-backend-services-get')
p = self.load_policy(
{'name': 'one-lb-backend-services',
'resource': 'gcp.loadbalancer-backend-service',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-backend-services-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#backendService')
self.assertEqual(instances[0]['name'], 'common-backend-service-0')
class LoadBalancingTargetInstanceTest(BaseTest):
def test_loadbalancer_target_instance_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-target-instances-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-target-instances',
'resource': 'gcp.loadbalancer-target-instance'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#targetInstance')
self.assertEqual(resources[0]['name'], 'new-target-instance')
def test_loadbalancer_target_instance_get(self):
factory = self.replay_flight_data('lb-target-instances-get')
p = self.load_policy(
{'name': 'one-lb-target-instances',
'resource': 'gcp.loadbalancer-target-instance',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-target-instances-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#targetInstance')
self.assertEqual(instances[0]['name'], 'custodian-target-instance-1')
class LoadBalancingTargetPoolTest(BaseTest):
def test_loadbalancer_target_pool_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-target-pools-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-target-pools',
'resource': 'gcp.loadbalancer-target-pool'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#targetPool')
self.assertEqual(resources[0]['name'], 'new-target-pool')
def test_loadbalancer_target_pool_get(self):
factory = self.replay_flight_data('lb-target-pools-get')
p = self.load_policy(
{'name': 'one-lb-target-pools',
'resource': 'gcp.loadbalancer-target-pool',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-target-pools-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#targetPool')
self.assertEqual(instances[0]['name'], 'custodian-target-pool-0')
class LoadBalancingForwardingRuleTest(BaseTest):
def test_loadbalancer_forwarding_rule_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-forwarding-rules-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-forwarding-rules',
'resource': 'gcp.loadbalancer-forwarding-rule'},
session_factory=factory)
resources = p.run()
self.assertEqual(len(resources), 1)
self.assertEqual(resources[0]['kind'], 'compute#forwardingRule')
self.assertEqual(resources[0]['name'], 'new-fe')
def test_loadbalancer_forwarding_rule_get(self):
factory = self.replay_flight_data('lb-forwarding-rules-get')
p = self.load_policy(
{'name': 'one-lb-forwarding-rules',
'resource': 'gcp.loadbalancer-forwarding-rule',
'mode': {
'type': 'gcp-audit',
'methods': []
}},
session_factory=factory)
exec_mode = p.get_execution_mode()
event = event_data('lb-forwarding-rules-get.json')
instances = exec_mode.run(event, None)
self.assertEqual(len(instances), 1)
self.assertEqual(instances[0]['kind'], 'compute#forwardingRule')
self.assertEqual(instances[0]['name'], 'custodian-frontend-tcp-0')
class LoadBalancingGlobalForwardingRuleTest(BaseTest):
def test_loadbalancer_global_forwarding_rule_query(self):
project_id = 'cloud-custodian'
factory = self.replay_flight_data('lb-global-forwarding-rules-query',
project_id=project_id)
p = self.load_policy(
{'name': 'all-lb-global-forwarding-rules',
| |
import torch
# math
import numpy as numpy
import numpy as np
import math
from numpy.linalg import inv
import random
from itertools import cycle
# io
from PIL import Image
# torchvision
import sys
sys.path.insert(0, '../pytorch-segmentation-detection/vision/') # from subrepo
from torchvision import transforms
from dense_correspondence_manipulation.utils.constants import *
# turns out to be faster to do this match generation on the CPU
# for the general size of params we expect
# also this will help by not taking up GPU memory,
# allowing batch sizes to stay large
dtype_float = torch.FloatTensor
dtype_long = torch.LongTensor
def pytorch_rand_select_pixel(width=640,height=480,num_samples=1):
two_rand_numbers = torch.rand(2,num_samples)
two_rand_numbers[0,:] = two_rand_numbers[0,:]*width
two_rand_numbers[1,:] = two_rand_numbers[1,:]*height
two_rand_ints = torch.floor(two_rand_numbers).type(dtype_long)
return (two_rand_ints[0], two_rand_ints[1])
def pytorch_rand_select_knot_pixels(knots, num_samples=1):
if num_samples >= len(knots):
pairs = knots
else:
pairs = random.sample(knots, num_samples)
x, y = [i[0] for i in pairs], [j[1] for j in pairs]
result = torch.Tensor([x, y]).type(dtype_long)
return (result[0], result[1])
#def pair_vertices(img_a_knots, img_b_knots):
# knots_a_list = []
# knots_b_list = []
# for i in range(len(img_a_knots)):
# if len(img_a_knots) != len(img_b_knots):
# print(len(img_a_knots), len(img_b_knots))
# if img_a_knots[i][1] and img_b_knots[i][1]:
# knots_a_list.append(img_a_knots[i][0])
# knots_b_list.append(img_b_knots[i][0])
# print("Matches:", len(knots_a_list))
# x_a, y_a = [i[0] for i in knots_a_list], [j[1] for j in knots_a_list]
# x_b, y_b = [i[0] for i in knots_b_list], [j[1] for j in knots_b_list]
# res_a, res_b = torch.Tensor([x_a, y_a]).type(dtype_long), torch.Tensor([x_b, y_b]).type(dtype_long)
# return ((res_a[0], res_a[1]), (res_b[0], res_b[1]))
def pair_vertices(img_a_knots, img_b_knots):
def zip_pixels(A, B):
zipped = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)
return list(zipped)
#paired = [zip_pixels(img_a_knots[i], img_b_knots[i]) for i in range(len(img_a_knots))]
paired = [list(zip(img_a_knots[i], img_b_knots[i])) for i in range(len(img_a_knots))]
paired = [item for sublist in paired for item in sublist]
knots_a_list, knots_b_list = [p[0] for p in paired], [p[1] for p in paired]
x_a, y_a = [i[0] for i in knots_a_list], [j[1] for j in knots_a_list]
x_b, y_b = [i[0] for i in knots_b_list], [j[1] for j in knots_b_list]
res_a, res_b = torch.Tensor([x_a, y_a]).type(dtype_long), torch.Tensor([x_b, y_b]).type(dtype_long)
return ((res_a[0], res_a[1]), (res_b[0], res_b[1]))
def get_default_K_matrix():
K = numpy.zeros((3,3))
K[0,0] = 520.0
K[1,1] = 520.0
K[0,2] = 319.5
K[1,2] = 239.5
K[2,2] = 1.0
return K
def get_body_to_rdf():
body_to_rdf = numpy.zeros((3,3))
body_to_rdf[0,1] = -1.0
body_to_rdf[1,2] = -1.0
body_to_rdf[2,0] = 1.0
return body_to_rdf
def invert_transform(transform4):
transform4_copy = numpy.copy(transform4)
R = transform4_copy[0:3,0:3]
R = numpy.transpose(R)
transform4_copy[0:3,0:3] = R
t = transform4_copy[0:3,3]
inv_t = -1.0 * numpy.transpose(R).dot(t)
transform4_copy[0:3,3] = inv_t
return transform4_copy
def apply_transform_torch(vec3, transform4):
ones_row = torch.ones_like(vec3[0,:]).type(dtype_float).unsqueeze(0)
vec4 = torch.cat((vec3,ones_row),0)
vec4 = transform4.mm(vec4)
return vec4[0:3]
def random_sample_from_masked_image(img_mask, num_samples):
"""
Samples num_samples (row, column) convention pixel locations from the masked image
Note this is not in (u,v) format, but in same format as img_mask
:param img_mask: numpy.ndarray
- masked image, we will select from the non-zero entries
- shape is H x W
:param num_samples: int
- number of random indices to return
:return: List of np.array
"""
idx_tuple = img_mask.nonzero()
num_nonzero = len(idx_tuple[0])
if num_nonzero == 0:
empty_list = []
return empty_list
rand_inds = random.sample(range(0,num_nonzero), num_samples)
sampled_idx_list = []
for i, idx in enumerate(idx_tuple):
sampled_idx_list.append(idx[rand_inds])
return sampled_idx_list
def random_sample_from_masked_image_torch(img_mask, num_samples):
"""
:param img_mask: Numpy array [H,W] or torch.Tensor with shape [H,W]
:type img_mask:
:param num_samples: an integer
:type num_samples:
:return: tuple of torch.LongTensor in (u,v) format. Each torch.LongTensor has shape
[num_samples]
:rtype:
"""
image_height, image_width = img_mask.shape
if isinstance(img_mask, np.ndarray):
img_mask_torch = torch.from_numpy(img_mask).float()
else:
img_mask_torch = img_mask
# This code would randomly subsample from the mask
mask = img_mask_torch.view(image_width*image_height,1).squeeze(1)
mask_indices_flat = torch.nonzero(mask)
if len(mask_indices_flat) == 0:
return (None, None)
rand_numbers = torch.rand(num_samples)*len(mask_indices_flat)
rand_indices = torch.floor(rand_numbers).long()
uv_vec_flattened = torch.index_select(mask_indices_flat, 0, rand_indices).squeeze(1)
uv_vec = utils.flattened_pixel_locations_to_u_v(uv_vec_flattened, image_width)
return uv_vec
def closest_knot(pixel, knots):
knots_arr = np.asarray(knots)
dist_2 = np.sum((knots_arr - pixel)**2, axis=1)
return knots[np.argmin(dist_2)]
def pixels_to_closest_knot(pixels, knots):
return [closest_knot(p, knots) for p in pixels]
def pinhole_projection_image_to_world(uv, z, K):
"""
Takes a (u,v) pixel location to it's 3D location in camera frame.
See https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html for a detailed explanation.
:param uv: pixel location in image
:type uv:
:param z: depth, in camera frame
:type z: float
:param K: 3 x 3 camera intrinsics matrix
:type K: numpy.ndarray
:return: (x,y,z) in camera frame
:rtype: numpy.array size (3,)
"""
u_v_1 = np.array([uv[0], uv[1], 1])
pos = z * np.matmul(inv(K),u_v_1)
return pos
def pinhole_projection_world_to_image(world_pos, K, camera_to_world=None):
"""
Projects from world position to camera coordinates
See https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
:param world_pos:
:type world_pos:
:param K:
:type K:
:return:
:rtype:
"""
world_pos_vec = np.append(world_pos, 1)
# transform to camera frame if camera_to_world is not None
if camera_to_world is not None:
world_pos_vec = np.dot(np.linalg.inv(camera_to_world), world_pos_vec)
# scaled position is [X/Z, Y/Z, 1] where X,Y,Z is the position in camera frame
scaled_pos = np.array([world_pos_vec[0]/world_pos_vec[2], world_pos_vec[1]/world_pos_vec[2], 1])
uv = np.dot(K, scaled_pos)[:2]
return uv
# in torch 0.3 we don't yet have torch.where(), although this
# is there in 0.4 (not yet stable release)
# for more see: https://discuss.pytorch.org/t/how-can-i-do-the-operation-the-same-as-np-where/1329/8
def where(cond, x_1, x_2):
"""
We follow the torch.where implemented in 0.4.
See http://pytorch.org/docs/master/torch.html?highlight=where#torch.where
For more discussion see https://discuss.pytorch.org/t/how-can-i-do-the-operation-the-same-as-np-where/1329/8
Return a tensor of elements selected from either x_1 or x_2, depending on condition.
:param cond: cond should be tensor with entries [0,1]
:type cond:
:param x_1: torch.Tensor
:type x_1:
:param x_2: torch.Tensor
:type x_2:
:return:
:rtype:
"""
cond = cond.type(dtype_float)
return (cond * x_1) + ((1-cond) * x_2)
def create_non_correspondences(uv_b_matches, img_b_shape, num_non_matches_per_match=100, img_b_mask=None):
"""
Takes in pixel matches (uv_b_matches) that correspond to matches in another image, and generates non-matches by just sampling in image space.
Optionally, the non-matches can be sampled from a mask for image b.
Returns non-matches as pixel positions in image b.
Please see 'coordinate_conventions.md' documentation for an explanation of pixel coordinate conventions.
## Note that arg uv_b_matches are the outputs of batch_find_pixel_correspondences()
:param uv_b_matches: tuple of torch.FloatTensors, where each FloatTensor is length n, i.e.:
(torch.FloatTensor, torch.FloatTensor)
:param img_b_shape: tuple of (H,W) which is the shape of the image
(optional)
:param num_non_matches_per_match: int
(optional)
:param img_b_mask: torch.FloatTensor (can be cuda or not)
- masked image, we will select from the non-zero entries
- shape is H x W
:return: tuple of torch.FloatTensors, i.e. (torch.FloatTensor, torch.FloatTensor).
- The first element of the tuple is all "u" pixel positions, and the right element of the tuple is all "v" positions
- Each torch.FloatTensor is of shape torch.Shape([num_matches, non_matches_per_match])
- This shape makes it so that each row of the non-matches corresponds to the row for the match in uv_a
"""
image_width = img_b_shape[1]
image_height = img_b_shape[0]
if uv_b_matches == None:
return None
num_matches = len(uv_b_matches[0])
def get_random_uv_b_non_matches():
return pytorch_rand_select_pixel(width=image_width,height=image_height,
num_samples=num_matches*num_non_matches_per_match)
if img_b_mask is not None:
img_b_mask_flat = img_b_mask.view(-1,1).squeeze(1)
mask_b_indices_flat = torch.nonzero(img_b_mask_flat)
if len(mask_b_indices_flat) == 0:
print "warning, empty mask b"
uv_b_non_matches = get_random_uv_b_non_matches()
else:
num_samples = num_matches*num_non_matches_per_match
rand_numbers_b = torch.rand(num_samples)*len(mask_b_indices_flat)
rand_indices_b = torch.floor(rand_numbers_b).long()
randomized_mask_b_indices_flat = torch.index_select(mask_b_indices_flat, 0, rand_indices_b).squeeze(1)
uv_b_non_matches = (randomized_mask_b_indices_flat%image_width, randomized_mask_b_indices_flat/image_width)
else:
uv_b_non_matches = get_random_uv_b_non_matches()
# for each in uv_a, we want non-matches
# first just randomly sample "non_matches"
# we will later move random samples that were too close to being matches
uv_b_non_matches = (uv_b_non_matches[0].view(num_matches,num_non_matches_per_match), uv_b_non_matches[1].view(num_matches,num_non_matches_per_match))
# uv_b_matches can now be used to make sure no "non_matches" are too close
# to preserve tensor size, rather than pruning, we can perturb these in pixel space
copied_uv_b_matches_0 = torch.t(uv_b_matches[0].repeat(num_non_matches_per_match, 1)).type(dtype_float)
copied_uv_b_matches_1 = torch.t(uv_b_matches[1].repeat(num_non_matches_per_match, 1)).type(dtype_float)
diffs_0 = copied_uv_b_matches_0 - uv_b_non_matches[0].type(dtype_float)
diffs_1 = copied_uv_b_matches_1 - uv_b_non_matches[1].type(dtype_float)
diffs_0_flattened = diffs_0.view(-1,1)
diffs_1_flattened = diffs_1.view(-1,1)
diffs_0_flattened = torch.abs(diffs_0_flattened).squeeze(1)
diffs_1_flattened = torch.abs(diffs_1_flattened).squeeze(1)
need_to_be_perturbed = torch.zeros_like(diffs_0_flattened)
ones = torch.zeros_like(diffs_0_flattened)
num_pixels_too_close = 1.0
threshold = torch.ones_like(diffs_0_flattened)*num_pixels_too_close
# determine which pixels are too close to being matches
need_to_be_perturbed = where(diffs_0_flattened < threshold, ones, need_to_be_perturbed)
need_to_be_perturbed = where(diffs_1_flattened < threshold, ones, need_to_be_perturbed)
minimal_perturb = num_pixels_too_close/2
minimal_perturb_vector = (torch.rand(len(need_to_be_perturbed))*2).floor()*(minimal_perturb*2)-minimal_perturb
std_dev = 10
random_vector = torch.randn(len(need_to_be_perturbed))*std_dev + minimal_perturb_vector
perturb_vector = need_to_be_perturbed*random_vector
uv_b_non_matches_0_flat = uv_b_non_matches[0].view(-1,1).type(dtype_float).squeeze(1)
uv_b_non_matches_1_flat = uv_b_non_matches[1].view(-1,1).type(dtype_float).squeeze(1)
uv_b_non_matches_0_flat = uv_b_non_matches_0_flat + perturb_vector
uv_b_non_matches_1_flat = uv_b_non_matches_1_flat + perturb_vector
# now just need to wrap around any that went out of bounds
# handle wrapping in width
lower_bound = 0.0
upper_bound = image_width*1.0 - 1
lower_bound_vec = torch.ones_like(uv_b_non_matches_0_flat) * lower_bound
upper_bound_vec = torch.ones_like(uv_b_non_matches_0_flat) * upper_bound
uv_b_non_matches_0_flat = where(uv_b_non_matches_0_flat > upper_bound_vec,
uv_b_non_matches_0_flat - upper_bound_vec,
uv_b_non_matches_0_flat)
uv_b_non_matches_0_flat = where(uv_b_non_matches_0_flat < lower_bound_vec,
uv_b_non_matches_0_flat + upper_bound_vec,
uv_b_non_matches_0_flat)
# handle wrapping in height
lower_bound = 0.0
upper_bound = image_height*1.0 - 1
lower_bound_vec = torch.ones_like(uv_b_non_matches_1_flat) * lower_bound
upper_bound_vec = torch.ones_like(uv_b_non_matches_1_flat) * upper_bound
uv_b_non_matches_1_flat = where(uv_b_non_matches_1_flat > upper_bound_vec,
uv_b_non_matches_1_flat | |
<reponame>wi11dey/pylabnet
import numpy as np
import copy
class Channel:
""" Class to represent a signal channel.
"""
def __init__(self, name, is_analog):
self.name = name
self.is_analog = is_analog
def __repr__(self):
return f"Channel({self.name}, {self.is_analog})"
def __eq__(self, other):
if not isinstance(other, Channel):
return False
return self.name == other.name
def __lt__(self, other):
return self.name < other.name
def __le__(self, other):
return self.name <= other.name
def __gt__(self, other):
return self.name >= other.name
def __ge__(self, other):
return self.name > other.name
def __hash__(self):
return hash(self.name)
class PulseBlock:
""" Class for construction of pulse sequences.
PulseBlock is essentially a container which has several "shelves" (channels),
and each pulse is represented by a "box" (Pulse object) sitting on the shelf.
Each "box" must have a name tag: "channel name - start time - duration".
PulseBlock makes no additional assumptions about the contents of the boxes.
Since the "boxes" do not necessarily cover the entire duration, there are
some gaps. To specify what is happening during the gaps, one uses DfltPulse
objects - "default pulses" (a single DfltPulse per channel).
PulseBlock handles everything related to keeping the "boxes" time-ordered
when new elements are added: it has methods for inserting additional "boxes"
into arbitrary (empty) places on the "shelf" and for merging several smaller
PulseBlocks into a large one.
--------------- Structure ---------------
The main attribute of PulseBlock object is p_dict - the pulse dictionary.
This is where the entire pulse sequence is stored. In the dictionary:
Key - the channel name;
Value - time-ordered list of Pulse objects for this channel.
After any operation, time axis origin is shifted for the entire PulseBlock
such that the beginning of earliest Pulse is set to 0.
PulseBlock assumes that each Pulse object has the following attributes:
ch - (str) channel name;
t0 - (numeric) pulse start time;
dur - (numeric) duration of the pulse,
dflt_dict attribute contains the default pulse objects:
Key - (str) channel name
Value - DfltPulse object
In addition, PulseBlock has the following attributes:
name (str) - name of the sequence
dur (numeric) - total duration of the sequence
(t0+dur of the latest Pulse object)
"""
def __init__(self, p_obj_list=None, dflt_dict=None, name='', use_auto_dflt=True):
""" Construct new PulseBlock.
Each argument is optional. One can pass non-default values to fill-in
some of the attributes during construction, but any pulses can be added
into any location later. Name can also be changed later.
:param p_obj_list: (opt) list of Pulse objects.
This argument is used to insert some pulses immediately at instantiation.
Example:
p_obj_list = [
pulse.PTrue(ch='ch1', t0=0, dur=1e-6),
pulse.PSin(ch='ch2', t0=1e-6, dur=1e-6, amp=1e-3, freq=2.5e9, ph=0)
]
:param dflt_dict: (opt) dictionary of default-pulse values.
Keys - channel names, values - DfltPulse objects
Can be filled-in at any point later - optional at instantiation.
Example:
dflt_dict = {
'aom': pulse.DFalse()
'analog_out': pulse.DConst(val=0.0)
}
:param name: (opt, str) pulse object name
:use_auto_dflt (bool): If True, auto-assign default pulses based
on pulses used in each track.
"""
self.name = name
self.dur = 0
self.p_dict = dict()
self.dflt_dict = dict()
self.use_auto_dflt = use_auto_dflt
self.latest_t0 = 0
self.latest_dur = 0
if dflt_dict is not None:
self.dflt_dict = copy.deepcopy(dflt_dict)
if p_obj_list is None:
p_obj_list = list()
# If only a single pulse_object is provided,
# wrap as list.
elif type(p_obj_list) is not list:
p_obj_list = [p_obj_list]
# Iterate through all given pulses and _insert them into the block
# (_insert should be used - it does not reset edges)
for p_obj in p_obj_list:
p_obj = copy.deepcopy(p_obj)
self._insert(p_obj=p_obj, use_auto_dflt=self.use_auto_dflt)
# Reset edges: set the left-most edge to zero
# and set self.dur to the right-most edge
self.reset_edges()
def _insert(self, p_obj, cflct_er=True, use_auto_dflt=True):
""" Technical method for inserting a new Pulse object into PulseBlock
Here start and stop edges of PulseBlock are not adjusted.
Insertion location is specified by Pulse object p_obj attributes:
ch - which channel to insert into. If the specified channel is not
yet present in the PulseBlock, the new channel is registered.
t0 - time to place the beginning of the p_obj with respect to the
beginning of PulseBlock. If t0 is negative, p_obj is inserted
before the earliest pulse in PulseBlock. Time origin is NOT
adjusted - p_obj will have negative t0.
:param p_obj: the Pulse object to be inserted
:param cflct_er: (bool) 'conflict-error' check.
If True, before actually inserting p_obj, a check is
performed to ensure that p_obj does not overlap with
existing pulses on the channel. In the case of overlap,
PulseBlock is not altered and ValueError is produced.
:use_auto_dflt: Assign default pulses based on auto_default parameter of
Pulse object.
"""
p_obj = copy.deepcopy(p_obj)
ch = Channel(name=p_obj.ch, is_analog=p_obj.is_analog)
# Sanity check:
# new pulse does not conflict with existing pulses
if cflct_er and ch in self.p_dict.keys():
p_list = self.p_dict[ch]
# Find the position, into which
# the new pulse should be inserted
t0_list = np.array(
[p_item.t0 for p_item in p_list]
)
idx = np.searchsorted(t0_list, p_obj.t0)
# If the new pulse will not be the left-most [idx = 0],
# check for overlap with existing pulse to the left
if idx > 0:
if not (p_list[idx - 1].t0 + p_list[idx - 1].dur) <= p_obj.t0:
cflct_item = p_list[idx - 1]
raise ValueError(
'insert(): conflict on ch="{}": given pulse \n'
' {}, t0={:.2e}, dur={:.2e} \n'
'overlaps with existing pulse to the left \n'
' {}, t0={:.2e}, dur={:.2e}'
''.format(
ch,
str(p_obj),
p_obj.t0,
p_obj.dur,
str(cflct_item),
cflct_item.t0,
cflct_item.dur
)
)
# If the new pulse will not be the right-most [idx = len-1],
# check for overlap with existing pulse to the right
if idx < len(p_list):
if not (p_obj.t0 + p_obj.dur) <= p_list[idx].t0:
cflct_item = p_list[idx]
raise ValueError(
'insert(): conflict on ch="{}": given pulse \n'
' {} t0={:.2e}, dur={:.2e} \n'
'overlaps with existing pulse to the right \n'
' {} t0={:.2e}, dur={:.2e}'
''.format(
ch,
str(p_obj),
p_obj.t0,
p_obj.dur,
str(cflct_item),
cflct_item.t0,
cflct_item.dur
)
)
# Check if the channel already exists with the samne name but a
# different type
for key in self.p_dict.keys():
if ch.name == key.name and ch.is_analog != key.is_analog:
raise ValueError('insert(): tried to insert pulse name {} '
'with pulse type {} when the channel already had pulses '
'of type {}'.format(
ch.name,
'analog' if ch.is_analog else 'digital',
'analog' if key.is_analog else 'digital'
)
)
# Create a new entry for 'ch' if it is not yet registered
if ch not in self.p_dict.keys():
self.p_dict[ch] = []
# Add p_obj as a new entry in 'ch' pulse list
self.p_dict[ch].append(p_obj)
# T-order pulses within 'ch'
self.p_dict[ch].sort(
key=lambda p_item: p_item.t0
)
# Automatically assign default pulse
if use_auto_dflt:
self.dflt_dict[ch] = p_obj.auto_default
# Update the latest values that have been added to the PB
self.latest_t0 = p_obj.t0
self.latest_dur = p_obj.dur
def insert(self, p_obj, cflct_er=True):
""" Insert a new Pulse object into PulseBlock
Insertion location is specified by Pulse object p_obj attributes:
ch - which channel to insert into. If the specified channel is not
yet present in the PulseBlock, the new channel is registered.
t0 - time to place the beginning of the p_obj with respect to the
beginning of PulseBlock. If t0 is negative, p_obj is inserted
before the earliest pulse in PulseBlock and time origin is
shifted into the beginning of p_obj.
:param p_obj: the Pulse object to be inserted
:param cflct_er: (bool) 'conflict-error' check.
If True, before actually inserting p_obj, a check is
performed to ensure that p_obj does not overlap with
existing pulses on the channel. In the case of overlap,
PulseBlock is not altered and ValueError is produced.
:return: None
"""
self._insert(p_obj=p_obj, cflct_er=cflct_er)
self.reset_edges()
def join(self, p_obj, name='', cflct_er=True):
""" Same as insert(), but instead of changing the existing PulseBlock,
a new one is created and the original PulseBlock is not altered.
:param name: name of the new PulseBlock object
:return: (PulseBlock) the new PulseBlock - self with p_obj inserted.
"""
new_pb = copy.deepcopy(self)
new_pb.name = name
new_pb.insert(
p_obj=p_obj,
cflct_er=cflct_er
)
return new_pb
def append(self, | |
sage: G.radius()
5
sage: G.diameter()
5
sage: G.girth()
6
Its chromatic number is `2` and its automorphism group is of order
`192`::
sage: G.chromatic_number()
2
sage: G.automorphism_group().cardinality()
192
It is a non-integral graph as it has irrational eigenvalues::
sage: G.characteristic_polynomial().factor()
(x - 3) * (x + 3) * (x - 1)^9 * (x + 1)^9 * (x^2 - 5)^6
It is a toroidal graph, and its embedding on a torus is dual to an
embedding of the Shrikhande graph (:meth:`ShrikhandeGraph
<GraphGenerators.ShrikhandeGraph>`).
"""
pos_dict = {}
for i in range(8):
pos_dict[i] = [float(cos((2*i) * pi/8)),
float(sin((2*i) * pi/8))]
pos_dict[8 + i] = [0.75 * pos_dict[i][0],
0.75 * pos_dict[i][1]]
pos_dict[16 + i] = [0.50 * pos_dict[i][0],
0.50 * pos_dict[i][1]]
pos_dict[24 + i] = [0.25 * pos_dict[i][0],
0.25 * pos_dict[i][1]]
edge_dict = {
0O00: [0O07, 0O01, 0O10], 0O10: [0O00, 0O27, 0O21],
0O01: [0O00, 0O02, 0O11], 0O11: [0O01, 0O20, 0O22],
0O02: [0O01, 0O03, 0O12], 0O12: [0O02, 0O21, 0O23],
0O03: [0O02, 0O04, 0O13], 0O13: [0O03, 0O22, 0O24],
0O04: [0O03, 0O05, 0O14], 0O14: [0O04, 0O23, 0O25],
0O05: [0O04, 0O06, 0O15], 0O15: [0O05, 0O24, 0O26],
0O06: [0O05, 0O07, 0O16], 0O16: [0O06, 0O25, 0O27],
0O07: [0O06, 0O00, 0O17], 0O17: [0O07, 0O26, 0O20],
0O20: [0O17, 0O11, 0O30], 0O30: [0O20, 0O35, 0O33],
0O21: [0O10, 0O12, 0O31], 0O31: [0O21, 0O36, 0O34],
0O22: [0O11, 0O13, 0O32], 0O32: [0O22, 0O37, 0O35],
0O23: [0O12, 0O14, 0O33], 0O33: [0O23, 0O30, 0O36],
0O24: [0O13, 0O15, 0O34], 0O34: [0O24, 0O31, 0O37],
0O25: [0O14, 0O16, 0O35], 0O35: [0O25, 0O32, 0O30],
0O26: [0O15, 0O17, 0O36], 0O36: [0O26, 0O33, 0O31],
0O27: [0O16, 0O10, 0O37], 0O37: [0O27, 0O34, 0O32],
}
return Graph(edge_dict, pos=pos_dict, name="Dyck graph")
def HortonGraph():
r"""
Returns the Horton Graph.
The Horton graph is a cubic 3-connected non-hamiltonian graph. For more
information, see the :wikipedia:`Horton_graph`.
EXAMPLES::
sage: g = graphs.HortonGraph()
sage: g.order()
96
sage: g.size()
144
sage: g.radius()
10
sage: g.diameter()
10
sage: g.girth()
6
sage: g.automorphism_group().cardinality()
96
sage: g.chromatic_number()
2
sage: g.is_hamiltonian() # not tested -- veeeery long
False
"""
g = Graph(name = "Horton Graph")
# Each group of the 6 groups of vertices is based on the same 3-regular
# graph.
from sage.graphs.generators.families import LCFGraph
lcf = LCFGraph(16,[5,-5],8)
lcf.delete_edge(15,0)
lcf.delete_edge(7,8)
for i in range(6):
for u,v in lcf.edges(labels=False):
g.add_edge((i,u),(i,v))
# Modifying the groups and linking them together
for i in range(3):
g.add_edge((2*i,0),(2*i+1,7))
g.add_edge((2*i+1,8),(2*i,7))
g.add_edge((2*i,15),(2*i+1,0))
g.add_edge((2*i,8),1)
g.add_edge((2*i+1,14),2)
g.add_edge((2*i+1,10),0)
# Embedding
for i in range(6):
_circle_embedding(g, [(i,j) for j in range(16)], center=(cos(2*i*pi/6),sin(2*i*pi/6)), radius=.3)
for i in range(3):
g.delete_vertex((2*i+1,15))
_circle_embedding(g, [0, 1, 2], radius=.2, shift=-0.75)
g.relabel()
return g
def EllinghamHorton54Graph():
r"""
Returns the Ellingham-Horton 54-graph.
For more information, see the :wikipedia:`Wikipedia page on the
Ellingham-Horton graphs <Ellingham-Horton_graph>`
EXAMPLES:
This graph is 3-regular::
sage: g = graphs.EllinghamHorton54Graph()
sage: g.is_regular(k=3)
True
It is 3-connected and bipartite::
sage: g.vertex_connectivity() # not tested - too long
3
sage: g.is_bipartite()
True
It is not Hamiltonian::
sage: g.is_hamiltonian() # not tested - too long
False
... and it has a nice drawing ::
sage: g.show(figsize=[10, 10]) # not tested - too long
TESTS::
sage: g.show() # long time
"""
from sage.graphs.generators.basic import CycleGraph
up = CycleGraph(16)
low = 2*CycleGraph(6)
for v in range(6):
low.add_edge(v, v + 12)
low.add_edge(v + 6, v + 12)
low.add_edge(12, 15)
low.delete_edge(1, 2)
low.delete_edge(8, 7)
low.add_edge(1, 8)
low.add_edge(7, 2)
# The set of vertices on top is 0..15
# Bottom left is 16..33
# Bottom right is 34..52
# The two other vertices are 53, 54
g = up + 2*low
g.name("Ellingham-Horton 54-graph")
g.set_pos({})
g.add_edges([(15, 4), (3, 8), (7, 12), (11, 0), (2, 13), (5, 10)])
g.add_edges([(30, 6), (29, 9), (48, 14), (47, 1)])
g.add_edge(32, 52)
g.add_edge(50, 52)
g.add_edge(33, 53)
g.add_edge(51, 53)
g.add_edge(52, 53)
# Top
_circle_embedding(g, list(range(16)), center=(0, .5), shift=.5, radius=.5)
# Bottom-left
_circle_embedding(g, list(range(16, 22)), center=(-1.5, -1))
_circle_embedding(g, list(range(22, 28)), center=(-1.5, -1), radius=.5)
_circle_embedding(g, list(range(28, 34)), center=(-1.5, -1), radius=.7)
# Bottom right
_circle_embedding(g, list(range(34, 40)), center=(1.5, -1))
_circle_embedding(g, list(range(40, 46)), center=(1.5, -1), radius=.5)
_circle_embedding(g, list(range(46, 52)), center=(1.5, -1), radius=.7)
d = g.get_pos()
d[52] = (-.3, -2.5)
d[53] = (.3, -2.5)
d[31] = (-2.2, -.9)
d[28] = (-.8, -.9)
d[46] = (2.2, -.9)
d[49] = (.8, -.9)
return g
def EllinghamHorton78Graph():
r"""
Returns the Ellingham-Horton 78-graph.
For more information, see the :wikipedia:`Wikipedia page on the
Ellingham-Horton graphs
<http://en.wikipedia.org/wiki/Ellingham%E2%80%93Horton_graph>`
EXAMPLES:
This graph is 3-regular::
sage: g = graphs.EllinghamHorton78Graph()
sage: g.is_regular(k=3)
True
It is 3-connected and bipartite::
sage: g.vertex_connectivity() # not tested - too long
3
sage: g.is_bipartite()
True
It is not Hamiltonian::
sage: g.is_hamiltonian() # not tested - too long
False
... and it has a nice drawing ::
sage: g.show(figsize=[10,10]) # not tested - too long
TESTS::
sage: g.show(figsize=[10, 10]) # not tested - too long
"""
g = Graph({
0: [1, 5, 60], 1: [2, 12], 2: [3, 7], 3: [4, 14], 4: [5, 9],
5: [6], 6: [7, 11], 7: [15], 8: [9, 13, 22], 9: [10],
10: [11, 72], 11: [12], 12: [13], 13: [14], 14: [72],
15: [16, 20], 16: [17, 27], 17: [18, 22], 18: [19, 29],
19: [20, 24], 20: [21], 21: [22, 26], 23: [24, 28, 72],
24: [25], 25: [26, 71], 26: [27], 27: [28], 28: [29],
29: [69], 30: [31, 35, 52], 31: [32, 42], 32: [33, 37],
33: [34, 43], 34: [35, 39], 35: [36], 36: [41, 63],
37: [65, 66], 38: [39, 59, 74], 39: [40], 40: [41, 44],
41: [42], 42: [74], 43: [44, 74], 44: [45], 45: [46, 50],
46: [47, 57], 47: [48, 52], 48: [49, 75], 49: [50, 54],
50: [51], 51: [52, 56], 53: [54, 58, 73], 54: [55],
55: [56, 59], 56: [57], 57: [58], 58: [75], 59: [75],
60: [61, 64], 61: [62, 71], 62: [63, 77], 63: [67],
64: [65, 69], 65: [77], 66: [70, 73], 67: [68, 73],
68: [69, 76], 70: [71, 76], 76: [77]}, pos={})
_circle_embedding(g, list(range(15)), center=(-2.5, 1.5))
_circle_embedding(g, list(range(15, 30)), center=(-2.5, -1.5))
_circle_embedding(g, [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 74, 43, 44], center=(2.5, 1.5))
_circle_embedding(g, [45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 75, 59], center=(2.5, -1.5))
d = g.get_pos()
d[76] = (-.2, -.1)
d[77] = (.2, .1)
d[38] = (2.2, .1)
d[52] = (2.3, -.1)
d[15] = (-2.1, -.1)
d[72] = (-2.1, .1)
_line_embedding(g, [60, 61, 62, 63], first=(-1, 2), last=(1, 2))
_line_embedding(g, [64, 65, 37], first=(-.5, 1.5), last=(1.2, 1.5))
_line_embedding(g, [66, 73, 67, 68, 69], first=(1.2, -2),
last=(-.8, -2))
_line_embedding(g, [66, 70, 71], first=(.7, -1.5), last=(-1, -1.5))
g.name("Ellingham-Horton 78-graph")
return g
def ErreraGraph():
r"""
Returns the Errera graph.
For more information, see this
`Wikipedia article on the Errera graph <http://en.wikipedia.org/wiki/Errera_graph>`_.
EXAMPLES:
The Errera graph is named after <NAME>. It is a planar graph
on 17 vertices and having 45 edges. ::
sage: G = graphs.ErreraGraph(); G
Errera graph: Graph on 17 vertices
sage: G.is_planar()
True
sage: G.order()
17
sage: G.size()
45
The Errera graph is Hamiltonian with radius 3, diameter 4, girth 3,
and chromatic number 4. ::
sage: G.is_hamiltonian()
True
sage: G.radius()
3
sage: G.diameter()
4
sage: G.girth()
3
sage: G.chromatic_number()
4
Each vertex degree is either 5 or 6. That is, if `f` counts the
number of vertices of degree 5 and `s` counts the number of vertices
of degree 6, then `f + s` is equal to the order of the Errera
graph. ::
sage: D = G.degree_sequence()
sage: D.count(5) + D.count(6) == G.order()
True
The automorphism group of the Errera graph is isomorphic to the
dihedral group of order 20. ::
sage: ag = G.automorphism_group()
sage: ag.is_isomorphic(DihedralGroup(10))
True
"""
edge_dict = {
0: [1,7,14,15,16],
1: [2,9,14,15],
2: [3,8,9,10,14],
3: [4,9,10,11],
4: [5,10,11,12],
5: [6,11,12,13],
6: [7,8,12,13,16],
7: [13,15,16],
8: [10,12,14,16],
9: [11,13,15],
10: [12],
11: [13],
13: [15],
14: [16]}
return Graph(edge_dict, name="Errera graph")
def F26AGraph():
r"""
Return the F26A graph.
The F26A graph is a symmetric bipartite cubic graph with 26 | |
<reponame>ritchie46/flopy
import os
import platform
import socket
import copy
import json
import numpy as np
from datetime import datetime
import time
from .metadata import acdd
import flopy
# globals
FILLVALUE = -99999.9
ITMUNI = {0: "undefined", 1: "seconds", 2: "minutes", 3: "hours", 4: "days",
5: "years"}
PRECISION_STRS = ["f4", "f8", "i4"]
STANDARD_VARS = ["longitude", "latitude", "layer", "elevation", "time"]
path = os.path.split(__file__)[0]
with open(path + '/longnames.json') as f:
NC_LONG_NAMES = json.load(f)
class Logger(object):
"""
Basic class for logging events during the linear analysis calculations
if filename is passed, then an file handle is opened
Parameters
----------
filename : bool or string
if string, it is the log file to write. If a bool, then log is
written to the screen. echo (bool): a flag to force screen output
Attributes
----------
items : dict
tracks when something is started. If a log entry is
not in items, then it is treated as a new entry with the string
being the key and the datetime as the value. If a log entry is
in items, then the end time and delta time are written and
the item is popped from the keys
"""
def __init__(self, filename, echo=False):
self.items = {}
self.echo = bool(echo)
if filename == True:
self.echo = True
self.filename = None
elif filename:
self.f = open(filename, 'w', 0) # unbuffered
self.t = datetime.now()
self.log("opening " + str(filename) + " for logging")
else:
self.filename = None
def log(self, phrase):
"""
log something that happened
Parameters
----------
phrase : str
the thing that happened
"""
pass
t = datetime.now()
if phrase in self.items.keys():
s = str(t) + ' finished: ' + str(phrase) + ", took: " + \
str(t - self.items[phrase]) + '\n'
if self.echo:
print(s, )
if self.filename:
self.f.write(s)
self.items.pop(phrase)
else:
s = str(t) + ' starting: ' + str(phrase) + '\n'
if self.echo:
print(s, )
if self.filename:
self.f.write(s)
self.items[phrase] = copy.deepcopy(t)
def warn(self, message):
"""
Write a warning to the log file
Parameters
----------
message : str
the warning text
"""
s = str(datetime.now()) + " WARNING: " + message + '\n'
if self.echo:
print(s, )
if self.filename:
self.f.write(s)
return
class NetCdf(object):
"""
Support for writing a netCDF4 compliant file from a flopy model
Parameters
----------
output_filename : str
Name of the .nc file to write
model : flopy model instance
time_values : the entries for the time dimension
if not None, the constructor will initialize
the file. If None, the perlen array of ModflowDis
will be used
z_positive : str ('up' or 'down')
Positive direction of vertical coordinates written to NetCDF file.
(default 'down')
verbose : if True, stdout is verbose. If str, then a log file
is written to the verbose file
forgive : what to do if a duplicate variable name is being created. If
True, then the newly requested var is skipped. If False, then
an exception is raised.
**kwargs : keyword arguments
modelgrid : flopy.discretization.Grid instance
user supplied model grid which will be used in lieu of the model
object modelgrid for netcdf production
Notes
-----
This class relies heavily on the grid and modeltime objects,
including these attributes: lenuni, itmuni, start_datetime, and proj4.
Make sure these attributes have meaningful values.
"""
def __init__(self, output_filename, model, time_values=None,
z_positive='up', verbose=None, prj=None, logger=None,
forgive=False, **kwargs):
assert output_filename.lower().endswith(".nc")
if verbose is None:
verbose = model.verbose
if logger is not None:
self.logger = logger
else:
self.logger = Logger(verbose)
self.var_attr_dict = {}
self.log = self.logger.log
if os.path.exists(output_filename):
self.logger.warn("removing existing nc file: " + output_filename)
os.remove(output_filename)
self.output_filename = output_filename
self.forgive = bool(forgive)
self.model = model
self.model_grid = model.modelgrid
if "modelgrid" in kwargs:
self.model_grid = kwargs.pop("modelgrid")
self.model_time = model.modeltime
if prj is not None:
self.model_grid.proj4 = prj
if self.model_grid.grid_type == 'structured':
self.dimension_names = ('layer', 'y', 'x')
STANDARD_VARS.extend(['delc', 'delr'])
# elif self.model_grid.grid_type == 'vertex':
# self.dimension_names = ('layer', 'ncpl')
else:
raise Exception('Grid type {} not supported.'.format(
self.model_grid.grid_type))
self.shape = self.model_grid.shape
try:
import dateutil.parser
except:
print('python-dateutil is not installed\n' +
'try pip install python-dateutil')
return
self.start_datetime = self._dt_str(dateutil.parser.parse(
self.model_time.start_datetime))
self.logger.warn("start datetime:{0}".format(str(self.start_datetime)))
proj4_str = self.model_grid.proj4
if proj4_str is None:
proj4_str = 'epsg:4326'
self.log(
'Warning: model has no coordinate reference system specified. '
'Using default proj4 string: {}'.format(proj4_str))
self.proj4_str = proj4_str
self.grid_units = self.model_grid.units
self.z_positive = z_positive
if self.grid_units is None:
self.grid_units = "undefined"
assert self.grid_units in ["feet", "meters", "undefined"], \
"unsupported length units: " + self.grid_units
self.time_units = self.model_time.time_units
# this gives us confidence that every NetCdf instance
# has the same attributes
self.log("initializing attributes")
self._initialize_attributes()
self.log("initializing attributes")
self.time_values_arg = time_values
self.log("initializing file")
self.initialize_file(time_values=self.time_values_arg)
self.log("initializing file")
def __add__(self, other):
new_net = NetCdf.zeros_like(self)
if np.isscalar(other) or isinstance(other, np.ndarray):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:] + \
other
elif isinstance(other, NetCdf):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:] + \
other.nc.variables[vname][:]
else:
raise Exception("NetCdf.__add__(): unrecognized other:{0}". \
format(str(type(other))))
return new_net
def __sub__(self, other):
new_net = NetCdf.zeros_like(self)
if np.isscalar(other) or isinstance(other, np.ndarray):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:] - \
other
elif isinstance(other, NetCdf):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:] - \
other.nc.variables[vname][:]
else:
raise Exception("NetCdf.__sub__(): unrecognized other:{0}". \
format(str(type(other))))
return new_net
def __mul__(self, other):
new_net = NetCdf.zeros_like(self)
if np.isscalar(other) or isinstance(other, np.ndarray):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:] * \
other
elif isinstance(other, NetCdf):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:] * \
other.nc.variables[vname][:]
else:
raise Exception("NetCdf.__mul__(): unrecognized other:{0}". \
format(str(type(other))))
return new_net
def __div__(self, other):
return self.__truediv__(other)
def __truediv__(self, other):
new_net = NetCdf.zeros_like(self)
with np.errstate(invalid="ignore"):
if np.isscalar(other) or isinstance(other, np.ndarray):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][
:] / \
other
elif isinstance(other, NetCdf):
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][
:] / \
other.nc.variables[vname][
:]
else:
raise Exception("NetCdf.__sub__(): unrecognized other:{0}". \
format(str(type(other))))
return new_net
def append(self, other, suffix="_1"):
assert isinstance(other, NetCdf) or isinstance(other, dict)
if isinstance(other, NetCdf):
for vname in other.var_attr_dict.keys():
attrs = other.var_attr_dict[vname].copy()
var = other.nc.variables[vname]
new_vname = vname
if vname in self.nc.variables.keys():
if vname not in STANDARD_VARS:
new_vname = vname + suffix
if "long_name" in attrs:
attrs["long_name"] += " " + suffix
else:
continue
assert new_vname not in self.nc.variables.keys(), \
"var already exists:{0} in {1}". \
format(new_vname, ",".join(self.nc.variables.keys()))
attrs["max"] = var[:].max()
attrs["min"] = var[:].min()
new_var = self.create_variable(new_vname, attrs,
var.dtype,
dimensions=var.dimensions)
new_var[:] = var[:]
else:
for vname, array in other.items():
vname_norm = self.normalize_name(vname)
assert vname_norm in self.nc.variables.keys(), "dict var not in " \
"self.vars:{0}-->". \
format(
vname) + \
",".join(
self.nc.variables.keys())
new_vname = vname_norm + suffix
assert new_vname not in self.nc.variables.keys()
attrs = self.var_attr_dict[vname_norm].copy()
attrs["max"] = np.nanmax(array)
attrs["min"] = np.nanmin(array)
attrs["name"] = new_vname
attrs["long_name"] = attrs["long_name"] + ' ' + suffix
var = self.nc.variables[vname_norm]
# assert var.shape == array.shape,\
# "{0} shape ({1}) doesn't make array shape ({2})".\
# format(new_vname,str(var.shape),str(array.shape))
new_var = self.create_variable(new_vname, attrs,
var.dtype,
dimensions=var.dimensions)
try:
new_var[:] = array
except:
new_var[:, 0] = array
return
def copy(self, output_filename):
new_net = NetCdf.zeros_like(self, output_filename=output_filename)
for vname in self.var_attr_dict.keys():
new_net.nc.variables[vname][:] = self.nc.variables[vname][:]
return new_net
@classmethod
def zeros_like(cls, other, output_filename=None,
verbose=None, logger=None):
new_net = NetCdf.empty_like(other, output_filename=output_filename,
verbose=verbose, logger=logger)
# add the vars to the instance
for vname in other.var_attr_dict.keys():
if new_net.nc.variables.get(vname) is not None:
new_net.logger.warn("variable {0} already defined, skipping". \
format(vname))
continue
new_net.log("adding variable {0}".format(vname))
var = other.nc.variables[vname]
data = var[:]
try:
mask = data.mask
data = np.array(data)
except:
mask = None
new_data = np.zeros_like(data)
new_data[mask] = FILLVALUE
new_var = new_net.create_variable(vname,
other.var_attr_dict[vname],
var.dtype,
dimensions=var.dimensions)
new_var[:] = new_data
new_net.log("adding variable {0}".format(vname))
global_attrs = {}
for attr in other.nc.ncattrs():
if attr not in new_net.nc.ncattrs():
global_attrs[attr] = other.nc[attr]
new_net.add_global_attributes(global_attrs)
return new_net
@classmethod
def empty_like(cls, other, output_filename=None,
verbose=None, logger=None):
if output_filename is None:
output_filename = str(
time.mktime(datetime.now().timetuple())) + ".nc"
while os.path.exists(output_filename):
print('{}...already exists'.format(output_filename))
output_filename = str(
time.mktime(datetime.now().timetuple())) + ".nc"
print('creating temporary netcdf file...' +
'{}'.format(output_filename))
new_net = cls(output_filename, other.model,
time_values=other.time_values_arg, verbose=verbose,
logger=logger)
return new_net
def difference(self, other, minuend="self", mask_zero_diff=True,
onlydiff=True):
"""
make a new NetCDF instance that is the difference with another
netcdf file
Parameters
----------
other : either an str filename of a netcdf file or
a netCDF4 instance
minuend : (optional) the order of the difference operation.
Default is self (e.g. self - other). Can | |
#!/usr/bin/python
# logging should be setup first so imported modules' logging is configured too
import os
from vai.dpuv1.rt import logging_mp
log_file = os.environ['VAI_ALVEO_ROOT'] + "/neptune/logging.ini"
logging_mp.setup_logger(log_file, 'neptune')
from datetime import datetime
import json
import signal
import threading
import time
import tornado.ioloop
import tornado.web
import tornado.websocket
import uuid
import importlib
import logging
import six
if six.PY3:
import asyncio
import numpy as np
from tornado.options import define, options, parse_command_line
if six.PY3:
from tornado.platform.asyncio import AnyThreadEventLoopPolicy
from neptune.common import DummyClass, list_submodules, hinted_tuple_hook
if six.PY3:
from neptune.common_py3 import cancel_async_tasks
else:
from neptune.common import cancel_async_tasks
import neptune.construct as construct
from neptune.service_manager import ServiceManager
from neptune.node_manager import NodeManager
from vai.dpuv1.rt import xstream
define("port", default=8998, help="run web server on this port", type=int)
define("wsport", default=8999, help="run websocket server on this port", type=int)
define("debug", default=True, help="run in debug mode")
logger = logging.getLogger(__name__)
class IndexHandler(tornado.web.RequestHandler):
def get(self, *args):
self.render("index.html", wsport=options.wsport)
class ListServiceHandler(tornado.web.RequestHandler):
def get(self, *args):
ret = {'services': []}
try:
services_list = ServiceManager().list()
services = []
for name, svc in services_list.items():
services.append({
'name': name,
'state': svc['state'],
'url': svc['url'],
'throughput': svc['throughput']
})
services.sort(key=lambda x: x['name'])
ret = {'services': services}
except Exception as e:
logger.exception("List service error")
self.write(json.dumps(ret, sort_keys=True))
class QueryServiceHandler(tornado.web.RequestHandler):
def get(self, *args):
service_name = self.get_argument("service")
ret = {}
try:
services_list = ServiceManager().list()
if service_name in services_list:
ret = services_list[service_name]
del ret['service']
except Exception as e:
logger.exception("Query service error")
self.write(json.dumps(ret, sort_keys=True))
class StartServiceHandler(tornado.web.RequestHandler):
def get(self, *args):
service_name = self.get_argument("id")
runtime_args = self.get_argument("args", {})
ServiceManager().start(service_name, runtime_args)
self.write("service started")
def post(self, *args):
data = json.loads(self.request.body)
service_name = data["id"] # in unicode
runtime_args = data["args"] if 'args' in data else {}
ServiceManager().start(service_name, runtime_args)
self.write("service started")
class StopServiceHandler(tornado.web.RequestHandler):
def get(self, *args):
service_name = self.get_argument("id")
ServiceManager().stop(service_name)
self.write("service stopped")
class ConstructServiceHandler(tornado.web.RequestHandler):
def get(self, *args):
self.write("POST a recipe to this address to construct it")
def post(self, *args):
"""
Parse JSON arguments in POST body. In Requests module, use json key to
pass in arguments, not data (which may clobber JSON objects)
"""
recipe = json.loads(self.request.body, object_hook=hinted_tuple_hook)
tornado_handler = construct.construct(recipe)
name = str(recipe['name'])
url = str(recipe['url'])
self.application.add_handlers(
r".*", # match any host
tornado_handler
)
self.write("service %s constructed at /serve/%s" % (name, url))
# FIXME clients being able to destroy services others may be using is problematic
class DestructServiceHandler(tornado.web.RequestHandler):
def _destroy(self):
url = str(self.get_argument("url"))
name = str(self.get_argument("name"))
fake_request = DummyClass()
found_index = -1
# There's no method in Tornado to delete an added handler currently.
# By examining the source, the code below works to do so. If Tornado
# adds an API to do this, this code should be replaced. It may also
# break with changes to Tornado (tested with Tornado 5.1.1 on 8/15/2019)
for index, parent_rule in enumerate(self.application.default_router.rules):
rules = parent_rule.target.rules
for rule in rules:
fake_request.path = r"/serve/" + url
if isinstance(rule.matcher.match(fake_request), dict):
found_index = index
return found_index, name, url
def get(self, *args):
self.write("POST the name and url of the service to destroy") # TODO only should specify one
def post(self, *args):
found_index, name, url = self._destroy()
if found_index != -1:
del self.application.default_router.rules[found_index]
ServiceManager().remove(name)
recipe_cache = os.environ["VAI_ALVEO_ROOT"] + "/neptune/recipes/recipe_%s.bak" % name
os.remove(recipe_cache)
self.write("service destroyed at /serve/%s" % url)
else:
self.write("Service %s cannot be destroyed as it does not exist" % name)
class RenderHandler(tornado.web.RequestHandler):
def get(self, *args):
url = self.request.uri
url_arg = url.split('/')[-1]
html = url_arg + ".html"
self.render(html, wsport=options.wsport)
class RequestIdGenerator(object):
def __init__(self):
self.handler_ids = {}
def get(self, name='__default__'):
if name not in self.handler_ids:
self.handler_ids[name] = 0
curr_id = self.handler_ids[name]
self.handler_ids[name] = (curr_id + 1) % 10000 # wraparound
return curr_id
class WebSocketHandler(tornado.websocket.WebSocketHandler):
clientConnections = []
def __init__(self, *args, **kwargs):
super(WebSocketHandler, self).__init__(*args, **kwargs)
print("[WS] websocket ready")
def open(self):
self.id = str(uuid.uuid4())
self.last_send = None
print("[WS] websocket opened %s" % self.id)
self.send('id', self.id)
WebSocketHandler.clientConnections.append(self)
def on_message(self, messageStr):
try:
print('[WS] message received from %s: %s' % (self.id, messageStr))
message = json.loads(messageStr)
if message['topic'] == 'update_id':
origId = message['id']
self.id = origId # take over original id
except:
pass
def on_close(self):
print("[WS] websocket closed %s" % self.id)
WebSocketHandler.clientConnections.remove(self)
def send(self, topic, msg):
if not msg:
return
now = time.time()
if self.last_send and (now - self.last_send) < 0.05:
# don't flood the client with too many messages; drop
return
self.last_send = now
try:
msg_POD = {}
msg_POD['time'] = datetime.now().isoformat()
msg_POD['topic'] = topic
msg_POD['message'] = msg
self.write_message(json.dumps(msg_POD))
except Exception as e:
print(e)
@staticmethod
def send_to_client(id, topic, msg):
try:
for c in WebSocketHandler.clientConnections:
if c.id == id:
c.send(topic, msg)
except:
pass
@staticmethod
def broadcast(topic, msg):
try:
for c in WebSocketHandler.clientConnections:
c.send(topic, msg)
except:
pass
def check_origin(self, origin):
return True
class ServerWebApplication(tornado.web.Application):
def __init__(self):
self.request_id_gen = RequestIdGenerator()
handlers = self.init_handlers()
super(ServerWebApplication, self).__init__(
handlers,
cookie_secret="COOKIE_SECRET",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=False, #? should be true?
autoreload=False,
debug=options.debug
)
def init_handlers(self):
"""
Define the basic REST handlers. These cannot be destroyed.
Returns:
List: List of handler tuples for initializing a Tornado web app
"""
handlers = []
handlers.append((r"/", IndexHandler))
handlers.append((r"/services/list", ListServiceHandler))
handlers.append((r"/services/query", QueryServiceHandler))
handlers.append((r"/services/start", StartServiceHandler))
handlers.append((r"/services/stop", StopServiceHandler))
handlers.append((r"/services/construct", ConstructServiceHandler))
handlers.append((r"/services/destruct", DestructServiceHandler))
handlers.append((r"/render/([^/]+)", RenderHandler))
return handlers
class ServerApp(object):
def __init__(self):
signal.signal(signal.SIGINT, self.signal_handler)
# signal.signal(signal.SIGQUIT, self.sigquit_handler)
self.do_exit = False
self.hbeat_id = 0
self.hbeat = 0
# self.do_restart = False
self.xserver = xstream.Server()
parse_command_line()
self.web_app = ServerWebApplication()
# Add handlers for default services here so they can be destroyed if
# needed. Handlers installed in the web_app __init__ cannot be destroyed.
recipes = self.get_recipes()
for recipe in recipes:
tornado_handler = construct.construct(recipe)
self.web_app.add_handlers(
r".*", # match any host
tornado_handler
)
self.web_server = self.web_app.listen(options.port)
self.ws_app = tornado.web.Application([(r"/", WebSocketHandler)])
self.ws_server = self.ws_app.listen(options.wsport)
self.xspub = xstream.Publisher()
self.xs2server = threading.Thread(target=ServerApp.xstream2server)
self.xs2server.start()
self.heartbeat_thread = threading.Thread(target=ServerApp.heartbeat, args=(lambda: self.do_exit,))
self.heartbeat_thread.start()
@staticmethod
def get_recipes():
"""
Get all recipes from the recipes folder. If recipe_*.bak files exist,
use those to construct services. Otherwise, construct from source using
the default recipe functions.
"""
recipes = []
recipes_cache = os.environ["VAI_ALVEO_ROOT"] + "/neptune/recipes/"
file_names = [fn for fn in os.listdir(recipes_cache)
if fn.startswith('recipe_') and fn.endswith('.bak')]
if file_names:
logger.info("Constructing services from cache")
for file_name in file_names:
with open(recipes_cache + file_name) as f:
recipes.append(json.load(f, object_hook=hinted_tuple_hook))
else:
logger.info("Constructing services from source")
modules = list_submodules('neptune.recipes')
for module_path in modules:
module = importlib.import_module(module_path)
attrs = dir(module)
for attr in attrs:
if attr.startswith('recipe_'):
recipe = getattr(module, attr)
if callable(recipe):
recipes.append(recipe().to_dict())
return recipes
@staticmethod
def xstream2server():
xs = xstream.Subscribe("__server__")
while True:
# subscribe to special "__server__" channel for
# other processes to send messages to this server
# e.g. speedodata -> websockets
msg_str = xs.get_msg()
if msg_str is None:
break
try:
msg = json.loads(msg_str)
if msg['topic'] == 'speedodata':
WebSocketHandler.broadcast(msg['topic'], msg['message'])
elif msg['topic'] == 'callback' and 'callback_id' in msg:
# print("sending callback message")
# print(msg['message'])
WebSocketHandler.send_to_client(\
msg['callback_id'], msg['topic'], msg['message'])
elif msg['topic'] == 'xs_throughput':
report = json.loads(msg['message'])
#print(report)
for name, throughput in report.items():
serviceName = name.split('.')[0]
edgeName = name[name.find('.')+1:]
ServiceManager().update_throughput_stats(serviceName,
edgeName, throughput)
except:
pass
cancel_async_tasks()
@staticmethod
def heartbeat(stop):
xs = xstream.Subscribe("__heartbeat__", timeout=5000)
service_manager = ServiceManager()
node_status = {}
def check_services(node_status):
if stop:
return
invalid_services = []
for service, status in node_status.items():
last_valid = status['last_valid']
service_state = service_manager._services[service]['state']
is_starting = service_state == service_manager.STARTING
is_started = service_state == service_manager.STARTED
# if the service has been stopped, clear it
if service_state == service_manager.STOPPED:
invalid_services.append(service)
# if there's a discrepancy in what the service_manager says
# and what we have cached, clear it
elif is_starting and node_status[service]['is_started']:
invalid_services.append(service)
# if it's started and hasn't been valid in the last n secs,
# restart it
elif is_started and now - last_valid > 5:
logger.warning("Service %s is dead, restarting" % service)
service_manager.stop(service)
service_manager.start(service)
node_status[service]['is_started'] = False
for service in invalid_services:
del node_status[service]
logger = logging.getLogger(__name__)
while True:
if stop():
break
# when enabling coverage, this line will raise an exception for some
# reason. For now, just catching it
try:
msg_str = xs.get_msg()
now = time.time()
except Exception:
logger.exception("Shouldn't happen")
# the get_msg timed out, i.e. no heartbeats received
if msg_str == (None, None):
check_services(node_status)
continue
msg = json.loads(msg_str)
service = msg['service']
channel = msg['channel']
# if this is the first time we've seen this service
if service not in node_status:
_first_edge, last_edge = service_manager._get_graph_io(service)
node_status[service] = {
'last_valid': 0, # saves the last time this service was valid
'is_started': False, # our check that services haven't stopped
'last_edge': last_edge[0], # saves the last edge of the service
'channels': {} # save heartbeat times | |
_dst_type, bool _normalized,
int _ksize, int _border_mode=1)
init(self, int _max_width, int _src_type, int _dst_type, bool _normalized,
int _ksize)
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize, CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1, CvScalar _border_value=cvScalarAll(0))
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize, CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1)
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize, CvPoint _anchor=cvPoint(-1,-1))
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize)
init(self, int _max_width, int _src_type, int _dst_type, CvMat _kx,
CvMat _ky, CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1, CvScalar _border_value=cvScalarAll(0))
init(self, int _max_width, int _src_type, int _dst_type, CvMat _kx,
CvMat _ky, CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1)
init(self, int _max_width, int _src_type, int _dst_type, CvMat _kx,
CvMat _ky, CvPoint _anchor=cvPoint(-1,-1))
init(self, int _max_width, int _src_type, int _dst_type, CvMat _kx,
CvMat _ky)
"""
return _cv.CvLaplaceFilter_init(*args)
def is_normalized(*args):
"""is_normalized(self) -> bool"""
return _cv.CvLaplaceFilter_is_normalized(*args)
def is_basic_laplacian(*args):
"""is_basic_laplacian(self) -> bool"""
return _cv.CvLaplaceFilter_is_basic_laplacian(*args)
CvLaplaceFilter_swigregister = _cv.CvLaplaceFilter_swigregister
CvLaplaceFilter_swigregister(CvLaplaceFilter)
class CvMorphology(CvBaseImageFilter):
"""Proxy of C++ CvMorphology class"""
__swig_setmethods__ = {}
for _s in [CvBaseImageFilter]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, CvMorphology, name, value)
__swig_getmethods__ = {}
for _s in [CvBaseImageFilter]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, CvMorphology, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(self) -> CvMorphology
__init__(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0),
CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1, CvScalar _border_value=cvScalarAll(0)) -> CvMorphology
__init__(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0),
CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1) -> CvMorphology
__init__(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0),
CvPoint _anchor=cvPoint(-1,-1)) -> CvMorphology
__init__(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0)) -> CvMorphology
__init__(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element) -> CvMorphology
"""
this = _cv.new_CvMorphology(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _cv.delete_CvMorphology
__del__ = lambda self : None;
def init(*args):
"""
init(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0),
CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1, CvScalar _border_value=cvScalarAll(0))
init(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0),
CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1)
init(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0),
CvPoint _anchor=cvPoint(-1,-1))
init(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element, CvSize _ksize=cvSize(0,0))
init(self, int _operation, int _max_width, int _src_dst_type,
int _element_shape, CvMat _element)
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize, CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1, CvScalar _border_value=cvScalarAll(0))
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize, CvPoint _anchor=cvPoint(-1,-1),
int _border_mode=1)
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize, CvPoint _anchor=cvPoint(-1,-1))
init(self, int _max_width, int _src_type, int _dst_type, bool _is_separable,
CvSize _ksize)
"""
return _cv.CvMorphology_init(*args)
def clear(*args):
"""clear(self)"""
return _cv.CvMorphology_clear(*args)
def get_element(*args):
"""get_element(self) -> CvMat"""
return _cv.CvMorphology_get_element(*args)
def get_element_shape(*args):
"""get_element_shape(self) -> int"""
return _cv.CvMorphology_get_element_shape(*args)
def get_operation(*args):
"""get_operation(self) -> int"""
return _cv.CvMorphology_get_operation(*args)
def get_element_sparse_buf(*args):
"""get_element_sparse_buf(self) -> uchar"""
return _cv.CvMorphology_get_element_sparse_buf(*args)
def get_element_sparse_count(*args):
"""get_element_sparse_count(self) -> int"""
return _cv.CvMorphology_get_element_sparse_count(*args)
RECT = _cv.CvMorphology_RECT
CROSS = _cv.CvMorphology_CROSS
ELLIPSE = _cv.CvMorphology_ELLIPSE
CUSTOM = _cv.CvMorphology_CUSTOM
BINARY = _cv.CvMorphology_BINARY
GRAYSCALE = _cv.CvMorphology_GRAYSCALE
ERODE = _cv.CvMorphology_ERODE
DILATE = _cv.CvMorphology_DILATE
def init_binary_element(*args):
"""
init_binary_element(CvMat _element, int _element_shape, CvPoint _anchor=cvPoint(-1,-1))
init_binary_element(CvMat _element, int _element_shape)
"""
return _cv.CvMorphology_init_binary_element(*args)
if _newclass:init_binary_element = staticmethod(init_binary_element)
__swig_getmethods__["init_binary_element"] = lambda x: init_binary_element
CvMorphology_swigregister = _cv.CvMorphology_swigregister
CvMorphology_swigregister(CvMorphology)
def CvMorphology_init_binary_element(*args):
"""
init_binary_element(CvMat _element, int _element_shape, CvPoint _anchor=cvPoint(-1,-1))
CvMorphology_init_binary_element(CvMat _element, int _element_shape)
"""
return _cv.CvMorphology_init_binary_element(*args)
class CvLevMarq(_object):
"""Proxy of C++ CvLevMarq class"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, CvLevMarq, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, CvLevMarq, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(self) -> CvLevMarq
__init__(self, int nparams, int nerrs, CvTermCriteria criteria=cvTermCriteria(2 +1,30,DBL_EPSILON),
bool completeSymmFlag=False) -> CvLevMarq
__init__(self, int nparams, int nerrs, CvTermCriteria criteria=cvTermCriteria(2 +1,30,DBL_EPSILON)) -> CvLevMarq
__init__(self, int nparams, int nerrs) -> CvLevMarq
"""
this = _cv.new_CvLevMarq(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _cv.delete_CvLevMarq
__del__ = lambda self : None;
def init(*args):
"""
init(self, int nparams, int nerrs, CvTermCriteria criteria=cvTermCriteria(2 +1,30,DBL_EPSILON),
bool completeSymmFlag=False)
init(self, int nparams, int nerrs, CvTermCriteria criteria=cvTermCriteria(2 +1,30,DBL_EPSILON))
init(self, int nparams, int nerrs)
"""
return _cv.CvLevMarq_init(*args)
def update(*args):
"""update(self, CvMat param, CvMat J, CvMat err) -> bool"""
return _cv.CvLevMarq_update(*args)
def updateAlt(*args):
"""updateAlt(self, CvMat param, CvMat JtJ, CvMat JtErr, double errNorm) -> bool"""
return _cv.CvLevMarq_updateAlt(*args)
def clear(*args):
"""clear(self)"""
return _cv.CvLevMarq_clear(*args)
def step(*args):
"""step(self)"""
return _cv.CvLevMarq_step(*args)
DONE = _cv.CvLevMarq_DONE
STARTED = _cv.CvLevMarq_STARTED
CALC_J = _cv.CvLevMarq_CALC_J
CHECK_ERR = _cv.CvLevMarq_CHECK_ERR
__swig_setmethods__["mask"] = _cv.CvLevMarq_mask_set
__swig_getmethods__["mask"] = _cv.CvLevMarq_mask_get
if _newclass:mask = _swig_property(_cv.CvLevMarq_mask_get, _cv.CvLevMarq_mask_set)
__swig_setmethods__["prevParam"] = _cv.CvLevMarq_prevParam_set
__swig_getmethods__["prevParam"] = _cv.CvLevMarq_prevParam_get
if _newclass:prevParam = _swig_property(_cv.CvLevMarq_prevParam_get, _cv.CvLevMarq_prevParam_set)
__swig_setmethods__["param"] = _cv.CvLevMarq_param_set
__swig_getmethods__["param"] = _cv.CvLevMarq_param_get
if _newclass:param = _swig_property(_cv.CvLevMarq_param_get, _cv.CvLevMarq_param_set)
__swig_setmethods__["J"] = _cv.CvLevMarq_J_set
__swig_getmethods__["J"] = _cv.CvLevMarq_J_get
if _newclass:J = _swig_property(_cv.CvLevMarq_J_get, _cv.CvLevMarq_J_set)
__swig_setmethods__["err"] = _cv.CvLevMarq_err_set
__swig_getmethods__["err"] = _cv.CvLevMarq_err_get
if _newclass:err = _swig_property(_cv.CvLevMarq_err_get, _cv.CvLevMarq_err_set)
__swig_setmethods__["JtJ"] = _cv.CvLevMarq_JtJ_set
__swig_getmethods__["JtJ"] = _cv.CvLevMarq_JtJ_get
if _newclass:JtJ = _swig_property(_cv.CvLevMarq_JtJ_get, _cv.CvLevMarq_JtJ_set)
__swig_setmethods__["JtJN"] = _cv.CvLevMarq_JtJN_set
__swig_getmethods__["JtJN"] = _cv.CvLevMarq_JtJN_get
if _newclass:JtJN = _swig_property(_cv.CvLevMarq_JtJN_get, _cv.CvLevMarq_JtJN_set)
__swig_setmethods__["JtErr"] = _cv.CvLevMarq_JtErr_set
__swig_getmethods__["JtErr"] = _cv.CvLevMarq_JtErr_get
if _newclass:JtErr = _swig_property(_cv.CvLevMarq_JtErr_get, _cv.CvLevMarq_JtErr_set)
__swig_setmethods__["JtJV"] = _cv.CvLevMarq_JtJV_set
__swig_getmethods__["JtJV"] = _cv.CvLevMarq_JtJV_get
if _newclass:JtJV = _swig_property(_cv.CvLevMarq_JtJV_get, _cv.CvLevMarq_JtJV_set)
__swig_setmethods__["JtJW"] = _cv.CvLevMarq_JtJW_set
__swig_getmethods__["JtJW"] = _cv.CvLevMarq_JtJW_get
if _newclass:JtJW = _swig_property(_cv.CvLevMarq_JtJW_get, _cv.CvLevMarq_JtJW_set)
__swig_setmethods__["prevErrNorm"] = _cv.CvLevMarq_prevErrNorm_set
__swig_getmethods__["prevErrNorm"] = _cv.CvLevMarq_prevErrNorm_get
if _newclass:prevErrNorm = _swig_property(_cv.CvLevMarq_prevErrNorm_get, _cv.CvLevMarq_prevErrNorm_set)
__swig_setmethods__["errNorm"] = _cv.CvLevMarq_errNorm_set
__swig_getmethods__["errNorm"] = _cv.CvLevMarq_errNorm_get
if _newclass:errNorm = _swig_property(_cv.CvLevMarq_errNorm_get, _cv.CvLevMarq_errNorm_set)
__swig_setmethods__["lambdaLg10"] = _cv.CvLevMarq_lambdaLg10_set
__swig_getmethods__["lambdaLg10"] = _cv.CvLevMarq_lambdaLg10_get
if _newclass:lambdaLg10 = _swig_property(_cv.CvLevMarq_lambdaLg10_get, _cv.CvLevMarq_lambdaLg10_set)
__swig_setmethods__["criteria"] = _cv.CvLevMarq_criteria_set
__swig_getmethods__["criteria"] = _cv.CvLevMarq_criteria_get
if _newclass:criteria = _swig_property(_cv.CvLevMarq_criteria_get, _cv.CvLevMarq_criteria_set)
__swig_setmethods__["state"] = _cv.CvLevMarq_state_set
__swig_getmethods__["state"] = _cv.CvLevMarq_state_get
if _newclass:state = _swig_property(_cv.CvLevMarq_state_get, _cv.CvLevMarq_state_set)
__swig_setmethods__["iters"] = _cv.CvLevMarq_iters_set
__swig_getmethods__["iters"] = _cv.CvLevMarq_iters_get
if _newclass:iters = _swig_property(_cv.CvLevMarq_iters_get, _cv.CvLevMarq_iters_set)
__swig_setmethods__["completeSymmFlag"] = _cv.CvLevMarq_completeSymmFlag_set
__swig_getmethods__["completeSymmFlag"] = _cv.CvLevMarq_completeSymmFlag_get
if _newclass:completeSymmFlag = _swig_property(_cv.CvLevMarq_completeSymmFlag_get, _cv.CvLevMarq_completeSymmFlag_set)
CvLevMarq_swigregister = _cv.CvLevMarq_swigregister
CvLevMarq_swigregister(CvLevMarq)
class CvTuple_CvPoint_2(_object):
"""Proxy of C++ CvTuple_CvPoint_2 class"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, CvTuple_CvPoint_2, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, CvTuple_CvPoint_2, name)
__repr__ = _swig_repr
__swig_setmethods__["val"] = _cv.CvTuple_CvPoint_2_val_set
__swig_getmethods__["val"] = _cv.CvTuple_CvPoint_2_val_get
if _newclass:val = _swig_property(_cv.CvTuple_CvPoint_2_val_get, _cv.CvTuple_CvPoint_2_val_set)
def __setitem__(*args):
"""__setitem__(self, int i, CvPoint obj)"""
return _cv.CvTuple_CvPoint_2___setitem__(*args)
def __getitem__(*args):
"""__getitem__(self, int i) -> CvPoint"""
return _cv.CvTuple_CvPoint_2___getitem__(*args)
def __init__(self, *args):
"""__init__(self) -> CvTuple_CvPoint_2"""
this = _cv.new_CvTuple_CvPoint_2(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _cv.delete_CvTuple_CvPoint_2
__del__ = lambda self : None;
CvTuple_CvPoint_2_swigregister = _cv.CvTuple_CvPoint_2_swigregister
CvTuple_CvPoint_2_swigregister(CvTuple_CvPoint_2)
class CvTuple_float_2(_object):
"""Proxy of C++ CvTuple_float_2 class"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, CvTuple_float_2, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, CvTuple_float_2, name)
__repr__ = _swig_repr
__swig_setmethods__["val"] = _cv.CvTuple_float_2_val_set
__swig_getmethods__["val"] = _cv.CvTuple_float_2_val_get
if _newclass:val = _swig_property(_cv.CvTuple_float_2_val_get, _cv.CvTuple_float_2_val_set)
def __setitem__(*args):
"""__setitem__(self, int i, float obj)"""
return _cv.CvTuple_float_2___setitem__(*args)
def __getitem__(*args):
"""__getitem__(self, int i) -> float"""
return _cv.CvTuple_float_2___getitem__(*args)
def __init__(self, *args):
"""__init__(self) -> CvTuple_float_2"""
this = _cv.new_CvTuple_float_2(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _cv.delete_CvTuple_float_2
__del__ = lambda self : None;
CvTuple_float_2_swigregister = _cv.CvTuple_float_2_swigregister
CvTuple_float_2_swigregister(CvTuple_float_2)
class CvTuple_float_3(_object):
"""Proxy of C++ CvTuple_float_3 class"""
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, CvTuple_float_3, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, CvTuple_float_3, name)
__repr__ = _swig_repr
__swig_setmethods__["val"] = _cv.CvTuple_float_3_val_set
__swig_getmethods__["val"] = _cv.CvTuple_float_3_val_get
if _newclass:val = _swig_property(_cv.CvTuple_float_3_val_get, _cv.CvTuple_float_3_val_set)
def __setitem__(*args):
"""__setitem__(self, int i, float obj)"""
return _cv.CvTuple_float_3___setitem__(*args)
def __getitem__(*args):
"""__getitem__(self, int i) -> float"""
return _cv.CvTuple_float_3___getitem__(*args)
def __init__(self, *args):
"""__init__(self) -> CvTuple_float_3"""
this = _cv.new_CvTuple_float_3(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _cv.delete_CvTuple_float_3
__del__ = lambda self : None;
CvTuple_float_3_swigregister = _cv.CvTuple_float_3_swigregister
CvTuple_float_3_swigregister(CvTuple_float_3)
class CvSeq_CvPoint(CvSeq):
"""Proxy of C++ CvSeq_CvPoint class"""
__swig_setmethods__ = {}
for _s in [CvSeq]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, CvSeq_CvPoint, name, value)
__swig_getmethods__ = {}
for _s in [CvSeq]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, CvSeq_CvPoint, name)
__repr__ = _swig_repr
def cast(*args):
"""cast(CvSeq seq) -> CvSeq_CvPoint"""
return _cv.CvSeq_CvPoint_cast(*args)
if _newclass:cast = staticmethod(cast)
__swig_getmethods__["cast"] = lambda x: cast
def __getitem__(*args):
"""__getitem__(self, int i) -> CvPoint"""
| |
directly passed to the
corresponding plotting tools of the ParaMonte library to
draw the corresponding subplots, if they are activated.
Example usage:
.. code-block:: python
layout.contour.contour.kws.colors = "blue"
currentFig
A structure whose attributes are the outputs of various plotting
tools used to make the current figure. These include the handle
to the current figure, the handle to the current axes in the plot,
the handle to the colorbar (if any exists), and other Python
plotting tools used to make to generate the figure.
**Returns**
self
An object of class ``GridPlot``.
---------------------------------------------------------------------------
"""
################################################################################################################################
#### __init__
################################################################################################################################
def __init__( self
, plotType # : str
, dataFrame = None # : tp.Optional[ pd.DataFrame ] = None
, methodName = "ParaMonte" # : tp.Optional[ str ] = "ParaMonte"
, reportEnabled = True # : tp.Optional[ bool ] = True
, resetPlot = None
):
super().__init__( plotType = plotType
, dataFrame = dataFrame
, methodName = methodName
, reportEnabled = reportEnabled
, resetPlot = resetPlot
)
self._reset()
if resetPlot is None: self._resetPlot = self._reset
self._progress.note()
################################################################################################################################
#### _reset
################################################################################################################################
def _reset(self):
super()._reset()
self.columns = None
self.ccolumn = [] # use the default colormap data (which is the data count)
self.pairgrid = Struct()
self.pairgrid.kws = Struct()
self.colorbar = Struct()
self.colorbar.enabled = True
self.colorbar.kws = Struct()
############################################################################################################################
#### setup corner types
############################################################################################################################
cornerNames = [ "line"
, "scatter"
, "lineScatter"
, "contourf"
, "contour"
]
self.plotType = Struct()
self.plotType.diag = Struct()
self.plotType.diag.enabled = True
self.plotType.diag.value = "histplot"
self.plotType.diag.names = ["histplot"]
self.plotType.upper = Struct()
self.plotType.upper.enabled = True
self.plotType.upper.value = "lineScatter"
self.plotType.upper.names = dcopy(cornerNames)
self.plotType.lower = Struct()
self.plotType.lower.enabled = True
self.plotType.lower.value = "contour"
self.plotType.lower.names = dcopy(cornerNames)
############################################################################################################################
#### setup subplot templates
############################################################################################################################
template = Struct()
# target
template.target = Struct()
template.target.axvline = Struct()
template.target.axvline.kws = Struct()
template.target.axhline = Struct()
template.target.axhline.kws = Struct()
template.target.scatter = Struct()
template.target.scatter.kws = Struct()
template.target.axvline.kws.linewidth = 0.5
template.target.axvline.kws.linestyle = "-"
template.target.axvline.kws.zorder = 1000
template.target.axvline.kws.color = "orangered"
template.target.axhline.kws.linewidth = 0.5
template.target.axhline.kws.linestyle = "-"
template.target.axhline.kws.zorder = 1000
template.target.axhline.kws.color = "orangered"
template.target.scatter.kws.s = 20
template.target.scatter.kws.color = "orangered"
template.target.scatter.kws.zorder = 1002
# contour
template.contour = Struct()
template.contour.enabled = True
template.contour.kws = Struct()
template.contour.kws.cmap = "winter"
template.contour.kws.alpha = 1
template.contour.kws.levels = 10
template.contour.kws.linewidths = 1
template.contour.kws.linestyles = "solid"
# contourf
template.contourf = Struct()
template.contourf.enabled = True
template.contourf.kws = Struct()
template.contourf.kws.cmap = "Blues"
template.contourf.kws.alpha = 1
template.contourf.kws.levels = 50
# histplot
template.histplot = Struct()
template.histplot.enabled = True
template.histplot.kws = Struct()
template.histplot.kws.kde = False
template.histplot.kws.bins = "auto"
template.histplot.kws.stat = "count"
template.histplot.kws.kde_kws = dict()
template.histplot.kws.binwidth = None
template.histplot.kws.binrange = None
template.histplot.kws.multiple = "stack"
template.histplot.kws.element = "step"
template.histplot.kws.legend = False
template.histplot.kws.shrink = 1
template.histplot.kws.color = None
template.histplot.kws.fill = True
template.histplot.kws.common_norm = True
template.histplot.kws.common_bins = False
template.histplot.kws.line_kws = dict()
template.histplot.kws.line_kws["linewidth"] = 0
template.histplot.kws.line_kws["linestyle"] = "-"
# legend template
template.legend = Struct()
template.legend.enabled = False
template.legend.kws = Struct()
# colorbar template
template.colorbar = Struct()
template.colorbar.enabled = False
template.colorbar.kws = Struct()
# line / scatter / lineScatter
template.scatter = Struct()
template.scatter.enabled = True
template.scatter.kws = Struct()
template.scatter.kws.s = 2
template.scatter.kws.c = None
template.scatter.kws.cmap = "winter"
template.scatter.kws.alpha = 1
template.scatter.kws.edgecolor = None
template.scatter.kws.zorder = 2
template.plot = Struct()
template.plot.enabled = False
template.plot.kws = Struct()
template.plot.kws.linewidth = 1
template.plot.kws.zorder = 1
template.lineCollection = Struct()
template.lineCollection.enabled = True
template.lineCollection.kws = Struct()
template.lineCollection.kws.cmap = "winter"
template.lineCollection.kws.alpha = 1
template.lineCollection.kws.linewidth = 1
# figure
template.figure = Struct()
template.figure.kws = Struct()
template.figure.enabled = False
############################################################################################################################
#### setup subplots layout
############################################################################################################################
self.layout = Struct()
self.layout.contour = Struct()
self.layout.contour.figure = dcopy(template.figure)
self.layout.contour.contour = dcopy(template.contour)
self.layout.contour.colorbar = dcopy(template.colorbar)
#self.layout.contour.target = dcopy(template.target)
self.layout.contour.noiseDensity = 1.e-3
self.layout.contour.limits = None
self.layout.contour.gridSize = 512
self.layout.contourf = Struct()
self.layout.contourf.figure = dcopy(template.figure)
self.layout.contourf.contourf = dcopy(template.contourf)
self.layout.contourf.colorbar = dcopy(template.colorbar)
#self.layout.contourf.target = dcopy(template.target)
self.layout.contourf.noiseDensity = 1.e-5
self.layout.contourf.limits = None
self.layout.contourf.gridSize = 512
self.layout.histplot = Struct()
self.layout.histplot.figure = dcopy(template.figure)
self.layout.histplot.histplot = dcopy(template.histplot)
self.layout.histplot.legend = dcopy(template.legend)
#self.layout.histplot.target = dcopy(template.target)
self.layout.line = Struct()
self.layout.line.figure = dcopy(template.figure)
self.layout.line.plot = dcopy(template.plot)
self.layout.line.lineCollection = dcopy(template.lineCollection)
self.layout.line.colorbar = dcopy(template.colorbar)
self.layout.line.legend = dcopy(template.legend)
#self.layout.line.target = dcopy(template.target)
self.layout.scatter = Struct()
self.layout.scatter.figure = dcopy(template.figure)
self.layout.scatter.scatter = dcopy(template.scatter)
self.layout.scatter.colorbar = dcopy(template.colorbar)
self.layout.scatter.legend = dcopy(template.legend)
#self.layout.scatter.target = dcopy(template.target)
self.layout.lineScatter = Struct()
self.layout.lineScatter.figure = dcopy(template.figure)
self.layout.lineScatter.plot = dcopy(template.plot)
self.layout.lineScatter.scatter = dcopy(template.scatter)
self.layout.lineScatter.lineCollection = dcopy(template.lineCollection)
self.layout.lineScatter.colorbar = dcopy(template.colorbar)
self.layout.lineScatter.legend = dcopy(template.legend)
#self.layout.lineScatter.target = dcopy(template.target)
self.layout.lineScatter.plot.enabled = True
self.layout.lineScatter.plot.kws.alpha = 0.2
self.layout.lineScatter.plot.kws.color = "grey"
self.layout.lineScatter.plot.kws.linewidth = 0.75
self.layout.lineScatter.lineCollection.enabled = False
############################################################################################################################
self._isdryrun = True
self.make()
self._isdryrun = False
################################################################################################################################
#### __call__
################################################################################################################################
def __call__( self
, reself : tp.Optional[ bool ] = False
, **kwargs
):
"""
Call the ``make()`` method of the current
instance of the class.
**Parameters**
Any arguments that can be passed to the
``make()`` method of the plot object.
**Returns**
Any return value from the ``make()``
method of the plot object.
"""
return self.make(reself, **kwargs)
################################################################################################################################
#### make
################################################################################################################################
def make( self
, reself : tp.Optional[ bool ] = False
, **kwargs
):
"""
Generate a grid plot from the selected
columns of the object's dataFrame.
**Parameters**
reself
A logical variable. If ``True``, an instance of
the object will be returned to the calling routine
upon exit. The default value is ``False``.
**Returns**
The object self if ``reself = True`` otherwise, ``None``.
However, this method causes side-effects by manipulating
the existing attributes of the object.
"""
for key in kwargs.keys():
if hasattr(self,key):
setattr(self, key, kwargs[key])
elif key=="dataFrame":
setattr( self, "_dfref", wref.ref(kwargs[key]) )
else:
raise Exception ( "Unrecognized input '"+key+"' class attribute detected." + newline
+ self._getDocString()
)
self._cEnabled = self.ccolumn is not None
############################################################################################################################
#### verify the plot types to draw
############################################################################################################################
if self.plotType.upper.enabled and (not (isinstance(self.plotType.upper.value,str) and self.plotType.upper.value in self.plotType.upper.names)):
raise Exception ( "Unrecognized input value for the \"plotType.upper.value\" of the GridPlot object." + newline
+ "The possible plot type names are given in \"plotType.upper.value\" of the object." + newline
+ self._getDocString()
)
if self.plotType.lower.enabled and (not (isinstance(self.plotType.lower.value,str) and self.plotType.lower.value in self.plotType.lower.names)):
raise Exception ( "Unrecognized input value for the \"plotType.lower.value\" of the GridPlot object." + newline
+ "The possible plot type names are given in \"plotType.lower.value\" of the object." + newline
+ self._getDocString()
)
if self.plotType.diag.enabled and (not (isinstance(self.plotType.diag.value,str) and self.plotType.diag.value in self.plotType.diag.names)):
raise Exception ( "Unrecognized input value for the \"plotType.diag.value\" of the GridPlot object." + newline
+ "The possible plot type names are given in \"plotType.diag.value\" of the object." + newline
+ self._getDocString()
)
############################################################################################################################
############################################################################################################################
if self._isdryrun: return
############################################################################################################################
############################################################################################################################
import seaborn as sns
import matplotlib.pyplot as plt
plt.ion() # turn on the interactive mode. Used to detach the figure from the command line in ipython
############################################################################################################################
#### generate figure and axes if needed
############################################################################################################################
self._constructBasePlot()
############################################################################################################################
#### check data type
############################################################################################################################
self._checkDataType()
############################################################################################################################
#### check rows presence. This must be checked here, because it depends on the integrity of the in input dataFrame.
############################################################################################################################
if self.rows is None: self.rows = range(len(self._dfref().index))
############################################################################################################################
#### check columns presence. This must be checked here, because it depends on the integrity of the in input dataFrame.
############################################################################################################################
# assign x columns to plot
#if isinstance(self.columns,list):
try:
self._colnames, self._colindex = pm.dfutils.getColNamesIndex(self._dfref().columns,self.columns)
colindexlen = len(self._colindex)
except:
raise Exception ( "The columns component of the current GridPlot object must point to" + newline
+ "the names of a set of the columns of the input dataFrame to the GridPlot" + newline
+ "class constructor." + newline
+ self._getDocString()
)
if colindexlen==0:
raise Exception ( "The length of the ``columns`` component of the GridPlot object cannot be zero." + newline
+ self._getDocString()
)
# set color data
if self._cEnabled:
if isinstance(self.ccolumn,str) or isinstance(self.ccolumn,int):
self._ccolname, self._ccolindex = pm.dfutils.getColNamesIndex(self._dfref().columns,self.ccolumn)
#self._cdata = self._dfref().iloc[self.rows,self._colindex[0]].values.flatten()
elif isinstance(self.ccolumn,list) and len(self.ccolumn)==0:
self._ccolname = "Count"
self._ccolindex = []
else:
raise Exception ( "The ccolumn component of the current GridPlot object must point to" + newline
+ "the names of a column of the input dataFrame to the GridPlot" + newline
+ "class constructor. It represents the set of values that will " + | |
certain uses of the "is" operator, like those
involving comparisons between instance methods, or constants.
Check their documentation for more info.
[5] The "%" operator is also used for string formatting; the same
precedence applies.
[6] The power operator "**" binds less tightly than an arithmetic
or bitwise unary operator on its right, that is, "2**-1" is "0.5".
"""
, 'pass':
"""The "pass" statement
********************
pass_stmt ::= "pass"
"pass" is a null operation --- when it is executed, nothing happens.
It is useful as a placeholder when a statement is required
syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
"""
, 'power':
"""The power operator
******************
The power operator binds more tightly than unary operators on its
left; it binds less tightly than unary operators on its right. The
syntax is:
power ::= ( await_expr | primary ) ["**" u_expr]
Thus, in an unparenthesized sequence of power and unary operators, the
operators are evaluated from right to left (this does not constrain
the evaluation order for the operands): "-1**2" results in "-1".
The power operator has the same semantics as the built-in "pow()"
function, when called with two arguments: it yields its left argument
raised to the power of its right argument. The numeric arguments are
first converted to a common type, and the result is of that type.
For int operands, the result has the same type as the operands unless
the second argument is negative; in that case, all arguments are
converted to float and a float result is delivered. For example,
"10**2" returns "100", but "10**-2" returns "0.01".
Raising "0.0" to a negative power results in a "ZeroDivisionError".
Raising a negative number to a fractional power results in a "complex"
number. (In earlier versions it raised a "ValueError".)
"""
, 'raise':
"""The "raise" statement
*********************
raise_stmt ::= "raise" [expression ["from" expression]]
If no expressions are present, "raise" re-raises the last exception
that was active in the current scope. If no exception is active in
the current scope, a "RuntimeError" exception is raised indicating
that this is an error.
Otherwise, "raise" evaluates the first expression as the exception
object. It must be either a subclass or an instance of
"BaseException". If it is a class, the exception instance will be
obtained when needed by instantiating the class with no arguments.
The *type* of the exception is the exception instance's class, the
*value* is the instance itself.
A traceback object is normally created automatically when an exception
is raised and attached to it as the "__traceback__" attribute, which
is writable. You can create an exception and set your own traceback in
one step using the "with_traceback()" exception method (which returns
the same exception instance, with its traceback set to its argument),
like so:
raise Exception("foo occurred").with_traceback(tracebackobj)
The "from" clause is used for exception chaining: if given, the second
*expression* must be another exception class or instance, which will
then be attached to the raised exception as the "__cause__" attribute
(which is writable). If the raised exception is not handled, both
exceptions will be printed:
>>> try:
... print(1 / 0)
... except Exception as exc:
... raise RuntimeError("Something bad happened") from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
A similar mechanism works implicitly if an exception is raised inside
an exception handler or a "finally" clause: the previous exception is
then attached as the new exception's "__context__" attribute:
>>> try:
... print(1 / 0)
... except:
... raise RuntimeError("Something bad happened")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
Exception chaining can be explicitly suppressed by specifying "None"
in the "from" clause:
>>> try:
... print(1 / 0)
... except:
... raise RuntimeError("Something bad happened") from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
Additional information on exceptions can be found in section
Exceptions, and information about handling exceptions is in section
The try statement.
Changed in version 3.3: "None" is now permitted as "Y" in "raise X
from Y".
New in version 3.3: The "__suppress_context__" attribute to suppress
automatic display of the exception context.
"""
, 'return':
"""The "return" statement
**********************
return_stmt ::= "return" [expression_list]
"return" may only occur syntactically nested in a function definition,
not within a nested class definition.
If an expression list is present, it is evaluated, else "None" is
substituted.
"return" leaves the current function call with the expression list (or
"None") as return value.
When "return" passes control out of a "try" statement with a "finally"
clause, that "finally" clause is executed before really leaving the
function.
In a generator function, the "return" statement indicates that the
generator is done and will cause "StopIteration" to be raised. The
returned value (if any) is used as an argument to construct
"StopIteration" and becomes the "StopIteration.value" attribute.
In an asynchronous generator function, an empty "return" statement
indicates that the asynchronous generator is done and will cause
"StopAsyncIteration" to be raised. A non-empty "return" statement is
a syntax error in an asynchronous generator function.
"""
, 'sequence-types':
"""Emulating container types
*************************
The following methods can be defined to implement container objects.
Containers usually are sequences (such as lists or tuples) or mappings
(like dictionaries), but can represent other containers as well. The
first set of methods is used either to emulate a sequence or to
emulate a mapping; the difference is that for a sequence, the
allowable keys should be the integers *k* for which "0 <= k < N" where
*N* is the length of the sequence, or slice objects, which define a
range of items. It is also recommended that mappings provide the
methods "keys()", "values()", "items()", "get()", "clear()",
"setdefault()", "pop()", "popitem()", "copy()", and "update()"
behaving similar to those for Python's standard dictionary objects.
The "collections" module provides a "MutableMapping" abstract base
class to help create those methods from a base set of "__getitem__()",
"__setitem__()", "__delitem__()", and "keys()". Mutable sequences
should provide methods "append()", "count()", "index()", "extend()",
"insert()", "pop()", "remove()", "reverse()" and "sort()", like Python
standard list objects. Finally, sequence types should implement
addition (meaning concatenation) and multiplication (meaning
repetition) by defining the methods "__add__()", "__radd__()",
"__iadd__()", "__mul__()", "__rmul__()" and "__imul__()" described
below; they should not define other numerical operators. It is
recommended that both mappings and sequences implement the
"__contains__()" method to allow efficient use of the "in" operator;
for mappings, "in" should search the mapping's keys; for sequences, it
should search through the values. It is further recommended that both
mappings and sequences implement the "__iter__()" method to allow
efficient iteration through the container; for mappings, "__iter__()"
should be the same as "keys()"; for sequences, it should iterate
through the values.
object.__len__(self)
Called to implement the built-in function "len()". Should return
the length of the object, an integer ">=" 0. Also, an object that
doesn't define a "__bool__()" method and whose "__len__()" method
returns zero is considered to be false in a Boolean context.
**CPython implementation detail:** In CPython, the length is
required to be at most "sys.maxsize". If the length is larger than
"sys.maxsize" some features (such as "len()") may raise
"OverflowError". To prevent raising "OverflowError" by truth value
testing, an object must define a "__bool__()" method.
object.__length_hint__(self)
Called to implement "operator.length_hint()". Should return an
estimated length for the object (which may be greater or less than
the actual length). The length must be an integer ">=" 0. This
method is purely an optimization and is never required for
correctness.
New in version 3.4.
Note: Slicing is done exclusively with the following three methods.
A call like
a[1:2] = b
is translated to
a[slice(1, 2, None)] = b
and so forth. Missing slice items are always filled in with "None".
object.__getitem__(self, key)
Called to implement evaluation of "self[key]". For sequence types,
the accepted keys should be integers and slice objects. Note that
the special interpretation of negative indexes (if the class wishes
to emulate a sequence type) | |
import atexit
import os
import threading
import time
from collections import OrderedDict
from sys import version_info
if version_info[0] >= 3:
import configparser as ConfigParser
else:
import ConfigParser
_MODE_NAV = 'navigate'
_MODE_ADJ = 'adjust'
_MODE_TXT = 'entry'
class MenuIcon:
arrow_left = [0, 0, 8, 24, 8, 0, 0, 0]
arrow_right = [0, 0, 2, 3, 2, 0, 0, 0]
arrow_up = [0, 4, 14, 0, 0, 0, 0, 0]
arrow_down = [0, 0, 0, 0, 0, 14, 4, 0]
arrow_left_right = [0, 0, 10, 27, 10, 0, 0, 0]
arrow_up_down = [0, 4, 14, 0, 0, 14, 4, 0]
play = [0, 24, 30, 31, 30, 24, 0, 0]
pause = [0, 27, 27, 27, 27, 27, 0, 0]
back = [0, 8, 30, 9, 1, 1, 14, 0]
bar_left = [0, 3, 2, 2, 2, 2, 3, 0]
bar_right = [0, 24, 8, 8, 8, 8, 24, 0]
bar_full = [0, 31, 0, 31, 31, 0, 31, 0]
bar_empty = [0, 32, 0, 0, 0, 0, 32, 0]
class StoppableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
self.daemon = True
def start(self):
if not self.isAlive():
self.stop_event.clear()
threading.Thread.start(self)
def stop(self):
if self.isAlive():
# set event to signal thread to terminate
self.stop_event.set()
# block calling thread until thread really has terminated
self.join()
class AsyncWorker(StoppableThread):
def __init__(self, todo):
StoppableThread.__init__(self)
self.todo = todo
def run(self):
while not self.stop_event.is_set():
if self.todo() is False:
self.stop_event.set()
break
class Menu:
"""
This class accepts a list of menu items,
Each key corresponds to a text item displayed on the menu
Each value can either be:
* A nested list, for a sub-menu
* A function, which is called immediately on select
* A class derived from MenuOption, providing interactive functionality
"""
def __init__(self, *args, **kwargs):
"""
structure, lcd, idle_handler = None, idle_time = 60
"""
self.menu_options = OrderedDict()
self.lcd = None
self.idle_handler = None
self.input_handler = None
self.idle_time = 60 * 1000
self.config_file = 'dot3k.cfg'
# Track displayed text for auto-scroll
self.last_text = ['', '', '']
self.last_change = [0, 0, 0]
if len(args) > 0 and args[0] is not None:
self.menu_options = args[0]
if len(args) > 1:
self.lcd = args[1]
if len(args) > 2:
self.idle_handler = args[2]
if len(args) > 3:
self.idle_time = args[3] * 1000
if 'structure' in kwargs.keys() and kwargs['structure'] is not None:
self.menu_options = kwargs['structure']
if 'lcd' in kwargs.keys():
self.lcd = kwargs['lcd']
if 'idle_handler' in kwargs.keys():
self.idle_handler = kwargs['idle_handler']
if 'idle_time' in kwargs.keys():
self.idle_time = kwargs['idle_time'] * 1000
if 'input_handler' in kwargs.keys():
self.input_handler = kwargs['input_handler']
if 'config_file' in kwargs.keys():
self.config_file = kwargs['config_file']
self.list_location = []
self.current_position = 0
self.idle = False
self.mode = _MODE_NAV
self.config = ConfigParser.ConfigParser()
self.config.read([self.config_file, os.path.expanduser('~/.' + self.config_file)])
if type(self.menu_options) is dict or type(self.menu_options) is OrderedDict:
self._setup_menu(self.menu_options)
self.last_action = self.millis()
self._thread = AsyncWorker(self._update)
atexit.register(self.save)
def run(self):
self._thread.start()
atexit.register(self.stop)
def stop(self):
self._thread.stop()
def _update(self):
self.redraw()
time.sleep(0.05)
def millis(self):
return int(round(time.time() * 1000))
def add_item(self, path, handler):
if not type(path) is list:
path = path.split('/')
loc = self.menu_options
last = path.pop()
while len(path) > 0:
key = path.pop(0)
if key not in loc:
loc[key] = OrderedDict()
loc = loc[key]
loc[last] = handler
if isinstance(loc[last], MenuOption):
loc[last].setup(self.config)
def save(self):
if version_info[0] >= 3:
with open('dot3k.cfg', 'wt', encoding='utf-8') as configfile:
self.config.write(configfile)
else:
with open('dot3k.cfg', 'wb') as configfile:
self.config.write(configfile)
print('Config saved to dot3k.cfg')
def _setup_menu(self, menu):
for key in menu:
value = menu[key]
if type(value) is dict or type(value) is OrderedDict:
self._setup_menu(value)
elif isinstance(value, MenuOption):
value.setup(self.config)
def current_submenu(self):
"""
Traverse the list of indexes in list_location
and find the relevant nested listionary
"""
menu = self.menu_options
for location in self.list_location:
menu = menu[list(menu.keys())[location]]
return menu
def current_value(self):
return self.current_submenu()[self.current_key()]
def current_key(self):
"""
Convert the integer current_position into
a valid key for the currently selected listionary
"""
return list(self.current_submenu().keys())[self.current_position]
def next_position(self):
position = self.current_position + 1
position %= len(self.current_submenu())
return position
def previous_position(self):
position = self.current_position - 1
position %= len(self.current_submenu())
return position
def select_option(self):
"""
Navigate into, or handle selected menu option accordingly
"""
if type(self.current_value()) is dict or type(self.current_value()) is OrderedDict:
self.list_location.append(self.current_position)
self.current_position = 0
elif isinstance(self.current_value(), MenuOption):
self.mode = _MODE_ADJ
self.current_value().begin()
elif callable(self.current_submenu()[self.current_key()]):
self.current_submenu()[self.current_key()]()
def prev_option(self):
"""
Decrement the option pointer,
select previous menu item
"""
self.current_position = self.previous_position()
def next_option(self):
"""
Increment the option pointer,
select next menu item
"""
self.current_position = self.next_position()
def exit_option(self):
"""
Exit current submenu and restore position
in previous menu
"""
if len(self.list_location) > 0:
self.current_position = self.list_location.pop()
def start_input(self):
if self.input_handler is None:
return False
self.current_value().text_entry = False
self.input_handler.begin()
self.input_handler.set_value(self.current_value().initial_value())
self.input_handler.set_prompt(self.current_value().input_prompt())
self.mode = _MODE_TXT
def finish_input(self):
if self.input_handler.cancel_input:
self.current_value().cancel_input()
self.input_handler.cancel_input = False
self.input_handler.cleanup()
self.mode = _MODE_ADJ
else:
self.current_value().receive_input(self.input_handler.get_value())
self.input_handler.cleanup()
self.mode = _MODE_ADJ
def select(self):
"""
Handle "select" action
"""
self.last_action = self.millis()
if self.idle:
self.idle = False
self.idle_handler.cleanup()
self.idle_handler.idling = False
return True
if self.mode == _MODE_NAV:
self.select_option()
elif self.mode == _MODE_ADJ:
# The "select" call must return true to exit the adjust
if self.current_value().select() is True:
self.mode = _MODE_NAV
elif self.mode == _MODE_TXT:
if self.input_handler.select():
self.finish_input()
def cancel(self):
self.last_action = self.millis()
if self.idle:
self.idle = False
self.idle_handler.cleanup()
self.idle_handler.idling = False
return True
if self.mode == _MODE_NAV:
self.exit_option()
if self.mode == _MODE_ADJ:
self.current_value().cleanup()
self.mode = _MODE_NAV
def up(self):
self.last_action = self.millis()
if self.idle:
self.idle = False
self.idle_handler.cleanup()
self.idle_handler.idling = False
return True
if self.mode == _MODE_NAV:
self.prev_option()
elif self.mode == _MODE_ADJ:
self.current_value().up()
elif self.mode == _MODE_TXT:
self.input_handler.up()
def down(self):
self.last_action = self.millis()
if self.idle:
self.idle = False
self.idle_handler.cleanup()
self.idle_handler.idling = False
return True
if self.mode == _MODE_NAV:
self.next_option()
elif self.mode == _MODE_ADJ:
self.current_value().down()
elif self.mode == _MODE_TXT:
self.input_handler.down()
def left(self):
self.last_action = self.millis()
if self.idle:
self.idle = False
self.idle_handler.cleanup()
self.idle_handler.idling = False
return True
if self.mode == _MODE_NAV:
self.exit_option()
elif self.mode == _MODE_ADJ:
if not self.current_value().left():
self.current_value().cleanup()
self.mode = _MODE_NAV
elif self.mode == _MODE_TXT:
self.input_handler.left()
def right(self):
self.last_action = self.millis()
if self.idle:
self.idle = False
self.idle_handler.cleanup()
self.idle_handler.idling = False
return True
if self.mode == _MODE_NAV:
self.select_option()
elif self.mode == _MODE_ADJ:
self.current_value().right()
elif self.mode == _MODE_TXT:
self.input_handler.right()
def clear_row(self, row):
self.lcd.set_cursor_position(0, row)
self.lcd.write(' ' * self.lcd.COLS)
def write_row(self, row, text):
self.lcd.set_cursor_position(0, row)
while len(text) < self.lcd.COLS:
text += ' '
self.lcd.write(text[0:self.lcd.COLS])
def write_option(self, *args, **kwargs):
row = 0
text = ''
icon = ''
margin = 0
scroll = False
scroll_padding = ' '
scroll_delay = 2000
scroll_repeat = 10000
scroll_speed = 200
if len(args) > 0:
row = args[0]
if len(args) > 1:
text = args[1]
if len(args) > 2:
icon = args[2]
if len(args) > 3:
margin = args[3]
if 'row' in kwargs.keys():
row = kwargs['row']
if 'text' in kwargs.keys():
text = kwargs['text']
if 'icon' in kwargs.keys():
icon = kwargs['icon']
if 'margin' in kwargs.keys():
margin = kwargs['margin']
if 'scroll' in kwargs.keys() and kwargs['scroll'] == True:
scroll = True
if 'scroll_speed' in kwargs.keys():
scroll_speed = kwargs['scroll_speed']
if 'scroll_repeat' in kwargs.keys():
scroll_repeat = kwargs['scroll_repeat']
if 'scroll_delay' in kwargs.keys():
scroll_delay = kwargs['scroll_delay']
if 'scroll_padding' in kwargs.keys():
scroll_padding = kwargs['scroll_padding']
if icon == None:
icon = ''
if margin == None:
margin = 0
current_row = ''
if self.last_text[row] != text:
self.last_text[row] = text
self.last_change[row] = self.millis()
if scroll:
text += scroll_padding
if scroll and self.millis() - self.last_change[row] > scroll_delay:
pos = int(((self.millis() - self.last_change[row] - scroll_delay) / scroll_speed) % len(text))
text = text[pos:] + text[:pos]
if pos == len(text) - 1:
self.last_change[row] = self.millis() + scroll_repeat
current_row += icon
while len(current_row) < margin:
current_row += ' '
current_row += text
self.write_row(row, current_row)
def get_menu_item(self, index):
return list(self.current_submenu().keys())[index]
def redraw(self):
if self.can_idle() and isinstance(self.idle_handler, MenuOption):
if not self.idle:
self.idle_handler.idling = True
self.idle_handler.begin()
self.idle = True
self.idle_handler.redraw(self)
return False
if self.mode == _MODE_NAV:
self.write_option(
row=1,
text=self.get_menu_item(self.current_position),
icon=chr(252),
margin=1
)
if len(self.current_submenu()) > 2:
self.write_option(
row=0,
text=self.get_menu_item(self.previous_position()),
margin=1
)
else:
self.clear_row(0)
if len(self.current_submenu()) > 1:
self.write_option(
row=2,
text=self.get_menu_item(self.next_position()),
margin=1
)
else:
self.clear_row(2)
# Call the redraw function of the endpoint Class
elif self.mode == _MODE_ADJ:
self.current_value().redraw(self)
if self.current_value().text_entry:
self.start_input()
elif self.mode == _MODE_TXT:
self.input_handler.redraw(self)
def can_idle(self):
if self.millis() - self.last_action >= self.idle_time:
if self.mode == _MODE_NAV:
return True
| |
+ m.b184 - m.b260 <= 0)
m.c3669 = Constraint(expr= - m.b179 + m.b185 - m.b261 <= 0)
m.c3670 = Constraint(expr= - m.b180 + m.b181 - m.b262 <= 0)
m.c3671 = Constraint(expr= - m.b180 + m.b182 - m.b263 <= 0)
m.c3672 = Constraint(expr= - m.b180 + m.b183 - m.b264 <= 0)
m.c3673 = Constraint(expr= - m.b180 + m.b184 - m.b265 <= 0)
m.c3674 = Constraint(expr= - m.b180 + m.b185 - m.b266 <= 0)
m.c3675 = Constraint(expr= - m.b181 + m.b182 - m.b267 <= 0)
m.c3676 = Constraint(expr= - m.b181 + m.b183 - m.b268 <= 0)
m.c3677 = Constraint(expr= - m.b181 + m.b184 - m.b269 <= 0)
m.c3678 = Constraint(expr= - m.b181 + m.b185 - m.b270 <= 0)
m.c3679 = Constraint(expr= - m.b182 + m.b183 - m.b271 <= 0)
m.c3680 = Constraint(expr= - m.b182 + m.b184 - m.b272 <= 0)
m.c3681 = Constraint(expr= - m.b182 + m.b185 - m.b273 <= 0)
m.c3682 = Constraint(expr= - m.b183 + m.b184 - m.b274 <= 0)
m.c3683 = Constraint(expr= - m.b183 + m.b185 - m.b275 <= 0)
m.c3684 = Constraint(expr= - m.b184 + m.b185 - m.b276 <= 0)
m.c3685 = Constraint(expr= - m.b186 + m.b187 - m.b199 <= 0)
m.c3686 = Constraint(expr= - m.b186 + m.b188 - m.b200 <= 0)
m.c3687 = Constraint(expr= - m.b186 + m.b189 - m.b201 <= 0)
m.c3688 = Constraint(expr= - m.b186 + m.b190 - m.b202 <= 0)
m.c3689 = Constraint(expr= - m.b186 + m.b191 - m.b203 <= 0)
m.c3690 = Constraint(expr= - m.b186 + m.b192 - m.b204 <= 0)
m.c3691 = Constraint(expr= - m.b186 + m.b193 - m.b205 <= 0)
m.c3692 = Constraint(expr= - m.b186 + m.b194 - m.b206 <= 0)
m.c3693 = Constraint(expr= - m.b186 + m.b195 - m.b207 <= 0)
m.c3694 = Constraint(expr= - m.b186 + m.b196 - m.b208 <= 0)
m.c3695 = Constraint(expr= - m.b186 + m.b197 - m.b209 <= 0)
m.c3696 = Constraint(expr= - m.b186 + m.b198 - m.b210 <= 0)
m.c3697 = Constraint(expr= - m.b187 + m.b188 - m.b211 <= 0)
m.c3698 = Constraint(expr= - m.b187 + m.b189 - m.b212 <= 0)
m.c3699 = Constraint(expr= - m.b187 + m.b190 - m.b213 <= 0)
m.c3700 = Constraint(expr= - m.b187 + m.b191 - m.b214 <= 0)
m.c3701 = Constraint(expr= - m.b187 + m.b192 - m.b215 <= 0)
m.c3702 = Constraint(expr= - m.b187 + m.b193 - m.b216 <= 0)
m.c3703 = Constraint(expr= - m.b187 + m.b194 - m.b217 <= 0)
m.c3704 = Constraint(expr= - m.b187 + m.b195 - m.b218 <= 0)
m.c3705 = Constraint(expr= - m.b187 + m.b196 - m.b219 <= 0)
m.c3706 = Constraint(expr= - m.b187 + m.b197 - m.b220 <= 0)
m.c3707 = Constraint(expr= - m.b187 + m.b198 - m.b221 <= 0)
m.c3708 = Constraint(expr= - m.b188 + m.b189 - m.b222 <= 0)
m.c3709 = Constraint(expr= - m.b188 + m.b190 - m.b223 <= 0)
m.c3710 = Constraint(expr= - m.b188 + m.b191 - m.b224 <= 0)
m.c3711 = Constraint(expr= - m.b188 + m.b192 - m.b225 <= 0)
m.c3712 = Constraint(expr= - m.b188 + m.b193 - m.b226 <= 0)
m.c3713 = Constraint(expr= - m.b188 + m.b194 - m.b227 <= 0)
m.c3714 = Constraint(expr= - m.b188 + m.b195 - m.b228 <= 0)
m.c3715 = Constraint(expr= - m.b188 + m.b196 - m.b229 <= 0)
m.c3716 = Constraint(expr= - m.b188 + m.b197 - m.b230 <= 0)
m.c3717 = Constraint(expr= - m.b188 + m.b198 - m.b231 <= 0)
m.c3718 = Constraint(expr= - m.b189 + m.b190 - m.b232 <= 0)
m.c3719 = Constraint(expr= - m.b189 + m.b191 - m.b233 <= 0)
m.c3720 = Constraint(expr= - m.b189 + m.b192 - m.b234 <= 0)
m.c3721 = Constraint(expr= - m.b189 + m.b193 - m.b235 <= 0)
m.c3722 = Constraint(expr= - m.b189 + m.b194 - m.b236 <= 0)
m.c3723 = Constraint(expr= - m.b189 + m.b195 - m.b237 <= 0)
m.c3724 = Constraint(expr= - m.b189 + m.b196 - m.b238 <= 0)
m.c3725 = Constraint(expr= - m.b189 + m.b197 - m.b239 <= 0)
m.c3726 = Constraint(expr= - m.b189 + m.b198 - m.b240 <= 0)
m.c3727 = Constraint(expr= - m.b190 + m.b191 - m.b241 <= 0)
m.c3728 = Constraint(expr= - m.b190 + m.b192 - m.b242 <= 0)
m.c3729 = Constraint(expr= - m.b190 + m.b193 - m.b243 <= 0)
m.c3730 = Constraint(expr= - m.b190 + m.b194 - m.b244 <= 0)
m.c3731 = Constraint(expr= - m.b190 + m.b195 - m.b245 <= 0)
m.c3732 = Constraint(expr= - m.b190 + m.b196 - m.b246 <= 0)
m.c3733 = Constraint(expr= - m.b190 + m.b197 - m.b247 <= 0)
m.c3734 = Constraint(expr= - m.b190 + m.b198 - m.b248 <= 0)
m.c3735 = Constraint(expr= - m.b191 + m.b192 - m.b249 <= 0)
m.c3736 = Constraint(expr= - m.b191 + m.b193 - m.b250 <= 0)
m.c3737 = Constraint(expr= - m.b191 + m.b194 - m.b251 <= 0)
m.c3738 = Constraint(expr= - m.b191 + m.b195 - m.b252 <= 0)
m.c3739 = Constraint(expr= - m.b191 + m.b196 - m.b253 <= 0)
m.c3740 = Constraint(expr= - m.b191 + m.b197 - m.b254 <= 0)
m.c3741 = Constraint(expr= - m.b191 + m.b198 - m.b255 <= 0)
m.c3742 = Constraint(expr= - m.b192 + m.b193 - m.b256 <= 0)
m.c3743 = Constraint(expr= - m.b192 + m.b194 - m.b257 <= 0)
m.c3744 = Constraint(expr= - m.b192 + m.b195 - m.b258 <= 0)
m.c3745 = Constraint(expr= - m.b192 + m.b196 - m.b259 <= 0)
m.c3746 = Constraint(expr= - m.b192 + m.b197 - m.b260 <= 0)
m.c3747 = Constraint(expr= - m.b192 + m.b198 - m.b261 <= 0)
m.c3748 = Constraint(expr= - m.b193 + m.b194 - m.b262 <= 0)
m.c3749 = Constraint(expr= - m.b193 + m.b195 - m.b263 <= 0)
m.c3750 = Constraint(expr= - m.b193 + m.b196 - m.b264 <= 0)
m.c3751 = Constraint(expr= - m.b193 + m.b197 - m.b265 <= 0)
m.c3752 = Constraint(expr= - m.b193 + m.b198 - m.b266 <= 0)
m.c3753 = Constraint(expr= - m.b194 + m.b195 - m.b267 <= 0)
m.c3754 = Constraint(expr= - m.b194 + m.b196 - m.b268 <= 0)
m.c3755 = Constraint(expr= - m.b194 + m.b197 - m.b269 <= 0)
m.c3756 = Constraint(expr= - m.b194 + m.b198 - m.b270 <= 0)
m.c3757 = Constraint(expr= - m.b195 + m.b196 - m.b271 <= 0)
m.c3758 = Constraint(expr= - m.b195 + m.b197 - m.b272 <= 0)
m.c3759 = Constraint(expr= - m.b195 + m.b198 - m.b273 <= 0)
m.c3760 = Constraint(expr= - m.b196 + m.b197 - m.b274 <= 0)
m.c3761 = Constraint(expr= - m.b196 + m.b198 - m.b275 <= 0)
m.c3762 = Constraint(expr= - m.b197 + m.b198 - m.b276 <= 0)
m.c3763 = Constraint(expr= - m.b199 + m.b200 - m.b211 <= 0)
m.c3764 = Constraint(expr= - m.b199 + m.b201 - m.b212 <= 0)
m.c3765 = Constraint(expr= - m.b199 + m.b202 - m.b213 <= 0)
m.c3766 = Constraint(expr= - m.b199 + m.b203 - m.b214 <= 0)
m.c3767 = Constraint(expr= - m.b199 + m.b204 - m.b215 <= 0)
m.c3768 = Constraint(expr= - m.b199 + m.b205 - m.b216 <= 0)
m.c3769 = Constraint(expr= - m.b199 + m.b206 - m.b217 <= 0)
m.c3770 = Constraint(expr= - m.b199 + m.b207 - m.b218 <= 0)
m.c3771 = Constraint(expr= - m.b199 + m.b208 - m.b219 <= 0)
m.c3772 = Constraint(expr= - m.b199 + m.b209 - m.b220 <= 0)
m.c3773 = Constraint(expr= - m.b199 + m.b210 - m.b221 <= 0)
m.c3774 = Constraint(expr= - m.b200 + m.b201 - m.b222 <= 0)
m.c3775 = Constraint(expr= - m.b200 + m.b202 - m.b223 <= 0)
m.c3776 = Constraint(expr= - m.b200 + m.b203 - m.b224 <= 0)
m.c3777 = Constraint(expr= - m.b200 + m.b204 - m.b225 <= 0)
m.c3778 = Constraint(expr= - m.b200 + m.b205 - m.b226 <= 0)
m.c3779 = Constraint(expr= - m.b200 + m.b206 - m.b227 <= 0)
m.c3780 = Constraint(expr= - m.b200 + m.b207 - m.b228 <= 0)
m.c3781 = Constraint(expr= - m.b200 + m.b208 - m.b229 <= 0)
m.c3782 = Constraint(expr= - m.b200 + m.b209 - m.b230 <= 0)
m.c3783 = Constraint(expr= - m.b200 + m.b210 - m.b231 <= 0)
m.c3784 = Constraint(expr= - m.b201 + m.b202 - m.b232 <= 0)
m.c3785 = Constraint(expr= - m.b201 + m.b203 - m.b233 <= 0)
m.c3786 = Constraint(expr= - m.b201 + m.b204 - m.b234 <= 0)
m.c3787 = Constraint(expr= - m.b201 + m.b205 - m.b235 <= 0)
m.c3788 = Constraint(expr= - m.b201 + m.b206 - m.b236 <= 0)
m.c3789 = Constraint(expr= - m.b201 + m.b207 - m.b237 <= 0)
m.c3790 = Constraint(expr= - m.b201 + m.b208 - m.b238 <= 0)
m.c3791 = Constraint(expr= - m.b201 + m.b209 - m.b239 <= 0)
m.c3792 = Constraint(expr= - m.b201 + m.b210 - m.b240 <= 0)
m.c3793 = Constraint(expr= - m.b202 + m.b203 - m.b241 <= 0)
m.c3794 = Constraint(expr= - m.b202 + m.b204 - m.b242 <= 0)
m.c3795 = Constraint(expr= - m.b202 + m.b205 - m.b243 <= 0)
m.c3796 = Constraint(expr= - m.b202 | |
<gh_stars>1-10
import numpy as np
import copy
#np.random.seed(0)
nc = 0
#import pylab
def comupute_enhanced(proba, actual_pos,cascade={}):
#assert()
infl = cascade["infl"] #,50)
amount = cascade["amount"] #,4)
down = cascade["down"]#,10)
damount = cascade["damount"]#,1 / 10000.)
cproba = np.zeros_like(proba) + 1
for position, direction, init_position in actual_pos:
# print(position,direction,cproba,max(position-infl),position)
if direction == "L":
cproba[position:min(position + infl, len(cproba) - 1)] *= amount
if direction == "R":
cproba[max(position - infl, 0):position] *= amount
if direction == "L":
cproba[position:min(position + down, len(cproba) - 1)] *= damount
if direction == "R":
cproba[max(position - down, 0):position] *= damount
return cproba
def generate_newp_cascade(pos, proba, avail,actual_pos=[],cascade={}):
#print("cascade",actual_pos)
newp = []
finished = False
cproba = comupute_enhanced(proba, actual_pos,cascade)
filter = proba != 0
npossible = np.sum(filter)
"""
f = pylab.figure()
f.add_subplot(211)
pylab.plot(cproba)
f.add_subplot(212)
pylab.plot(proba * cproba)
pylab.plot(proba)
pylab.show()
"""
if npossible > avail:
newp = list(np.random.choice(pos[filter], size=avail,replace=False,
p=proba[filter] * cproba[filter] / (np.sum(cproba[filter] * proba[filter]))))
else:
newp = list(pos[filter])
finished = True
for p in newp:
proba[p] = 0
newp.sort()
return pos, proba, newp, finished
def generate_newp_no_corre(pos, proba, avail,actual_pos=[],cascade={},previous =[]):
#Return a list of #avail site
#Modify proba and previous
#print(cascade)
if cascade != {} :
pos, proba, newp, finished = generate_newp_cascade(pos, proba, avail, actual_pos=actual_pos,cascade=cascade)
return pos, proba, newp, finished,[]
newp = []
finished = False
#first call generate ordered list of origins
if previous == [] and np.sum(proba) != 0:
size = np.sum(proba != 0)
previous = list(np.random.choice(pos,size=size,
replace=False,
p=proba/np.sum(proba)))
n = len(previous)
# check for passivation
for i in range(n)[::-1]:
if proba[previous[i]] == 0:
previous.pop(i)
# generate avail position
for p in range(n):
if len(previous) != 0:
next_pos = previous.pop(0)
if proba[next_pos] != 0:
newp.append(next_pos)
proba[next_pos] = 0
if len(newp) == avail:
break
else:
finished = True
# Set the proba of initiation to 0
for ipos in newp:
proba[ipos] = 0
newp.sort()
return pos, proba, newp, finished,previous
class Chrom:
def __init__(self,start,end,timespend=[]):
self.start = start
self.end = end
self.actual_pos = [] # Positions of the forks
self.list_events = []
self.delta = []
self.rfd = np.zeros(end-start)
self.mrt = np.zeros(end-start) + np.nan
self.debug = False
self.lt = []
self.timespend = timespend
self.t=0
self.la = []
self.oldp =[]
#print("Times.",self.timespend)
if len(self.timespend) != 0:
# timespend is the item in kb necessary to travel a bin.
# it must be an integer
self.constant_speed = False
assert(self.timespend.dtype==np.int)
else:
self.constant_speed = True
#self.timespend = np.ones(end-start,dtype=np.int)
def append_forks(self,pos):
deb=False
if deb:
print("Append frks",pos)
print("Before",self.actual_pos)
if not np.isnan(self.mrt[self.rc(pos)]) :
self.check(show=True,msg="Non null position %.2f, value %.2f" %(pos,self.mrt[self.rc(pos)]))
raise "Non nul"
self.mrt[self.rc(pos)]=self.t
self.la.append(pos)
if self.debug:
print("New Fork",pos)
shift=0
if not self.constant_speed :
shift=0.5
found=False
self.list_evens = []
#print(self.actual_pos)
if len(self.actual_pos) != 0 and self.actual_pos[0][0] > pos:
if self.list_events != []:
self.list_events[0] = [self.actual_pos[0][0]-pos,[1,2]]
self.list_events.insert(0,[pos,[0]])
#for p in self.list_events[2:]:
self.actual_pos.insert(0, [pos+shift, "L",pos+shift])
self.actual_pos.insert(1, [pos+shift, "R",pos+shift])
found = True
else:
for p2 in range(len(self.actual_pos)-1):
if self.actual_pos[p2+1][0] > pos >= self.actual_pos[p2][0]:
self.actual_pos.insert(p2+1, [pos+shift, "L",pos+shift])
self.actual_pos.insert(p2+2, [pos+shift, "R",pos+shift])
found = True
break
if not found:
self.actual_pos.extend([[pos+shift, "L",pos+shift], [pos+shift, "R",pos+shift]])
if self.list_events == []:
self.list_events.append([pos-self.start,[0]])
self.list_events.append([self.end-pos,[1]])
#print(self.actual_pos)
#self.check()
if deb:
print("Afetr")
print(self.actual_pos)
self.list_events_comp()
def list_events_comp(self,shift=0):
# Compute the lists of next collisions
if self.actual_pos == []:
self.list_events = []
return []
delta = []
pause = []
start = 0
end = None
deb=False
if deb:
print("Startc")
def time_to_meet(start=0,end=None,extremity=False):
if self.constant_speed:
time = end-start
else:
time = np.sum(self.timespend[self.rc(start):self.rc(end)])
if self.rc(end)< len(self.timespend) - 1:
time += (round(end,5)-int(end)) * self.timespend[self.rc(end)]
time -= (round(start,5) - int(start)) * self.timespend[self.rc(start)]
#print(self.speed[start:end])
#print("t",start,end,time,end-start,extremity)
#only one fork progressing
#if time > 100:
# print(start,end,time,extremity)
if extremity:
if self.constant_speed:
return int(time)
else:
return time
#Must be divided by 2 as both strand progress
#print("h",start,end,time)
if self.constant_speed:
if time % 2 == 0:
return int(time // 2)
else:
return int(time // 2 + 1)
else:
return time / 2
if self.actual_pos[0][1] == "L":
delta.append([time_to_meet(self.start,self.actual_pos[0][0],extremity=True), [0+shift]])
if self.actual_pos[0][0]-self.start < 0:
raise
start = 1
if deb:
print("start,shift")
if self.actual_pos[-1][1] == "R":
end = -1
if deb:
print(start,end)
print("Full",self.actual_pos)
print("view",self.actual_pos[start:end])
view = self.actual_pos[start:end]
i = 0
# if not (len(delta) == 2 and len(actual_pos) == 2):
for p1, p2 in zip(view[::2], view[1::2]):
"""
deltapt = p2[0]-p1[0]
if deltapt % 2 == 0:
deltapt = (p2[0]-p1[0])//2
else:
deltapt = (p2[0] - p1[0]) // 2 + 1
"""
assert(p1[1] == "R")
assert(p2[1] == "L")
delta.append([time_to_meet(p1[0],p2[0]), [2*i+start+shift, 2*i+1+start+shift]])
#print(p2[0] ,p1[0],(p2[0]-p1[0])//2+1)
#print(delta)
#print(delta)
i += 1
if self.actual_pos[-1][1] == "R":
delta.append([time_to_meet(self.actual_pos[-1][0],self.end,extremity=True), [len(self.actual_pos)-1+shift]])
self.list_events = delta
if deb:
print(start)
print(self.actual_pos)
print(self.list_events)
print("End")
return self.list_events
#delta.sort()
def rc(self,pos):
#Relative coordinate
return int(pos-self.start)
def approx(self,p, r=7):
return round(p, r)
def evolvep(self,p, time, proba,d=1):
#Evolve one fork at position p
# with array of speed ,
# for a given time
def checkbound(p):
return max(0,min(self.rc(p),len(self.mrt)-1))
def assign_mrt_rfd(p,ev):
pos = checkbound(p)
if d == 1:
t = self.t+ev
else:
t = self.t + ev #+ 1
#print(pos, t)
if np.isnan(self.mrt[pos]):
self.mrt[pos] = t
self.rfd[pos] = d
proba[min(pos+self.start,len(proba)-1)]=0
else:
if self.mrt[pos] > t:
self.mrt[pos] = t
self.rfd[pos] = d
proba[min(pos + self.start, len(proba) - 1)] = 0
#else:
# if forward
r0 = p - int(p)
if d == 1:
ev = self.timespend[checkbound(int(p))] * (1 - r0)
else:
ev = self.timespend[checkbound(int(p))] * r0
if ev <= time:
p = int(p) + d
else:
p = p + d / self.timespend[checkbound(int(p))] * time
assign_mrt_rfd(p,ev)
return self.approx(p)
while ev < time:
assign_mrt_rfd(p,ev)
ev += self.timespend[checkbound(int(p))]
p += d
# print(ev,time)
if abs(ev - time) < 0.001:
# print("equal")
if d == -1:
assign_mrt_rfd(p, ev)
return p + 1
else:
assign_mrt_rfd(p, ev)
return p
else:
if d == 1:
p -= 1
toev = (self.timespend[checkbound(int(p))] - (ev - time)) / self.timespend[checkbound(int(p))]
return self.approx(p + d * toev)
else:
p += 1
toev = (self.timespend[checkbound(int(p))] - (ev - time)) / self.timespend[checkbound(int(p))]
return self.approx(p - d + d * toev)
def evolve(self,time,proba,filter_termination=None):
# evolve the chromosome of 'time' step
remove = []
termination = []
avail = 0
deb=False
if deb:
print("evolve",time)
for d in self.list_events:
deltat,particules = d
d[0] -= time
if round(d[0],3) <= 0:
# if collision, avail + recompute list_events
#print("Col",p)
if len(particules) == 2:
avail += 1
delta_original = abs(self.actual_pos[particules[0]][2] - self.actual_pos[particules[1]][2])
if (filter_termination is None) or filter_termination <= delta_original:
termination.append(int(self.actual_pos[particules[0]][0]/2+self.actual_pos[particules[1]][0]/2))
if deb:
print(particules,termination)
for part in particules:
remove.append(part)
for p in self.actual_pos:
#print(p[0], time)
if p[1] == "L":
if self.constant_speed:
self.rfd[self.rc(p[0] - time):self.rc(p[0])] = -1
self.mrt[self.rc(p[0] - time):self.rc(p[0])] = np.arange(self.t, self.t+time)[::-1]
proba[p[0] - time:p[0]]=0
p[0] -= time
else:
previous = 0 + p[0]
p[0] = self.evolvep(p[0],time,proba,d=-1)
else:
if self.constant_speed:
self.rfd[self.rc(p[0]):self.rc(p[0] + time)] = 1
self.mrt[self.rc(p[0]):self.rc(p[0] + time)] = np.arange(self.t, self.t + time)
proba[p[0]:p[0] + time] = 0
p[0] += time
else:
p[0] = self.evolvep(p[0], time, proba,d=1)
delete = []
if remove != []:
#print("collision")
#print(self.actual_pos)
#print(self.list_events)
#print(remove,len(self.actual_pos))
for p in remove[::-1]:
#print(p)
delete.append(self.actual_pos.pop(p))
self.list_events_comp()
self.lt.extend(termination)
self.t += time
# CHekc termination:
for ter in termination:
if np.isnan(self.mrt[self.rc(ter)]):
self.check(show=True, msg="dt %f Termination not completed %.2f\n remve %s" % (time,ter,str(delete)))
return termination,avail
def min_time(self):
#print("Le",self.list_events)
mini = 1e6
for d in self.list_events:
if d[0] < mini:
mini = round(d[0],7)
#print(mini)
return mini
def check(self,show=False,msg=""):
for p1, p2 in zip(self.actual_pos[:-1], self.actual_pos[1:]):
if not(p1[0] <= p2[0]) or (not ([p1[1],p2[1]] in [["L","R"],["R","L"]])) or show:
for actp in self.oldp:
print(actp)
#print(self.oldp)
print(self.start,self.end)
print(p1, p2)
print("List activation",self.la)
print("List term",self.lt)
print(self.list_events)
print(self.actual_pos)
import pylab
f = pylab.figure()
f.add_subplot(211)
pylab.suptitle("RFD")
pylab.plot(np.arange(self.start,self.end),self.rfd)
f.add_subplot(212)
pylab.plot(np.arange(self.start, self.end), self.mrt)
print(msg)
pylab.show()
raise
self.oldp.append(copy.deepcopy(self.actual_pos)+[])
def fast_rep(distrib, diff, debug=False, kon=0.001, fork_speed=0.3,
single_mol_exp=False, single_mol_exp_sub_sample=50,
pulse_size=2,cascade={},breaks=None,continuous=False,
binsize=5,dori=30,list_chrom_ret=False,timespend=[],
filter_termination=None,introduction_time=None,
correct_activation=True,dario=False):
#np.random.seed(0)
pos = np.arange(len(distrib))
if not continuous:
init_ori = np.random.choice(pos, p=distrib/np.sum(distrib), size=int(len(distrib)*binsize/dori))
init_distrib = np.zeros_like(distrib)
# print(l)
for p in init_ori:
init_distrib[p] += 1
#print(sum(init_distrib))
else:
init_distrib = distrib / np.sum(distrib)
if dario:
init_distrib = distrib
# print(sum(init_distrib))
d3p= init_distrib
introduced = 0
if introduction_time is None:
time = 0
avail = diff
else:
time = 0 # very important because if not the first event is when the first diffusing element cover one ch
avail = 1
if correct_activation:
avail=1
proba = d3p.copy()
pos = np.arange(len(d3p))
single_mol_exp_v = []
#print("SME", single_mol_exp)
actual_pos = | |
equal to the storage space allowed to the Grid
member with the smallest amount of space allowed.
"""
_infoblox_type = 'grid:filedistribution'
_fields = ['allow_uploads', 'backup_storage', 'current_usage',
'enable_anonymous_ftp', 'global_status', 'name',
'storage_limit']
_search_for_update_fields = ['name']
_updateable_search_fields = []
_all_searchable_fields = ['name']
_return_fields = ['allow_uploads', 'current_usage', 'global_status',
'name', 'storage_limit']
_remap = {}
_shadow_fields = ['_ref']
class GridLicensePool(InfobloxObject):
""" GridLicensePool: Grid License Pool object.
Corresponds to WAPI object 'grid:license_pool'
This object represents the Grid license pool.
Fields:
assigned: The number of dynamic licenses allocated to vNIOS
appliances.
expiration_status: The license expiration status.
expiry_date: The expiration timestamp of the license.
installed: The total number of dynamic licenses allowed for this
license pool.
key: The license string for the license pool.
limit: The limitation of dynamic license that can be allocated from
the license pool.
limit_context: The license limit context.
model: The supported vNIOS virtual appliance model.
subpools: The license pool subpools.
temp_assigned: The total number of temporary dynamic licenses
allocated to vNIOS appliances.
type: The license type.
"""
_infoblox_type = 'grid:license_pool'
_fields = ['assigned', 'expiration_status', 'expiry_date', 'installed',
'key', 'limit', 'limit_context', 'model', 'subpools',
'temp_assigned', 'type']
_search_for_update_fields = ['type']
_updateable_search_fields = []
_all_searchable_fields = ['key', 'limit', 'model', 'type']
_return_fields = ['type']
_remap = {}
_shadow_fields = ['_ref']
_custom_field_processing = {
'subpools': GridLicensesubpool.from_dict,
}
class GridLicensePoolContainer(InfobloxObject):
""" GridLicensePoolContainer: Grid License Pool Container object.
Corresponds to WAPI object 'grid:license_pool_container'
This object represents the Grid license pool container.
Fields:
last_entitlement_update: The timestamp when the last pool licenses
were updated.
lpc_uid: The world-wide unique ID for the license pool container.
"""
_infoblox_type = 'grid:license_pool_container'
_fields = ['last_entitlement_update', 'lpc_uid']
_search_for_update_fields = []
_updateable_search_fields = []
_all_searchable_fields = []
_return_fields = []
_remap = {}
_shadow_fields = ['_ref']
def allocate_licenses(self, *args, **kwargs):
return self._call_func("allocate_licenses", *args, **kwargs)
class GridMaxminddbinfo(InfobloxObject):
""" GridMaxminddbinfo: Topology DB Info object.
Corresponds to WAPI object 'grid:maxminddbinfo'
The information about Topology DB.
Fields:
binary_major_version: The major version of DB binary format.
binary_minor_version: The minor version of DB binary format.
build_time: The time at which the DB was built.
database_type: The structure of data records ("GeoLite2-Country",
GeoLite2-City", etc.).
deployment_time: The time at which the current Topology DB was
deployed.
member: The member for testing the connection.
topology_type: The topology type.
"""
_infoblox_type = 'grid:maxminddbinfo'
_fields = ['binary_major_version', 'binary_minor_version', 'build_time',
'database_type', 'deployment_time', 'member', 'topology_type']
_search_for_update_fields = ['topology_type']
_updateable_search_fields = []
_all_searchable_fields = ['topology_type']
_return_fields = ['binary_major_version', 'binary_minor_version',
'build_time', 'database_type', 'deployment_time',
'member', 'topology_type']
_remap = {}
_shadow_fields = ['_ref']
class GridMemberCloudapi(InfobloxObject):
""" GridMemberCloudapi: Member Cloud API object.
Corresponds to WAPI object 'grid:member:cloudapi'
Class that represents member Cloud configuration settings.
Fields:
allow_api_admins: Defines which administrators are allowed to
perform Cloud API request on the Grid Member: no administrators
(NONE), any administrators (ALL) or administrators in the ACL
list (LIST). Default is ALL.
allowed_api_admins: List of administrators allowed to perform Cloud
Platform API requests on that member.
enable_service: Controls whether the Cloud API service runs on the
member or not.
extattrs: Extensible attributes associated with the object.For valid
values for extensible attributes, see the following information.
gateway_config: Structure containing all the information related to
Gateway configuration for the member
member: The related Grid Member.
status: Status of Cloud API service on the member.
"""
_infoblox_type = 'grid:member:cloudapi'
_fields = ['allow_api_admins', 'allowed_api_admins', 'enable_service',
'extattrs', 'gateway_config', 'member', 'status']
_search_for_update_fields = []
_updateable_search_fields = []
_all_searchable_fields = []
_return_fields = ['allow_api_admins', 'allowed_api_admins',
'enable_service', 'extattrs', 'member', 'status']
_remap = {}
_shadow_fields = ['_ref']
_custom_field_processing = {
'allowed_api_admins': GridCloudapiUser.from_dict,
}
class GridServicerestartGroup(InfobloxObject):
""" GridServicerestartGroup: Service Restart Group object.
Corresponds to WAPI object 'grid:servicerestart:group'
The Grid Service Restart Group object provides the following
information about the restart: applicable services, members, restart
order, and periodicity.
Fields:
comment: Comment for the Restart Group; maximum 256 characters.
extattrs: Extensible attributes associated with the object.For valid
values for extensible attributes, see the following information.
is_default: Determines if this Restart Group is the default group.
last_updated_time: The timestamp when the status of the latest
request has changed.
members: The list of members belonging to the group.
mode: The default restart method for this Restart Group.
name: The name of this Restart Group.
position: The order to restart.
recurring_schedule: The recurring schedule for restart of a group.
requests: The list of requests associated with a restart group.
service: The applicable service for this Restart Group.
status: The restart status for a restart group.
"""
_infoblox_type = 'grid:servicerestart:group'
_fields = ['comment', 'extattrs', 'is_default', 'last_updated_time',
'members', 'mode', 'name', 'position', 'recurring_schedule',
'requests', 'service', 'status']
_search_for_update_fields = ['name', 'service']
_updateable_search_fields = ['comment', 'name', 'service']
_all_searchable_fields = ['comment', 'is_default', 'name', 'service']
_return_fields = ['comment', 'extattrs', 'name', 'service']
_remap = {}
_shadow_fields = ['_ref']
class GridServicerestartGroupOrder(InfobloxObject):
""" GridServicerestartGroupOrder: Restart Group Order object.
Corresponds to WAPI object 'grid:servicerestart:group:order'
The Grid Service Restart Group Order Setting is used to set the
restart order for particular services and members.
Fields:
groups: The ordered list of the Service Restart Group.
"""
_infoblox_type = 'grid:servicerestart:group:order'
_fields = ['groups']
_search_for_update_fields = []
_updateable_search_fields = []
_all_searchable_fields = []
_return_fields = []
_remap = {}
_shadow_fields = ['_ref']
class GridServicerestartRequest(InfobloxObject):
""" GridServicerestartRequest: Restart Request object.
Corresponds to WAPI object 'grid:servicerestart:request'
The Restart Request object provides information and statistics about
the service restart routine for the Service Restart Group.
Fields:
error: The error message if restart has failed.
forced: Indicates if this is a force restart.
group: The name of the Restart Group associated with the request.
last_updated_time: The timestamp when the status of the request has
changed.
member: The member to restart.
needed: Indicates if restart is needed.
order: The order to restart.
result: The result of the restart operation.
service: The service to restart.
state: The state of the request.
"""
_infoblox_type = 'grid:servicerestart:request'
_fields = ['error', 'forced', 'group', 'last_updated_time', 'member',
'needed', 'order', 'result', 'service', 'state']
_search_for_update_fields = ['group']
_updateable_search_fields = []
_all_searchable_fields = ['group', 'member']
_return_fields = ['error', 'group', 'result', 'state']
_remap = {}
_shadow_fields = ['_ref']
class GridServicerestartRequestChangedobject(InfobloxObject):
""" GridServicerestartRequestChangedobject: Grid service restart
request changed object.
Corresponds to WAPI object
'grid:servicerestart:request:changedobject'
The Grid service restart request changed object provides information
about changes that are waiting for the restart.
Fields:
action: The operation on the changed object.
changed_properties: The list of changed properties in the object.
changed_time: The time when the object was changed.
object_name: The name of the changed object.
object_type: The type of the changed object. This is undefined if
the object is not supported.
user_name: The name of the user who changed the object properties.
"""
_infoblox_type = 'grid:servicerestart:request:changedobject'
_fields = ['action', 'changed_properties', 'changed_time', 'object_name',
'object_type', 'user_name']
_search_for_update_fields = ['user_name']
_updateable_search_fields = []
_all_searchable_fields = ['user_name']
_return_fields = ['action', 'changed_properties', 'changed_time',
'object_name', 'object_type', 'user_name']
_remap = {}
_shadow_fields = ['_ref']
class GridServicerestartStatus(InfobloxObject):
""" GridServicerestartStatus: Restart Status object.
Corresponds to WAPI object 'grid:servicerestart:status'
The Restart Status object provides information and statistics about
service restart routine for the Grid or Service Restart Group.
Fields:
failures: The number of failed requests.
finished: The number of finished requests.
grouped: The type of grouping.
needed_restart: The number of created yet unprocessed requests for
restart.
no_restart: The number of requests that did not require a restart.
parent: A reference to the grid or grid:servicerestart:group object
associated with the request.
pending: The number of requests that are pending a restart.
pending_restart: The number of forced or needed requests pending for
restart.
processing: The number of not forced and not needed requests pending
for restart.
restarting: The number of service restarts for corresponding
members.
success: The number of requests associated with successful restarts.
timeouts: The number of timeout requests.
"""
_infoblox_type = 'grid:servicerestart:status'
_fields = ['failures', 'finished', 'grouped', 'needed_restart',
'no_restart', 'parent', 'pending', 'pending_restart',
'processing', 'restarting', 'success', 'timeouts']
_search_for_update_fields = ['parent']
_updateable_search_fields = []
_all_searchable_fields = ['parent']
_return_fields = ['failures', 'finished', 'grouped', 'needed_restart',
'no_restart', 'parent', 'pending', 'pending_restart',
'processing', 'restarting', 'success', 'timeouts']
_remap = {}
_shadow_fields = ['_ref']
class GridThreatanalytics(InfobloxObject):
""" GridThreatanalytics: Grid threat analytics object.
Corresponds to WAPI object 'grid:threatanalytics'
To mitigate DNS data exfiltration, | |
"""Cascade RCNN Model."""
from __future__ import absolute_import
import os
import mxnet as mx
from mxnet import autograd
from mxnet.gluon import nn
from .rcnn_target import RCNNTargetSampler, RCNNTargetGenerator
from ..rcnn import RCNN2
from ..rpn import RPN
from ...nn.coder import NormalizedBoxCenterDecoder, MultiPerClassDecoder
from easydict import EasyDict as edict
from ..rpn import RPNTargetGenerator
__all__ = ['CascadeRCNN', 'get_cascade_rcnn',
'cascade_rcnn_resnet50_v1b_voc',
'cascade_rcnn_vgg16_voc',
'cascade_rcnn_vgg16_pruned_voc',
'cascade_rcnn_vgg16_pruned_coco']
class CascadeRCNN(RCNN2):
r"""Faster RCNN network.
Parameters
----------
features : gluon.HybridBlock
Base feature extractor before feature pooling layer.
top_features : gluon.HybridBlock
Tail feature extractor after feature pooling layer.
train_patterns : str
Matching pattern for trainable parameters.
scales : iterable of float
The areas of anchor boxes.
We use the following form to compute the shapes of anchors:
.. math::
width_{anchor} = size_{base} \times scale \times \sqrt{ 1 / ratio}
height_{anchor} = size_{base} \times scale \times \sqrt{ratio}
ratios : iterable of float
The aspect ratios of anchor boxes. We expect it to be a list or tuple.
classes : iterable of str
Names of categories, its length is ``num_class``.
roi_mode : str
ROI pooling mode. Currently support 'pool' and 'align'.
roi_size : tuple of int, length 2
(height, width) of the ROI region.
stride : int, default is 16
Feature map stride with respect to original image.
This is usually the ratio between original image size and feature map size.
rpn_channel : int, default is 1024
Channel number used in RPN convolutional layers.
nms_thresh : float, default is 0.3.
Non-maximum suppression threshold. You can speficy < 0 or > 1 to disable NMS.
nms_topk : int, default is 400
Apply NMS to top k detection results, use -1 to disable so that every Detection
result is used in NMS.
num_sample : int, default is 128
Number of samples for RCNN targets.
pos_iou_thresh : float, default is 0.5
Proposal whose IOU larger than ``pos_iou_thresh`` is regarded as positive samples.
neg_iou_thresh_high : float, default is 0.5
Proposal whose IOU smaller than ``neg_iou_thresh_high``
and larger than ``neg_iou_thresh_low`` is regarded as negative samples.
Proposals with IOU in between ``pos_iou_thresh`` and ``neg_iou_thresh`` are
ignored.
neg_iou_thresh_low : float, default is 0.0
See ``neg_iou_thresh_high``.
pos_ratio : float, default is 0.25
``pos_ratio`` defines how many positive samples (``pos_ratio * num_sample``) is
to be sampled.
"""
def __init__(self, features, top_features, top_features_2nd,
top_features_3rd, classes,
short=600, max_size=1000, train_patterns=None,
nms_thresh=0.3, nms_topk=400, post_nms=100,
roi_mode='align', roi_size=(14, 14), stride=16, clip=None,
rpn_channel=1024, base_size=16, scales=(0.5, 1, 2),
ratios=(8, 16, 32), alloc_size=(128, 128), rpn_nms_thresh=0.7,
rpn_train_pre_nms=12000, rpn_train_post_nms=2000,
rpn_test_pre_nms=6000, rpn_test_post_nms=300, rpn_min_size=16,
num_sample=128, pos_iou_thresh=0.5, pos_ratio=0.25,
additional_output=False, **kwargs):
super(CascadeRCNN, self).__init__(
features=features, top_features=top_features,
top_features_2nd=top_features_2nd, top_features_3rd=top_features_3rd,
classes=classes,
short=short, max_size=max_size, train_patterns=train_patterns,
nms_thresh=nms_thresh, nms_topk=nms_topk, post_nms=post_nms,
roi_mode=roi_mode, roi_size=roi_size, stride=stride, clip=clip, **kwargs)
self._max_batch = 1 # currently only support batch size = 1
self._num_sample = num_sample
self._rpn_test_post_nms = rpn_test_post_nms
self._classes = classes
stds_2nd = (.05, .05, .1, .1)
stds_3rd = (.033, .033, .067, .067)
means_2nd= (0., 0., 0., 0.)
self._target_generator = {RCNNTargetGenerator(self.num_class,means_2nd,stds=(.1, .1, .2, .2))}
self._target_generator_2nd = {RCNNTargetGenerator(self.num_class, means_2nd, stds_2nd)}
self._target_generator_3rd = {RCNNTargetGenerator(self.num_class, means_2nd, stds_3rd)}
self._rpn_target_generator = set([RPNTargetGenerator(
num_sample=256, pos_iou_thresh=0.7,
neg_iou_thresh=0.3, pos_ratio=0.5,
stds=(1., 1., 1., 1.))])
with self.name_scope():
self.rpn = RPN(
channels=rpn_channel, stride=stride, base_size=base_size,
scales=scales, ratios=ratios, alloc_size=alloc_size,
clip=clip, nms_thresh=rpn_nms_thresh, train_pre_nms=rpn_train_pre_nms,
train_post_nms=rpn_train_post_nms, test_pre_nms=rpn_test_pre_nms,
test_post_nms=rpn_test_post_nms, min_size=rpn_min_size)
self.sampler = RCNNTargetSampler(
num_image=self._max_batch, num_proposal=rpn_train_post_nms,
num_sample=num_sample, pos_iou_thresh=pos_iou_thresh,pos_iou_thresh_hg=1, pos_ratio=pos_ratio)
self.sampler_2nd = RCNNTargetSampler(
num_image=self._max_batch, num_proposal=self._num_sample,
num_sample=self._num_sample, pos_iou_thresh=0.6,pos_iou_thresh_hg=0.95, pos_ratio=0.25)
self.sampler_3rd = RCNNTargetSampler(
num_image=self._max_batch, num_proposal=self._num_sample,
num_sample=self._num_sample, pos_iou_thresh=0.7,pos_iou_thresh_hg=0.95, pos_ratio=0.25)
self.box_decoder_2nd = NormalizedBoxCenterDecoder(stds=(.05, .05, .1, .1))
self.box_decoder_3rd = NormalizedBoxCenterDecoder(stds=(.033, .033, .067, .067))
@property
def target_generator(self):
"""Returns stored target generator
Returns
-------
mxnet.gluon.HybridBlock
The RCNN target generator
"""
return list(self._target_generator)[0]
@property
def target_generator_2nd(self):
return list(self._target_generator_2nd)[0]
@property
def target_generator_3rd(self):
return list(self._target_generator_3rd)[0]
@property
def rpn_target_generator(self):
return list(self._rpn_target_generator)[0]
def ROIExtraction(self, F, feature, bbox):
roi = self.add_batchid(F, bbox)
# ROI features
if self._roi_mode == 'pool':
pooled_feat = F.ROIPooling(feature, roi, self._roi_size, 1. / self._stride)
elif self._roi_mode == 'align':
pooled_feat = F.contrib.ROIAlign(feature, roi, self._roi_size, 1. / self._stride, sample_ratio=2)
else:
raise ValueError("Invalid roi mode: {}".format(self._roi_mode))
return pooled_feat
def add_batchid(self, F, bbox):
num_roi = self._num_sample if autograd.is_training() else self._rpn_test_post_nms
with autograd.pause():
roi_batchid = F.arange(0, self._max_batch, repeat=num_roi)
# remove batch dim because ROIPooling require 2d input
roi = F.concat(*[roi_batchid.reshape((-1, 1)), bbox.reshape((-1, 4))], dim=-1)
roi = F.stop_gradient(roi)
return roi
def decode_bbox(self, source_bbox, encoded_bbox, stds):
with autograd.pause():
box_decoder = NormalizedBoxCenterDecoder(stds=stds)
roi = box_decoder(encoded_bbox, self.box_to_center(source_bbox))
#roi = roi.reshape((1,-1, 4))
return roi
# pylint: disable=arguments-differ
def hybrid_forward(self, F, x, gt_box=None):
"""Forward Faster-RCNN network.
The behavior during traing and inference is different.
Parameters
----------
x : mxnet.nd.NDArray or mxnet.symbol
The network input tensor.
gt_box : type, only required during training
The ground-truth bbox tensor with shape (1, N, 4).
Returns
-------
(ids, scores, bboxes)
During inference, returns final class id, confidence scores, bounding
boxes.
"""
def _split(x, axis, num_outputs, squeeze_axis):
x = F.split(x, axis=axis, num_outputs=num_outputs, squeeze_axis=squeeze_axis)
if isinstance(x, list):
return x
else:
return [x]
feat = self.features(x)
# RPN proposals
if autograd.is_training():
rpn_score, rpn_box, raw_rpn_score, raw_rpn_box, anchors = self.rpn(feat, F.zeros_like(x))
# print(rpn_box.shape)
# rpn_index = F.Custom(rpn_box, op_type='clip_rpn_box')
# index = int(rpn_index.sum().asnumpy())
# rpn_box = rpn_box.slice_axis(axis=1,begin=0,end =index)
# #rpn_box = self.rpn_box_clip(rpn_box)
assert gt_box is not None
rpn_box, samples, matches = self.sampler(rpn_box, gt_box)
else:
_, rpn_box = self.rpn(feat, F.zeros_like(x))
# ROI features (ROI pooling or ROI Align)
num_roi = self._num_sample if autograd.is_training() else self._rpn_test_post_nms
pooled_feat = self.ROIExtraction(F=F, feature=feat, bbox=rpn_box)
top_feat = self.top_features(pooled_feat)
#top_feat = self.global_avg_pool(top_feat)
cls_pred = self.class_predictor(top_feat)
box_pred = self.box_predictor(top_feat)
# cls_pred (B * N, C) -> (B, N, C)
cls_pred = cls_pred.reshape((self._max_batch, num_roi, self.num_class + 1))
# box_pred (B * N, C * 4) -> (B, N, C, 4)
box_pred = box_pred.reshape((self._max_batch, num_roi, 1, 4))
# casscade rcnn
with autograd.pause():
roi_2nd = self.box_decoder(F.squeeze(box_pred.transpose((0, 2, 1, 3)), axis=1), self.box_to_center(rpn_box))
#roi_2nd = self.decode_bbox(source_bbox=rpn_box, \
# encoded_bbox=F.squeeze(box_pred.transpose((0, 2, 1, 3)), axis=1), stds=(.1, .1, .2, .2))
# roi_2nd_score =
if autograd.is_training():
roi_2nd, samples_2nd, matches_2nd = self.sampler_2nd(roi_2nd, gt_box)
pooled_feat_2nd = self.ROIExtraction(F=F, feature=feat, bbox=roi_2nd)
top_feat_2nd = self.top_features_2nd(pooled_feat_2nd)
cls_pred_2nd = self.class_predictor_2nd(top_feat_2nd)
box_pred_2nd = self.box_predictor_2nd(top_feat_2nd)
# cls_pred (B * N, C) -> (B, N, C)
cls_pred_2nd = cls_pred_2nd.reshape((self._max_batch, num_roi, self.num_class + 1))
# box_pred (B * N, C * 4) -> (B, N, C, 4)
box_pred_2nd = box_pred_2nd.reshape((self._max_batch, num_roi, 1, 4))
# decode rcnn box
with autograd.pause():
roi_3rd = self.box_decoder_2nd(F.squeeze(box_pred_2nd.transpose((0, 2, 1, 3)), axis=1), self.box_to_center(roi_2nd))
#roi_3rd = self.decode_bbox(source_bbox=roi_2nd, \
#encoded_bbox=F.squeeze(box_pred_2nd.transpose((0, 2, 1, 3)), axis=1), stds=(.05, .05, .1, .1))
if autograd.is_training():
roi_3rd, samples_3rd, matches_3rd = self.sampler_3rd(roi_3rd, gt_box)
pooled_feat_3rd = self.ROIExtraction(F=F, feature=feat, bbox=roi_3rd)
top_feat_3rd = self.top_features_3rd(pooled_feat_3rd)
cls_pred_3rd = self.class_predictor_3rd(top_feat_3rd)
box_pred_3rd = self.box_predictor_3rd(top_feat_3rd)
# cls_pred (B * N, C) -> (B, N, C)
cls_pred_3rd = cls_pred_3rd.reshape((self._max_batch, num_roi, self.num_class + 1))
# box_pred (B * N, C * 4) -> (B, N, C, 4)
box_pred_3rd = box_pred_3rd.reshape((self._max_batch, num_roi, 1, 4))
# no need to convert bounding boxes in training, just return
if autograd.is_training():
rpn_result = raw_rpn_score, raw_rpn_box, anchors
cascade_rcnn_result = [ [cls_pred, box_pred, rpn_box, samples, matches ],
[cls_pred_2nd, box_pred_2nd, roi_2nd, samples_2nd, matches_2nd],
[cls_pred_3rd, box_pred_3rd, roi_3rd, samples_3rd, matches_3rd ] ]
return rpn_result, cascade_rcnn_result
# cls_ids (B, N, C), scores (B, N, C)
cls_prob_3rd = F.softmax(cls_pred_3rd, axis=-1)
cls_prob_2nd = F.softmax(cls_pred_2nd, axis=-1)
cls_prob_1st = F.softmax(cls_pred, axis=-1)
cls_prob_3rd_avg = F.ElementWiseSum(cls_prob_3rd,cls_prob_2nd,cls_prob_1st)
cls_ids, scores = self.cls_decoder(cls_prob_3rd_avg )
# cls_ids, scores (B, N, C) -> (B, C, N) -> (B, C, N, 1)
cls_ids = cls_ids.transpose((0, 2, 1)).reshape((0, 0, 0, 1))
scores = scores.transpose((0, 2, 1)).reshape((0, 0, 0, 1))
# box_pred (B, N, C, 4) -> (B, C, N, 4)
box_pred = box_pred_3rd.transpose((0, 2, 1, 3))
# rpn_boxes (B, N, 4) -> B * (1, N, 4)
rpn_boxes = _split(roi_3rd, axis=0, num_outputs=self._max_batch, squeeze_axis=False)
# cls_ids, scores (B, C, N, 1) -> B * (C, N, 1)
cls_ids = _split(cls_ids, axis=0, num_outputs=self._max_batch, squeeze_axis=True)
scores = _split(scores, axis=0, num_outputs=self._max_batch, squeeze_axis=True)
# box_preds (B, C, N, 4) -> B * (C, N, 4)
box_preds = _split(box_pred, axis=0, num_outputs=self._max_batch, squeeze_axis=True)
# per batch predict, nms, each class has topk outputs
results = []
for rpn_box, cls_id, score, box_pred in zip(rpn_boxes, cls_ids, scores, box_preds):
# box_pred (C, N, 4) rpn_box (1, N, 4) -> bbox (C, N, 4)
bbox = self.box_decoder_3rd(box_pred, self.box_to_center(rpn_box))
bbox = F.repeat(bbox, repeats=self.num_class, axis=0)
# res (C, N, 6)
#print("cls_id:{} score:{} box:{}".format(cls_id.shape,score.shape,bbox.shape))
res | |
status = utools._verify_version("tarballfile")
self.assertEqual(status, (False, ''))
mock_call.return_value = 0
mock_verok.return_value = False
mock_isfile.return_value = True
status = utools._verify_version("tarballfile")
# self.assertEqual(status, (False, ''))
mock_call.return_value = 0
mock_verok.return_value = True
mock_getver.return_value = '2.0.0'
mock_isfile.return_value = True
status = utools._verify_version("tarballfile")
self.assertEqual(status, (True, '2.0.0'))
@mock.patch('udocker.FileUtil')
@mock.patch('udocker.os.listdir')
@mock.patch('udocker.LocalRepository')
def test_09_purge(self, mock_localrepo, mock_listdir, mock_futil):
"""Test09 UdockerTools.purge()."""
mock_listdir.return_value = []
utools = udocker.UdockerTools(mock_localrepo)
utools.purge()
self.assertFalse(mock_futil.return_value.remove.called)
mock_listdir.return_value = ["F1", "F2"]
utools = udocker.UdockerTools(mock_localrepo)
utools.purge()
self.assertTrue(mock_futil.return_value.remove.called)
@mock.patch('udocker.os.path.isfile')
@mock.patch('udocker.UdockerTools._install')
@mock.patch('udocker.UdockerTools._verify_version')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.Msg')
@mock.patch('udocker.subprocess.call')
@mock.patch('udocker.UdockerTools.__init__')
def test_10__install(self, mock_init, mock_call, mock_msg, mock_local,
mock_ver_version, mock_ins, mock_isfile):
"""Test10 UdockerTools._install()."""
mock_init.return_value = None
utools = udocker.UdockerTools(None)
utools.localrepo = mock_local
mock_local.bindir = ""
mock_msg.level = 0
mock_call.return_value = 1
mock_ver_version.return_value = False
mock_ins.return_value = False
mock_isfile.return_value = False
status = utools._install("tarballfile")
self.assertFalse(status)
mock_call.return_value = 0
mock_ver_version.return_value = True
mock_ins.return_value = True
mock_isfile.return_value = True
status = utools._install("tarballfile")
self.assertTrue(status)
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.GetURL')
def test_11__get_mirrors(self, mock_geturl, mock_localrepo):
"""Test11 UdockerTools._get_mirrors()."""
mock_geturl.return_value = None
mirrors = "https://download.ncg.ingrid.pt/udocker-1.1.3.tar.gz"
utools = udocker.UdockerTools(mock_localrepo)
status = utools._get_mirrors(mirrors)
self.assertEqual(status, [mirrors])
@mock.patch.object(udocker.UdockerTools, '_get_file')
@mock.patch.object(udocker.UdockerTools, '_get_mirrors')
@mock.patch('udocker.json.load')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.GetURL')
def test_12_get_installinfo(self, mock_geturl, mock_localrepo, mock_jload,
mock_getmirr, mock_getfile):
"""Test12 UdockerTools.get_installinfo()."""
mock_geturl.return_value = None
mirrors = "https://download.ncg.ingrid.pt/udocker-1.1.3.tar.gz"
mock_getmirr.return_value = [mirrors]
mock_getfile.return_value = "udocker-1.1.3.tar.gz"
dictdata = {"architecture": "amd64",
"messages": {"AttachStderr": False}}
json_data = json.dumps(dictdata)
mock_jload.return_value = dictdata
with mock.patch(BUILTINS + '.open',
mock.mock_open(read_data=json_data)):
utools = udocker.UdockerTools(mock_localrepo)
data = utools.get_installinfo()
self.assertEqual(data, dictdata)
@mock.patch.object(udocker.UdockerTools, '_install')
@mock.patch.object(udocker.UdockerTools, '_verify_version')
@mock.patch.object(udocker.UdockerTools, '_get_file')
@mock.patch.object(udocker.UdockerTools, '_get_mirrors')
@mock.patch('udocker.FileUtil.remove')
@mock.patch('udocker.Msg')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.GetURL')
def test_13__install_logic(self, mock_geturl, mock_localrepo, mock_msg,
mock_futilrm, mock_getmirr, mock_getfile,
mock_ver, mock_inst):
"""Test13 UdockerTools._install_logic()."""
mock_geturl.return_value = None
mock_futilrm.return_value = None
mirrors = "https://download.ncg.ingrid.pt/udocker-1.1.3.tar.gz"
mock_getmirr.return_value = [mirrors]
mock_getfile.return_value = "udocker-1.1.3.tar.gz"
mock_ver.return_value = (True, "1.1.3")
mock_inst.return_value = True
utools = udocker.UdockerTools(mock_localrepo)
status = utools._install_logic()
self.assertTrue(mock_getmirr.called)
self.assertEqual(mock_msg.call_count, 2)
self.assertTrue(mock_getfile.called)
self.assertTrue(mock_inst.called)
self.assertTrue(status)
mock_geturl.return_value = None
mock_futilrm.return_value = None
mirrors = "https://download.ncg.ingrid.pt/udocker-1.1.3.tar.gz"
mock_getmirr.return_value = [mirrors]
mock_getfile.return_value = "udocker-1.1.3.tar.gz"
mock_ver.return_value = (False, "1.1.3")
utools = udocker.UdockerTools(mock_localrepo)
status = utools._install_logic()
self.assertEqual(mock_msg.call_count, 4)
self.assertFalse(status)
@mock.patch('udocker.Config')
@mock.patch('udocker.Msg')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.GetURL')
@mock.patch.object(udocker.UdockerTools, 'get_installinfo')
@mock.patch.object(udocker.UdockerTools, '_install_logic')
@mock.patch.object(udocker.UdockerTools, '_instructions')
@mock.patch.object(udocker.UdockerTools, 'is_available')
def test_14_install(self, mock_is, mock_instr, mock_install, mock_getinst,
mock_geturl, mock_localrepo, mock_msg, mock_config):
"""Test14 UdockerTools.install()"""
# Is available no force
mock_geturl.return_value = None
mock_is.return_value = True
utools = udocker.UdockerTools(mock_localrepo)
status = utools.install()
self.assertTrue(mock_is.called)
self.assertTrue(status)
# No autoinstall
mock_geturl.return_value = None
mock_is.return_value = False
utools = udocker.UdockerTools(mock_localrepo)
utools._autoinstall = False
status = utools.install()
self.assertTrue(mock_is.called)
self.assertTrue(mock_msg().err.called)
self.assertFalse(status)
# No tarball
mock_geturl.return_value = None
mock_is.return_value = False
mock_getinst.return_value = "JSONinstall"
utools = udocker.UdockerTools(mock_localrepo)
utools._autoinstall = True
utools._tarball = ""
status = utools.install()
self.assertTrue(mock_is.called)
self.assertTrue(mock_msg().err.called)
self.assertTrue(status)
# Download ok
mock_geturl.return_value = None
mock_is.return_value = False
mock_install.return_value = True
mock_getinst.return_value = "JSONinstall"
udocker.Config = mock_config
udocker.Config.autoinstall = True
udocker.Config.installretry = 1
utools = udocker.UdockerTools(mock_localrepo)
utools._tarball = "http://node.domain/filename.tgz"
status = utools.install()
self.assertTrue(mock_install.called)
self.assertTrue(mock_msg().err.called)
self.assertTrue(mock_getinst.called)
self.assertTrue(status)
class ElfPatcherTestCase(unittest.TestCase):
"""Test ElfPatcher: Patch container executables."""
@classmethod
def setUpClass(cls):
"""Setup test."""
set_env()
@mock.patch('udocker.os.path.realpath')
@mock.patch('udocker.LocalRepository')
def test_01_init(self, mock_local, mock_rpath):
""" Test01 ElfPatcher constructor."""
mock_rpath.return_value = "/cont/ROOT"
container_id = "SOME-RANDOM-ID"
udocker.ElfPatcher(mock_local, container_id)
self.assertTrue(mock_rpath.called)
@mock.patch('udocker.sys.exit')
@mock.patch('udocker.os.path.realpath')
@mock.patch('udocker.Msg')
@mock.patch('udocker.HostInfo.arch')
@mock.patch('udocker.FileUtil')
@mock.patch('udocker.LocalRepository')
def test_02_select_patchelf(self, mock_local, mock_futil,
mock_arch, mock_msg, mock_rpath, mock_exit):
"""Test02 ElfPatcher().select_patchelf(). Set patchelf executable."""
container_id = "SOME-RANDOM-ID"
mock_arch.return_value = "amd64"
mock_futil.return_value.find_file_in_dir.return_value = "patchelf-x86_64"
mock_rpath.return_value = "/ROOT"
elfp = udocker.ElfPatcher(mock_local, container_id)
output = elfp.select_patchelf()
self.assertEqual(output, "patchelf-x86_64")
mock_futil.return_value.find_file_in_dir.return_value = ""
mock_exit.return_value = None
elfp = udocker.ElfPatcher(mock_local, container_id)
elfp.select_patchelf()
self.assertTrue(mock_msg.return_value.err.called)
self.assertTrue(mock_exit.called)
@mock.patch('udocker.os.path.realpath')
@mock.patch('udocker.LocalRepository')
def test_03__replace(self, mock_local, mock_rpath):
""" Test03 ElfPatcher()._replace()."""
container_id = "SOME-RANDOM-ID"
cmd = ["#f", "-al"]
path = "/bin/ls"
mock_rpath.return_value = "/ROOT"
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp._replace(cmd, path)
self.assertEqual(status, ["/bin/ls", "-al"])
@mock.patch('udocker.os.path.islink')
@mock.patch('udocker.os.path.stat')
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.walk')
@mock.patch('udocker.os.access')
@mock.patch('udocker.LocalRepository')
def test_04__walk_fs(self, mock_local, mock_access, mock_walk,
mock_path, mock_stat, mock_islink):
"""Test04 ElfPatcher()._walk_fs()."""
container_id = "SOME-RANDOM-ID"
mock_walk.return_value = [('/tmp', ('dir',), ('file',)), ]
mock_islink.return_value = False
mock_stat.return_value.st_uid = ""
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp._walk_fs("cmd", "/tmp", elfp.BIN)
self.assertFalse(status)
@mock.patch('udocker.os.path')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.ElfPatcher._walk_fs')
@mock.patch('udocker.ElfPatcher.select_patchelf')
def test_05_guess_elf_loader(self, mock_spelf, mock_walk,
mock_local, mock_path):
"""Test05 ElfPatcher().guess_elf_loader()."""
container_id = "SOME-RANDOM-ID"
mock_spelf.return_value = "ld.so"
mock_walk.return_value = ""
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.guess_elf_loader(), "")
mock_walk.return_value = "ld.so"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.guess_elf_loader(), "ld.so")
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.FileUtil.getdata')
@mock.patch('udocker.ElfPatcher.guess_elf_loader')
def test_06_get_original_loader(self, mock_guess, mock_futils,
mock_local, mock_exists, mock_path):
"""Test06 ElfPatcher().get_original_loader()."""
container_id = "SOME-RANDOM-ID"
mock_exists.return_value = True
mock_futils.return_value.strip.return_value = "ld.so"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_original_loader(), "ld.so")
mock_exists.return_value = False
mock_guess.return_value = "ld.so"
mock_futils.return_value.strip.return_value = "ld.so"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_original_loader(), "ld.so")
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.ElfPatcher.get_original_loader')
def test_07_get_container_loader(self, mock_gol, mock_local,
mock_exists, mock_path):
"""Test07 ElfPatcher().get_container_loader()."""
container_id = "SOME-RANDOM-ID"
mock_gol.return_value = ""
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_container_loader(), "")
mock_exists.return_value = True
mock_gol.return_value = "ld.so"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_container_loader(),
elfp._container_root + "/" + "ld.so")
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.FileUtil.getdata')
def test_08_get_patch_last_path(self, mock_getdata, mock_local,
mock_exists, mock_path):
"""Test08 ElfPatcher().get_patch_last_path()."""
container_id = "SOME-RANDOM-ID"
mock_getdata.return_value = ""
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_patch_last_path(), "")
mock_getdata.return_value = "/tmp"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_patch_last_path(), "/tmp")
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.ElfPatcher.get_patch_last_path')
@mock.patch('udocker.Msg')
def test_09_check_container_path(self, mock_msg, mock_lpath,
mock_local, mock_exists, mock_path):
"""Test09 ElfPatcher().check_container_path()."""
container_id = "SOME-RANDOM-ID"
mock_lpath.return_value = "/tmp"
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp.check_container_path()
self.assertFalse(status)
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.FileUtil.getdata')
def test_10_get_patch_last_time(self, mock_getdata, mock_local,
mock_exists, mock_path):
"""Test10 ElfPatcher().get_patch_last_time()."""
container_id = "SOME-RANDOM-ID"
mock_getdata.return_value = "30"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertEqual(elfp.get_patch_last_time(), "30")
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.FileUtil.putdata')
@mock.patch('udocker.ElfPatcher.guess_elf_loader')
@mock.patch('udocker.ElfPatcher.select_patchelf')
@mock.patch('udocker.ElfPatcher.get_container_loader')
@mock.patch('udocker.ElfPatcher')
def test_11_patch_binaries(self, mock_elfp, mock_gcl, mock_select,
mock_guess, mock_putdata, mock_local,
mock_exists, mock_path):
"""Test11 ElfPatcher().patch_binaries()."""
container_id = "SOME-RANDOM-ID"
mock_exists.return_value = True
mock_gcl.return_value = "/usr/bin/ld"
mock_select.return_value = "runc-arm"
mock_putdata.side_effect = ["10", "/tmp"]
mock_guess.return_value = "/usr/bin/ld"
mock_elfp.return_value._container_root.return_value = "/tmp/ROOT"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertTrue(elfp.patch_binaries())
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.ElfPatcher.guess_elf_loader')
@mock.patch('udocker.ElfPatcher.select_patchelf')
@mock.patch('udocker.ElfPatcher.get_container_loader')
@mock.patch('udocker.ElfPatcher')
def test_12_restore_binaries(self, mock_elfp, mock_gcl, mock_select,
mock_guess, mock_local,
mock_exists, mock_path):
"""Test12 ElfPatcher().restore_binaries()."""
container_id = "SOME-RANDOM-ID"
mock_exists.return_value = True
mock_gcl.return_value = "/usr/bin/ld"
mock_select.return_value = "runc-arm"
mock_guess.return_value = "/usr/bin/ld"
mock_elfp.return_value._container_root.return_value = "/tmp/ROOT"
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertTrue(elfp.restore_binaries())
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.ElfPatcher.get_container_loader')
@mock.patch('udocker.FileUtil.size')
@mock.patch('udocker.FileUtil.copyto')
@mock.patch('udocker.FileUtil.getdata')
def test_13_patch_ld(self, mock_getdata,
mock_copyto, mock_size,
mock_gcl, mock_local,
mock_exists, mock_path):
"""Test13 ElfPatcher().patch_ld(). Patch ld.so"""
container_id = "SOME-RANDOM-ID"
mock_size.return_value = -1
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertFalse(elfp.patch_ld())
mock_size.return_value = 20
mock_copyto.return_value = False
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertFalse(elfp.patch_ld())
mock_size.return_value = 20
mock_copyto.return_value = True
mock_getdata.return_value = []
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertFalse(elfp.patch_ld())
mock_size.return_value = 20
mock_copyto.return_value = True
mock_getdata.return_value = []
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertFalse(elfp.patch_ld("OUTPUT_ELF"))
@mock.patch('udocker.Msg')
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.ElfPatcher.get_container_loader')
@mock.patch('udocker.FileUtil.size')
@mock.patch('udocker.FileUtil.copyto')
def test_14_restore_ld(self, mock_copyto, mock_size,
mock_gcl, mock_local,
mock_exists, mock_path, mock_msg):
"""Test14 ElfPatcher().restore_ld(). Restore ld.so"""
container_id = "SOME-RANDOM-ID"
mock_size.return_value = -1
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertFalse(elfp.restore_ld())
mock_size.return_value = 20
mock_copyto.return_value = True
elfp = udocker.ElfPatcher(mock_local, container_id)
self.assertTrue(elfp.restore_ld())
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
@mock.patch('udocker.Uprocess.get_output')
def test_15__get_ld_config(self, mock_upout,
mock_local, mock_exists, mock_path):
"""Test15 ElfPatcher()._get_ld_config()."""
container_id = "SOME-RANDOM-ID"
mock_upout.return_value = []
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp._get_ld_config()
self.assertEqual(status, [])
mock_upout.return_value = \
"ld.so.cache => /tmp/ROOT/etc/ld.so.cache\n" \
"ld.so.cache => /tmp/ROOT/etc/ld.so"
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp._get_ld_config()
self.assertIsInstance(status, list)
@mock.patch('udocker.os.path.realpath')
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.access')
@mock.patch('udocker.os.walk')
@mock.patch('udocker.os.path.isfile')
@mock.patch('udocker.LocalRepository')
def test_16__find_ld_libdirs(self, mock_local, mock_isfile, mock_walk,
mock_access, mock_path, mock_rpath):
"""Test16 ElfPatcher()._find_ld_libdirs()."""
container_id = "SOME-RANDOM-ID"
mock_rpath.return_value = "/ROOT"
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp._find_ld_libdirs()
self.assertEqual(status, [])
root_path = "/udocker/cont"
mock_walk.return_value = [("/ROOT", ["ROOT"], ["ld-linux-x86-64.so.2"]), ]
mock_access.return_value = True
mock_isfile.return_value = True
mock_rpath.return_value = "/ROOT"
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp._find_ld_libdirs(root_path)
# self.assertEqual(status, ['ROOT'])
@mock.patch.object(udocker.ElfPatcher, '_find_ld_libdirs')
@mock.patch('udocker.FileUtil.putdata')
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
def test_17_get_ld_libdirs(self, mock_local, mock_exists,
mock_path, mock_put, mock_find):
"""Test17 ElfPatcher().get_ld_libdirs(). Get ld library paths"""
container_id = "SOME-RANDOM-ID"
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp.get_ld_libdirs()
self.assertEqual(status, [''])
mock_exists.return_value = False
mock_find.return_value = ['/lib', '/usr/lib']
mock_put.return_value = '/lib:/usr/lib'
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp.get_ld_libdirs(True)
self.assertTrue(mock_find.called)
self.assertTrue(mock_put.called)
self.assertEqual(status, ['/lib', '/usr/lib'])
@mock.patch.object(udocker.ElfPatcher, '_get_ld_config')
@mock.patch('udocker.os.path')
@mock.patch('udocker.os.path.exists')
@mock.patch('udocker.LocalRepository')
def test_18_get_ld_library_path(self, mock_local,
mock_exists, mock_path, mock_get_ld):
"""Test18 ElfPatcher().get_ld_library_path(). Get ld library paths"""
container_id = "SOME-RANDOM-ID"
mock_get_ld.return_value = []
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp.get_ld_library_path()
self.assertEqual(status, '')
mock_get_ld.return_value = ['/lib', '/usr/lib']
elfp = udocker.ElfPatcher(mock_local, container_id)
status = elfp.get_ld_library_path()
self.assertEqual(status, '/lib:/usr/lib:')
class NixAuthenticationTestCase(unittest.TestCase):
"""Test NixAuthentication() *nix authentication portably."""
@classmethod
def setUpClass(cls):
"""Setup test."""
set_env()
def test_01_init(self):
"""Test01 NixAuthentication() constructor."""
auth = udocker.NixAuthentication()
self.assertEqual(auth.passwd_file, None)
self.assertEqual(auth.group_file, None)
auth = udocker.NixAuthentication("passwd", "group")
self.assertEqual(auth.passwd_file, "passwd")
self.assertEqual(auth.group_file, "group")
def test_02__user_in_subid(self):
"""Test02 NixAuthentication()._user_in_subid()."""
sfile = "/etc/subuid"
auth = udocker.NixAuthentication()
auth.passwd_file = ""
subid_line = StringIO('root:296608:65536')
with mock.patch(BUILTINS + '.open') as mopen:
mopen.return_value.__iter__ = (
lambda self: iter(subid_line.readline, ''))
name = auth._user_in_subid(sfile, "root")
self.assertEqual(name, [('296608', '65536')])
@mock.patch('udocker.NixAuthentication._user_in_subid')
def test_03_user_in_subuid(self, mock_usubid):
"""Test03 NixAuthentication().user_in_subuid()."""
mock_usubid.return_value = [('296608', '65536')]
subid_line = StringIO('root:296608:65536')
auth = udocker.NixAuthentication()
auth.passwd_file = ""
status = auth.user_in_subuid("root")
@mock.patch('udocker.NixAuthentication._user_in_subid')
def | |
<gh_stars>10-100
import re
import logging
from ..common.optconst import *
from .lgmisc import LGParseError
from typing import List, Optional, Union, Tuple
from decimal import Decimal
"""
Utilities for parsing postscript notated tokens and links, returned by Link Grammar API method Linkage.postscript()
"""
__all__ = ['strip_token', 'parse_tokens', 'parse_links', 'parse_postscript', 'skip_lines', 'trim_garbage',
'get_link_set', 'prepare_tokens', 'skip_command_response', 'skip_linkage_header', 'split_ps_parses',
'get_sentence_text', 'get_linkage_cost', 'PS_TIMEOUT_EXPIRED', 'PS_PANIC_DETECTED']
__version__ = "1.0.0"
def strip_token(token) -> str:
"""
Strip off suffix substring
:param token: token string
:return: stripped token if a suffix found, the same token otherwise
"""
if token.startswith("["):
return token
pos = token.find("[")
# If "[" is not found
if pos < 0:
pos = token.find(".", 0 if token[0] != "." else 1)
# If "." is not found return token as is.
if pos <= 0:
return token
return token[:pos:]
def find_end_of_token(text, start_pos: int) -> int:
# Assume the open brace is already skipped
braces = 1
brackets = 0
pos = start_pos
text_len = len(text)
while pos < text_len:
current = text[pos]
if current == r")":
# if not "[)]"
if not brackets:
# If not "())"
if pos + 1 >= text_len or text[pos + 1] != r")":
braces -= 1
if not braces:
return pos
elif current == r"[":
# If not "([)"
if pos + 1 >= text_len or text[pos + 1] != r")":
brackets += 1
elif current == r"]" and brackets:
brackets -= 1
pos += 1
return pos
def parse_tokens(txt, opt) -> (list, int):
"""
Parse string of tokens, taken from postscript notated LG parse output.
After several iterations it became obvious that all tokens should be kept in the original list in order to
avoid issues with links. All filtering necessary for ULL output is now done in print_output(). All filtering
necessary for parseability statistics estimation is done in prepare_tokens().
:param txt: String token line extracted from postfix notation output string returned by Linkage.postfix()
method.
:param opt: Bit mask option value (see parse_test() description for more details).
:return: List of tokens.
"""
tokens = []
offset = 0
# Skip the open brace
start_pos = 1
end_pos = txt.find(")(")
if end_pos < 0:
end_pos = len(txt)-1
while end_pos - start_pos > 0:
token = txt[start_pos:end_pos:]
# Strip LG suffixes if the option is set.
if opt & BIT_STRIP == BIT_STRIP:
token = strip_token(token)
# All walls are supplied with leading and trailing hashes as agreed for the project.
if token.find("-WALL") > 0:
if token in ["RIGHT-WALL", "LEFT-WALL"]:
tokens.append(r"###" + token + r"###")
elif token in ["[RIGHT-WALL]", "[LEFT-WALL]"]:
tokens.append(r"###" + token[1:-1] + r"###")
else:
# Even if LEFT-WALL is not defined in .dict file it is still added into the token list
# in order for token numbering to be started from one as agreed for ULL project.
if start_pos == 1:
tokens.append(r"###LEFT-WALL###")
offset = 1
# By default all tokens are kept lower case.
if opt & BIT_CAPS == 0:
token = token.lower()
tokens.append(token)
start_pos = end_pos + 2
end_pos = txt.find(")(", start_pos + 1)
if end_pos < 0:
end_pos = len(txt)-1
return tokens, offset
def prepare_tokens(tokens: list, options: int) -> list:
"""
Prepare (filter) list of tokens according to the options flags for statistics calculation.
:param tokens: Initial list of tokens obtained from parse_tokens().
:param options: Bit flags.
:return: Filtered list of tokens.
"""
token_count = len(tokens)
first_token = 0
last_token = token_count - 1
if not token_count:
return tokens
if options & BIT_NO_LWALL:
if tokens[0].startswith(r"###") or tokens[0].startswith(r"[##"):
first_token += 1
# RIGHT-WALL is not needed if LEFT-WALL is stripped off
if tokens[last_token].startswith(r"###") or tokens[last_token].startswith(r"[##"):
last_token -= 1
if not (options & BIT_RWALL) and (tokens[last_token].startswith(r"###") or tokens[last_token].startswith(r"[##")):
last_token -= 1
if options & BIT_NO_PERIOD:
rw = tokens[last_token] if tokens[last_token].startswith(r"###") or tokens[last_token].startswith(r"[##") \
else None
# Skip RIGHT-WALL if any
if last_token and tokens[last_token] in [r"###RIGHT-WALL###", r"[###RIGHT-WALL###]"]:
last_token -= 1
# Skip period or period in brackets if any
if last_token and tokens[last_token] in [r"[.]", r"."]:
last_token -= 1
# If both period and RIGHT-WALL were found
if rw is not None:
# RIGHT-WALL is added to the new list
return tokens[first_token:last_token+1] + [rw]
return tokens[first_token:last_token+1]
def parse_links(txt: str, tokens: list, offset: int) -> list:
"""
Parse links represented in postfix notation and return them as a list of tuples.
:param txt: Link list in postfix notation, obtained either from LG API or from link-parser postfix output.
:param tokens: List of tokens previously extracted from postfix notated output.
:param offset: Token index offset. Equals to 1 if tested grammar has no LEFT-WALL and the former was added
during postscript parsing. Offset is necessary for the links to have their indexes properly
updated.
:return: List of tuples representing token to token links.
"""
links = []
token_count = len(tokens)
start_pos = 1
end_pos = txt.find("]")
q = re.compile('(\d+)\s(\d+)\s\d+\s\(.+\)')
while end_pos - start_pos > 0:
mm = q.match(txt[start_pos:end_pos:])
if mm is not None:
index1, index2 = int(mm.group(1))+offset, int(mm.group(2))+offset
if index2 < token_count:
links.append((index1, index2))
start_pos = end_pos + 2
end_pos = txt.find("]", start_pos)
return links
def parse_postscript(text: str, options: int) -> ([], []):
"""
Parse postscript notation of the linkage.
:param text: Text string returned by Linkage.postscript() method.
:param options Bit mask, representing different parsing options. See `optconst.py` for details.
:return: Tuple of two lists: (tokens, links).
"""
p = re.compile('\[(\(.+?\)+?)\]\[(.*?)\]\[0\]', re.S)
m = p.match(text.replace("\n", ""))
if m is not None:
tokens, offset = parse_tokens(m.group(1), options)
links = parse_links(m.group(2), tokens, offset)
return tokens, links
raise LGParseError(f"parse_postscript(): regex does not match for:\n{text}")
def get_link_set(tokens: list, links: Union[list, set], options: int) -> set:
"""
Create link set from link list filtering out unnecessary links according to options bit flags.
:param tokens: Token list.
:param links: Link list.
:param options: Integer bit mask variable.
:return: Filtered set of links.
"""
all_link_set = set(links) if isinstance(links, list) else links
exc_link_set = set()
token_count = len(tokens)
if token_count:
last_token = token_count - 1
if options & BIT_NO_LWALL and tokens[0].find("WALL") > -1:
exc_link_set |= set({(0, i) for i in range(1, token_count)})
if tokens[last_token].startswith(r"###"):
exc_link_set |= set({(i, last_token) for i in range(token_count)})
if options & BIT_NO_PERIOD:
if tokens[last_token].startswith(r"###"):
last_token -= 1
if tokens[last_token] == ".":
exc_link_set |= set({(i, last_token) for i in range(token_count)})
if len(exc_link_set):
return all_link_set - exc_link_set
return all_link_set
def skip_lines(text: str, lines_to_skip: int) -> int:
"""
Skip specified number of lines from the beginning of a text string.
:param text: Text string with zero or many '\n' in.
:param lines_to_skip: Number of lines to skip.
:return: Return position of the first character after the specified number of lines is skipped.
"""
l = len(text)
pos = 0
cnt = lines_to_skip
while l and cnt:
if text[pos] == "\n":
cnt -= 1
pos += 1
return pos
def skip_command_response(text: str) -> int:
"""
Skip specified number of lines from the beginning of a text string.
:param text: Text string with zero or many '\n' in.
:return: Return position of the first character after the command response is skipped.
"""
l = len(text)
pos, old = 0, 0
while l:
if text[pos] == "\n":
line = text[old:pos]
if len(line) and not (line.startswith("Debug:") or line.find(" set to ") >= 0):
return old
old = pos + 1 if pos + 1 < l else pos
pos += 1
return pos
def trim_garbage(text: str) -> int:
"""
Strip all characters from the end of string until ']' is reached.
:param text: Text string.
:return: Return position of a character following ']' or zero in case of a null string.
"""
l = len(text) - 1
while l:
if text[l] == "]":
return l+1
l -= 1
pos = text.rfind("Bye.")
if pos > 0:
return pos
l = len(text) - 1
while text[l] == " " or text[l] == "\n":
l -= 1
return l
PS_TIMEOUT_EXPIRED = BIT_EXCLUDE_TIMEOUTED
PS_PANIC_DETECTED = BIT_EXCLUDE_PANICED
PS_EXPLOSION_DETECTED = BIT_EXCLUDE_EXPLOSION
def skip_linkage_header(text: str) -> (int, int):
"""
Skip linkage text header while checking timiouts and panic mode.
:param text: Text string | |
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import h5py
import copy
import time
import os
from whacc import utils
def isnotebook():
try:
c = str(get_ipython().__class__)
shell = get_ipython().__class__.__name__
if 'colab' in c:
return True
elif shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
if isnotebook():
from tqdm.notebook import tqdm
else:
from tqdm import tqdm
def stack_imgs_lag(imgs, frames_1=None, buffer=2, shift_to_the_right_by=0):
if frames_1 is None:
frames_1 = [imgs.shape[0]]
array_group = []
for k1, k2 in utils.loop_segments(frames_1):
x = (np.random.random(imgs[0].shape) * 255).astype(np.uint8)
tile_axes = [1] * len(x.shape) + [buffer]
x = np.tile(x[:, :, None], tile_axes)
tmp1 = x.copy()
for ii, stack_i in enumerate(range(k1, k2)):
x = np.concatenate((x, imgs[stack_i][:, :, None]), axis=2)
x = np.concatenate((x, tmp1), axis=2)
for k3 in range(k2 - k1):
array_group.append(x[:, :, k3 + shift_to_the_right_by: k3 + 1 + buffer + shift_to_the_right_by])
return np.asarray(array_group)
def get_h5_key_and_concatenate(h5_list, key_name='labels'):
"""
simply extract and concatenate all of one key "key_name" from many H5 files, I use it to get balance the data touch
and not touch frames when training a model with a list of different H5 files
Parameters
----------
h5_list : list
list of full paths to H5 file(s).
key_name : str
default 'labels', the key to get the data from the H5 file
"""
h5_list = utils.make_list(h5_list, suppress_warning=True)
for i, k in enumerate(h5_list):
with h5py.File(k, 'r') as h:
if i == 0:
out = np.asarray(h[key_name][:])
else:
out = np.concatenate((out, h[key_name][:]))
return out
def get_h5_key_and_dont_concatenate(h5_list, key_name='labels'):
"""
simply extract and concatenate all of one key "key_name" from many H5 files, I use it to get balance the data touch
and not touch frames when training a model with a list of different H5 files
Parameters
----------
h5_list : list
list of full paths to H5 file(s).
key_name : str
default 'labels', the key to get the data from the H5 file
"""
out = []
for i, k in enumerate(h5_list):
with h5py.File(k, 'r') as h:
out.append(list(h[key_name][:]))
return out
def clone_h5_basic_info(H5_list, fold_name=None, file_end='_QUICK_SAVE.h5'):
"""
copies all the info form H5 into another H5 file NOT INCLUDING the labels or images. so it have all the file info,
like names and pole locations and polate match max value stack. anything with 'images' , 'MODEL__' or 'labels' is
not copied over to the new file.
Parameters
----------
H5_list : list
list of H5 files to clone
fold_name : str
default None, where to place the cloned H5 files. if left blank it will place in the same folder as the original file
file_end : str
default '_QUICK_SAVE.h5', how to change the name of the H5 file to be cloned to differentiate it from the original
Returns
-------
all_new_h5s: list
list of new H5 full file names
"""
if fold_name is not None:
try:
os.mkdir(fold_name)
except:
pass
all_new_h5s = []
for h5 in H5_list:
if fold_name is not None:
new_fn = fold_name + os.path.sep + os.path.basename(h5)[:-3] + file_end
else: #
new_fn = os.path.dirname(h5) + os.path.sep + os.path.basename(h5)[:-3] + file_end
all_new_h5s.append(new_fn)
try:
os.remove(new_fn)
except:
pass
with h5py.File(new_fn, 'w') as f1:
with h5py.File(h5, 'r') as f2:
for i, k in enumerate(f2.keys()):
if 'images' != k and 'MODEL__' not in k and 'labels' not in k:
f1.create_dataset(k, data=f2[k][:])
f2.close()
f1.close()
return all_new_h5s
def del_h5_with_term(h5_list, str_2_cmp):
"""
Parameters
----------
h5_list : list
list of H5 strings (full path)
str_2_cmp : str
will delete keys with this in their title ... e.g. '__RETRAIN'
"""
for k2 in h5_list:
with h5py.File(k2, 'a') as h5_source:
for k in h5_source.keys():
if str_2_cmp in k:
print('del--> ' + k)
del h5_source[k]
print('_______')
def split_h5_loop_segments(h5_to_split_list, split_percentages, temp_base_name, chunk_size=10000,
add_numbers_to_name=True,
disable_TQDM=False, set_seed=None, color_channel=True):
"""Randomly splits images from a list of H5 file(s) into len(split_percentages) different H5 files.
Parameters
----------
h5_to_split_list : list
list of strings with full file names to the H5 file(s) to be split
split_percentages : list
list of numbers, can be ints [20, 1, 1] and or floats [.8, .2], it simply takes the sum and creates a percentage
temp_base_name : str or list
full path to new h5 file e.g "'/Users/phil/tempH5_" and the program will add the number and the ".h5"
in this case tempH5_0.h5, tempH5_1.h5, tempH5_2.h5 etc. or if it is a list it must be equal in length to
'split_percentages' and each file will be named based on that list
chunk_size = int
default 10000, max amount of frames to hold in memory at a time before storing in H5 file. Should almost never
be an issue but just in case you can set to a lower value if you experience memory issues.
add_numbers_to_name = bool
default true, just in case you don't want the numbers on the end of your h5 file.
Returns
Examples
--------
from whacc import image_tools, utils
h5_to_split_list = "/Users/phil/Downloads/untitled folder 2/AH0000x000000_small_tester.h5"
h5_to_split_list = [h5_to_split_list]
utils.print_h5_keys(h5_to_split_list[0])
bd = '/Users/phil/Downloads/untitled folder 2/'
image_tools.split_h5_loop_segments(h5_to_split_list, [1, 3], [bd+'TRASH', bd+'TRASH2'], chunk_size=10000, add_numbers_to_name=False,
disable_TQDM=False, set_seed = None)
-------
"""
if isinstance(temp_base_name, str):
temp_base_name = [temp_base_name] * len(split_percentages)
else:
assert len(temp_base_name) == len(
split_percentages), """if 'temp_base_name' is a list of strings, it must be equal in length to 'split_percentages'"""
for i, k in enumerate(temp_base_name):
if k[-3:] == '.h5':
temp_base_name[i] = temp_base_name[i][:-3]
frame_num_array_list = get_h5_key_and_dont_concatenate(h5_to_split_list, 'frame_nums')
total_frames = len(get_h5_key_and_concatenate(h5_to_split_list, key_name='labels'))
cnt1 = 0
h5_creators = dict()
split_percentages = split_percentages / np.sum(split_percentages)
# assert(sum(split_percentages)==1)
final_names = []
for iii, h5_to_split in enumerate(h5_to_split_list):
with h5py.File(h5_to_split, 'r') as h:
tmp_frame_list = frame_num_array_list[iii]
L = len(tmp_frame_list)
if set_seed is not None:
np.random.seed(set_seed)
mixed_inds = np.random.choice(L, L, replace=False)
random_segment_inds = np.split(mixed_inds, np.ceil(L * np.cumsum(split_percentages[:-1])).astype('int'))
random_segment_inds = [sorted(tmpk) for tmpk in random_segment_inds]
random_frame_inds = [[None]] * len(random_segment_inds)
list_of_new_frame_nums = [[None]] * len(random_segment_inds)
loop_seg_list = list(utils.loop_segments(tmp_frame_list))
for pi, p in enumerate(random_segment_inds):
tmp1 = []
tmp2 = []
for pp in p:
x = list(loop_seg_list[pp])
tmp1 += list(range(x[0], x[1]))
tmp2.append(tmp_frame_list[pp])
random_frame_inds[pi] = tmp1
list_of_new_frame_nums[pi] = tmp2
for i, k in enumerate(split_percentages): # for each new h5 created
if iii == 0: # create the H5 creators
if add_numbers_to_name:
final_names.append(temp_base_name[i] + '_' + str(i) + '.h5')
else:
final_names.append(temp_base_name[i] + '.h5')
h5_creators[i] = h5_iterative_creator(final_names[-1],
overwrite_if_file_exists=True,
close_and_open_on_each_iteration=True,
color_channel=color_channel)
ims = []
labels = []
for ii in tqdm(sorted(random_frame_inds[i]), disable=disable_TQDM, total=total_frames, initial=cnt1):
cnt1 += 1
ims.append(h['images'][ii])
labels.append(h['labels'][ii])
if ii > 0 and ii % chunk_size == 0:
h5_creators[i].add_to_h5(np.asarray(ims), np.asarray(labels))
ims = []
labels = []
h5_creators[i].add_to_h5(np.asarray(ims), np.asarray(labels))
with h5py.File(h5_creators[i].h5_full_file_name,
'r+') as h2: # wanted to do this to allow NONE as input and still have frame nums, but I need to have an append after creating and its a pain
frame_nums = np.asarray(list_of_new_frame_nums[i])
if 'frame_nums' not in h2.keys():
h2.create_dataset('frame_nums', shape=np.shape(frame_nums), maxshape=(None,), chunks=True,
data=frame_nums)
else:
h2['frame_nums'].resize(h2['frame_nums'].shape[0] + frame_nums.shape[0], axis=0)
h2['frame_nums'][-frame_nums.shape[0]:] = frame_nums
# # add the frame info to each
# for i, frame_nums in enumerate(list_of_new_frame_nums):
# with h5py.File(h5_creators[i].h5_full_file_name, 'r+') as h:
# h.create_dataset('frame_nums', shape=np.shape(frame_nums), data=frame_nums)
return final_names
def make_sure_frame_nums_exist(h5file):
with h5py.File(h5file, 'r+') as h:
key_list = list(h.keys())
if 'frame_nums' in key_list:
print("""'frame_nums' already in the key list""")
return None
if 'trial_nums_and_frame_nums' not in key_list:
print(
"""key 'trial_nums_and_frame_nums' must be in the provided h5 this is the only reason program exists""")
return None
frame_nums = h['trial_nums_and_frame_nums'][1, :]
h.create_dataset('frame_nums', shape=np.shape(frame_nums), data=frame_nums)
def split_h5(h5_to_split_list, split_percentages, temp_base_name, chunk_size=10000, add_numbers_to_name=True,
disable_TQDM=False, skip_if_label_is_neg_1=False, set_seed=None, color_channel=True):
"""Randomly splits images from a list of H5 file(s) into len(split_percentages) different H5 files.
Parameters
----------
h5_to_split_list : list
list of strings with full file names to the H5 file(s) to be split
split_percentages : list
list of numbers, can be ints [20, 1, 1] and or floats [.8, .2], it simply takes the sum and creates a percentage
temp_base_name : str or list
full path to new h5 file e.g "'/Users/phil/tempH5_" and the program will add the number and the ".h5"
in this case tempH5_0.h5, tempH5_1.h5, tempH5_2.h5 etc. or if it is a list it must be equal in | |
from typing import Dict, List, Optional, Tuple
from datetime import datetime, timedelta
from cachetools import TTLCache
from pandas import DataFrame, Series
import numpy as np
## Indicator libs
import talib.abstract as ta
from finta import TA as fta
import technical.indicators as ftt
from technical.indicators import hull_moving_average
from technical.indicators import PMAX, zema
from technical.indicators import cmf
## FT stuffs
from freqtrade.strategy import IStrategy, merge_informative_pair, stoploss_from_open, IntParameter, DecimalParameter, CategoricalParameter
import freqtrade.vendor.qtpylib.indicators as qtpylib
from freqtrade.exchange import timeframe_to_minutes
from freqtrade.persistence import Trade
from skopt.space import Dimension
### @Rallipanos mod
"""
NOTE:
docker-compose run --rm freqtrade hyperopt -c user_data/config-backtesting.json --strategy IchimokuHaulingV8a --hyperopt-loss SortinoHyperOptLossDaily --spaces roi buy sell --timerange=1624940400-1630447200 -j 4 -e 1000
"""
class MacheteV8bRallimod2(IStrategy):
# Buy hyperspace params:
buy_params = {
"buy_should_use_get_buy_signal_offset_strategy": True,
"buy_should_use_get_buy_signal_bbrsi_strategy": False,
"ewo_high": 2.327,
"rsi_buy": 45,
"base_nb_candles_buy": 14,
"low_offset": 0.965
}
# Sell hyperspace params:
sell_params = {
"cstp_bail_how": "roc",
"cstp_bail_roc": -0.032,
"cstp_bail_time": 1108,
"cstp_bb_trailing_input": "bb_lowerband_neutral_inf",
"cstp_threshold": -0.036,
"cstp_trailing_max_stoploss": 0.054,
"cstp_trailing_only_offset_is_reached": 0.09,
"cstp_trailing_stop_profit_devider": 2,
"droi_pullback": True,
"droi_pullback_amount": 0.01,
"droi_pullback_respect_table": False,
"droi_trend_type": "any",
"base_nb_candles_sell": 24,
"high_offset": 0.991,
"high_offset_2": 0.995
}
# ROI table:
minimal_roi = {
"0": 0.279,
"92": 0.109,
"245": 0.059,
"561": 0.02
}
# Stoploss:
stoploss = -0.05#-0.046
# Trailing stop:
trailing_stop = False
#trailing_stop_positive = 0.0247
#trailing_stop_positive_offset = 0.0248
#trailing_only_offset_is_reached = True
use_custom_stoploss = False
# buy signal
buy_should_use_get_buy_signal_offset_strategy = CategoricalParameter([True, False], default=buy_params['buy_should_use_get_buy_signal_offset_strategy'], space='buy', optimize=True)
buy_should_use_get_buy_signal_bbrsi_strategy = CategoricalParameter([True, False], default=buy_params['buy_should_use_get_buy_signal_bbrsi_strategy'], space='buy', optimize=True)
# Dynamic ROI
droi_trend_type = CategoricalParameter(['rmi', 'ssl', 'candle', 'any'], default=sell_params['droi_trend_type'], space='sell', optimize=True)
droi_pullback = CategoricalParameter([True, False], default=sell_params['droi_pullback'], space='sell', optimize=True)
droi_pullback_amount = DecimalParameter(0.005, 0.02, default=sell_params['droi_pullback_amount'], space='sell')
droi_pullback_respect_table = CategoricalParameter([True, False], default=sell_params['droi_pullback_respect_table'], space='sell', optimize=True)
# Custom Stoploss
cstp_threshold = DecimalParameter(-0.05, 0, default=sell_params['cstp_threshold'], space='sell')
cstp_bail_how = CategoricalParameter(['roc', 'time', 'any'], default=sell_params['cstp_bail_how'], space='sell', optimize=True)
cstp_bail_roc = DecimalParameter(-0.05, -0.01, default=sell_params['cstp_bail_roc'], space='sell')
cstp_bail_time = IntParameter(720, 1440, default=sell_params['cstp_bail_time'], space='sell')
cstp_trailing_only_offset_is_reached = DecimalParameter(0.01, 0.06, default=sell_params['cstp_trailing_only_offset_is_reached'], space='sell')
cstp_trailing_stop_profit_devider = IntParameter(2, 4, default=sell_params['cstp_trailing_stop_profit_devider'], space='sell')
cstp_trailing_max_stoploss = DecimalParameter(0.02, 0.08, default=sell_params['cstp_trailing_max_stoploss'], space='sell')
cstp_bb_trailing_input = CategoricalParameter(['bb_lowerband_trend', 'bb_lowerband_trend_inf', 'bb_lowerband_neutral', 'bb_lowerband_neutral_inf', 'bb_upperband_neutral_inf'], default=sell_params['cstp_bb_trailing_input'], space='sell', optimize=True)
fast_ewo = 50
slow_ewo = 200
ewo_high = DecimalParameter(2.0, 12.0, default=buy_params['ewo_high'], space='buy', optimize=True)
rsi_buy = IntParameter(30, 70, default=buy_params['rsi_buy'], space='buy', optimize=True)
base_nb_candles_buy = IntParameter(5, 80, default=buy_params['base_nb_candles_buy'], space='buy', optimize=True)
base_nb_candles_sell = IntParameter(5, 80, default=sell_params['base_nb_candles_sell'], space='sell', optimize=True)
high_offset = DecimalParameter(0.95, 1.1, default=sell_params['high_offset'], space='sell', optimize=True)
high_offset_2 = DecimalParameter(0.99, 1.5, default=sell_params['high_offset_2'], space='sell', optimize=True)
# nested hyperopt class
class HyperOpt:
# defining as dummy, so that no error is thrown about missing
# sell indicator space when hyperopting for all spaces
@staticmethod
def indicator_space() -> List[Dimension]:
return []
custom_trade_info = {}
custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes
# run "populate_indicators" only for new candle
process_only_new_candles = False
# Experimental settings (configuration will overide these if set)
use_sell_signal = True
sell_profit_only = False
ignore_roi_if_buy_signal = False
startup_candle_count = 200#149
use_dynamic_roi = True
timeframe = '5m'
informative_timeframe = '1h'
# Optional order type mapping
order_types = {
'buy': 'limit',
'sell': 'limit',
'stoploss': 'market',
'stoploss_on_exchange': False
}
def informative_pairs(self):
pairs = self.dp.current_whitelist()
informative_pairs = [(pair, self.informative_timeframe) for pair in pairs]
return informative_pairs
#
# Processing indicators
#
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair'])
if not self.dp:
return dataframe
dataframe = self.get_buy_signal_indicators(dataframe, metadata)
informative_tmp = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.informative_timeframe)
informative = self.get_market_condition_indicators(informative_tmp.copy(), metadata)
informative = self.get_custom_stoploss_indicators(informative, metadata)
dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.informative_timeframe, ffill=True)
dataframe.rename(columns=lambda s: s.replace("_{}".format(self.informative_timeframe), "_inf"), inplace=True)
# Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest
if self.dp.runmode.value in ('backtest', 'hyperopt'):
self.custom_trade_info[metadata['pair']]['roc_inf'] = dataframe[['date', 'roc_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['atr_inf'] = dataframe[['date', 'atr_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['sroc_inf'] = dataframe[['date', 'sroc_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['ssl-dir_inf'] = dataframe[['date', 'ssl-dir_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['rmi-up-trend_inf'] = dataframe[['date', 'rmi-up-trend_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['candle-up-trend_inf'] = dataframe[['date', 'candle-up-trend_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['bb_lowerband_trend_inf'] = dataframe[['date', 'bb_lowerband_trend_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['bb_lowerband_trend_inf'] = dataframe[['date', 'bb_lowerband_trend_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['bb_lowerband_neutral_inf'] = dataframe[['date', 'bb_lowerband_neutral_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['bb_lowerband_neutral_inf'] = dataframe[['date', 'bb_lowerband_neutral_inf']].copy().set_index('date')
self.custom_trade_info[metadata['pair']]['bb_upperband_neutral_inf'] = dataframe[['date', 'bb_upperband_neutral_inf']].copy().set_index('date')
return dataframe
def get_buy_signal_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe['sma_9'] = ta.SMA(dataframe, timeperiod=9)
dataframe['EWO'] = EWO(dataframe, self.fast_ewo, self.slow_ewo)
for val in self.base_nb_candles_buy.range:
dataframe[f'ma_buy_{val}'] = ta.EMA(dataframe, timeperiod=val)
for val in self.base_nb_candles_sell.range:
dataframe[f'ma_sell_{val}'] = ta.EMA(dataframe, timeperiod=val)
dataframe['rsi_fast'] = ta.RSI(dataframe, timeperiod=4)
dataframe['rsi_slow'] = ta.RSI(dataframe, timeperiod=20)
dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
dataframe['bb_lowerband'] = bollinger['lower']
dataframe['hma_5'] = hull_moving_average(dataframe, 5, 'close')
dataframe['ema_25'] = ta.EMA(dataframe, timeperiod=25)
dataframe['ema_60'] = ta.EMA(dataframe, timeperiod=60)
dataframe['uptrend_5m'] = dataframe['ema_25'] > dataframe['ema_60']
return dataframe
def get_market_condition_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
displacement = 30
ichimoku = ftt.ichimoku(dataframe, conversion_line_period=20, base_line_periods=60, laggin_span=120, displacement=displacement)
dataframe['chikou_span'] = ichimoku['chikou_span']
dataframe['tenkan_sen'] = ichimoku['tenkan_sen']
dataframe['kijun_sen'] = ichimoku['kijun_sen']
dataframe['senkou_a'] = ichimoku['senkou_span_a']
dataframe['senkou_b'] = ichimoku['senkou_span_b']
dataframe['leading_senkou_span_a'] = ichimoku['leading_senkou_span_a']
dataframe['leading_senkou_span_b'] = ichimoku['leading_senkou_span_b']
dataframe['cloud_green'] = ichimoku['cloud_green'] * 1
dataframe['cloud_red'] = ichimoku['cloud_red'] * -1
ssl = SSLChannels_ATR(dataframe, 10)
dataframe['sslDown'] = ssl[0]
dataframe['sslUp'] = ssl[1]
#dataframe['vfi'] = fta.VFI(dataframe, period=14)
# Summary indicators
dataframe['future_green'] = ichimoku['cloud_green'].shift(displacement).fillna(0).astype('int') * 2
dataframe['chikou_high'] = ((dataframe['chikou_span'] > dataframe['senkou_a']) & (dataframe['chikou_span'] > dataframe['senkou_b'])).shift(displacement).fillna(0).astype('int')
dataframe['go_long'] = ((dataframe['tenkan_sen'] > dataframe['kijun_sen']) & (dataframe['close'] > dataframe['leading_senkou_span_a']) & (dataframe['close'] > dataframe['leading_senkou_span_b']) & (dataframe['future_green'] > 0) & (dataframe['chikou_high'] > 0)).fillna(0).astype('int') * 3
dataframe['max'] = dataframe['high'].rolling(3).max()
dataframe['min'] = dataframe['low'].rolling(6).min()
dataframe['upper'] = np.where(dataframe['max'] > dataframe['max'].shift(),1,0)
dataframe['lower'] = np.where(dataframe['min'] < dataframe['min'].shift(),1,0)
dataframe['up_trend'] = np.where(dataframe['upper'].rolling(5, min_periods=1).sum() != 0,1,0)
dataframe['dn_trend'] = np.where(dataframe['lower'].rolling(5, min_periods=1).sum() != 0,1,0)
return dataframe
def get_custom_stoploss_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
bollinger_neutral = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=1)
dataframe['bb_lowerband_neutral'] = bollinger_neutral['lower']
dataframe['bb_middleband_neutral'] = bollinger_neutral['mid']
dataframe['bb_upperband_neutral'] = bollinger_neutral['upper']
bollinger_trend = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
dataframe['bb_lowerband_trend'] = bollinger_trend['lower']
dataframe['bb_middleband_trend'] = bollinger_trend['mid']
dataframe['bb_upperband_trend'] = bollinger_trend['upper']
dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
dataframe['roc'] = ta.ROC(dataframe, timeperiod=9)
dataframe['rmi'] = RMI(dataframe, length=24, mom=5)
ssldown, sslup = SSLChannels_ATR(dataframe, length=21)
dataframe['sroc'] = SROC(dataframe, roclen=21, emalen=13, smooth=21)
dataframe['ssl-dir'] = np.where(sslup > ssldown,'up','down')
dataframe['rmi-up'] = np.where(dataframe['rmi'] >= dataframe['rmi'].shift(),1,0)
dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(5).sum() >= 3,1,0)
dataframe['candle-up'] = np.where(dataframe['close'] >= dataframe['close'].shift(),1,0)
dataframe['candle-up-trend'] = np.where(dataframe['candle-up'].rolling(5).sum() >= 3,1,0)
return dataframe
#
# Processing buy signals
#
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(
(self.get_buy_signal_offset_strategy(dataframe) == True)
|
(self.get_buy_signal_bbrsi_strategy(dataframe) == True)
)
#(dataframe['sslUp_inf'] > dataframe['sslDown_inf'])
,'buy'] = 1
return dataframe
def get_buy_signal_offset_strategy(self, dataframe: DataFrame):
signal = (
(self.buy_should_use_get_buy_signal_offset_strategy.value == True) &
(dataframe['sma_9'] < dataframe[f'ma_buy_{self.base_nb_candles_buy.value}'])&
(dataframe['rsi_fast']< dataframe['rsi_slow'])&
(dataframe['rsi_fast'] <35)&
(dataframe['rsi_fast'] >4)&
(dataframe['EWO'] > self.ewo_high.value) &
(dataframe['close'] < ta.EMA(dataframe['close'], timeperiod = 14) * 0.970) &
(dataframe['rsi'] < self.rsi_buy.value) &
(dataframe['volume'] > 0)
)
return signal
def get_buy_signal_bbrsi_strategy(self, dataframe: DataFrame):
signal = (
(self.buy_should_use_get_buy_signal_bbrsi_strategy.value == True) &
(dataframe['sslUp_inf'] > dataframe['sslDown_inf'])&
(dataframe['uptrend_5m'] == 0)&
(dataframe['rsi'] < 40) &
(dataframe['rsi_fast']< dataframe['rsi_slow'])&
(dataframe['close'].shift(1) < dataframe['bb_lowerband']*1)&
(dataframe['EWO'] > self.ewo_high.value) &
(dataframe['volume'] > 0)
)
return signal
#
# Processing sell signals
#
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
dataframe.loc[
(qtpylib.crossed_above(dataframe['sslDown_inf'], dataframe['sslUp_inf']))
& (
(qtpylib.crossed_below(dataframe['tenkan_sen_inf'], dataframe['kijun_sen_inf']))
|(qtpylib.crossed_below(dataframe['close_inf'], dataframe['kijun_sen_inf']))|
(
(dataframe['close']>dataframe['sma_9'])&
(dataframe['close'] > (dataframe[f'ma_sell_{self.base_nb_candles_sell.value}'] * self.high_offset_2.value)) &
#(dataframe['rsi']>150)&
(dataframe['volume'] > 0)&
(dataframe['rsi_fast']>dataframe['rsi_slow'])
)
) #&
# NOTE: I keep the volume checks of feels like it has not much benifit when trading leverage tokens, maybe im wrong!?
#(dataframe['vfi'] < 0.0) &
#(dataframe['volume'] > 0)
,'sell'] = 1
return dataframe
#
# Custom Stoploss
#
def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float:
trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60)
if self.config['runmode'].value in ('live', 'dry_run'):
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
sroc = dataframe['sroc_inf'].iat[-1]
bb_trailing = dataframe[self.cstp_bb_trailing_input.value].iat[-1]
# If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!)
else:
sroc = self.custom_trade_info[trade.pair]['sroc_inf'].loc[current_time]['sroc_inf']
bb_trailing = self.custom_trade_info[trade.pair][self.cstp_bb_trailing_input.value].loc[current_time][self.cstp_bb_trailing_input.value]
if current_profit < self.cstp_threshold.value:
if self.cstp_bail_how.value == 'roc' or self.cstp_bail_how.value == 'any':
# Dynamic bailout based on rate of change
if (sroc/100) <= self.cstp_bail_roc.value:
return 0.001
if self.cstp_bail_how.value == 'time' or self.cstp_bail_how.value == 'any':
# Dynamic bailout based on time
if trade_dur > self.cstp_bail_time.value:
return 0.001
if current_profit < self.cstp_trailing_only_offset_is_reached.value:
if current_rate <= bb_trailing:
return 0.001
else:
return -1
desired_stoploss = current_profit / self.cstp_trailing_stop_profit_devider.value
return max(min(desired_stoploss, self.cstp_trailing_max_stoploss.value), 0.025)
#
# Dynamic ROI
#
def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]:
minimal_roi = self.minimal_roi
_, table_roi = self.min_roi_reached_entry(trade_dur)
# see if we have the data we need to do this, otherwise fall back to the standard table
if self.custom_trade_info and trade and trade.pair in self.custom_trade_info:
if self.config['runmode'].value in ('live', 'dry_run'):
dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe)
rmi_trend = dataframe['rmi-up-trend_inf'].iat[-1]
candle_trend = dataframe['candle-up-trend_inf'].iat[-1]
ssl_dir = dataframe['ssl-dir_inf'].iat[-1]
# If in backtest or hyperopt, get the indicator | |
visible at higher resolutions; when zoomed-out the available area will be displayed
as a shaded region. The surface reflectance geometric median (geomedian) is a pixel composite
mosaic of a time series of earth observations. The value of a pixel in a an annual geomedian
image is the statistical median of all observations for that pixel from a calendar year.
Annual mosaics are available for the following years:
Landsat 5: 1988 to 1999, 2004 to 2007, 2009 to 2011;
For more information, see http://pid.geoscience.gov.au/dataset/ga/120374
For service status information, see https://status.dea.ga.gov.au""",
# The WMS name for the layer
"name": "ls5_nbart_geomedian_annual",
# The Datacube name for the associated data product
"product_name": "ls5_nbart_geomedian_annual",
# The Datacube name for the associated pixel-quality product (optional)
# The name of the associated Datacube pixel-quality product
# "pq_dataset": "ls8_level1_usgs",
# The name of the measurement band for the pixel-quality product
# (Only required if pq_dataset is set)
# "pq_manual_data_merge": True,
# "data_manual_merge": True,
# "pq_band": "quality",
# "always_fetch_bands": [ "quality" ],
# Min zoom factor - sets the zoom level where the cutover from indicative polygons
# to actual imagery occurs.
"min_zoom_factor": 35.0,
# The fill-colour of the indicative polygons when zoomed out.
# Triplets (rgb) or quadruplets (rgba) of integers 0-255.
"zoomed_out_fill_colour": [150, 180, 200, 160],
# Time Zone. In hours added to UTC (maybe negative)
# Used for rounding off scene times to a date.
# 9 is good value for imagery of Australia.
"time_zone": 9,
# Extent mask function
# Determines what portions of dataset is potentially meaningful data.
"extent_mask_func": lambda data, band: data[band] != data[band].attrs['nodata'],
# Flags listed here are ignored in GetFeatureInfo requests.
# (defaults to empty list)
"ignore_info_flags": [],
"data_manual_merge": True,
"always_fetch_bands": [],
"apply_solar_corrections": False,
# Define layer wide legend graphic if no style is passed
# to GetLegendGraphic
"legend": {
# "url": ""
"styles": ["ndvi", "ndwi"]
},
"wcs_default_bands": ["red", "green", "blue"],
# A function that extracts the "sub-product" id (e.g. path number) from a dataset. Function should return a (small) integer
# If None or not specified, the product has no sub-layers.
# "sub_product_extractor": lambda ds: int(s3_path_pattern.search(ds.uris[0]).group("path")),
# A prefix used to describe the sub-layer in the GetCapabilities response.
# E.g. sub-layer 109 will be described as "Landsat Path 109"
# "sub_product_label": "Landsat Path",
# Bands to include in time-dimension "pixel drill".
# Don't activate in production unless you really know what you're doing.
# "band_drill": ["nir", "red", "green", "blue"],
# Styles.
#
# See band_mapper.py
#
# The various available spectral bands, and ways to combine them
# into a single rgb image.
# The examples here are ad hoc
#
"styles": [
# Examples of styles which are linear combinations of the available spectral bands.
#
{
"name": "simple_rgb",
"title": "Simple RGB",
"abstract": "Simple true-colour image, using the red, green and blue bands",
"components": {
"red": {
"red": 1.0
},
"green": {
"green": 1.0
},
"blue": {
"blue": 1.0
}
},
# The raw band value range to be compressed to an 8 bit range for the output image tiles.
# Band values outside this range are clipped to 0 or 255 as appropriate.
"scale_range": [0.0, 3000.0]
},
{
"name": "infrared_green",
"title": "False colour - Green, SWIR, NIR",
"abstract": "False Colour image with SWIR1->Red, NIR->Green, and Green->Blue",
"components": {
"red": {
"swir1": 1.0
},
"green": {
"nir": 1.0
},
"blue": {
"green": 1.0
}
},
"scale_range": [0.0, 3000.0]
},
#
# Examples of non-linear heat-mapped styles.
{
"name": "ndvi",
"title": "NDVI - Red, NIR",
"abstract": "Normalised Difference Vegetation Index - a derived index that correlates well with the existence of vegetation",
"index_function": lambda data: (data["nir"] - data["red"]) / (data["nir"] + data["red"]),
"needed_bands": ["red", "nir"],
"color_ramp": [
{
"value": -0.0,
"color": "#8F3F20",
"alpha": 0.0
},
{
"value": 0.0,
"color": "#8F3F20",
"alpha": 1.0
},
{
"value": 0.1,
"color": "#A35F18"
},
{
"value": 0.2,
"color": "#B88512"
},
{
"value": 0.3,
"color": "#CEAC0E"
},
{
"value": 0.4,
"color": "#E5D609"
},
{
"value": 0.5,
"color": "#FFFF0C"
},
{
"value": 0.6,
"color": "#C3DE09"
},
{
"value": 0.7,
"color": "#88B808"
},
{
"value": 0.8,
"color": "#529400"
},
{
"value": 0.9,
"color": "#237100"
},
{
"value": 1.0,
"color": "#114D04"
}
]
},
{
"name": "ndwi",
"title": "NDWI - Green, SWIR",
"abstract": "Normalised Difference Water Index - a derived index that correlates well with the existence of water",
"index_function": lambda data: (data["green"] - data["swir1"]) / (data["swir1"] + data["green"]),
"needed_bands": ["green", "swir1"],
"color_ramp": [
{
"value": -0.0,
"color": "#8F3F20",
"alpha": 0.0
},
{
"value": 0.0,
"color": "#8F3F20",
"alpha": 1.0
},
{
"value": 1.0,
"color": "#0303FF",
},
]
},
{
"name": "blue",
"title": "Blue - 490",
"abstract": "Blue band, centered on 490nm",
"components": {
"red": {
"blue": 1.0
},
"green": {
"blue": 1.0
},
"blue": {
"blue": 1.0
}
},
"scale_range": [0.0, 3000.0]
},
{
"name": "green",
"title": "Green - 560",
"abstract": "Green band, centered on 560nm",
"components": {
"red": {
"green": 1.0
},
"green": {
"green": 1.0
},
"blue": {
"green": 1.0
}
},
"scale_range": [0.0, 3000.0]
},
{
"name": "red",
"title": "Red - 660",
"abstract": "Red band, centered on 660nm",
"components": {
"red": {
"red": 1.0
},
"green": {
"red": 1.0
},
"blue": {
"red": 1.0
}
},
"scale_range": [0.0, 3000.0]
},
{
"name": "nir",
"title": "Near Infrared (NIR) - 840",
"abstract": "Near infra-red band, centered on 840nm",
"components": {
"red": {
"nir": 1.0
},
"green": {
"nir": 1.0
},
"blue": {
"nir": 1.0
}
},
"scale_range": [0.0, 3000.0]
},
{
"name": "swir1",
"title": "Shortwave Infrared (SWIR) - 1650",
"abstract": "Short wave infra-red band 1, centered on 1650nm",
"components": {
"red": {
"swir1": 1.0
},
"green": {
"swir1": 1.0
},
"blue": {
"swir1": 1.0
}
},
"scale_range": [0.0, 3000.0]
},
{
"name": "swir2",
"title": "Shortwave Infrared (SWIR) - 2220",
"abstract": "Short wave infra-red band 2, centered on 2220nm",
"components": {
"red": {
"swir2": 1.0
},
"green": {
"swir2": 1.0
},
"blue": {
"swir2": 1.0
}
},
"scale_range": [0.0, 3000.0]
}
],
# Default style (if request does not specify style)
# MUST be defined in the styles list above.
# (Looks like Terria assumes this is the first style in the list, but this is
# not required by the standard.)
"default_style": "simple_rgb",
}
]
},
{
# Name and title of the platform layer.
# Platform layers are not mappable. The name is for internal server use only.
"name": "landsat8_barest_earth",
"title": "Barest Earth",
"abstract": """
A `weighted geometric median’ approach has been used to estimate the median surface reflectance of the barest state (i.e., least vegetation) observed through Landsat-8 OLI observations from 2013 to September 2018 to generate a six-band Landsat-8 Barest Earth pixel composite mosaic over the Australian continent.
The bands include BLUE (0.452 - 0.512), GREEN (0.533 - 0.590), RED, (0.636 - 0.673) NIR (0.851 - 0.879), SWIR1 (1.566 - 1.651) and SWIR2 (2.107 - 2.294) wavelength regions. The weighted median approach is robust to outliers (such as cloud, shadows, saturation, corrupted pixels) and also maintains the relationship between all the spectral wavelengths in the spectra observed through time. The product reduces the influence of vegetation and allows for more direct mapping of soil and rock mineralogy.
Reference: <NAME>, <NAME>, and <NAME> (2018). Revealing the Australian Continent at its Barest, submitted.
Mosaics are available for the following years:
Landsat 8: 2013 to 2017;
""",
# Link removed until eCat record is "published_external", not "published_internal"
# For more information, see the dataset record: http://pid.geoscience.gov.au/dataset/ga/122573
# Products available for this platform.
# For each product, the "name" is the Datacube name, and the label is used
# to describe the label to end-users.
"products": [
{
# Included as a keyword for the layer
"label": "Landsat 8",
# Included as a keyword for the layer
"type": "Barest Earth",
# Included as a keyword for the layer
"variant": "25m",
"abstract": """
A `weighted geometric median’ approach has been used | |
(module 'network'): ns3::Socket::SocketType [enumeration]
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::SocketAddressTag [class]
module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTosTag [class]
module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class]
module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class]
module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## spectrum-phy.h (module 'spectrum'): ns3::SpectrumPhy [class]
module.add_class('SpectrumPhy', import_from_module='ns.spectrum', parent=root_module['ns3::Object'])
## spectrum-signal-parameters.h (module 'spectrum'): ns3::SpectrumSignalParameters [struct]
module.add_class('SpectrumSignalParameters', import_from_module='ns.spectrum', parent=root_module['ns3::SimpleRefCount< ns3::SpectrumSignalParameters, ns3::empty, ns3::DefaultDeleter<ns3::SpectrumSignalParameters> >'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## application.h (module 'network'): ns3::Application [class]
module.add_class('Application', import_from_module='ns.network', parent=root_module['ns3::Object'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## data-rate.h (module 'network'): ns3::DataRateChecker [class]
module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## data-rate.h (module 'network'): ns3::DataRateValue [class]
module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## lorawan-enddevice-application.h (module 'lorawan'): ns3::LoRaWANEndDeviceApplication [class]
module.add_class('LoRaWANEndDeviceApplication', parent=root_module['ns3::Application'])
## lorawan-error-model.h (module 'lorawan'): ns3::LoRaWANErrorModel [class]
module.add_class('LoRaWANErrorModel', parent=root_module['ns3::Object'])
## lorawan-gateway-application.h (module 'lorawan'): ns3::LoRaWANGatewayApplication [class]
module.add_class('LoRaWANGatewayApplication', parent=root_module['ns3::Application'])
## lorawan-interference-helper.h (module 'lorawan'): ns3::LoRaWANInterferenceHelper [class]
module.add_class('LoRaWANInterferenceHelper', parent=root_module['ns3::SimpleRefCount< ns3::LoRaWANInterferenceHelper, ns3::empty, ns3::DefaultDeleter<ns3::LoRaWANInterferenceHelper> >'])
## lorawan-mac.h (module 'lorawan'): ns3::LoRaWANMac [class]
module.add_class('LoRaWANMac', parent=root_module['ns3::Object'])
## lorawan-mac.h (module 'lorawan'): ns3::LoRaWANMac::LoRaWANMacRDC [class]
module.add_class('LoRaWANMacRDC', parent=root_module['ns3::Object'], outer_class=root_module['ns3::LoRaWANMac'])
## lorawan-gateway-application.h (module 'lorawan'): ns3::LoRaWANNetworkServer [class]
module.add_class('LoRaWANNetworkServer', parent=root_module['ns3::Object'])
## lorawan-phy.h (module 'lorawan'): ns3::LoRaWANPhy [class]
module.add_class('LoRaWANPhy', parent=root_module['ns3::SpectrumPhy'])
## lorawan-spectrum-signal-parameters.h (module 'lorawan'): ns3::LoRaWANSpectrumSignalParameters [struct]
module.add_class('LoRaWANSpectrumSignalParameters', parent=root_module['ns3::SpectrumSignalParameters'])
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class]
module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## lorawan-net-device.h (module 'lorawan'): ns3::LoRaWANNetDevice [class]
module.add_class('LoRaWANNetDevice', parent=root_module['ns3::NetDevice'])
module.add_container('std::vector< ns3::LoRaWANChannel >', 'ns3::LoRaWANChannel', container_type=u'vector')
module.add_container('std::vector< ns3::LoRaWANDataRate >', 'ns3::LoRaWANDataRate', container_type=u'vector')
module.add_container('std::vector< ns3::Ptr< ns3::LoRaWANGatewayApplication > >', 'ns3::Ptr< ns3::LoRaWANGatewayApplication >', container_type=u'vector')
module.add_container('std::deque< ns3::LoRaWANNSDSQueueElement * >', 'ns3::LoRaWANNSDSQueueElement *', container_type=u'dequeue')
module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map')
module.add_container('std::vector< ns3::LoRaWANSubBand >', 'ns3::LoRaWANSubBand', container_type=u'vector')
module.add_container('std::vector< ns3::EventId >', 'ns3::EventId', container_type=u'vector')
module.add_container('std::vector< ns3::Ptr< ns3::LoRaWANMac > >', 'ns3::Ptr< ns3::LoRaWANMac >', container_type=u'vector')
module.add_container('std::vector< ns3::Ptr< ns3::LoRaWANPhy > >', 'ns3::Ptr< ns3::LoRaWANPhy >', container_type=u'vector')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANPhyEnumeration, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::SetTRXStateConfirmCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANPhyEnumeration, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::SetTRXStateConfirmCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANPhyEnumeration, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::SetTRXStateConfirmCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, unsigned int, ns3::Ptr< ns3::Packet >, unsigned char, unsigned char, unsigned char, unsigned char, ns3::empty, ns3::empty, ns3::empty >', u'ns3::PdDataIndicationCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, unsigned int, ns3::Ptr< ns3::Packet >, unsigned char, unsigned char, unsigned char, unsigned char, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::PdDataIndicationCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, unsigned int, ns3::Ptr< ns3::Packet >, unsigned char, unsigned char, unsigned char, unsigned char, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::PdDataIndicationCallback&')
typehandlers.add_type_alias(u'ns3::LoRaWANPhyRxStatus', u'ns3::LoRaWANPhyRxStatus')
typehandlers.add_type_alias(u'ns3::LoRaWANPhyRxStatus*', u'ns3::LoRaWANPhyRxStatus*')
typehandlers.add_type_alias(u'ns3::LoRaWANPhyRxStatus&', u'ns3::LoRaWANPhyRxStatus&')
module.add_typedef(root_module['ns3::LoRaWANPhyRxStatus'], 'LoRaWANPhyRxStatus')
typehandlers.add_type_alias(u'ns3::LoRaWANSubBand', u'ns3::LoRaWANSubBand')
typehandlers.add_type_alias(u'ns3::LoRaWANSubBand*', u'ns3::LoRaWANSubBand*')
typehandlers.add_type_alias(u'ns3::LoRaWANSubBand&', u'ns3::LoRaWANSubBand&')
module.add_typedef(root_module['ns3::LoRaWANSubBand'], 'LoRaWANSubBand')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANDataConfirmParams, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::DataConfirmCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANDataConfirmParams, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::DataConfirmCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANDataConfirmParams, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::DataConfirmCallback&')
typehandlers.add_type_alias(u'ns3::FlowIdTag', u'ns3::LoRaWANPhyTraceIdTag')
typehandlers.add_type_alias(u'ns3::FlowIdTag*', u'ns3::LoRaWANPhyTraceIdTag*')
typehandlers.add_type_alias(u'ns3::FlowIdTag&', u'ns3::LoRaWANPhyTraceIdTag&')
module.add_typedef(root_module['ns3::FlowIdTag'], 'LoRaWANPhyTraceIdTag')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogNodePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogNodePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogNodePrinter&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANPhyEnumeration, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::PdDataConfirmCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANPhyEnumeration, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::PdDataConfirmCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANPhyEnumeration, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::PdDataConfirmCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::LoRaWANMac >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::BeginTxCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::LoRaWANMac >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::BeginTxCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::LoRaWANMac >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::BeginTxCallback&')
typehandlers.add_type_alias(u'ns3::LoRaWANNSDSQueueElement', u'ns3::LoRaWANNSDSQueueElement')
typehandlers.add_type_alias(u'ns3::LoRaWANNSDSQueueElement*', u'ns3::LoRaWANNSDSQueueElement*')
typehandlers.add_type_alias(u'ns3::LoRaWANNSDSQueueElement&', u'ns3::LoRaWANNSDSQueueElement&')
module.add_typedef(root_module['ns3::LoRaWANNSDSQueueElement'], 'LoRaWANNSDSQueueElement')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::LoRaWANMac >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::EndTxCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::LoRaWANMac >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::EndTxCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::LoRaWANMac >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::EndTxCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::PdDataDestroyedCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::PdDataDestroyedCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::PdDataDestroyedCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANDataIndicationParams, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::DataIndicationCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANDataIndicationParams, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::DataIndicationCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::LoRaWANDataIndicationParams, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::DataIndicationCallback&')
typehandlers.add_type_alias(u'ns3::LoRaWANEndDeviceInfoNS', u'ns3::LoRaWANEndDeviceInfoNS')
typehandlers.add_type_alias(u'ns3::LoRaWANEndDeviceInfoNS*', u'ns3::LoRaWANEndDeviceInfoNS*')
typehandlers.add_type_alias(u'ns3::LoRaWANEndDeviceInfoNS&', u'ns3::LoRaWANEndDeviceInfoNS&')
module.add_typedef(root_module['ns3::LoRaWANEndDeviceInfoNS'], 'LoRaWANEndDeviceInfoNS')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogTimePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogTimePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogTimePrinter&')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace Hash
nested_module = | |
= np.dot(L, LAMBDA_LTXTAcorrY)
sigma2 = np.mean(YTAcorrY -
np.sum(LTXTAcorrY * LAMBDA_LTXTAcorrY, axis=0))\
/ (n_T - n_X0)
LL = n_V * (-np.log(sigma2) * (n_T - n_X0) * 0.5
+ np.log(1 - rho1**2) * n_run * 0.5
- self._half_log_det(X0TAX0)
- self._half_log_det(LAMBDA_i))
deriv_L = np.dot(XTAcorrY, LAMBDA_LTXTAcorrY.T) / sigma2 \
- np.dot(np.dot(XTAcorrXL, LAMBDA_LTXTAcorrY),
LAMBDA_LTXTAcorrY.T) / sigma2 \
- np.linalg.solve(LAMBDA_i, XTAcorrXL.T).T * n_V
# These terms are used to construct derivative to a1.
dXTAX_drho1 = - XTDX + 2 * rho1 * XTFX
dX0TAX0_drho1 = - X0TDX0 + 2 * rho1 * X0TFX0
dXTAX0_drho1 = - XTDX0 + 2 * rho1 * XTFX0
invX0TAX0_X0TAX = np.linalg.solve(X0TAX0, XTAX0.T)
dXTAX0_drho1_invX0TAX0_X0TAX = np.dot(dXTAX0_drho1, invX0TAX0_X0TAX)
dXTAcorrX_drho1 = dXTAX_drho1 - dXTAX0_drho1_invX0TAX0_X0TAX \
- dXTAX0_drho1_invX0TAX0_X0TAX.T \
+ np.dot(np.dot(invX0TAX0_X0TAX.T, dX0TAX0_drho1),
invX0TAX0_X0TAX)
dLTXTAcorrXL_drho1 = np.dot(np.dot(L.T, dXTAcorrX_drho1), L)
dYTAY_drho1 = - YTDY_diag + 2 * rho1 * YTFY_diag
dX0TAY_drho1 = - X0TDY + 2 * rho1 * X0TFY
invX0TAX0_X0TAY = np.linalg.solve(X0TAX0, X0TAY)
dYTAX0_drho1_invX0TAX0_X0TAY = np.sum(dX0TAY_drho1
* invX0TAX0_X0TAY, axis=0)
dYTAcorrY_drho1 = dYTAY_drho1 - dYTAX0_drho1_invX0TAX0_X0TAY * 2\
+ np.sum(invX0TAX0_X0TAY *
np.dot(dX0TAX0_drho1, invX0TAX0_X0TAY), axis=0)
dXTAY_drho1 = - XTDY + 2 * rho1 * XTFY
dXTAcorrY_drho1 = dXTAY_drho1 \
- np.dot(dXTAX0_drho1, invX0TAX0_X0TAY) \
- np.dot(invX0TAX0_X0TAX.T, dX0TAY_drho1) \
+ np.dot(np.dot(invX0TAX0_X0TAX.T, dX0TAX0_drho1),
invX0TAX0_X0TAY)
deriv_a1 = 2.0 / (np.pi * (1 + a1**2)) \
* (n_V * (- n_run * rho1 / (1 - rho1**2)
- 0.5 * np.trace(np.linalg.solve(
X0TAX0, dX0TAX0_drho1))
- 0.5 * np.trace(np.linalg.solve(
LAMBDA_i, dLTXTAcorrXL_drho1)))
- 0.5 * np.sum(dYTAcorrY_drho1) / sigma2
+ np.sum(dXTAcorrY_drho1 * L_LAMBDA_LTXTAcorrY) / sigma2
- 0.5 * np.sum(np.dot(dXTAcorrX_drho1, L_LAMBDA_LTXTAcorrY)
* L_LAMBDA_LTXTAcorrY) / sigma2)
deriv = np.empty(np.size(param))
deriv[idx_param_sing['Cholesky']] = deriv_L[l_idx]
deriv[idx_param_sing['a1']] = deriv_a1
return -LL, -deriv
def _loglike_AR1_null(self, param, YTY_diag, YTDY_diag, YTFY_diag,
X0TX0, X0TDX0, X0TFX0, X0TY, X0TDY, X0TFY,
n_T, n_V, n_run, n_X0):
# This function calculates the log likelihood of data given AR(1)
# parameters of noise as free parameters.
# Free parameters are in param.
# It serves as a null model which assumes no response to design
# matrix.
a1 = param
rho1 = 2.0 / np.pi * np.arctan(a1) # auto-regressive coefficients
YTAY = self._make_ar1_quad_form(YTY_diag, YTDY_diag, YTFY_diag, rho1)
# dimension: space,
# A/sigma2 is the inverse of noise covariance matrix in each voxel.
# YTAY means Y'AY
X0TAX0 = X0TX0[None, :, :] - rho1[:, None, None] \
* X0TDX0[None, :, :] \
+ rho1[:, None, None]**2 * X0TFX0[None, :, :]
# dimension: space*#baseline*#baseline
X0TAY = self._make_ar1_quad_form(X0TY, X0TDY, X0TFY, rho1)
# dimension: #baseline*space
# X0TAX0_i = np.linalg.solve(X0TAX0, np.identity(n_X0)[None, :, :])
X0TAX0_i = np.linalg.inv(X0TAX0)
# dimension: space*#baseline*#baseline
YTAcorrY = YTAY - np.sum(X0TAY * np.einsum('ijk,ki->ji',
X0TAX0_i, X0TAY), axis=0)
# dimension: space,
sigma2 = YTAcorrY / (n_T - n_X0)
# dimension: space,
LL = - np.sum(np.log(sigma2)) * (n_T - n_X0) * 0.5 \
+ np.sum(np.log(1 - rho1**2)) * n_run * 0.5 \
- np.sum(self._half_log_det(X0TAX0)) \
- (n_T - n_X0) * n_V * (1 + np.log(2 * np.pi)) * 0.5
# The following are for calculating the derivative to a1
deriv_a1 = np.empty(n_V)
dYTAY_drho1 = self._make_ar1_quad_form_grad(YTDY_diag, YTFY_diag, rho1)
# dimension: space,
dX0TAX0_drho1 = - X0TDX0 \
+ 2 * rho1[:, None, None] * X0TFX0
# dimension: space*rank*rank
dX0TAY_drho1 = self._make_ar1_quad_form_grad(X0TDY, X0TFY, rho1)
# dimension: rank*space
# The following are executed for each voxel.
for i_v in range(n_V):
# All variables with _ele as suffix are for data of just one voxel
invX0TAX0_X0TAY_ele = np.dot(X0TAX0_i[i_v, :, :], X0TAY[:, i_v])
# preparation for the variable below
dYTAcorrY_drho1_ele = dYTAY_drho1[i_v] \
- np.dot(dX0TAY_drho1[:, i_v], invX0TAX0_X0TAY_ele) * 2\
+ np.dot(np.dot(invX0TAX0_X0TAY_ele, dX0TAX0_drho1[i_v, :, :]),
invX0TAX0_X0TAY_ele)
deriv_a1[i_v] = 2 / np.pi / (1 + a1[i_v]**2) \
* (- n_run * rho1[i_v] / (1 - rho1[i_v]**2)
- np.einsum('ij,ij', X0TAX0_i[i_v, :, :],
dX0TAX0_drho1[i_v, :, :]) * 0.5
- dYTAcorrY_drho1_ele * 0.5 / sigma2[i_v])
deriv = deriv_a1
return -LL, -deriv
class GBRSA(BRSA):
"""Group Bayesian representational Similarity Analysis (GBRSA)
Given the time series of neural imaging data in a region of interest
(ROI) and the hypothetical neural response (design matrix) to
each experimental condition of interest,
calculate the shared covariance matrix of
the voxels(recording unit)' response to each condition,
and the relative SNR of each voxels.
The relative SNR could be considered as the degree of contribution
of each voxel to this shared covariance matrix.
A correlation matrix converted from the covariance matrix
will be provided as a quantification of neural representational similarity.
Both tools provide estimation of SNR and noise parameters at the end,
and both tools provide empirical Bayesian estimates of activity patterns
beta, together with weight map of nuisance signals beta0.
The differences of this tool from BRSA are:
(1) It allows fitting a shared covariance matrix (which can be converted
to similarity matrix) across multiple subjects.
This is analogous to SRM under funcalign submodule. Because of using
multiple subjects, the result is less noisy.
(2) In the fitting process, the SNR and noise parameters are marginalized
for each voxel. Therefore, this tool should be faster than BRSA
when analyzing an ROI of hundreds to thousands voxels. It does not
provide a spatial smoothness prior on SNR though.
(3) The voxel-wise pseudo-SNR and noise parameters estimated are
posterior mean estimates, while those estimated by BRSA are
maximum-a-posterior estimates.
If your goal is to perform searchlight RSA with relatively fewer voxels
on single subject, BRSA should be faster. However, GBRSA can in principle
be used together with searchlight in a template space such as MNI.
.. math::
Y = X \\cdot \\beta + X_0 \\cdot \\beta_0 + \\epsilon
\\beta_i \\sim N(0,(s_{i} \\sigma_{i})^2 U)
See also `.BRSA`.
Parameters
----------
n_iter : int. Default: 50
Number of maximum iterations to run the algorithm.
rank : int. Default: None
The rank of the covariance matrix.
If not provided, the covariance matrix will be assumed
to be full rank. When you have many conditions
(e.g., calculating the similarity matrix of responses to each event),
you might want to start with specifying a lower rank and use metrics
such as AIC or BIC to decide the optimal rank. The log likelihood
for the fitted data can be retrieved through private attributes
_LL_train\_. Note that this log likelihood score is only used
here for selecting hyperparameters such as rank. For any formal
model comparison, we recommend using score() function on left-out
data.
auto_nuisance: boolean. Default: True
In order to model spatial correlation between voxels that cannot
be accounted for by common response captured in the design matrix,
we assume that a set of time courses not related to the task
conditions are shared across voxels with unknown amplitudes.
One approach is for users to provide time series which they consider
as nuisance but exist in the noise (such as head motion).
The other way is to take the first n_nureg principal components
in the residual after subtracting the response to the design matrix
from the data, and use these components as the nuisance regressor.
This flag is for the second approach. If turned on,
PCA or factor analysis will be applied to the residuals
to obtain new nuisance regressors in each round of fitting.
These two approaches can be combined. If the users provide nuisance
regressors and set this flag as True, then the first n_nureg
principal components of the residuals after subtracting
both the responses to design matrix and the user-supplied nuisance
regressors will be used in addition to the nuisance regressors
provided by the users.
Note that nuisance regressor is not required from user. If it is
not provided, DC components for each run will be included as nuisance
regressor regardless of the auto_nuisance parameter.
n_nureg: Optional[int]. Default: None
Number of nuisance regressors to use in order to model signals
shared across voxels not captured by the design matrix.
This number is in addition to any nuisance regressor that the user
has already provided.
If set to None, the number of nuisance regressors will be
automatically determined based on <NAME>
and <NAME>'s approximate estimation | |
<reponame>nsankar/AutoTS
"""Tools for generating and forecasting with ensembles of models."""
import datetime
import numpy as np
import pandas as pd
import json
from autots.evaluator.auto_model import PredictionObject
from autots.evaluator.auto_model import create_model_id
def Best3Ensemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
):
"""Generate mean forecast for ensemble of models."""
id_list = list(ensemble_params['models'].keys())
model_indexes = [idx for idx, x in enumerate(forecasts_list) if x in id_list]
ens_df = pd.DataFrame(0, index=forecasts[0].index, columns=forecasts[0].columns)
for idx, x in enumerate(forecasts):
if idx in model_indexes:
ens_df = ens_df + forecasts[idx]
ens_df = ens_df / len(model_indexes)
ens_df_lower = pd.DataFrame(
0, index=forecasts[0].index, columns=forecasts[0].columns
)
for idx, x in enumerate(lower_forecasts):
if idx in model_indexes:
ens_df_lower = ens_df_lower + lower_forecasts[idx]
ens_df_lower = ens_df_lower / len(model_indexes)
ens_df_upper = pd.DataFrame(
0, index=forecasts[0].index, columns=forecasts[0].columns
)
for idx, x in enumerate(upper_forecasts):
if idx in model_indexes:
ens_df_upper = ens_df_upper + upper_forecasts[idx]
ens_df_upper = ens_df_upper / len(model_indexes)
ens_runtime = datetime.timedelta(0)
for idx, x in enumerate(forecasts_runtime):
if idx in model_indexes:
ens_runtime = ens_runtime + forecasts_runtime[idx]
ens_result = PredictionObject(
model_name="Ensemble",
forecast_length=len(ens_df.index),
forecast_index=ens_df.index,
forecast_columns=ens_df.columns,
lower_forecast=ens_df_lower,
forecast=ens_df,
upper_forecast=ens_df_upper,
prediction_interval=prediction_interval,
predict_runtime=datetime.timedelta(0),
fit_runtime=ens_runtime,
model_parameters=ensemble_params,
)
return ens_result
def DistEnsemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
):
"""Generate forecast for distance ensemble."""
first_model_index = forecasts_list.index(ensemble_params['FirstModel'])
second_model_index = forecasts_list.index(ensemble_params['SecondModel'])
forecast_length = forecasts[0].shape[0]
dis_frac = ensemble_params['dis_frac']
first_bit = int(np.ceil(forecast_length * dis_frac))
second_bit = int(np.floor(forecast_length * (1 - dis_frac)))
ens_df = (
forecasts[first_model_index]
.head(first_bit)
.append(forecasts[second_model_index].tail(second_bit))
)
ens_df_lower = (
lower_forecasts[first_model_index]
.head(first_bit)
.append(lower_forecasts[second_model_index].tail(second_bit))
)
ens_df_upper = (
upper_forecasts[first_model_index]
.head(first_bit)
.append(upper_forecasts[second_model_index].tail(second_bit))
)
id_list = list(ensemble_params['models'].keys())
model_indexes = [idx for idx, x in enumerate(forecasts_list) if x in id_list]
ens_runtime = datetime.timedelta(0)
for idx, x in enumerate(forecasts_runtime):
if idx in model_indexes:
ens_runtime = ens_runtime + forecasts_runtime[idx]
ens_result_obj = PredictionObject(
model_name="Ensemble",
forecast_length=len(ens_df.index),
forecast_index=ens_df.index,
forecast_columns=ens_df.columns,
lower_forecast=ens_df_lower,
forecast=ens_df,
upper_forecast=ens_df_upper,
prediction_interval=prediction_interval,
predict_runtime=datetime.timedelta(0),
fit_runtime=ens_runtime,
model_parameters=ensemble_params,
)
return ens_result_obj
def HorizontalEnsemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
):
"""Generate forecast for per_series ensembling."""
id_list = list(ensemble_params['models'].keys())
mod_dic = {x: idx for idx, x in enumerate(forecasts_list) if x in id_list}
forecast_df, u_forecast_df, l_forecast_df = (
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
)
for series, mod_id in ensemble_params['series'].items():
l_idx = mod_dic[mod_id]
try:
c_fore = forecasts[l_idx][series]
forecast_df = pd.concat([forecast_df, c_fore], axis=1)
except Exception as e:
repr(e)
print(forecasts[l_idx].columns)
print(forecasts[l_idx].head())
# upper
c_fore = upper_forecasts[l_idx][series]
u_forecast_df = pd.concat([u_forecast_df, c_fore], axis=1)
# lower
c_fore = lower_forecasts[l_idx][series]
l_forecast_df = pd.concat([l_forecast_df, c_fore], axis=1)
ens_runtime = datetime.timedelta(0)
for idx, x in enumerate(forecasts_runtime):
if idx in list(mod_dic.values()):
ens_runtime = ens_runtime + forecasts_runtime[idx]
ens_result = PredictionObject(
model_name="Ensemble",
forecast_length=len(forecast_df.index),
forecast_index=forecast_df.index,
forecast_columns=forecast_df.columns,
lower_forecast=l_forecast_df,
forecast=forecast_df,
upper_forecast=u_forecast_df,
prediction_interval=prediction_interval,
predict_runtime=datetime.timedelta(0),
fit_runtime=ens_runtime,
model_parameters=ensemble_params,
)
return ens_result
def HDistEnsemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
):
"""Generate forecast for per_series per distance ensembling."""
id_list = list(ensemble_params['models'].keys())
mod_dic = {x: idx for idx, x in enumerate(forecasts_list) if x in id_list}
forecast_length = forecasts[0].shape[0]
dist_n = int(np.ceil(ensemble_params['dis_frac'] * forecast_length))
dist_last = forecast_length - dist_n
forecast_df, u_forecast_df, l_forecast_df = (
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
)
for series, mod_id in ensemble_params['series1'].items():
l_idx = mod_dic[mod_id]
try:
c_fore = forecasts[l_idx][series]
forecast_df = pd.concat([forecast_df, c_fore], axis=1)
except Exception as e:
repr(e)
print(forecasts[l_idx].columns)
print(forecasts[l_idx].head())
# upper
c_fore = upper_forecasts[l_idx][series]
u_forecast_df = pd.concat([u_forecast_df, c_fore], axis=1)
# lower
c_fore = lower_forecasts[l_idx][series]
l_forecast_df = pd.concat([l_forecast_df, c_fore], axis=1)
forecast_df2, u_forecast_df2, l_forecast_df2 = (
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
)
for series, mod_id in ensemble_params['series2'].items():
l_idx = mod_dic[mod_id]
try:
c_fore = forecasts[l_idx][series]
forecast_df2 = pd.concat([forecast_df2, c_fore], axis=1)
except Exception as e:
repr(e)
print(forecasts[l_idx].columns)
print(forecasts[l_idx].head())
# upper
c_fore = upper_forecasts[l_idx][series]
u_forecast_df2 = pd.concat([u_forecast_df2, c_fore], axis=1)
# lower
c_fore = lower_forecasts[l_idx][series]
l_forecast_df2 = pd.concat([l_forecast_df2, c_fore], axis=1)
forecast_df = pd.concat(
[forecast_df.head(dist_n), forecast_df2.tail(dist_last)], axis=0
)
u_forecast_df = pd.concat(
[u_forecast_df.head(dist_n), u_forecast_df2.tail(dist_last)], axis=0
)
l_forecast_df = pd.concat(
[l_forecast_df.head(dist_n), l_forecast_df2.tail(dist_last)], axis=0
)
ens_runtime = datetime.timedelta(0)
for idx, x in enumerate(forecasts_runtime):
if idx in list(mod_dic.values()):
ens_runtime = ens_runtime + forecasts_runtime[idx]
ens_result = PredictionObject(
model_name="Ensemble",
forecast_length=len(forecast_df.index),
forecast_index=forecast_df.index,
forecast_columns=forecast_df.columns,
lower_forecast=l_forecast_df,
forecast=forecast_df,
upper_forecast=u_forecast_df,
prediction_interval=prediction_interval,
predict_runtime=datetime.timedelta(0),
fit_runtime=ens_runtime,
model_parameters=ensemble_params,
)
return ens_result
def EnsembleForecast(
ensemble_str,
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
):
"""Return PredictionObject for given ensemble method."""
s3list = ['best3', 'best3horizontal']
if ensemble_params['model_name'].lower().strip() in s3list:
ens_forecast = Best3Ensemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
)
return ens_forecast
if ensemble_params['model_name'].lower().strip() == 'dist':
ens_forecast = DistEnsemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
)
return ens_forecast
hlist = ['horizontal', 'probabilistic']
if ensemble_params['model_name'].lower().strip() in hlist:
ens_forecast = HorizontalEnsemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
)
return ens_forecast
if ensemble_params['model_name'].lower().strip() == 'hdist':
ens_forecast = HDistEnsemble(
ensemble_params,
forecasts_list,
forecasts,
lower_forecasts,
upper_forecasts,
forecasts_runtime,
prediction_interval,
)
return ens_forecast
def EnsembleTemplateGenerator(
initial_results, forecast_length: int = 14, ensemble: str = "simple"
):
"""Generate ensemble templates given a table of results."""
ensemble_templates = pd.DataFrame()
if 'simple' in ensemble:
ens_temp = initial_results.model_results.drop_duplicates(subset='ID')
ens_temp = ens_temp[ens_temp['Ensemble'] == 0]
# best 3, all can be of same model type
best3nonunique = ens_temp.nsmallest(3, columns=['Score'])
if best3nonunique.shape[0] == 3:
ensemble_models = {}
for index, row in best3nonunique.iterrows():
temp_dict = {
'Model': row['Model'],
'ModelParameters': row['ModelParameters'],
'TransformationParameters': row['TransformationParameters'],
}
ensemble_models[row['ID']] = temp_dict
best3nu_params = {
'Model': 'Ensemble',
'ModelParameters': json.dumps(
{'model_name': 'Best3', 'models': ensemble_models}
),
'TransformationParameters': '{}',
'Ensemble': 1,
}
best3nu_params = pd.DataFrame(best3nu_params, index=[0])
ensemble_templates = pd.concat([ensemble_templates, best3nu_params], axis=0)
# best 3, by SMAPE, RMSE, SPL
bestsmape = ens_temp.nsmallest(1, columns=['smape_weighted'])
bestrmse = ens_temp.nsmallest(2, columns=['rmse_weighted'])
bestmae = ens_temp.nsmallest(3, columns=['spl_weighted'])
best3metric = pd.concat([bestsmape, bestrmse, bestmae], axis=0)
best3metric = best3metric.drop_duplicates().head(3)
if best3metric.shape[0] == 3:
ensemble_models = {}
for index, row in best3metric.iterrows():
temp_dict = {
'Model': row['Model'],
'ModelParameters': row['ModelParameters'],
'TransformationParameters': row['TransformationParameters'],
}
ensemble_models[row['ID']] = temp_dict
best3m_params = {
'Model': 'Ensemble',
'ModelParameters': json.dumps(
{'model_name': 'Best3', 'models': ensemble_models}
),
'TransformationParameters': '{}',
'Ensemble': 1,
}
best3m_params = pd.DataFrame(best3m_params, index=[0])
ensemble_templates = pd.concat([ensemble_templates, best3m_params], axis=0)
# best 3, all must be of different model types
ens_temp = (
ens_temp.sort_values('Score', ascending=True, na_position='last')
.groupby('Model')
.head(1)
.reset_index(drop=True)
)
best3unique = ens_temp.nsmallest(3, columns=['Score'])
# only run if there are more than 3 model types available...
if best3unique.shape[0] == 3:
ensemble_models = {}
for index, row in best3unique.iterrows():
temp_dict = {
'Model': row['Model'],
'ModelParameters': row['ModelParameters'],
'TransformationParameters': row['TransformationParameters'],
}
ensemble_models[row['ID']] = temp_dict
best3u_params = {
'Model': 'Ensemble',
'ModelParameters': json.dumps(
{'model_name': 'Best3', 'models': ensemble_models}
),
'TransformationParameters': '{}',
'Ensemble': 1,
}
best3u_params = pd.DataFrame(best3u_params, index=[0])
ensemble_templates = pd.concat(
[ensemble_templates, best3u_params], axis=0, ignore_index=True
)
if 'distance' in ensemble:
dis_frac = 0.2
first_bit = int(np.ceil(forecast_length * dis_frac))
last_bit = int(np.floor(forecast_length * (1 - dis_frac)))
not_ens_list = initial_results.model_results[
initial_results.model_results['Ensemble'] == 0
]['ID'].tolist()
ens_per_ts = initial_results.per_timestamp_smape[
initial_results.per_timestamp_smape.index.isin(not_ens_list)
]
first_model = ens_per_ts.iloc[:, 0:first_bit].mean(axis=1).idxmin()
last_model = (
ens_per_ts.iloc[:, first_bit : (last_bit + first_bit)].mean(axis=1).idxmin()
)
ensemble_models = {}
best3 = initial_results.model_results[
initial_results.model_results['ID'].isin([first_model, last_model])
].drop_duplicates(
subset=['Model', 'ModelParameters', 'TransformationParameters']
)
for index, row in best3.iterrows():
temp_dict = {
'Model': row['Model'],
'ModelParameters': row['ModelParameters'],
'TransformationParameters': row['TransformationParameters'],
}
ensemble_models[row['ID']] = temp_dict
best3u_params = {
'Model': 'Ensemble',
'ModelParameters': json.dumps(
{
'model_name': 'Dist',
'models': ensemble_models,
'dis_frac': dis_frac,
'FirstModel': first_model,
'SecondModel': last_model,
}
),
'TransformationParameters': '{}',
'Ensemble': 1,
}
best3u_params = pd.DataFrame(best3u_params, index=[0])
ensemble_templates = pd.concat(
[ensemble_templates, best3u_params], axis=0, ignore_index=True
)
dis_frac = 0.5
first_bit = int(np.ceil(forecast_length * dis_frac))
last_bit = int(np.floor(forecast_length * (1 - dis_frac)))
not_ens_list = initial_results.model_results[
initial_results.model_results['Ensemble'] == 0
]['ID'].tolist()
ens_per_ts = initial_results.per_timestamp_smape[
initial_results.per_timestamp_smape.index.isin(not_ens_list)
]
first_model = ens_per_ts.iloc[:, 0:first_bit].mean(axis=1).idxmin()
last_model = (
ens_per_ts.iloc[:, first_bit : (last_bit + first_bit)].mean(axis=1).idxmin()
)
ensemble_models = {}
best3 = initial_results.model_results[
initial_results.model_results['ID'].isin([first_model, last_model])
].drop_duplicates(
subset=['Model', 'ModelParameters', 'TransformationParameters']
)
for index, row in best3.iterrows():
temp_dict = {
'Model': row['Model'],
'ModelParameters': row['ModelParameters'],
'TransformationParameters': row['TransformationParameters'],
}
ensemble_models[row['ID']] = temp_dict
best3u_params = {
'Model': 'Ensemble',
'ModelParameters': json.dumps(
{
'model_name': 'Dist',
'models': ensemble_models,
'dis_frac': dis_frac,
'FirstModel': first_model,
'SecondModel': last_model,
}
),
'TransformationParameters': '{}',
'Ensemble': 1,
}
best3u_params = pd.DataFrame(best3u_params, index=[0])
ensemble_templates = pd.concat(
[ensemble_templates, best3u_params], axis=0, ignore_index=True
)
if ('horizontal' in ensemble) or ('probabilistic' in ensemble):
# per_series = model.initial_results.per_series_mae.copy()
if 'horizontal' in ensemble:
per_series = initial_results.per_series_mae.copy()
elif 'probabilistic' in ensemble:
per_series = initial_results.per_series_spl.copy()
mods = pd.Series()
per_series_des = per_series.copy()
n_models = 3
# choose best per series, remove those series, then choose next best
for x in range(n_models):
n_dep = 5 if x < 2 else 10
n_dep = (
n_dep if per_series_des.shape[0] > n_dep else per_series_des.shape[0]
)
models_pos = []
tr_df = pd.DataFrame()
for _ in range(n_dep):
cr_df = pd.DataFrame(per_series_des.idxmin()).transpose()
tr_df = pd.concat([tr_df, cr_df], axis=0)
models_pos.extend(per_series_des.idxmin().tolist())
per_series_des[per_series_des == per_series_des.min()] = np.nan
cur_mods = pd.Series(models_pos).value_counts()
cur_mods = cur_mods.sort_values(ascending=False).head(1)
mods = mods.combine(cur_mods, max, fill_value=0)
rm_cols = tr_df[tr_df.isin(mods.index.tolist())]
| |
<gh_stars>0
# coding: utf-8
"""
ThingsBoard REST API
For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>. # noqa: E501
OpenAPI spec version: 2.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from tb_rest_client.api_client import ApiClient
class RpcV2ControllerApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def delete_resource_using_delete(self, rpc_id, **kwargs): # noqa: E501
"""deleteResource # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_resource_using_delete(rpc_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str rpc_id: rpcId (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_resource_using_delete_with_http_info(rpc_id, **kwargs) # noqa: E501
else:
(data) = self.delete_resource_using_delete_with_http_info(rpc_id, **kwargs) # noqa: E501
return data
def delete_resource_using_delete_with_http_info(self, rpc_id, **kwargs): # noqa: E501
"""deleteResource # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_resource_using_delete_with_http_info(rpc_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str rpc_id: rpcId (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['rpc_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_resource_using_delete" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'rpc_id' is set
if ('rpc_id' not in params or
params['rpc_id'] is None):
raise ValueError("Missing the required parameter `rpc_id` when calling `delete_resource_using_delete`") # noqa: E501
collection_formats = {}
path_params = {}
if 'rpc_id' in params:
path_params['rpcId'] = params['rpc_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/rpc/persistent/{rpcId}', 'DELETE',
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=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_persisted_rpc_by_device_using_get(self, device_id, page_size, page, rpc_status, **kwargs): # noqa: E501
"""getPersistedRpcByDevice # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_persisted_rpc_by_device_using_get(device_id, page_size, page, rpc_status, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str device_id: deviceId (required)
:param int page_size: pageSize (required)
:param int page: page (required)
:param str rpc_status: rpcStatus (required)
:param str text_search: textSearch
:param str sort_property: sortProperty
:param str sort_order: sortOrder
:return: PageDataRpc
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_persisted_rpc_by_device_using_get_with_http_info(device_id, page_size, page, rpc_status, **kwargs) # noqa: E501
else:
(data) = self.get_persisted_rpc_by_device_using_get_with_http_info(device_id, page_size, page, rpc_status, **kwargs) # noqa: E501
return data
def get_persisted_rpc_by_device_using_get_with_http_info(self, device_id, page_size, page, rpc_status, **kwargs): # noqa: E501
"""getPersistedRpcByDevice # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_persisted_rpc_by_device_using_get_with_http_info(device_id, page_size, page, rpc_status, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str device_id: deviceId (required)
:param int page_size: pageSize (required)
:param int page: page (required)
:param str rpc_status: rpcStatus (required)
:param str text_search: textSearch
:param str sort_property: sortProperty
:param str sort_order: sortOrder
:return: PageDataRpc
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['device_id', 'page_size', 'page', 'rpc_status', 'text_search', 'sort_property', 'sort_order'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_persisted_rpc_by_device_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'device_id' is set
if ('device_id' not in params or
params['device_id'] is None):
raise ValueError("Missing the required parameter `device_id` when calling `get_persisted_rpc_by_device_using_get`") # noqa: E501
# verify the required parameter 'page_size' is set
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_persisted_rpc_by_device_using_get`") # noqa: E501
# verify the required parameter 'page' is set
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_persisted_rpc_by_device_using_get`") # noqa: E501
# verify the required parameter 'rpc_status' is set
if ('rpc_status' not in params or
params['rpc_status'] is None):
raise ValueError("Missing the required parameter `rpc_status` when calling `get_persisted_rpc_by_device_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'device_id' in params:
path_params['deviceId'] = params['device_id'] # noqa: E501
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size'])) # noqa: E501
if 'page' in params:
query_params.append(('page', params['page'])) # noqa: E501
if 'rpc_status' in params:
query_params.append(('rpcStatus', params['rpc_status'])) # noqa: E501
if 'text_search' in params:
query_params.append(('textSearch', params['text_search'])) # noqa: E501
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property'])) # noqa: E501
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/rpc/persistent/device/{deviceId}{?pageSize,page,rpcStatus,textSearch,sortProperty,sortOrder}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataRpc', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_persisted_rpc_using_get(self, rpc_id, **kwargs): # noqa: E501
"""getPersistedRpc # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_persisted_rpc_using_get(rpc_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str rpc_id: rpcId (required)
:return: Rpc
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_persisted_rpc_using_get_with_http_info(rpc_id, **kwargs) # noqa: E501
else:
(data) = self.get_persisted_rpc_using_get_with_http_info(rpc_id, **kwargs) # noqa: E501
return data
def get_persisted_rpc_using_get_with_http_info(self, rpc_id, **kwargs): # noqa: E501
"""getPersistedRpc # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_persisted_rpc_using_get_with_http_info(rpc_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str rpc_id: rpcId (required)
:return: Rpc
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['rpc_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_persisted_rpc_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'rpc_id' is set
if ('rpc_id' not in params or
params['rpc_id'] is None):
raise ValueError("Missing the required parameter `rpc_id` when calling `get_persisted_rpc_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'rpc_id' in params:
path_params['rpcId'] = params['rpc_id'] # 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(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/rpc/persistent/{rpcId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Rpc', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def handle_one_way_device_rpc_request_using_post1(self, body, device_id, **kwargs): # noqa: E501
"""handleOneWayDeviceRPCRequest # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.handle_one_way_device_rpc_request_using_post1(body, device_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str body: requestBody (required)
:param str device_id: deviceId (required)
:return: DeferredResultResponseEntity
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.handle_one_way_device_rpc_request_using_post1_with_http_info(body, device_id, **kwargs) # noqa: E501
else:
(data) = self.handle_one_way_device_rpc_request_using_post1_with_http_info(body, device_id, **kwargs) # noqa: E501
return data
def handle_one_way_device_rpc_request_using_post1_with_http_info(self, body, device_id, **kwargs): # noqa: E501
"""handleOneWayDeviceRPCRequest # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.handle_one_way_device_rpc_request_using_post1_with_http_info(body, device_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str body: requestBody (required)
:param str | |
from .functions import defun, defun_wrapped
def _hermite_param(ctx, n, z, parabolic_cylinder):
"""
Combined calculation of the Hermite polynomial H_n(z) (and its
generalization to complex n) and the parabolic cylinder
function D.
"""
n, ntyp = ctx._convert_param(n)
z = ctx.convert(z)
q = -ctx.mpq_1_2
# For re(z) > 0, 2F0 -- http://functions.wolfram.com/
# HypergeometricFunctions/HermiteHGeneral/06/02/0009/
# Otherwise, there is a reflection formula
# 2F0 + http://functions.wolfram.com/HypergeometricFunctions/
# HermiteHGeneral/16/01/01/0006/
#
# TODO:
# An alternative would be to use
# http://functions.wolfram.com/HypergeometricFunctions/
# HermiteHGeneral/06/02/0006/
#
# Also, the 1F1 expansion
# http://functions.wolfram.com/HypergeometricFunctions/
# HermiteHGeneral/26/01/02/0001/
# should probably be used for tiny z
if not z:
T1 = [2, ctx.pi], [n, 0.5], [], [q*(n-1)], [], [], 0
if parabolic_cylinder:
T1[1][0] += q*n
return T1,
can_use_2f0 = ctx.isnpint(-n) or ctx.re(z) > 0 or \
(ctx.re(z) == 0 and ctx.im(z) > 0)
expprec = ctx.prec*4 + 20
if parabolic_cylinder:
u = ctx.fmul(ctx.fmul(z,z,prec=expprec), -0.25, exact=True)
w = ctx.fmul(z, ctx.sqrt(0.5,prec=expprec), prec=expprec)
else:
w = z
w2 = ctx.fmul(w, w, prec=expprec)
rw2 = ctx.fdiv(1, w2, prec=expprec)
nrw2 = ctx.fneg(rw2, exact=True)
nw = ctx.fneg(w, exact=True)
if can_use_2f0:
T1 = [2, w], [n, n], [], [], [q*n, q*(n-1)], [], nrw2
terms = [T1]
else:
T1 = [2, nw], [n, n], [], [], [q*n, q*(n-1)], [], nrw2
T2 = [2, ctx.pi, nw], [n+2, 0.5, 1], [], [q*n], [q*(n-1)], [1-q], w2
terms = [T1,T2]
# Multiply by prefactor for D_n
if parabolic_cylinder:
expu = ctx.exp(u)
for i in range(len(terms)):
terms[i][1][0] += q*n
terms[i][0].append(expu)
terms[i][1].append(1)
return tuple(terms)
@defun
def hermite(ctx, n, z, **kwargs):
return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 0), [], **kwargs)
@defun
def pcfd(ctx, n, z, **kwargs):
r"""
Gives the parabolic cylinder function in Whittaker's notation
`D_n(z) = U(-n-1/2, z)` (see :func:`~mpmath.pcfu`).
It solves the differential equation
.. math ::
y'' + \left(n + \frac{1}{2} - \frac{1}{4} z^2\right) y = 0.
and can be represented in terms of Hermite polynomials
(see :func:`~mpmath.hermite`) as
.. math ::
D_n(z) = 2^{-n/2} e^{-z^2/4} H_n\left(\frac{z}{\sqrt{2}}\right).
**Plots**
.. literalinclude :: /modules/mpmath/plots/pcfd.py
.. image :: /modules/mpmath/plots/pcfd.png
**Examples**
>>> from mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> pcfd(0,0); pcfd(1,0); pcfd(2,0); pcfd(3,0)
1.0
0.0
-1.0
0.0
>>> pcfd(4,0); pcfd(-3,0)
3.0
0.6266570686577501256039413
>>> pcfd('1/2', 2+3j)
(-5.363331161232920734849056 - 3.858877821790010714163487j)
>>> pcfd(2, -10)
1.374906442631438038871515e-9
Verifying the differential equation::
>>> n = mpf(2.5)
>>> y = lambda z: pcfd(n,z)
>>> z = 1.75
>>> chop(diff(y,z,2) + (n+0.5-0.25*z**2)*y(z))
0.0
Rational Taylor series expansion when `n` is an integer::
>>> taylor(lambda z: pcfd(5,z), 0, 7)
[0.0, 15.0, 0.0, -13.75, 0.0, 3.96875, 0.0, -0.6015625]
"""
return ctx.hypercomb(lambda: _hermite_param(ctx, n, z, 1), [], **kwargs)
@defun
def pcfu(ctx, a, z, **kwargs):
r"""
Gives the parabolic cylinder function `U(a,z)`, which may be
defined for `\Re(z) > 0` in terms of the confluent
U-function (see :func:`~mpmath.hyperu`) by
.. math ::
U(a,z) = 2^{-\frac{1}{4}-\frac{a}{2}} e^{-\frac{1}{4} z^2}
U\left(\frac{a}{2}+\frac{1}{4},
\frac{1}{2}, \frac{1}{2}z^2\right)
or, for arbitrary `z`,
.. math ::
e^{-\frac{1}{4}z^2} U(a,z) =
U(a,0) \,_1F_1\left(-\tfrac{a}{2}+\tfrac{1}{4};
\tfrac{1}{2}; -\tfrac{1}{2}z^2\right) +
U'(a,0) z \,_1F_1\left(-\tfrac{a}{2}+\tfrac{3}{4};
\tfrac{3}{2}; -\tfrac{1}{2}z^2\right).
**Examples**
Connection to other functions::
>>> from mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> z = mpf(3)
>>> pcfu(0.5,z)
0.03210358129311151450551963
>>> sqrt(pi/2)*exp(z**2/4)*erfc(z/sqrt(2))
0.03210358129311151450551963
>>> pcfu(0.5,-z)
23.75012332835297233711255
>>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2))
23.75012332835297233711255
>>> pcfu(0.5,-z)
23.75012332835297233711255
>>> sqrt(pi/2)*exp(z**2/4)*erfc(-z/sqrt(2))
23.75012332835297233711255
"""
n, _ = ctx._convert_param(a)
return ctx.pcfd(-n-ctx.mpq_1_2, z)
@defun
def pcfv(ctx, a, z, **kwargs):
r"""
Gives the parabolic cylinder function `V(a,z)`, which can be
represented in terms of :func:`~mpmath.pcfu` as
.. math ::
V(a,z) = \frac{\Gamma(a+\tfrac{1}{2}) (U(a,-z)-\sin(\pi a) U(a,z)}{\pi}.
**Examples**
Wronskian relation between `U` and `V`::
>>> from mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> a, z = 2, 3
>>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)
0.7978845608028653558798921
>>> sqrt(2/pi)
0.7978845608028653558798921
>>> a, z = 2.5, 3
>>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)
0.7978845608028653558798921
>>> a, z = 0.25, -1
>>> pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z)
0.7978845608028653558798921
>>> a, z = 2+1j, 2+3j
>>> chop(pcfu(a,z)*diff(pcfv,(a,z),(0,1))-diff(pcfu,(a,z),(0,1))*pcfv(a,z))
0.7978845608028653558798921
"""
n, ntype = ctx._convert_param(a)
z = ctx.convert(z)
q = ctx.mpq_1_2
r = ctx.mpq_1_4
if ntype == 'Q' and ctx.isint(n*2):
# Faster for half-integers
def h():
jz = ctx.fmul(z, -1j, exact=True)
T1terms = _hermite_param(ctx, -n-q, z, 1)
T2terms = _hermite_param(ctx, n-q, jz, 1)
for T in T1terms:
T[0].append(1j)
T[1].append(1)
T[3].append(q-n)
u = ctx.expjpi((q*n-r)) * ctx.sqrt(2/ctx.pi)
for T in T2terms:
T[0].append(u)
T[1].append(1)
return T1terms + T2terms
v = ctx.hypercomb(h, [], **kwargs)
if ctx._is_real_type(n) and ctx._is_real_type(z):
v = ctx._re(v)
return v
else:
def h(n):
w = ctx.square_exp_arg(z, -0.25)
u = ctx.square_exp_arg(z, 0.5)
e = ctx.exp(w)
l = [ctx.pi, q, ctx.exp(w)]
Y1 = l, [-q, n*q+r, 1], [r-q*n], [], [q*n+r], [q], u
Y2 = l + [z], [-q, n*q-r, 1, 1], [1-r-q*n], [], [q*n+1-r], [1+q], u
c, s = ctx.cospi_sinpi(r+q*n)
Y1[0].append(s)
Y2[0].append(c)
for Y in (Y1, Y2):
Y[1].append(1)
Y[3].append(q-n)
return Y1, Y2
return ctx.hypercomb(h, [n], **kwargs)
@defun
def pcfw(ctx, a, z, **kwargs):
r"""
Gives the parabolic cylinder function `W(a,z)` defined in (DLMF 12.14).
**Examples**
Value at the origin::
>>> from mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> a = mpf(0.25)
>>> pcfw(a,0)
0.9722833245718180765617104
>>> power(2,-0.75)*sqrt(abs(gamma(0.25+0.5j*a)/gamma(0.75+0.5j*a)))
0.9722833245718180765617104
>>> diff(pcfw,(a,0),(0,1))
-0.5142533944210078966003624
>>> -power(2,-0.25)*sqrt(abs(gamma(0.75+0.5j*a)/gamma(0.25+0.5j*a)))
-0.5142533944210078966003624
"""
n, _ = ctx._convert_param(a)
z = ctx.convert(z)
def terms():
phi2 = ctx.arg(ctx.gamma(0.5 + ctx.j*n))
phi2 = (ctx.loggamma(0.5+ctx.j*n) - ctx.loggamma(0.5-ctx.j*n))/2j
rho = ctx.pi/8 + 0.5*phi2
# XXX: cancellation computing k
k = ctx.sqrt(1 + ctx.exp(2*ctx.pi*n)) - ctx.exp(ctx.pi*n)
C = ctx.sqrt(k/2) * ctx.exp(0.25*ctx.pi*n)
yield C * ctx.expj(rho) * ctx.pcfu(ctx.j*n, z*ctx.expjpi(-0.25))
yield C * ctx.expj(-rho) * ctx.pcfu(-ctx.j*n, z*ctx.expjpi(0.25))
v = ctx.sum_accurately(terms)
if ctx._is_real_type(n) and ctx._is_real_type(z):
v = ctx._re(v)
return v
"""
Even/odd PCFs. Useful?
@defun
def pcfy1(ctx, a, z, **kwargs):
a, _ = ctx._convert_param(n)
z = ctx.convert(z)
def h():
w = ctx.square_exp_arg(z)
w1 = ctx.fmul(w, -0.25, exact=True)
w2 = ctx.fmul(w, 0.5, exact=True)
e = ctx.exp(w1)
return [e], [1], [], [], [ctx.mpq_1_2*a+ctx.mpq_1_4], [ctx.mpq_1_2], w2
return ctx.hypercomb(h, [], **kwargs)
@defun
def pcfy2(ctx, a, z, **kwargs):
a, _ = ctx._convert_param(n)
z = ctx.convert(z)
def h():
w = ctx.square_exp_arg(z)
w1 = ctx.fmul(w, -0.25, exact=True)
w2 = ctx.fmul(w, 0.5, exact=True)
e = ctx.exp(w1)
return [e, z], [1, 1], [], [], [ctx.mpq_1_2*a+ctx.mpq_3_4], \
[ctx.mpq_3_2], w2
return ctx.hypercomb(h, [], **kwargs)
"""
@defun_wrapped
def gegenbauer(ctx, n, a, z, **kwargs):
# Special cases: a+0.5, a*2 poles
if ctx.isnpint(a):
return 0*(z+n)
if ctx.isnpint(a+0.5):
# TODO: something else is required here
# E.g.: gegenbauer(-2, -0.5, 3) == -12
if ctx.isnpint(n+1):
raise NotImplementedError("Gegenbauer function with two limits")
def h(a):
a2 = 2*a
T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z)
return [T]
return ctx.hypercomb(h, [a], **kwargs)
def h(n):
a2 = 2*a
T = [], [], [n+a2], [n+1, a2], [-n, n+a2], [a+0.5], 0.5*(1-z)
return [T]
return ctx.hypercomb(h, [n], **kwargs)
@defun_wrapped
def jacobi(ctx, n, a, b, x, **kwargs):
if not ctx.isnpint(a):
def h(n):
return (([], [], [a+n+1], [n+1, a+1], [-n, a+b+n+1], [a+1], (1-x)*0.5),)
return ctx.hypercomb(h, [n], **kwargs)
if not ctx.isint(b):
def h(n, a):
return (([], [], [-b], [n+1, -b-n], [-n, a+b+n+1], [b+1], (x+1)*0.5),)
return ctx.hypercomb(h, [n, a], **kwargs)
# XXX: determine appropriate limit
return ctx.binomial(n+a,n) * ctx.hyp2f1(-n,1+n+a+b,a+1,(1-x)/2, **kwargs)
@defun_wrapped
def laguerre(ctx, n, a, z, **kwargs):
# XXX: limits, poles
#if ctx.isnpint(n):
# return 0*(a+z)
def h(a):
return (([], [], [a+n+1], [a+1, n+1], [-n], [a+1], z),)
return ctx.hypercomb(h, [a], **kwargs)
@defun_wrapped
def legendre(ctx, n, x, **kwargs):
if ctx.isint(n):
n = int(n)
# Accuracy near zeros
if (n + (n < 0)) & 1:
if not x:
return x
mag = ctx.mag(x)
if mag < -2*ctx.prec-10:
return x
if mag < -5:
ctx.prec += -mag
return ctx.hyp2f1(-n,n+1,1,(1-x)/2, **kwargs)
@defun
def legenp(ctx, n, m, z, type=2, **kwargs):
# Legendre function, 1st kind
n = ctx.convert(n)
m = ctx.convert(m)
# Faster
if not m:
return ctx.legendre(n, z, **kwargs)
# TODO: correct evaluation at singularities
if type == 2:
def h(n,m):
g = m*0.5
T = [1+z, 1-z], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z)
return (T,)
return ctx.hypercomb(h, [n,m], **kwargs)
if type == 3:
def h(n,m):
g = m*0.5
T = [z+1, z-1], [g, -g], [], [1-m], [-n, n+1], [1-m], 0.5*(1-z)
return (T,)
return ctx.hypercomb(h, [n,m], **kwargs)
raise ValueError("requires type=2 or type=3")
@defun
def legenq(ctx, n, m, z, type=2, **kwargs):
# Legendre function, 2nd kind
n = ctx.convert(n)
m = ctx.convert(m)
z = ctx.convert(z)
if z in (1, -1):
#if ctx.isint(m):
| |
Source - http://adamcoster.com/2011/01/13/python-clean-up-and-translate-nucleotide-sequences/
'''
return ''.join([gencode.get(sequence[3*i:3*i+3],'X') for i in range(len(sequence)//3)])
# Atoms
backbone_atoms = set(['N', 'CA', 'C', 'O'])
def pdb_atom_name_to_element(s):
'''s should be a string taken from columns 12-15 (zero-indexed) inclusive of a PDB coordinate line.'''
assert(len(s) == 4)
if len(s.strip()) == 4:
assert(s[0] == 'H' or s[0] == 'C' or s[0] == 'O') # "If the name of a hydrogen has four characters, it is left-justified starting in column 13; if it has fewer than four characters, it is left-justified starting in column 14. If the name of a hydrogen has four characters, it is left-justified starting in column 13; if it has fewer than four characters, it is left-justified starting in column 14."
return s[0] # I think this works for hydrogen - I do not know if it is generally correct for carbon and oxygen but something like this is necessary - see CE11 in 1DAN. The correct approach is described somewhere in the IUPAC recommendations (Pure Appl Chem 70:117 (1998), http://www.iupac.org/publications/pac/1998/pdf/7001x0117.pdf.
else:
return s[:2].strip() # see the ATOM section of PDB format documentation. The element name is stored in these positions, right-justified.
###
# Substitution matrices
# Create full matrices to make the lookup logic simpler
# e.g. "pam250.get(x, y) or pam250.get(y, x)" fails due to Python's semantics when the first term is 0 and the second is None - in this case None is returned whereas 0 is what is probably wanted.
# "pam250.get(x, y) or pam250.get(y, x) or 0" is just plain ugly
###
try:
# The amino acid codes BXZ in these blosum62 and pam250 matrices appear to
# be amino acid ambiguity codes
from Bio.SubsMat.MatrixInfo import blosum62 as _blosum62, pam250 as _pam250
pam250 = {}
for k, v in _pam250.items():
if k[0] != k[1]:
assert((k[1], k[0])) not in _pam250
pam250[(k[1], k[0])] = v
pam250[(k[0], k[1])] = v
blosum62 = {}
for k, v in _blosum62.items():
if k[0] != k[1]:
assert((k[1], k[0])) not in _blosum62
blosum62[(k[1], k[0])] = v
blosum62[(k[0], k[1])] = v
except ImportError:
# Biopython is not available on chef.
pam250 = {}
blosum62 = {}
###
# Sequences
#
class Sequence(object):
''' A class to hold a list of Residues in the same chain.
This class maintains two elements:
1) order List(ID) : a list of residue IDs in the order of addition;
2) sequence Dict(ID->Residue) : a map from residue IDs to a Residue object (chain, residue ID, residue type, sequence_type).
'''
def __init__(self, sequence_type = None):
self.order = []
self.sequence = {}
self.sequence_type = sequence_type
if sequence_type:
assert(sequence_type == 'Protein' or sequence_type == 'DNA' or sequence_type == 'RNA' or sequence_type == 'Protein skeleton' or sequence_type == 'Ligand' or sequence_type == 'Unknown')
self.special_insertion_count = 1
def __iter__(self):
self._iter_index = 0
return self
def __getitem__(self, item):
return self.sequence[item]
def __len__(self):
return len(self.sequence)
def ids(self):
return list(self.sequence.keys())
def __next__(self): # todo: This is __next__ in Python 3.x
try:
id = self.order[self._iter_index]
self._iter_index += 1
return id, self.sequence[id]
except:
raise StopIteration
def __eq__(self, other):
'''Equality is defined on residue ID and type.'''
num_res = len(self.order)
if num_res != len(other.order):
return False
for x in range(num_res):
if self.order[x] != other.order[x]:
return False
if self.sequence[self.order[x]] != other.sequence[other.order[x]]:
return False
return True
def add(self, r):
'''Takes an id and a Residue r and adds them to the Sequence.'''
id = r.get_residue_id()
if self.order:
last_id = self.order[-1]
# KAB - allow for multiresidue noncanonicals
if id in self.order:
raise colortext.Exception('Warning: using code to "allow for multiresidue noncanonicals" - check this case manually.')
id = '%s.%d'%(str(id),self.special_insertion_count)
self.special_insertion_count += 1
assert(r.Chain == self.sequence[last_id].Chain)
assert(r.residue_type == self.sequence[last_id].residue_type)
self.order.append(id)
self.sequence[id] = r
def set_type(self, sequence_type):
'''Set the type of a Sequence if it has not been set.'''
if not(self.sequence_type):
for id, r in self.sequence.items():
assert(r.residue_type == None)
r.residue_type = sequence_type
self.sequence_type = sequence_type
def __repr__(self):
sequence = self.sequence
return "".join([sequence[id].ResidueAA for id in self.order])
@staticmethod
def from_sequence(chain, list_of_residues, sequence_type = None):
'''Takes in a chain identifier and protein sequence and returns a Sequence object of Residues, indexed from 1.'''
s = Sequence(sequence_type)
count = 1
for ResidueAA in list_of_residues:
s.add(Residue(chain, count, ResidueAA, sequence_type))
count += 1
return s
class InconsistentMappingException(Exception): pass
class SequenceMap(object):
''' A class to map the IDs of one Sequence to another.'''
def __init__(self):
self.map = {}
self.substitution_scores = {}
@staticmethod
def from_dict(d):
for k, v in d.items():
assert(type(k) == int or type(k) == bytes or type(k) == str)
assert(type(v) == int or type(v) == bytes or type(v) == str)
s = SequenceMap()
s.map = d
s.substitution_scores = dict.fromkeys(list(d.keys()), None)
return s
def add(self, key, value, substitution_score):
self[key] = value
self.substitution_scores[key] = substitution_score
def remove(self, key):
if self.map.get(key):
del self.map[key]
if self.substitution_scores.get(key):
del self.substitution_scores[key]
def matches(self, other):
overlap = set(self.keys()).intersection(set(other.keys()))
for k in overlap:
if self[k] != other[k]:
return False
return True
def get_mismatches(self, other):
overlap = set(self.keys()).intersection(set(other.keys()))
return [k for k in overlap if self[k] != other[k]]
def substitution_scores_match(self, other):
'''Check to make sure that the substitution scores agree. If one map has a null score and the other has a non-null score, we trust the other's score and vice versa.'''
overlap = set(self.substitution_scores.keys()).intersection(set(other.substitution_scores.keys()))
for k in overlap:
if not(self.substitution_scores[k] == None or other.substitution_scores[k] == None):
if self.substitution_scores[k] != other.substitution_scores[k]:
return False
return True
def get(self, k, default_value = None):
return self.map.get(k, default_value)
def keys(self):
return list(self.map.keys())
def values(self):
return list(self.map.values())
def __getitem__(self, item):
return self.map.get(item)
def __setitem__(self, key, value):
assert(type(key) == int or type(key) == bytes or type(key) == str)
assert(type(value) == int or type(value) == bytes or type(value) == str)
self.map[key] = value
self.substitution_scores[key] = None
def __next__(self): # todo: This is __next__ in Python 3.x
try:
id = self._iter_keys.pop()
return id, self.map[id], self.substitution_scores[id]
except:
raise StopIteration
def __iter__(self):
self._iter_keys = set(self.map.keys())
return self
def __eq__(self, other):
if list(self.keys()) == list(other.keys()):
for k in list(self.keys()):
if self[k] != other[k]:
return False
return True
else:
return False
def __le__(self, other):
if set(self.keys()).issubset == set(other.keys()):
for k in list(self.keys()):
if self[k] != other[k]:
return False
return True
else:
return False
def glue(self, other):
return self + other
def __add__(self, other):
'''Glue two maps together. The operation is defined on maps which agree on the intersection of their domain as:
(f + g)(x) = f(x) if x not in dom(f)
(f + g)(x) = g(x) if x not in dom(g)
(f + g)(x) = f(x) = g(x) if x in dom(f) n dom(g)
'''
if not self.matches(other):
overlap = set(self.keys()).intersection(set(other.keys()))
mismatches = [k for k in overlap if self[k] != other[k]]
raise InconsistentMappingException('The two maps disagree on the common domain elements %s.' % str(mismatches))
elif not self.substitution_scores_match(other):
overlap = set(self.substitution_scores.keys()).intersection(set(other.substitution_scores.keys()))
mismatches = [k for k in overlap if self.substitution_scores[k] != other.substitution_scores[k]]
raise InconsistentMappingException('The two maps scores disagree on the common domain elements %s.' % str(mismatches))
elif not self.__class__ == other.__class__:
raise InconsistentMappingException('''The two maps have different classes: '%s' and '%s'.''' % ( self.__class__, other.__class__))
else:
d, s = {}, {}
other_domain = set(other.keys()).difference(set(self.keys()))
for k in list(self.keys()):
d[k] = self.map[k]
s[k] = self.substitution_scores[k]
for k in other_domain:
assert(self.map.get(k) == None)
assert(self.substitution_scores.get(k) == None)
d[k] = other.map[k]
s[k] = other.substitution_scores[k]
o = self.__class__.from_dict(d)
o.substitution_scores = s
return o
def __repr__(self):
s = []
substitution_scores = self.substitution_scores
for k, v in sorted(self.map.items()):
if type(k) == bytes or type(k) == str:
key = "'%s'" % k
else:
key = str(k)
if type(v) == bytes or type(v) == str:
val = "'%s'" % v
else:
val = str(v)
if substitution_scores.get(k):
s.append('%s->%s (%s)' % (str(key), str(val), str(substitution_scores[k])))
else:
s.append('%s->%s' % (str(key), str(val)))
return ", ".join(s)
class PDBUniParcSequenceMap(SequenceMap):
''' A class to map the IDs of a PDB chain's Sequence (ATOM/SEQRES/FASTA) to a UniParc residue pairs (UniParcID, sequence index).
Mapping to tuples is necessary for some cases e.g. for chimeras like 1M7T.
'''
def __setitem__(self, key, value):
assert(len(value) == 2)
assert(type(key) == int or type(key) == bytes or type(key) == str)
assert((type(value[0]) == bytes or type(value[0]) == str) and (type(value[1]) | |
#!/usr/bin/env python
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
import json
import requests
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'}
DOCUMENTATION = '''
---
module: hashivault_oidc_auth_role
version_added: "4.1.1"
short_description: Hashicorp Vault OIDC secret engine role
description:
- Module to define an OIDC role that vault can generate dynamic credentials for vault
options:
url:
description:
- url for vault
default: to environment variable VAULT_ADDR
ca_cert:
description:
- "path to a PEM-encoded CA cert file to use to verify the Vault server TLS certificate"
default: to environment variable VAULT_CACERT
ca_path:
description:
- "path to a directory of PEM-encoded CA cert files to verify the Vault server TLS certificate : if ca_cert
is specified, its value will take precedence"
default: to environment variable VAULT_CAPATH
client_cert:
description:
- "path to a PEM-encoded client certificate for TLS authentication to the Vault server"
default: to environment variable VAULT_CLIENT_CERT
client_key:
description:
- "path to an unencrypted PEM-encoded private key matching the client certificate"
default: to environment variable VAULT_CLIENT_KEY
verify:
description:
- "if set, do not verify presented TLS certificate before communicating with Vault server : setting this
variable is not recommended except during testing"
default: to environment variable VAULT_SKIP_VERIFY
token:
description:
- token for vault
default: to environment variable VAULT_TOKEN
username:
description:
- username to login to vault.
default: to environment variable VAULT_USER
password:
description:
- password to login to vault.
default: to environment variable VAULT_PASSWORD
namespace:
description:
- namespace for vault
default: to environment variable VAULT_NAMESPACE
mount_point:
description:
- name of the secret engine mount name.
default: oidc
name:
description:
- name of the role in vault
bound_audiences:
description:
- List of `aud` claims to match against. Any match is sufficient.
user_claim:
description:
- The claim to use to uniquely identify the user; this will be used as the name for the Identity entity
alias created due to a successful login. The claim value must be a string.
default: sub
bound_subject:
description:
- If set, requires that the sub claim matches this value.
bound_claims:
description:
- If set, a map of claims/values to match against. The expected value may be a single string or a list of
strings.
groups_claim:
description:
- The claim to use to uniquely identify the set of groups to which the user belongs; this will be used as
the names for the Identity group aliases created due to a successful login. The claim value must be a
list of strings.
claim_mappings:
description:
- If set, a map of claims (keys) to be copied to specified metadata fields (values).
oidc_scopes:
description:
- If set, a list of OIDC scopes to be used with an OIDC role. The standard scope "openid" is automatically
included and need not be specified.
allowed_redirect_uris:
description:
- The list of allowed values for redirect_uri during OIDC logins.
- When using nested namespaces, use url encoding '%2F' instead of '/'
token_ttl:
description:
- The incremental lifetime for generated tokens. This current value of this will be referenced at renewal
time.
token_max_ttl:
description:
- The maximum lifetime for generated tokens. This current value of this will be referenced at renewal time.
token_policies:
description:
- List of policies to encode onto generated tokens. Depending on the auth method, this list may be
supplemented by user/group/other values.
token_bound_cidrs:
description:
- List of CIDR blocks; if set, specifies blocks of IP addresses which can authenticate successfully, and
ties the resulting token to these blocks as well.
token_explicit_max_ttl:
description:
- If set, will encode an explicit max TTL onto the token. This is a hard cap even if token_ttl and
token_max_ttl would otherwise allow a renewal.
token_no_default_policy:
description:
- If set, the default policy will not be set on generated tokens; otherwise it will be added to the policies
set in token_policies.
token_num_uses:
description:
- The maximum number of times a generated token may be used (within its lifetime); 0 means unlimited.
token_period:
description:
- If set, indicates that the token generated using this role should never expire. The token should be
renewed within the duration specified by this value. At each renewal, the token's TTL will be set to
the value of this parameter.
token_type:
description:
- The type of token that should be generated. Can be service, batch, or default to use the mount's tuned
default (which unless changed will be service tokens). For token store roles, there are two additional
possibilities (default-service and default-batch) which specify the type to return unless the client
requests a different type at generation time.
'''
EXAMPLES = '''
---
- hosts: localhost
tasks:
- hashivault_oidc_auth_role:
name: "gmail"
bound_audiences: ["123-456.apps.googleusercontent.com"]
allowed_redirect_uris: ["https://vault.com:8200/ui/vault/auth/oidc/oidc/callback"]
token_policies: ["test"]
- hosts: localhost
tasks:
- hashivault_oidc_auth_role:
name: "nested_ns_role"
bound_audiences: ["123-456.apps.googleusercontent.com"]
allowed_redirect_uris: ["https://vault.com:8200/ui/oidc/oidc/callback?namespace=namespaceone%2Fnamespacetwo"]
token_policies: ["test"]
'''
def main():
argspec = hashivault_argspec()
argspec['state'] = dict(required=False, type='str', default='present', choices=['present', 'absent'])
argspec['name'] = dict(required=True, type='str')
argspec['mount_point'] = dict(required=False, type='str', default='oidc')
argspec['user_claim'] = dict(required=False, type='str', default='sub')
argspec['allowed_redirect_uris'] = dict(required=True, type='list')
argspec['bound_audiences'] = dict(required=False, type='list', default=[])
argspec['bound_subject'] = dict(required=False, type='str', default='')
argspec['bound_claims'] = dict(required=False, type='dict')
argspec['groups_claim'] = dict(required=False, type='str', default='')
argspec['claim_mappings'] = dict(required=False, type='dict')
argspec['oidc_scopes'] = dict(required=False, type='list', default=[])
argspec['token_ttl'] = dict(required=False, type='int', default=0)
argspec['token_max_ttl'] = dict(required=False, type='int', default=0)
argspec['token_policies'] = dict(required=False, type='list', default=[])
argspec['policies'] = dict(required=False, type='list', default=[])
argspec['token_bound_cidrs'] = dict(required=False, type='list', default=[])
argspec['token_explicit_max_ttl'] = dict(required=False, type='int', default=0)
argspec['token_no_default_policy'] = dict(required=False, type='bool', default=False)
argspec['token_num_uses'] = dict(required=False, type='int', default=0)
argspec['token_period'] = dict(required=False, type='int', default=0)
argspec['token_type'] = dict(required=False, type='str', default='default')
argspec['clock_skew_leeway'] = dict(required=False, type='int', default=0)
argspec['expiration_leeway'] = dict(required=False, type='int', default=0)
argspec['not_before_leeway'] = dict(required=False, type='int', default=0)
supports_check_mode = False
module = hashivault_init(argspec, supports_check_mode)
result = hashivault_oidc_auth_role(module)
if result.get('failed'):
module.fail_json(**result)
else:
module.exit_json(**result)
@hashiwrapper
def hashivault_oidc_auth_role(module):
params = module.params
client = hashivault_auth_client(params)
mount_point = params.get('mount_point')
name = params.get('name')
state = params.get('state')
desired_state = dict()
current_state = dict()
exists = False
changed = False
token = params['token']
namespace = params['namespace']
headers = {'X-Vault-Token': token, 'X-Vault-Namespace': namespace}
url = params['url']
verify = params['verify']
ca_cert = params['ca_cert']
ca_path = params['ca_path']
# do not want a trailing slash in name and mount_point
if name[-1] == '/':
name = name.strip('/')
if mount_point[-1]:
mount_point = mount_point.strip('/')
desired_state['allowed_redirect_uris'] = params.get('allowed_redirect_uris')
desired_state['bound_audiences'] = params.get('bound_audiences')
desired_state['bound_claims'] = params.get('bound_claims')
desired_state['bound_subject'] = params.get('bound_subject')
desired_state['claim_mappings'] = params.get('claim_mappings')
desired_state['groups_claim'] = params.get('groups_claim')
desired_state['oidc_scopes'] = params.get('oidc_scopes')
desired_state['token_bound_cidrs'] = params.get('token_bound_cidrs')
desired_state['token_explicit_max_ttl'] = params.get('token_explicit_max_ttl')
desired_state['token_ttl'] = params.get('token_ttl')
desired_state['token_max_ttl'] = params.get('token_max_ttl')
desired_state['token_no_default_policy'] = params.get('token_no_default_policy')
desired_state['token_policies'] = params.get('token_policies')
desired_state['policies'] = params.get('policies')
desired_state['token_type'] = params.get('token_type')
desired_state['user_claim'] = params.get('user_claim')
desired_state['token_period'] = params.get('token_period')
desired_state['token_num_uses'] = params.get('token_num_uses')
desired_state['clock_skew_leeway'] = params.get('clock_skew_leeway')
desired_state['expiration_leeway'] = params.get('expiration_leeway')
desired_state['not_before_leeway'] = params.get('not_before_leeway')
# check if engine is enabled
try:
if (mount_point + "/") not in client.sys.list_auth_methods()['data'].keys():
return {'failed': True, 'msg': 'auth method is not enabled', 'rc': 1}
except:
if module.check_mode:
changed = True
else:
return {'failed': True, 'msg': 'auth mount is not enabled or namespace is not created', 'rc': 1}
# check if role exists
s = requests.Session()
exists = False
try:
if verify:
if ca_cert is not None:
verify = ca_cert
elif ca_path is not None:
verify = ca_path
current_state = s.get(url + '/v1/auth/' + mount_point + '/role/' + name, verify=verify, headers=headers)
if current_state.status_code == 200:
exists = True
except:
changed = True
if not exists and state == 'present':
changed = True
elif exists and state == 'absent':
changed = True
desired_state['role_type'] = "oidc"
desired_state['verbose_oidc_logging'] = False
if len(desired_state['token_policies']) == 0 and len(desired_state['policies']) > 0:
desired_state['token_policies'] = desired_state['policies']
if len(desired_state['policies']) == 0 and len(desired_state['token_policies']) > 0:
desired_state['policies'] = desired_state['token_policies']
# check if current role matches desired role values, if they dont match, set changed true
if exists and state == 'present':
current_state = current_state.json()['data']
for k, v in desired_state.items():
if v != current_state[k]:
changed = True
break
method = None
if changed and state == 'present' and not module.check_mode:
method = 'POST'
elif changed and state == 'absent' and not module.check_mode:
method = 'DELETE'
# make the changes!
if method is not None:
req = requests.Request(method, url + '/v1/auth/' + mount_point + '/role/' + name, headers=headers,
json=desired_state)
prepped = s.prepare_request(req)
resp = s.send(prepped)
| |
<filename>spaghetti/analysis.py
import numpy as np
class NetworkBase(object):
"""Base object for performing network analysis on a
``spaghetti.Network`` object.
Parameters
----------
ntw : spaghetti.Network
spaghetti Network object.
pointpattern : spaghetti.network.PointPattern
A spaghetti point pattern object.
nsteps : int
The number of steps at which the count of the nearest
neighbors is computed.
permutations : int
The number of permutations to perform. Default 99.
threshold : float
The level at which significance is computed.
(0.5 would be 97.5% and 2.5%).
distribution : str
The distribution from which random points are sampled
Either ``"uniform"`` or ``"poisson"``.
lowerbound : float
The lower bound at which the G-function is computed.
Default 0.
upperbound : float
The upper bound at which the G-function is computed.
Defaults to the maximum observed nearest neighbor distance.
Attributes
----------
sim : numpy.ndarray
simulated distance matrix
npts : int
pointpattern.npoints
xaxis : numpy.ndarray
observed x-axis of values
observed : numpy.ndarray
observed y-axis of values
"""
def __init__(
self,
ntw,
pointpattern,
nsteps=10,
permutations=99,
threshold=0.5,
distribution="poisson",
lowerbound=None,
upperbound=None,
):
# set initial class attributes
self.ntw = ntw
self.pointpattern = pointpattern
self.nsteps = nsteps
self.permutations = permutations
self.threshold = threshold
# set and validate the distribution
self.distribution = distribution
self.validatedistribution()
# create an empty array to store the simulated points
self.sim = np.empty((permutations, nsteps))
self.npts = self.pointpattern.npoints
# set the lower and upper bounds (lower only for G)
self.lowerbound = lowerbound
self.upperbound = upperbound
# compute the statistic (F, G, or K)
self.computeobserved()
self.computepermutations()
# compute the envelope vectors
self.computeenvelope()
def validatedistribution(self):
"""enusure statistical distribution is supported
"""
valid_distributions = ["uniform", "poisson"]
assert (
self.distribution in valid_distributions
), "Distribution not in {}".format(valid_distributions)
def computeenvelope(self):
"""compute upper and lower bounds of envelope
"""
upper = 1.0 - self.threshold / 2.0
lower = self.threshold / 2.0
self.upperenvelope = np.nanmax(self.sim, axis=0) * upper
self.lowerenvelope = np.nanmin(self.sim, axis=0) * lower
def setbounds(self, nearest):
"""set upper and lower bounds
"""
if self.lowerbound is None:
self.lowerbound = 0
if self.upperbound is None:
self.upperbound = np.nanmax(nearest)
class NetworkG(NetworkBase):
"""Compute a network constrained G statistic. This requires the
capability to compute a distance matrix between two point patterns.
In this case one will be observed and one will be simulated.
"""
def computeobserved(self):
"""compute the observed nearest
"""
# find nearest point that is not NaN
nearest = np.nanmin(self.ntw.allneighbordistances(self.pointpattern), axis=1)
self.setbounds(nearest)
# compute a G-Function
observedx, observedy = gfunction(
nearest, self.lowerbound, self.upperbound, nsteps=self.nsteps
)
# set observed values
self.observed = observedy
self.xaxis = observedx
def computepermutations(self):
"""compute permutations of the nearest
"""
# for each round of permutations
for p in range(self.permutations):
# simulate a point pattern
sim = self.ntw.simulate_observations(
self.npts, distribution=self.distribution
)
# find nearest observation
nearest = np.nanmin(self.ntw.allneighbordistances(sim), axis=1)
# compute a G-Function
simx, simy = gfunction(
nearest, self.lowerbound, self.upperbound, nsteps=self.nsteps
)
# label the permutation
self.sim[p] = simy
class NetworkK(NetworkBase):
"""Compute a network constrained K statistic. This requires the
capability to compute a distance matrix between two point patterns.
In this case one will be observed and one will be simulated.
Attributes
----------
lam : float
``lambda`` value
Notes
-----
Based on :cite:`Okabe2001`.
"""
def computeobserved(self):
"""compute the observed nearest
"""
# find nearest point that is not NaN
nearest = self.ntw.allneighbordistances(self.pointpattern)
self.setbounds(nearest)
# set the intensity (lambda)
self.lam = self.npts / sum(self.ntw.arc_lengths.values())
# compute a K-Function
observedx, observedy = kfunction(
nearest, self.upperbound, self.lam, nsteps=self.nsteps
)
# set observed values
self.observed = observedy
self.xaxis = observedx
def computepermutations(self):
"""compute permutations of the nearest
"""
# for each round of permutations
for p in range(self.permutations):
# simulate a point pattern
sim = self.ntw.simulate_observations(
self.npts, distribution=self.distribution
)
# find nearest observation
nearest = self.ntw.allneighbordistances(sim)
# compute a K-Function
simx, simy = kfunction(
nearest, self.upperbound, self.lam, nsteps=self.nsteps
)
# label the permutation
self.sim[p] = simy
class NetworkF(NetworkBase):
"""Compute a network constrained F statistic. This requires the
capability to compute a distance matrix between two point patterns.
In this case one will be observed and one will be simulated.
Attributes
----------
fsim : spaghetti.network.SimulatedPointPattern
simulated point pattern of ``self.nptsv points
"""
def computeobserved(self):
"""compute the observed nearest and simulated nearest
"""
# create an initial simulated point pattern
self.fsim = self.ntw.simulate_observations(self.npts)
# find nearest neighbor distances from
# the simulated to the observed
nearest = np.nanmin(
self.ntw.allneighbordistances(self.fsim, self.pointpattern), axis=1
)
self.setbounds(nearest)
# compute an F-function
observedx, observedy = ffunction(
nearest,
self.lowerbound,
self.upperbound,
nsteps=self.nsteps,
npts=self.npts,
)
# set observed values
self.observed = observedy
self.xaxis = observedx
def computepermutations(self):
"""compute permutations of the nearest
"""
# for each round of permutations
for p in range(self.permutations):
# simulate a point pattern
sim = self.ntw.simulate_observations(
self.npts, distribution=self.distribution
)
# find nearest observation
nearest = np.nanmin(self.ntw.allneighbordistances(sim, self.fsim), axis=1)
# compute an F-function
simx, simy = ffunction(
nearest, self.lowerbound, self.upperbound, self.npts, nsteps=self.nsteps
)
# label the permutation
self.sim[p] = simy
def gfunction(nearest, lowerbound, upperbound, nsteps=10):
"""Compute a G-Function
Parameters
----------
nearest : numpy.ndarray
A vector of nearest neighbor distances.
lowerbound : int or float
The starting value of the sequence.
upperbound : int or float
The end value of the sequence.
nsteps : int
The number of distance bands. Default is 10. Must be
non-negative.
Returns
-------
x : numpy.ndarray
x-axis of values
y : numpy.ndarray
y-axis of values
"""
# set observation count
nobs = len(nearest)
# create interval for x-axis
x = np.linspace(lowerbound, upperbound, nsteps)
# sort nearest neighbor distances
nearest = np.sort(nearest)
# create empty y-axis vector
y = np.empty(len(x))
# iterate over x-axis interval
for i, r in enumerate(x):
# slice out and count neighbors within radius
cnt = len(nearest[nearest <= r])
# if there is one or more neighbors compute `g`
if cnt > 0:
g = cnt / float(nobs)
# otherwise set `g` to zero
else:
g = 0
# label `g` on the y-axis
y[i] = g
return x, y
def kfunction(nearest, upperbound, intensity, nsteps=10):
"""Compute a K-Function
Parameters
----------
nearest : numpy.ndarray
A vector of nearest neighbor distances.
upperbound : int or float
The end value of the sequence.
intensity : float
lambda value
nsteps : int
The number of distance bands. Default is 10. Must be
non-negative.
Returns
-------
x : numpy.ndarray
x-axis of values
y : numpy.ndarray
y-axis of values
"""
# set observation count
nobs = len(nearest)
# create interval for x-axis
x = np.linspace(0, upperbound, nsteps)
# create empty y-axis vector
y = np.empty(len(x))
# iterate over x-axis interval
for i, r in enumerate(x):
# slice out and count neighbors within radius
y[i] = len(nearest[nearest <= r])
# compute k for y-axis vector
y *= intensity ** -1
return x, y
def ffunction(nearest, lowerbound, upperbound, npts, nsteps=10):
"""Compute an F-Function
Parameters
----------
nearest : numpy.ndarray
A vector of nearest neighbor distances.
lowerbound : int or float
The starting value of the sequence.
upperbound : int or float
The end value of the sequence.
npts : int
pointpattern.npoints
nsteps : int
The number of distance bands. Default is 10. Must be
non-negative.
Returns
-------
x : numpy.ndarray
x-axis of values
y : numpy.ndarray
y-axis of values
"""
# set observation count
nobs = len(nearest)
# create interval for x-axis
x = np.linspace(lowerbound, upperbound, nsteps)
# sort nearest neighbor distances
nearest = np.sort(nearest)
# create empty y-axis vector
y = np.empty(len(x))
# iterate over x-axis interval
for i, r in enumerate(x):
# slice out and count neighbors within radius
cnt = len(nearest[nearest <= r])
# if there is one or more neighbors compute `f`
if cnt > 0:
f = cnt / float(npts)
# otherwise set `f` to zero
else:
f = 0
# label `f` on the y-axis
y[i] | |
<filename>rally/task/validation.py
# Copyright 2014: Mirantis Inc.
# 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. 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 functools
import os
import re
from glanceclient import exc as glance_exc
from novaclient import exceptions as nova_exc
import six
from rally.common.i18n import _
from rally.common import yamlutils as yaml
from rally import consts
from rally import exceptions
from rally.plugins.openstack.context.nova import flavors as flavors_ctx
from rally.plugins.openstack import types as openstack_types
from rally.task import types
# TODO(boris-42): make the validators usable as a functions as well.
# At the moment validators can only be used as decorators.
class ValidationResult(object):
def __init__(self, is_valid, msg=None):
self.is_valid = is_valid
self.msg = msg
def validator(fn):
"""Decorator that constructs a scenario validator from given function.
Decorated function should return ValidationResult on error.
:param fn: function that performs validation
:returns: rally scenario validator
"""
def wrap_given(*args, **kwargs):
"""Dynamic validation decorator for scenario.
:param args: the arguments of the decorator of the benchmark scenario
ex. @my_decorator("arg1"), then args = ("arg1",)
:param kwargs: the keyword arguments of the decorator of the scenario
ex. @my_decorator(kwarg1="kwarg1"), then kwargs = {"kwarg1": "kwarg1"}
"""
@functools.wraps(fn)
def wrap_validator(config, clients, deployment):
# NOTE(amaretskiy): validator is successful by default
return (fn(config, clients, deployment, *args, **kwargs) or
ValidationResult(True))
def wrap_scenario(scenario):
# TODO(boris-42): remove this in future.
wrap_validator.permission = getattr(fn, "permission",
consts.EndpointPermission.USER)
scenario._meta_setdefault("validators", [])
scenario._meta_get("validators").append(wrap_validator)
return scenario
return wrap_scenario
return wrap_given
@validator
def number(config, clients, deployment, param_name, minval=None, maxval=None,
nullable=False, integer_only=False):
"""Checks that parameter is number that pass specified condition.
Ensure a parameter is within the range [minval, maxval]. This is a
closed interval so the end points are included.
:param param_name: Name of parameter to validate
:param minval: Lower endpoint of valid interval
:param maxval: Upper endpoint of valid interval
:param nullable: Allow parameter not specified, or parameter=None
:param integer_only: Only accept integers
"""
val = config.get("args", {}).get(param_name)
num_func = float
if integer_only:
# NOTE(boris-42): Force check that passed value is not float, this is
# important cause int(float_numb) won't raise exception
if type(val) == float:
return ValidationResult(False,
"%(name)s is %(val)s which hasn't int type"
% {"name": param_name, "val": val})
num_func = int
# None may be valid if the scenario sets a sensible default.
if nullable and val is None:
return ValidationResult(True)
try:
number = num_func(val)
if minval is not None and number < minval:
return ValidationResult(
False,
"%(name)s is %(val)s which is less than the minimum "
"(%(min)s)"
% {"name": param_name, "val": number, "min": minval})
if maxval is not None and number > maxval:
return ValidationResult(
False,
"%(name)s is %(val)s which is greater than the maximum "
"(%(max)s)"
% {"name": param_name, "val": number, "max": maxval})
return ValidationResult(True)
except (ValueError, TypeError):
return ValidationResult(
False,
"%(name)s is %(val)s which is not a valid %(type)s"
% {"name": param_name, "val": val, "type": num_func.__name__})
def _file_access_ok(filename, mode, param_name, required=True):
if not filename:
return ValidationResult(not required,
"Parameter %s required" % param_name)
if not os.access(os.path.expanduser(filename), mode):
return ValidationResult(
False, "Could not open %(filename)s with mode %(mode)s "
"for parameter %(param_name)s"
% {"filename": filename, "mode": mode, "param_name": param_name})
return ValidationResult(True)
@validator
def file_exists(config, clients, deployment, param_name, mode=os.R_OK,
required=True):
"""Validator checks parameter is proper path to file with proper mode.
Ensure a file exists and can be accessed with the specified mode.
Note that path to file will be expanded before access checking.
:param param_name: Name of parameter to validate
:param mode: Access mode to test for. This should be one of:
* os.F_OK (file exists)
* os.R_OK (file is readable)
* os.W_OK (file is writable)
* os.X_OK (file is executable)
If multiple modes are required they can be added, eg:
mode=os.R_OK+os.W_OK
:param required: Boolean indicating whether this argument is required.
"""
return _file_access_ok(config.get("args", {}).get(param_name), mode,
param_name, required)
def check_command_dict(command):
"""Check command-specifying dict `command', raise ValueError on error."""
if not isinstance(command, dict):
raise ValueError("Command must be a dictionary")
# NOTE(pboldin): Here we check for the values not for presence of the keys
# due to template-driven configuration generation that can leave keys
# defined but values empty.
if command.get("interpreter"):
script_file = command.get("script_file")
if script_file:
if "script_inline" in command:
raise ValueError(
"Exactly one of script_inline or script_file with "
"interpreter is expected: %r" % command)
# User tries to upload a shell? Make sure it is same as interpreter
interpreter = command.get("interpreter")
interpreter = (interpreter[-1]
if isinstance(interpreter, (tuple, list))
else interpreter)
if (command.get("local_path") and
command.get("remote_path") != interpreter):
raise ValueError(
"When uploading an interpreter its path should be as well"
" specified as the `remote_path' string: %r" % command)
elif not command.get("remote_path"):
# No interpreter and no remote command to execute is given
raise ValueError(
"Supplied dict specifies no command to execute,"
" either interpreter or remote_path is required: %r" % command)
unexpected_keys = set(command) - set(["script_file", "script_inline",
"interpreter", "remote_path",
"local_path", "command_args"])
if unexpected_keys:
raise ValueError(
"Unexpected command parameters: %s" % ", ".join(unexpected_keys))
@validator
def valid_command(config, clients, deployment, param_name, required=True):
"""Checks that parameter is a proper command-specifying dictionary.
Ensure that the command dictionary is a proper command-specifying
dictionary described in `vmtasks.VMTasks.boot_runcommand_delete' docstring.
:param param_name: Name of parameter to validate
:param required: Boolean indicating that the command dictionary is required
"""
# TODO(amaretskiy): rework this validator into ResourceType, so this
# will allow to validate parameters values as well
command = config.get("args", {}).get(param_name)
if command is None and not required:
return ValidationResult(True)
try:
check_command_dict(command)
except ValueError as e:
return ValidationResult(False, str(e))
for key in "script_file", "local_path":
if command.get(key):
return _file_access_ok(
filename=command[key],
mode=os.R_OK,
param_name=param_name + "." + key,
required=True)
return ValidationResult(True)
def _get_validated_image(config, clients, param_name):
image_context = config.get("context", {}).get("images", {})
image_args = config.get("args", {}).get(param_name)
image_ctx_name = image_context.get("image_name")
if not image_args:
msg = _("Parameter %s is not specified.") % param_name
return (ValidationResult(False, msg), None)
if "image_name" in image_context:
# NOTE(rvasilets) check string is "exactly equal to" a regex
# or image name from context equal to image name from args
if "regex" in image_args:
match = re.match(image_args.get("regex"), image_ctx_name)
if image_ctx_name == image_args.get("name") or (
"regex" in image_args and match):
image = {
"size": image_context.get("min_disk", 0),
"min_ram": image_context.get("min_ram", 0),
"min_disk": image_context.get("min_disk", 0)
}
return (ValidationResult(True), image)
try:
image_id = openstack_types.GlanceImage.transform(
clients=clients, resource_config=image_args)
image = clients.glance().images.get(image_id)
if hasattr(image, "to_dict"):
# NOTE(stpierre): Glance v1 images are objects that can be
# converted to dicts; Glance v2 images are already
# dict-like
image = image.to_dict()
if not image.get("size"):
image["size"] = 0
if not image.get("min_ram"):
image["min_ram"] = 0
if not image.get("min_disk"):
image["min_disk"] = 0
return (ValidationResult(True), image)
except (glance_exc.HTTPNotFound, exceptions.InvalidScenarioArgument):
message = _("Image '%s' not found") % image_args
return (ValidationResult(False, message), None)
def _get_flavor_from_context(config, flavor_value):
if "flavors" not in config.get("context", {}):
raise exceptions.InvalidScenarioArgument("No flavors context")
flavors = [flavors_ctx.FlavorConfig(**f)
for f in config["context"]["flavors"]]
resource = types.obj_from_name(resource_config=flavor_value,
resources=flavors, typename="flavor")
flavor = flavors_ctx.FlavorConfig(**resource)
flavor.id = "<context flavor: %s>" % flavor.name
return (ValidationResult(True), flavor)
def _get_validated_flavor(config, clients, param_name):
flavor_value = config.get("args", {}).get(param_name)
if not flavor_value:
msg = "Parameter %s is not specified." % param_name
return (ValidationResult(False, msg), None)
try:
flavor_id = openstack_types.Flavor.transform(
clients=clients, resource_config=flavor_value)
flavor = clients.nova().flavors.get(flavor=flavor_id)
return (ValidationResult(True), flavor)
except (nova_exc.NotFound, exceptions.InvalidScenarioArgument):
try:
return _get_flavor_from_context(config, flavor_value)
except exceptions.InvalidScenarioArgument:
pass
message = _("Flavor '%s' not found") % flavor_value
return (ValidationResult(False, message), None)
@validator
def validate_share_proto(config, clients, deployment):
"""Validates value of share protocol for creation of Manila share."""
allowed = ("NFS", "CIFS", "GLUSTERFS", "HDFS", )
share_proto = config.get("args", {}).get("share_proto")
if six.text_type(share_proto).upper() not in allowed:
message = _("Share protocol '%(sp)s' is invalid, allowed values are "
"%(allowed)s.") % {"sp": share_proto,
"allowed": "', '".join(allowed)}
return ValidationResult(False, message)
@validator
def image_exists(config, clients, deployment, param_name, nullable=False):
"""Returns validator for image_id
:param param_name: defines which variable should be used
to get image id value.
:param nullable: defines image id param is required
"""
image_value = config.get("args", {}).get(param_name)
if not image_value | |
# 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
from . import outputs
from ._inputs import *
__all__ = ['AppServiceArgs', 'AppService']
@pulumi.input_type
class AppServiceArgs:
def __init__(__self__, *,
app_service_plan_id: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
app_settings: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
auth_settings: Optional[pulumi.Input['AppServiceAuthSettingsArgs']] = None,
backup: Optional[pulumi.Input['AppServiceBackupArgs']] = None,
client_affinity_enabled: Optional[pulumi.Input[bool]] = None,
client_cert_enabled: Optional[pulumi.Input[bool]] = None,
connection_strings: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceConnectionStringArgs']]]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
https_only: Optional[pulumi.Input[bool]] = None,
identity: Optional[pulumi.Input['AppServiceIdentityArgs']] = None,
location: Optional[pulumi.Input[str]] = None,
logs: Optional[pulumi.Input['AppServiceLogsArgs']] = None,
name: Optional[pulumi.Input[str]] = None,
site_config: Optional[pulumi.Input['AppServiceSiteConfigArgs']] = None,
source_control: Optional[pulumi.Input['AppServiceSourceControlArgs']] = None,
storage_accounts: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceStorageAccountArgs']]]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a AppService resource.
:param pulumi.Input[str] app_service_plan_id: The ID of the App Service Plan within which to create this App Service.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which to create the App Service.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] app_settings: A key-value pair of App Settings.
:param pulumi.Input['AppServiceAuthSettingsArgs'] auth_settings: A `auth_settings` block as defined below.
:param pulumi.Input['AppServiceBackupArgs'] backup: A `backup` block as defined below.
:param pulumi.Input[bool] client_affinity_enabled: Should the App Service send session affinity cookies, which route client requests in the same session to the same instance?
:param pulumi.Input[bool] client_cert_enabled: Does the App Service require client certificates for incoming requests? Defaults to `false`.
:param pulumi.Input[Sequence[pulumi.Input['AppServiceConnectionStringArgs']]] connection_strings: One or more `connection_string` blocks as defined below.
:param pulumi.Input[bool] enabled: Is the App Service Enabled?
:param pulumi.Input[bool] https_only: Can the App Service only be accessed via HTTPS? Defaults to `false`.
:param pulumi.Input['AppServiceIdentityArgs'] identity: A Managed Service Identity block as defined below.
:param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
:param pulumi.Input['AppServiceLogsArgs'] logs: A `logs` block as defined below.
:param pulumi.Input[str] name: Specifies the name of the App Service. Changing this forces a new resource to be created.
:param pulumi.Input['AppServiceSiteConfigArgs'] site_config: A `site_config` block as defined below.
:param pulumi.Input['AppServiceSourceControlArgs'] source_control: A Source Control block as defined below
:param pulumi.Input[Sequence[pulumi.Input['AppServiceStorageAccountArgs']]] storage_accounts: One or more `storage_account` blocks as defined below.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags to assign to the resource.
"""
pulumi.set(__self__, "app_service_plan_id", app_service_plan_id)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if app_settings is not None:
pulumi.set(__self__, "app_settings", app_settings)
if auth_settings is not None:
pulumi.set(__self__, "auth_settings", auth_settings)
if backup is not None:
pulumi.set(__self__, "backup", backup)
if client_affinity_enabled is not None:
pulumi.set(__self__, "client_affinity_enabled", client_affinity_enabled)
if client_cert_enabled is not None:
pulumi.set(__self__, "client_cert_enabled", client_cert_enabled)
if connection_strings is not None:
pulumi.set(__self__, "connection_strings", connection_strings)
if enabled is not None:
pulumi.set(__self__, "enabled", enabled)
if https_only is not None:
pulumi.set(__self__, "https_only", https_only)
if identity is not None:
pulumi.set(__self__, "identity", identity)
if location is not None:
pulumi.set(__self__, "location", location)
if logs is not None:
pulumi.set(__self__, "logs", logs)
if name is not None:
pulumi.set(__self__, "name", name)
if site_config is not None:
pulumi.set(__self__, "site_config", site_config)
if source_control is not None:
pulumi.set(__self__, "source_control", source_control)
if storage_accounts is not None:
pulumi.set(__self__, "storage_accounts", storage_accounts)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="appServicePlanId")
def app_service_plan_id(self) -> pulumi.Input[str]:
"""
The ID of the App Service Plan within which to create this App Service.
"""
return pulumi.get(self, "app_service_plan_id")
@app_service_plan_id.setter
def app_service_plan_id(self, value: pulumi.Input[str]):
pulumi.set(self, "app_service_plan_id", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group in which to create the App Service.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="appSettings")
def app_settings(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A key-value pair of App Settings.
"""
return pulumi.get(self, "app_settings")
@app_settings.setter
def app_settings(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "app_settings", value)
@property
@pulumi.getter(name="authSettings")
def auth_settings(self) -> Optional[pulumi.Input['AppServiceAuthSettingsArgs']]:
"""
A `auth_settings` block as defined below.
"""
return pulumi.get(self, "auth_settings")
@auth_settings.setter
def auth_settings(self, value: Optional[pulumi.Input['AppServiceAuthSettingsArgs']]):
pulumi.set(self, "auth_settings", value)
@property
@pulumi.getter
def backup(self) -> Optional[pulumi.Input['AppServiceBackupArgs']]:
"""
A `backup` block as defined below.
"""
return pulumi.get(self, "backup")
@backup.setter
def backup(self, value: Optional[pulumi.Input['AppServiceBackupArgs']]):
pulumi.set(self, "backup", value)
@property
@pulumi.getter(name="clientAffinityEnabled")
def client_affinity_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Should the App Service send session affinity cookies, which route client requests in the same session to the same instance?
"""
return pulumi.get(self, "client_affinity_enabled")
@client_affinity_enabled.setter
def client_affinity_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "client_affinity_enabled", value)
@property
@pulumi.getter(name="clientCertEnabled")
def client_cert_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Does the App Service require client certificates for incoming requests? Defaults to `false`.
"""
return pulumi.get(self, "client_cert_enabled")
@client_cert_enabled.setter
def client_cert_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "client_cert_enabled", value)
@property
@pulumi.getter(name="connectionStrings")
def connection_strings(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceConnectionStringArgs']]]]:
"""
One or more `connection_string` blocks as defined below.
"""
return pulumi.get(self, "connection_strings")
@connection_strings.setter
def connection_strings(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceConnectionStringArgs']]]]):
pulumi.set(self, "connection_strings", value)
@property
@pulumi.getter
def enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Is the App Service Enabled?
"""
return pulumi.get(self, "enabled")
@enabled.setter
def enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enabled", value)
@property
@pulumi.getter(name="httpsOnly")
def https_only(self) -> Optional[pulumi.Input[bool]]:
"""
Can the App Service only be accessed via HTTPS? Defaults to `false`.
"""
return pulumi.get(self, "https_only")
@https_only.setter
def https_only(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "https_only", value)
@property
@pulumi.getter
def identity(self) -> Optional[pulumi.Input['AppServiceIdentityArgs']]:
"""
A Managed Service Identity block as defined below.
"""
return pulumi.get(self, "identity")
@identity.setter
def identity(self, value: Optional[pulumi.Input['AppServiceIdentityArgs']]):
pulumi.set(self, "identity", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter
def logs(self) -> Optional[pulumi.Input['AppServiceLogsArgs']]:
"""
A `logs` block as defined below.
"""
return pulumi.get(self, "logs")
@logs.setter
def logs(self, value: Optional[pulumi.Input['AppServiceLogsArgs']]):
pulumi.set(self, "logs", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Specifies the name of the App Service. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="siteConfig")
def site_config(self) -> Optional[pulumi.Input['AppServiceSiteConfigArgs']]:
"""
A `site_config` block as defined below.
"""
return pulumi.get(self, "site_config")
@site_config.setter
def site_config(self, value: Optional[pulumi.Input['AppServiceSiteConfigArgs']]):
pulumi.set(self, "site_config", value)
@property
@pulumi.getter(name="sourceControl")
def source_control(self) -> Optional[pulumi.Input['AppServiceSourceControlArgs']]:
"""
A Source Control block as defined below
"""
return pulumi.get(self, "source_control")
@source_control.setter
def source_control(self, value: Optional[pulumi.Input['AppServiceSourceControlArgs']]):
pulumi.set(self, "source_control", value)
@property
@pulumi.getter(name="storageAccounts")
def storage_accounts(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceStorageAccountArgs']]]]:
"""
One or more `storage_account` blocks as defined below.
"""
return pulumi.get(self, "storage_accounts")
@storage_accounts.setter
def storage_accounts(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceStorageAccountArgs']]]]):
pulumi.set(self, "storage_accounts", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
@pulumi.input_type
class _AppServiceState:
def __init__(__self__, *,
app_service_plan_id: Optional[pulumi.Input[str]] = None,
app_settings: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
auth_settings: Optional[pulumi.Input['AppServiceAuthSettingsArgs']] = None,
backup: Optional[pulumi.Input['AppServiceBackupArgs']] = None,
client_affinity_enabled: Optional[pulumi.Input[bool]] = None,
client_cert_enabled: Optional[pulumi.Input[bool]] = None,
connection_strings: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceConnectionStringArgs']]]] = None,
custom_domain_verification_id: Optional[pulumi.Input[str]] = None,
default_site_hostname: Optional[pulumi.Input[str]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
https_only: Optional[pulumi.Input[bool]] = None,
identity: Optional[pulumi.Input['AppServiceIdentityArgs']] = None,
location: Optional[pulumi.Input[str]] = None,
logs: Optional[pulumi.Input['AppServiceLogsArgs']] = None,
name: Optional[pulumi.Input[str]] = None,
outbound_ip_address_lists: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
outbound_ip_addresses: Optional[pulumi.Input[str]] = None,
possible_outbound_ip_address_lists: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
possible_outbound_ip_addresses: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
site_config: Optional[pulumi.Input['AppServiceSiteConfigArgs']] = None,
site_credentials: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceSiteCredentialArgs']]]] = None,
source_control: Optional[pulumi.Input['AppServiceSourceControlArgs']] = None,
storage_accounts: Optional[pulumi.Input[Sequence[pulumi.Input['AppServiceStorageAccountArgs']]]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
Input properties used for looking up and filtering AppService resources.
:param pulumi.Input[str] app_service_plan_id: The ID of the App Service Plan within which to create this App Service.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] app_settings: A key-value pair of App Settings.
:param pulumi.Input['AppServiceAuthSettingsArgs'] auth_settings: A `auth_settings` block as defined below.
:param pulumi.Input['AppServiceBackupArgs'] backup: A `backup` block as defined below.
:param pulumi.Input[bool] client_affinity_enabled: Should the App Service send session affinity cookies, which route client requests in the same session to the same instance?
:param pulumi.Input[bool] client_cert_enabled: Does the App Service require client certificates for incoming requests? Defaults to `false`.
:param pulumi.Input[Sequence[pulumi.Input['AppServiceConnectionStringArgs']]] connection_strings: One or more `connection_string` blocks as defined below.
:param pulumi.Input[str] custom_domain_verification_id: An identifier used by App Service to perform domain ownership verification via DNS TXT record.
:param pulumi.Input[str] default_site_hostname: The Default Hostname associated with the App Service - | |
<reponame>jgoodknight/spectroscopy<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 04 13:23:27 2013
Gone through for release 10 Feb 2017
@author: Joey
"""
import copy
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate
import scipy.interpolate
import Spacetime
class timeFunction(object):
"""
Abstract class to keep track of useful items for a function in time.
Must have a defined beginning and end, before and after which the function
is identically zero
"""
#Override arithmetic functions
def __mul__(self, other):
if isinstance(other, zeroTimeFunction):
return other
out = copy.copy(self)
out.myFunction = lambda t: self.myFunction(t) * other.myFunction(t)
return out
def __add__(self, other):
if isinstance(other, zeroTimeFunction):
return self
out = copy.copy(self)
out.myFunction = lambda t: self.myFunction(t) + other.myFunction(t)
newMin = min(out.timeRangeTuple[0], other.timeRangeTuple[0])
newMax = max(out.timeRangeTuple[1], other.timeRangeTuple[1])
out.timeRangeTuple = (newMin, newMax)
return out
def plot(self, nPoints = 2000):
"Plots from user-defined beginning to end of function for specified number of points"
plt.figure()
tVals = np.linspace(self.timeRangeTuple[0], self.timeRangeTuple[1], nPoints)
t = self.mySpace.unitHandler.femtosecondsFromTime(tVals)
fValues = self.myFunction(tVals)
plt.plot(t, fValues)
plt.xlabel(r"$t$ (fs)")
def plotInSimulationSpace(self):
"Plots using beginning/end and dt from mySpace"
plt.figure()
tVals = np.arange(self.timeRangeTuple[0], self.timeRangeTuple[1] + self.mySpace.dt, self.mySpace.dt)
t = self.mySpace.unitHandler.femtosecondsFromTime(tVals)
fValues = self.myFunction(tVals)
plt.plot(t, fValues)
plt.xlabel(r"$t$ (fs)")
def plotFT(self, maxFrequency, resolution):
"Plots the Fourier Transform of the function"
plt.figure()
w, s = self.fourierTransform(maxFrequency, resolution)
w = self.mySpace.unitHandler.wavenumbersFromEnergyUnits(w)
plt.plot(w, np.abs(s))
plt.xlabel(r"$\omega$ (cm$^{-1}$)")
def FT(self, maxFrequency, resolution):
"returns the Fourier Transform frewuency in wavenumbers and the amplitude"
w, s = self.fourierTransform(maxFrequency, resolution)
w = self.mySpace.unitHandler.wavenumbersFromEnergyUnits(w)
return w, s
def fourierTransform(self, maxFrequency, resolution):
tMax = 1.0 / resolution
N = maxFrequency / resolution
tValues = np.linspace(-tMax, tMax, N)
fValues = self.myFunction(tValues)
return self.mySpace.genericOneDimensionalFourierTransformFromZero(tValues, fValues, gaussianFilter=False)
def valueAtTime(self, t):
return self.myFunction(t)
def maxTime(self):
return self.timeRangeTuple[1]
def minTime(self):
return self.timeRangeTuple[0]
def shiftForward(self, deltaT):
self.T = self.T + deltaT
self.timeRangeTuple = (self.timeRangeTuple[0] + deltaT, self.timeRangeTuple[1] + deltaT)
return self
def integrate(self, dt):
"Integrates Amplitude to desired dt"
DT = dt
tValues = np.arange(self.minTime(), self.maxTime() + DT, DT)
Values = self.valueAtTime(tValues)
return scipy.integrate.simps(Values, dx = DT)
def integrateInSimulationSpace(self):
"Integrates Amplitude to mySpace.dt"
return self.integrate(self.mySpace.dt)
def setPhase(self, newPhase):
self.phi = newPhase
class zeroTimeFunction(timeFunction):
"A Time Function smart enough to know it's zero"
def __init__(self, space):
self.mySpace = space
self.myFunction = 0.0
self.timeRangeTuple = (np.inf, -np.inf)
self.timePillow = 0.0
self.T = 0.0
self.sigma = 0
def valueAtTime(self, t):
try:
return np.zeros(t.shape)
except:
return 0.0
def shiftForward(self, deltaT):
return self
def integrate(self, a):
return 0.0
def totalPower(self):
return 0.0
def plusFunction(self):
return zeroTimeFunction(self.mySpace)
def minusFunction(self):
return zeroTimeFunction(self.mySpace)
def pulseCopyAtNewTime(self, newTime):
return self
def pulseCopyJumpedForward(self, amountOfTimeToJumpForward):
return self
def fourierTransform(self):
return zeroTimeFunction(self.mySpace)
def myFourierTransformedFunction(self, w):
return np.zeros(w.shape)
class deltaFunction(timeFunction):
"A Function with ampltiude a/dt at specified time=loaction"
def __init__(self, space, location, dt=None):
self.mySpace = space
if dt is None:
self.DT = self.mySpace.dt
else:
self.DT = dt
self.height = 1.0 / self.mySpace.dt
self.T = location
self.timePillow = 5.0 * self.mySpace.dt #just to be safe
self.timeRangeTuple = (location - self.DT, location + self.DT)
def valueAtTime(self, t):
try:
t.shape
except:
if np.abs(t - self.T) < self.DT:
return self.height
else:
return 0.0
ones = np.ones(t.shape)
zeros = np.zeros(t.shape)
output = np.where(np.abs(t - self.T) > self.DT, zeros, ones)
return output * self.height
def pulseCopyAtNewTime(self, newTime):
output = copy.deepcopy(self)
output.T = newTime
return output
def pulseCopyJumpedForward(self, amountOfTimeToJumpForward):
output = copy.deepcopy(self)
output.T = amountOfTimeToJumpForward + self.T
return output
def totalPower(self):
return 1.0
class GaussianPulse(timeFunction):
"An abstract object to hold useful methods for dealing with Gaussian pulses"
def __init__(self,
space,
centerOmega,
timeSpread,
centerTime=None,
pulseDirection = None,
phi = 0.0,
amplitude = 1.00E-8,
normalizePower = False,
normalizeIntegral = True,
frequency_sign = 1.0):
self.mySpace = space
if pulseDirection is None: #not important yet, may be implemented later
pass
self.omega = centerOmega
self.sigma = timeSpread
self.phi = 0
self.k = pulseDirection
targetTimePillow = 6.0 * self.sigma #amount of padding needed between center of pulse and esdge of time
nDtInTargetPillow = np.ceil(targetTimePillow / self.mySpace.dt) + 1
self.timePillow = nDtInTargetPillow * self.mySpace.dt
#if no time is specified, then just give the pulse the needed pillow
if centerTime == None:
centerTime = self.timePillow
self.frequency_sign = frequency_sign
#search for the closest index to the specified center time
self.T = centerTime
self.timeRangeTuple = (self.T - self.timePillow, self.T + self.timePillow)
#the goal is to normalize the power or integral of the square of the function to one
self.amp = amplitude #start here; this is needed to make the function work
if normalizePower:
normalizer = self.totalPower()
self.amp = self.amp / math.sqrt(normalizer)
if normalizeIntegral:
normalizer = self.totalIntegral()
self.amp = self.amp / normalizer
def shiftToCenterTime(self, newT):
"Gives pulse a new center time"
delta_T = newT - self.T
self.T = newT
self.timeRangeTuple = (self.timeRangeTuple[0] + delta_T, self.timeRangeTuple[1] + delta_T)
def totalPower(self):
"Integral of the absolute value squared of the amplitude"
DT = self.mySpace.dt #/ 10.0
tValues = np.arange(self.minTime(), self.maxTime(), DT)
Values = np.abs(self.valueAtTime(tValues))**2.0
return scipy.integrate.simps(Values, dx = DT)
def totalIntegral(self):
"Integral of the absolute value of the amplitude"
DT = self.mySpace.dt #/ 10.0
tValues = np.arange(self.minTime(), self.maxTime(), DT)
Values = np.abs(self.valueAtTime(tValues))
return scipy.integrate.simps(Values, dx = DT)
def pulseCopyAtNewTime(self, newTime):
"Make copy and move to new time"
output = copy.deepcopy(self)
output.T = newTime
return output
def pulseCopyJumpedForward(self, amountOfTimeToJumpForward):
"Make copy and jump the pulse forward"
output = copy.deepcopy(self)
output.T = amountOfTimeToJumpForward + self.T
return output
class GaussianPulseTooCloseToEdgeOfTimeException(Exception):
def __init__(self, value):
self.value = value
class GaussianCosinePulse(GaussianPulse):
"Completely Real Pulse"
def myFunction(self, t):
coef = self.amp
shiftedTime = t - self.T
cosArg = -self.omega * shiftedTime + self.phi
cosTerm = np.cos(cosArg)
gausArg = -shiftedTime**2.0 / (2.0 * self.sigma**2.0)
gausTerm = np.exp(gausArg)
return coef * cosTerm * gausTerm
def myFourierTransformedFunction(self, w):
return self.minusFunction().myFourierTransformedFunction(w) + self.plusFunction().myFourierTransformedFunction(w)
def plusFunction(self):
return GaussianKPlusPulse(
self.mySpace,
self.omega,
self.sigma,
self.T,
self.k,
self.phi,
self.amp / 2.0,
normalizePower = False,
normalizeIntegral = False,
frequency_sign = -1.0)
def minusFunction(self):
return GaussianKMinusPulse(
self.mySpace,
self.omega,
self.sigma,
self.T,
self.k,
self.phi,
self.amp / 2.0,
normalizePower = False,
normalizeIntegral = False,
frequency_sign = 1.0)
class GaussianKPlusPulse(GaussianPulse):
"'Forward' Pulse which is complex and has positive energy"
def myFunction(self, t):
coef = self.amp
shiftedTime = t - self.T
expArg = -self.omega * shiftedTime + self.phi
expTerm = np.exp(1.0j * expArg)
gausArg = -shiftedTime**2.0 / (2.0 * self.sigma**2)
gausTerm = np.exp(gausArg)
return coef * expTerm * gausTerm
def myFourierTransformedFunction(self, w):
"""Defined as $\int e^{i \omega t} E(t) dt $ """
coef = self.amp * np.sqrt(2.0 * np.pi * self.sigma**2.0)
oscPart = np.exp(1.0j *w * self.T)
expPart = np.exp(-self.sigma**2 * (self.omega - w)**2 / 2.0)
return coef * oscPart * expPart
class GaussianKMinusPulse(GaussianPulse):
"'Backward' Pulse which is complex and negative energy"
def myFunction(self, t):
coef = self.amp
shiftedTime = t - self.T
expArg = self.omega * shiftedTime - self.phi
expTerm = np.exp(1.0j * expArg)
gausArg = -shiftedTime**2.0 / (2.0 * self.sigma**2.0)
gausTerm = np.exp(gausArg)
return coef * expTerm * gausTerm
def myFourierTransformedFunction(self, w):
"""Defined as $\int e^{i \omega t} E(t) dt $ """
coef = self.amp * np.sqrt(2.0 * np.pi * self.sigma**2.0)
oscPart = np.exp(1.0j *w * self.T)
expPart = np.exp(-self.sigma**2 * (self.omega + w)**2 / 2.0)
return coef * oscPart * expPart
class GaussianRazorBladedPulse(timeFunction):
"Object to handle a pulse which has been razor-bladed in frequency space"
k_MULTIPLIER = 80000000.0
time_window_high_frequency_multiplier = 10.0
time_domain_multiplier = 40
ZERO_TOLERANCE = 1.0E-3
def __init__(self, gaussian_pulse, cutoff_omega_low, cutoff_omega_high):
self.my_underlying_pulse = copy.deepcopy(gaussian_pulse)
self.mySpace = self.my_underlying_pulse.mySpace
self.low_frequency_cutoff = cutoff_omega_low
self.high_frequency_cutoff = cutoff_omega_high
self.T = gaussian_pulse.T
self.sigma = gaussian_pulse.sigma
self.frequency_sign = gaussian_pulse.frequency_sign
self.omega = gaussian_pulse.omega
self.k = GaussianRazorBladedPulse.k_MULTIPLIER / gaussian_pulse.mySpace.dt
self.normalizer | |
<reponame>vwesselkamp/deepfake-fingerprint-atacks<gh_stars>0
# Get Python six functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from builtins import range, zip
import six
###############################################################################
###############################################################################
###############################################################################
import inspect
import tensorflow.keras.backend as K
import tensorflow.keras.layers as keras_layers
import tensorflow.keras.models as keras_models
import numpy as np
import warnings
from tensorflow.python.keras.engine.input_layer import InputLayer
from . import checks as kchecks
from ... import layers as ilayers
from ... import utils as iutils
__all__ = [
"get_kernel",
"get_layer_inbound_count",
"get_layer_outbound_count",
"get_layer_neuronwise_io",
"copy_layer_wo_activation",
"copy_layer",
"pre_softmax_tensors",
"model_wo_softmax",
"fake_keras_layer",
"get_model_layers",
"model_contains",
"trace_model_execution",
"get_model_execution_trace",
"get_model_execution_graph",
"print_model_execution_graph",
"get_bottleneck_nodes",
"get_bottleneck_tensors",
"ReverseMappingBase",
"reverse_model",
]
###############################################################################
###############################################################################
###############################################################################
def get_kernel(layer):
"""Returns the kernel weights of a layer, i.e, w/o biases."""
ret = [x for x in layer.get_weights() if len(x.shape) > 1]
assert len(ret) == 1
return ret[0]
def get_input_layers(layer):
"""Returns all layers that created this layer's inputs."""
ret = set()
for node_index in range(len(layer._inbound_nodes)):
Xs = iutils.to_list(layer.get_input_at(node_index))
for X in Xs:
ret.add(X._keras_history[0])
return ret
###############################################################################
###############################################################################
###############################################################################
def get_layer_inbound_count(layer):
"""Returns the number inbound nodes of a layer."""
return len(layer._inbound_nodes)
def get_layer_outbound_count(layer):
"""Returns the number outbound nodes of a layer."""
return len(layer.outbound_nodes)
def get_layer_neuronwise_io(layer,
node_index=0,
Xs=None,
Ys=None,
return_i=True,
return_o=True):
"""Returns the input and output for each neuron in a layer
Returns the symbolic input and output for each neuron in a layer.
For a dense layer this is the input output itself.
For convolutional layers this method extracts for each neuron
the input output mapping.
At the moment this function is designed
to work with dense and conv2d layers.
:param layer: The targeted layer.
:param node_index: Index of the layer node to use.
:param Xs: Ignore the layer's input but use Xs instead.
:param Ys: Ignore the layer's output but use Ys instead.
:param return_i: Return the inputs.
:param return_o: Return the outputs.
:return: Inputs and outputs, if specified, for each individual neuron.
"""
if not kchecks.contains_kernel(layer):
raise NotImplementedError()
if Xs is None:
Xs = iutils.to_list(layer.get_input_at(node_index))
if Ys is None:
Ys = iutils.to_list(layer.get_output_at(node_index))
if isinstance(layer, keras_layers.Dense):
# Xs and Ys are already in shape.
ret_Xs = Xs
ret_Ys = Ys
elif isinstance(layer, keras_layers.Conv2D):
kernel = get_kernel(layer)
# Expect filter dimension to be last.
n_channels = kernel.shape[-1]
if return_i:
extract_patches = ilayers.ExtractConv2DPatches(kernel.shape[:2],
kernel.shape[2],
layer.strides,
layer.dilation_rate,
layer.padding)
# shape [samples, out_row, out_col, weight_size]
reshape = ilayers.Reshape((-1, np.product(kernel.shape[:3])))
ret_Xs = [reshape(extract_patches(x)) for x in Xs]
if return_o:
# Get Ys into shape (samples, channels)
if K.image_data_format() == "channels_first":
# Ys shape is [samples, channels, out_row, out_col]
def reshape(x):
x = ilayers.Transpose((0, 2, 3, 1))(x)
x = ilayers.Reshape((-1, n_channels))(x)
return x
else:
# Ys shape is [samples, out_row, out_col, channels]
def reshape(x):
x = ilayers.Reshape((-1, n_channels))(x)
return x
ret_Ys = [reshape(x) for x in Ys]
else:
raise NotImplementedError()
# Xs is (n, d) and Ys is (d, channels)
if return_i and return_o:
return ret_Xs, ret_Ys
elif return_i:
return ret_Xs
elif return_o:
return ret_Ys
else:
raise Exception()
def get_symbolic_weight_names(layer, weights=None):
"""Attribute names for weights
Looks up the attribute names of weight tensors.
:param layer: Targeted layer.
:param weights: A list of weight tensors.
:return: The attribute names of the weights.
"""
if weights is None:
weights = layer.weights
good_guesses = [
"kernel",
"bias",
"gamma",
"beta",
"moving_mean",
"moving_variance",
"depthwise_kernel",
"pointwise_kernel"
]
ret = []
for weight in weights:
for attr_name in good_guesses+dir(layer):
if(hasattr(layer, attr_name) and
id(weight) == id(getattr(layer, attr_name))):
ret.append(attr_name)
break
if len(weights) != len(ret):
raise Exception("Could not find symoblic weight name(s).")
return ret
def update_symbolic_weights(layer, weight_mapping):
"""Updates the symbolic tensors of a layer
Updates the symbolic tensors of a layer by replacing them.
Note this does not update the loss or anything alike!
Use with caution!
:param layer: Targeted layer.
:param weight_mapping: Dict with attribute name and weight tensors
as keys and values.
"""
trainable_weight_ids = [id(x) for x in layer._trainable_weights]
non_trainable_weight_ids = [id(x) for x in layer._non_trainable_weights]
for name, weight in six.iteritems(weight_mapping):
current_weight = getattr(layer, name)
current_weight_id = id(current_weight)
if current_weight_id in trainable_weight_ids:
idx = trainable_weight_ids.index(current_weight_id)
layer._trainable_weights[idx] = weight
else:
idx = non_trainable_weight_ids.index(current_weight_id)
layer._non_trainable_weights[idx] = weight
setattr(layer, name, weight)
def get_layer_from_config(old_layer,
new_config,
weights=None,
reuse_symbolic_tensors=True):
"""Creates a new layer from a config
Creates a new layer given a changed config and weights etc.
:param old_layer: A layer that shall be used as base.
:param new_config: The config to create the new layer.
:param weights: Weights to set in the new layer.
Options: np tensors, symbolic tensors, or None,
in which case the weights from old_layers are used.
:param reuse_symbolic_tensors: If the weights of the
old_layer are used copy the symbolic ones or copy
the Numpy weights.
:return: The new layer instance.
"""
new_layer = old_layer.__class__.from_config(new_config)
if weights is None:
if reuse_symbolic_tensors:
weights = old_layer.weights
else:
weights = old_layer.get_weights()
if len(weights) > 0:
input_shapes = old_layer.get_input_shape_at(0)
# todo: inspect and set initializers to something fast for speedup
new_layer.build(input_shapes)
is_np_weight = [isinstance(x, np.ndarray) for x in weights]
if all(is_np_weight):
new_layer.set_weights(weights)
else:
if any(is_np_weight):
raise ValueError("Expect either all weights to be "
"np tensors or symbolic tensors.")
symbolic_names = get_symbolic_weight_names(old_layer)
update = {name: weight
for name, weight in zip(symbolic_names, weights)}
update_symbolic_weights(new_layer, update)
return new_layer
def copy_layer_wo_activation(layer,
keep_bias=True,
name_template=None,
weights=None,
reuse_symbolic_tensors=True,
**kwargs):
"""Copy a Keras layer and remove the activations
Copies a Keras layer but remove potential activations.
:param layer: A layer that should be copied.
:param keep_bias: Keep a potential bias.
:param weights: Weights to set in the new layer.
Options: np tensors, symbolic tensors, or None,
in which case the weights from old_layers are used.
:param reuse_symbolic_tensors: If the weights of the
old_layer are used copy the symbolic ones or copy
the Numpy weights.
:return: The new layer instance.
"""
config = layer.get_config()
if name_template is None:
config["name"] = None
else:
config["name"] = name_template % config["name"]
if kchecks.contains_activation(layer):
config["activation"] = None
if hasattr(layer, "use_bias"):
if keep_bias is False and config.get("use_bias", True):
config["use_bias"] = False
if weights is None:
if reuse_symbolic_tensors:
weights = layer.weights[:-1]
else:
weights = layer.get_weights()[:-1]
return get_layer_from_config(layer, config, weights=weights, **kwargs)
def copy_layer(layer,
keep_bias=True,
name_template=None,
weights=None,
reuse_symbolic_tensors=True,
**kwargs):
"""Copy a Keras layer
Copies a Keras layer.
:param layer: A layer that should be copied.
:param keep_bias: Keep a potential bias.
:param weights: Weights to set in the new layer.
Options: np tensors, symbolic tensors, or None,
in which case the weights from old_layers are used.
:param reuse_symbolic_tensors: If the weights of the
old_layer are used copy the symbolic ones or copy
the Numpy weights.
:return: The new layer instance.
"""
config = layer.get_config()
if name_template is None:
config["name"] = None
else:
config["name"] = name_template % config["name"]
if hasattr(layer, "use_bias"):
if keep_bias is False and config.get("use_bias", True):
config["use_bias"] = False
if weights is None:
if reuse_symbolic_tensors:
weights = layer.weights[:-1]
else:
weights = layer.get_weights()[:-1]
return get_layer_from_config(layer, config, weights=weights, **kwargs)
def pre_softmax_tensors(Xs, should_find_softmax=True):
"""Finds the tensors that were preceeding a potential softmax."""
softmax_found = False
Xs = iutils.to_list(Xs)
ret = []
for x in Xs:
layer, node_index, tensor_index = x._keras_history
if kchecks.contains_activation(layer, activation="softmax"):
softmax_found = True
if isinstance(layer, keras_layers.Activation):
ret.append(layer.get_input_at(node_index))
else:
layer_wo_act = copy_layer_wo_activation(layer)
ret.append(layer_wo_act(layer.get_input_at(node_index)))
if should_find_softmax and not softmax_found:
raise Exception("No softmax found.")
return ret
def model_wo_softmax(model):
"""Creates a new model w/o the final softmax activation."""
return keras_models.Model(inputs=model.inputs,
outputs=pre_softmax_tensors(model.outputs),
name=model.name)
def fake_keras_layer(inputs, outputs):
if not all([hasattr(x, "_keras_history") for x in outputs]):
# Fake a layer
def f(tensors):
return outputs
if len(inputs):
output_shape = K.int_shape(inputs[0])
else:
output_shape = None
outputs = keras_layers.Lambda(f, output_shape=output_shape)(inputs)
outputs = iutils.to_list(outputs)
return outputs
###############################################################################
###############################################################################
###############################################################################
def get_model_layers(model):
"""Returns all layers of a model."""
ret = []
def collect_layers(container):
for layer in container.layers:
assert layer not in ret
ret.append(layer)
if kchecks.is_network(layer):
collect_layers(layer)
collect_layers(model)
return ret
def model_contains(model, layer_condition, return_only_counts=False):
if callable(layer_condition):
layer_condition = [layer_condition, ]
single_condition = True
else:
single_condition = False
layers = get_model_layers(model)
collected_layers = []
for condition in layer_condition:
tmp = [layer for layer in layers if condition(layer)]
collected_layers.append(tmp)
if return_only_counts is True:
collected_layers = [len(v) for v in collected_layers]
if single_condition is True:
return collected_layers[0]
else:
return collected_layers
###############################################################################
###############################################################################
###############################################################################
def apply_mapping_to_fused_bn_layer(mapping, fuse_mode="one_linear"):
"""
Applies a mapping to a linearized Batch Normalization layer.
:param mapping: The mapping to be applied.
Should take parameters layer and reverse_state and
return a mapping function.
:param fuse_mode: Either 'one_linear': apply the mapping
to a once linearized layer, or
| |
"%s = %d;" % (dim, 537), file=out ) # Could be randomized
print( file=out)
# Initialize operands (with structure if needed)
print( "% Initialize operands", file=out )
for operand in inop:
name = operand.get_name()
r, c = operand.get_size()
if isLowerTriangular( operand ):
print( "%% %s is lower triangular" % name, file=out )
#print( "%s = tril(rand(%s, %s));" % (name, r, c), file=out )
# [FIX] Just for conditioning purposes
print( "%s = tril(rand(%s, %s)) + %s * eye(%s);" % (name, r, c, r, r), file=out )
elif isUpperTriangular( operand ):
print( "%% %s is upper triangular" % name, file=out )
#print( "%s = triu(rand(%s, %s));" % (name, r, c), file=out )
# [FIX] Just for conditioning purposes
print( "%s = triu(rand(%s, %s)) + %s * eye(%s);" % (name, r, c, r, r), file=out )
elif isSPD( operand ):
print( "%% %s is SPD" % name, file=out )
print( "%s = rand(%s, %s);" % (name, r, c), file=out )
print( "%s = %s + %s' + %s*eye(%s);" % (name, name, name, r, r), file=out )
elif isSymmetric( operand ):
print( "%% %s is symmetric" % name, file=out )
print( "%s = rand(%s, %s);" % (name, r, c), file=out )
print( "%s = %s + %s';" % (name, name, name), file=out )
else:
print( "%% %s is general" % name, file=out )
print( "%s = rand(%s, %s);" % (name, r, c), file=out )
print( file=out)
## Test recursive implementation
#print( "% Test recursive implementation", file=out )
#print( "[%s] = %s( %s );" % (", ".join(outop_str), operation.name, ", ".join(inop_str)), file=out )
#for eq in operation.equation:
#lhs, rhs = eq.get_children()
##print( "fprintf('Norm: %%.15e\\n', norm( (%s) - (%s) ));" % (click2matlab(lhs), click2matlab(rhs)), file=out )
#print( "fprintf('Norm: %%.15e\\n', norm( (%s) - (%s) ));" % (lhs, click2matlab(rhs)), file=out )
#print( file=out)
# Test loop-based implementations
print( "% Test loop-based implementations", file=out )
for dim in dims:
if dim == "1":
continue
print("%sb = %d;" % (dim, 160), file=out)
print( file=out )
for algs_per_pme in operation.algs[1:]: # [FIXME] Not the first pme 1x1, copy actually produces an empty alg here
for alg in algs_per_pme:
alg_output = ", ".join(outop_str)
alg_input = ", ".join(inop_str)
alg_blks = ", ".join([ "%sb" % dim for dim in dims if dim != "1" ])
print( "[%s] = %s( %s, %s );" % (alg_output, alg.name, alg_input, alg_blks), file=out )
for op in outop:
#op_name = op.st_info[1].get_name()
op_name = op.get_name()
if isSymmetric(op):
if op.st_info[0] == ST_LOWER:
print("%s = tril(%s) + tril(%s,-1)';" % (op_name, op_name, op_name), file=out)
else: # ST_UPPER
print("%s = triu(%s) + triu(%s,1)';" % (op_name, op_name, op_name), file=out)
elif isLowerTriangular(op):
print("%s = tril(%s);" % (op_name, op_name), file=out)
elif isUpperTriangular(op):
print("%s = triu(%s);" % (op_name, op_name), file=out)
for eq in operation.equation:
lhs, rhs = eq.get_children()
print( "fprintf('Norm: %%.15e\\n', norm( (%s) - (%s) ));" % (click2matlab(lhs), click2matlab(rhs)), file=out )
#print( "fprintf('Norm: %%.15e\\n', norm( (%s) - (%s) ));" % (lhs, click2matlab(rhs)), file=out )
print( file=out )
print( "quit", file=out )
#
# Pretty printing a la FLAME
#
def pretty_print_fla_obj_decl( shape, part, repart, indent ):
if tuple(shape) == (3, 3):
return pretty_print_fla_obj_decl_2x2( part, repart, indent )
elif tuple(shape) == (1, 3):
return pretty_print_fla_obj_decl_1x2( part, repart, indent )
elif tuple(shape) == (3, 1):
return pretty_print_fla_obj_decl_2x1( part, repart, indent )
print( shape )
raise Exception
def pretty_print_fla_obj_decl_2x2( part, repart, indent ):
# To string!
ATL, ATR, \
ABL, ABR = part
ATL = str(ATL)
ATR = str(ATR)
ABL = str(ABL)
ABR = str(ABR)
A00, A01, A02, \
A10, A11, A12, \
A20, A21, A22 = repart
A00 = str(A00)
A01 = str(A01)
A02 = str(A02)
A10 = str(A10)
A11 = str(A11)
A12 = str(A12)
A20 = str(A20)
A21 = str(A21)
A22 = str(A22)
# Type
type = "FLA_Obj "
# spacing
spacing = " "
secondary_indent = indent + " "*len(type)
ternary_indent = secondary_indent + " "*(2*len(ATL)) + spacing + " " # 2 ","s, 1 space
# Some ascii documentation
"""
"""
#
line1 = indent + type + ATL + ", " + ATR + "," + spacing + A00 + ", " + A01 + ", " + A02 + ","
line2 = secondary_indent + ABL + ", " + ABR + "," + spacing + A10 + ", " + A11 + ", " + A12 + ","
line3 = ternary_indent + A20 + ", " + A21 + ", " + A22 + ";"
return "\n".join([ line1, line2, line3 ])
def pretty_print_fla_obj_decl_1x2( part, repart, indent ):
# To string!
AL, AR = part
AL = str(AL)
AR = str(AR)
A0, A1, A2 = repart
A0 = str(A0)
A1 = str(A1)
A2 = str(A2)
# Type
type = "FLA_Obj "
# spacing
spacing = " "
# Some ascii documentation
"""
"""
#
line1 = indent + type + AL + ", " + AR + "," + spacing + A0 + ", " + A1 + ", " + A2 + ","
return line1
def pretty_print_fla_obj_decl_2x1( part, repart, indent ):
# To string!
AT, \
AB = part
AT = str(AT)
AB = str(AB)
A0, \
A1, \
A2 = repart
A0 = str(A0)
A1 = str(A1)
A2 = str(A2)
# Type
type = "FLA_Obj "
# spacing
spacing = " "
secondary_indent = indent + " "*len(type)
ternary_indent = secondary_indent + " "*len(AT) + spacing + " " # 1 ","
# Some ascii documentation
"""
"""
#
line1 = indent + type + AT + "," + spacing + A0 + ","
line2 = secondary_indent + AB + "," + spacing + A1 + ","
line3 = ternary_indent + A2 + ";"
return "\n".join([ line1, line2, line3 ])
def pretty_print_part( shape, op, part_op, size, which, indent ):
if tuple(shape) == ('2','2'):
return pretty_print_part_2x2( shape, op, part_op, size, which, indent )
elif tuple(shape) == ('1','2'):
return pretty_print_part_1x2( shape, op, part_op, size, which, indent )
elif tuple(shape) == ('2','1'):
return pretty_print_part_2x1( shape, op, part_op, size, which, indent )
print( shape )
raise Exception
def pretty_print_part_2x2( shape, op, part_op, size, which, indent ):
A = op
ATL, ATR, \
ABL, ABR = part_op
fcall = "FLA_Part_2x2( "
which = "'%s'" % which
# Some ascii documentation
"""
"""
#
line1 = indent + "[%s, %s, ..." % (ATL, ATR)
line2 = indent + " %s, %s] = " % (ABL, ABR) + fcall + A + ", " + ", ".join(size) + ", " + which + " );"
return "\n".join([ line1, line2 ])
def pretty_print_part_1x2( shape, op, part_op, size, which, indent ):
A = op
AL, AR, = part_op
fcall = "FLA_Part_1x2( "
which = "'%s'" % which
# Some ascii documentation
"""
"""
#
line1 = indent + "[%s, %s] = " % (AL, AR) + fcall + A + ", " + size[1] + ", " + which + " );"
return line1
def pretty_print_part_2x1( shape, op, part_op, size, which, indent ):
A = op
AT, \
AB = part_op
fcall = "FLA_Part_2x1( "
which = "'%s'" % which
# Some ascii documentation
"""
"""
#
line1 = indent + "[%s, ..." % (AT)
line2 = indent + " %s] = " % (AB) + fcall + A + ", " + size[0] + ", " + which + " );"
return "\n".join([ line1, line2 ])
def pretty_print_repart( repart_or_cont, shape, part, repart, size, which, indent ):
if tuple(shape) == ('2','2'):
return pretty_print_repart_2x2( repart_or_cont, part, repart, size, which, indent )
elif tuple(shape) == ('1','2'):
return pretty_print_repart_1x2( repart_or_cont, part, repart, size, which, indent )
elif tuple(shape) == ('2','1'):
return pretty_print_repart_2x1( repart_or_cont, part, repart, size, which, indent )
print( shape )
raise Exception
def pretty_print_repart_2x2( repart_or_cont, part, repart, size, which, indent ):
ATL, ATR, \
ABL, ABR = part
A00, A01, A02, \
A10, A11, A12, \
A20, A21, A22 = repart
"""
[A00, A01, A02, ...
A10, A11, A12, ...
A20, A21, A22] = FLA_Repart_2x2_to_3x3( A_TL, A_TR, | |
'str'
},
'service': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'src-filter': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'srcintf-filter': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'ssl-algorithm': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'high',
'medium',
'low',
'custom'
],
'type': 'str'
},
'ssl-certificate': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'ssl-cipher-suites': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'list',
'options': {
'cipher': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'TLS-RSA-WITH-RC4-128-MD5',
'TLS-RSA-WITH-RC4-128-SHA',
'TLS-RSA-WITH-DES-CBC-SHA',
'TLS-RSA-WITH-3DES-EDE-CBC-SHA',
'TLS-RSA-WITH-AES-128-CBC-SHA',
'TLS-RSA-WITH-AES-256-CBC-SHA',
'TLS-RSA-WITH-AES-128-CBC-SHA256',
'TLS-RSA-WITH-AES-256-CBC-SHA256',
'TLS-RSA-WITH-CAMELLIA-128-CBC-SHA',
'TLS-RSA-WITH-CAMELLIA-256-CBC-SHA',
'TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256',
'TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256',
'TLS-RSA-WITH-SEED-CBC-SHA',
'TLS-RSA-WITH-ARIA-128-CBC-SHA256',
'TLS-RSA-WITH-ARIA-256-CBC-SHA384',
'TLS-DHE-RSA-WITH-DES-CBC-SHA',
'TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA',
'TLS-DHE-RSA-WITH-AES-128-CBC-SHA',
'TLS-DHE-RSA-WITH-AES-256-CBC-SHA',
'TLS-DHE-RSA-WITH-AES-128-CBC-SHA256',
'TLS-DHE-RSA-WITH-AES-256-CBC-SHA256',
'TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA',
'TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA',
'TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256',
'TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256',
'TLS-DHE-RSA-WITH-SEED-CBC-SHA',
'TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256',
'TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384',
'TLS-ECDHE-RSA-WITH-RC4-128-SHA',
'TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA',
'TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA',
'TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA',
'TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256',
'TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256',
'TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256',
'TLS-DHE-RSA-WITH-AES-128-GCM-SHA256',
'TLS-DHE-RSA-WITH-AES-256-GCM-SHA384',
'TLS-DHE-DSS-WITH-AES-128-CBC-SHA',
'TLS-DHE-DSS-WITH-AES-256-CBC-SHA',
'TLS-DHE-DSS-WITH-AES-128-CBC-SHA256',
'TLS-DHE-DSS-WITH-AES-128-GCM-SHA256',
'TLS-DHE-DSS-WITH-AES-256-CBC-SHA256',
'TLS-DHE-DSS-WITH-AES-256-GCM-SHA384',
'TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256',
'TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256',
'TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384',
'TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384',
'TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA',
'TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256',
'TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256',
'TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384',
'TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384',
'TLS-RSA-WITH-AES-128-GCM-SHA256',
'TLS-RSA-WITH-AES-256-GCM-SHA384',
'TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA',
'TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA',
'TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA256',
'TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA256',
'TLS-DHE-DSS-WITH-SEED-CBC-SHA',
'TLS-DHE-DSS-WITH-ARIA-128-CBC-SHA256',
'TLS-DHE-DSS-WITH-ARIA-256-CBC-SHA384',
'TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256',
'TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384',
'TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256',
'TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384',
'TLS-DHE-DSS-WITH-3DES-EDE-CBC-SHA',
'TLS-DHE-DSS-WITH-DES-CBC-SHA',
'TLS-AES-128-GCM-SHA256',
'TLS-AES-256-GCM-SHA384',
'TLS-CHACHA20-POLY1305-SHA256'
],
'type': 'str'
},
'id': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': False,
'6.4.2': False,
'6.4.5': False,
'7.0.0': False
},
'type': 'int'
},
'versions': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'list',
'choices': [
'ssl-3.0',
'tls-1.0',
'tls-1.1',
'tls-1.2',
'tls-1.3'
]
},
'priority': {
'required': False,
'revision': {
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'int'
}
}
},
'ssl-client-fallback': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-client-renegotiation': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'deny',
'allow',
'secure'
],
'type': 'str'
},
'ssl-client-session-state-max': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'int'
},
'ssl-client-session-state-timeout': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'int'
},
'ssl-client-session-state-type': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'time',
'count',
'both'
],
'type': 'str'
},
'ssl-dh-bits': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'768',
'1024',
'1536',
'2048',
'3072',
'4096'
],
'type': 'str'
},
'ssl-hpkp': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable',
'report-only'
],
'type': 'str'
},
'ssl-hpkp-age': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'int'
},
'ssl-hpkp-backup': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'ssl-hpkp-include-subdomains': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-hpkp-primary': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'ssl-hpkp-report-uri': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'str'
},
'ssl-hsts': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-hsts-age': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'int'
},
'ssl-hsts-include-subdomains': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-http-location-conversion': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-http-match-host': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-max-version': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'ssl-3.0',
'tls-1.0',
'tls-1.1',
'tls-1.2',
'tls-1.3'
],
'type': 'str'
},
'ssl-min-version': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'ssl-3.0',
'tls-1.0',
'tls-1.1',
'tls-1.2',
'tls-1.3'
],
'type': 'str'
},
'ssl-mode': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'half',
'full'
],
'type': 'str'
},
'ssl-pfs': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'require',
'deny',
'allow'
],
'type': 'str'
},
'ssl-send-empty-frags': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'ssl-server-algorithm': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'high',
'low',
'medium',
'custom',
'client'
],
'type': 'str'
},
'ssl-server-cipher-suites': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'list',
'options': {
'cipher': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'TLS-RSA-WITH-RC4-128-MD5',
'TLS-RSA-WITH-RC4-128-SHA',
'TLS-RSA-WITH-DES-CBC-SHA',
'TLS-RSA-WITH-3DES-EDE-CBC-SHA',
'TLS-RSA-WITH-AES-128-CBC-SHA',
'TLS-RSA-WITH-AES-256-CBC-SHA',
'TLS-RSA-WITH-AES-128-CBC-SHA256',
'TLS-RSA-WITH-AES-256-CBC-SHA256',
'TLS-RSA-WITH-CAMELLIA-128-CBC-SHA',
'TLS-RSA-WITH-CAMELLIA-256-CBC-SHA',
'TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256',
'TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256',
'TLS-RSA-WITH-SEED-CBC-SHA',
'TLS-RSA-WITH-ARIA-128-CBC-SHA256',
'TLS-RSA-WITH-ARIA-256-CBC-SHA384',
'TLS-DHE-RSA-WITH-DES-CBC-SHA',
'TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA',
'TLS-DHE-RSA-WITH-AES-128-CBC-SHA',
'TLS-DHE-RSA-WITH-AES-256-CBC-SHA',
'TLS-DHE-RSA-WITH-AES-128-CBC-SHA256',
'TLS-DHE-RSA-WITH-AES-256-CBC-SHA256',
'TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA',
'TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA',
'TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256',
'TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256',
'TLS-DHE-RSA-WITH-SEED-CBC-SHA',
'TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256',
'TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384',
'TLS-ECDHE-RSA-WITH-RC4-128-SHA',
'TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA',
'TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA',
'TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA',
'TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256',
'TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256',
'TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256',
'TLS-DHE-RSA-WITH-AES-128-GCM-SHA256',
'TLS-DHE-RSA-WITH-AES-256-GCM-SHA384',
'TLS-DHE-DSS-WITH-AES-128-CBC-SHA',
'TLS-DHE-DSS-WITH-AES-256-CBC-SHA',
'TLS-DHE-DSS-WITH-AES-128-CBC-SHA256',
'TLS-DHE-DSS-WITH-AES-128-GCM-SHA256',
'TLS-DHE-DSS-WITH-AES-256-CBC-SHA256',
'TLS-DHE-DSS-WITH-AES-256-GCM-SHA384',
'TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256',
'TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256',
'TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384',
'TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384',
'TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA',
'TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256',
'TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256',
'TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384',
'TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384',
'TLS-RSA-WITH-AES-128-GCM-SHA256',
'TLS-RSA-WITH-AES-256-GCM-SHA384',
'TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA',
'TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA',
'TLS-DHE-DSS-WITH-CAMELLIA-128-CBC-SHA256',
'TLS-DHE-DSS-WITH-CAMELLIA-256-CBC-SHA256',
'TLS-DHE-DSS-WITH-SEED-CBC-SHA',
'TLS-DHE-DSS-WITH-ARIA-128-CBC-SHA256',
'TLS-DHE-DSS-WITH-ARIA-256-CBC-SHA384',
'TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256',
'TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384',
'TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256',
'TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384',
'TLS-DHE-DSS-WITH-3DES-EDE-CBC-SHA',
'TLS-DHE-DSS-WITH-DES-CBC-SHA',
'TLS-AES-128-GCM-SHA256',
'TLS-AES-256-GCM-SHA384',
'TLS-CHACHA20-POLY1305-SHA256'
],
'type': 'str'
},
'priority': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'int'
},
'versions': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'type': 'list',
'choices': [
'ssl-3.0',
'tls-1.0',
'tls-1.1',
'tls-1.2',
'tls-1.3'
]
}
}
},
'ssl-server-max-version': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
'6.4.2': True,
'6.4.5': True,
'7.0.0': True
},
'choices': [
'ssl-3.0',
'tls-1.0',
'tls-1.1',
'tls-1.2',
'client',
'tls-1.3'
],
'type': 'str'
},
'ssl-server-min-version': {
'required': False,
'revision': {
'6.0.0': True,
'6.2.1': True,
'6.2.3': True,
'6.2.5': True,
'6.4.0': True,
| |
Z4SS --> Z1SS DN DB
3.38946826E-08 3 1000022 3 -3 # Z4SS --> Z1SS ST SB
3.13976400E-08 3 1000022 4 -4 # Z4SS --> Z1SS CH CB
1.98484599E-06 3 1000022 5 -5 # Z4SS --> Z1SS BT BB
3.11173693E-07 3 1000022 15 -15 # Z4SS --> Z1SS TAU- TAU+
8.10549281E-08 3 1000023 2 -2 # Z4SS --> Z2SS UP UB
9.33409083E-08 3 1000023 1 -1 # Z4SS --> Z2SS DN DB
9.33409083E-08 3 1000023 3 -3 # Z4SS --> Z2SS ST SB
8.10546581E-08 3 1000023 4 -4 # Z4SS --> Z2SS CH CB
5.49582580E-07 3 1000023 5 -5 # Z4SS --> Z2SS BT BB
6.36902442E-08 3 1000023 15 -15 # Z4SS --> Z2SS TAU- TAU+
1.95981002E-07 3 1000025 2 -2 # Z4SS --> Z3SS UP UB
2.52914703E-07 3 1000025 1 -1 # Z4SS --> Z3SS DN DB
2.52914703E-07 3 1000025 3 -3 # Z4SS --> Z3SS ST SB
1.95981002E-07 3 1000025 4 -4 # Z4SS --> Z3SS CH CB
1.33505694E-07 3 1000025 5 -5 # Z4SS --> Z3SS BT BB
5.73485686E-08 3 1000025 11 -11 # Z4SS --> Z3SS E- E+
5.73485686E-08 3 1000025 13 -13 # Z4SS --> Z3SS MU- MU+
5.19428589E-08 3 1000025 15 -15 # Z4SS --> Z3SS TAU- TAU+
1.14105603E-07 3 1000025 12 -12 # Z4SS --> Z3SS NUE ANUE
1.14105603E-07 3 1000025 14 -14 # Z4SS --> Z3SS NUM ANUM
1.14105603E-07 3 1000025 16 -16 # Z4SS --> Z3SS NUT ANUT
8.87805372E-02 2 1000022 25 # Z4SS --> Z1SS HL0
1.55075401E-01 2 1000023 25 # Z4SS --> Z2SS HL0
4.04461799E-03 2 1000011 -11 # Z4SS --> EL- E+
4.04461799E-03 2 -1000011 11 # Z4SS --> EL+ E-
4.04461334E-03 2 1000013 -13 # Z4SS --> MUL- MU+
4.04461334E-03 2 -1000013 13 # Z4SS --> MUL+ MU-
3.87980347E-03 2 2000011 -11 # Z4SS --> ER- E+
3.87980347E-03 2 -2000011 11 # Z4SS --> ER+ E-
3.87980253E-03 2 2000013 -13 # Z4SS --> MUR- MU+
3.87980253E-03 2 -2000013 13 # Z4SS --> MUR+ MU-
1.24651380E-02 2 1000015 -15 # Z4SS --> TAU1- TAU+
1.24651380E-02 2 -1000015 15 # Z4SS --> TAU1+ TAU-
6.93802815E-03 2 2000015 -15 # Z4SS --> TAU2- TAU+
6.93802815E-03 2 -2000015 15 # Z4SS --> TAU2+ TAU-
9.85569134E-03 2 1000012 -12 # Z4SS --> NUEL ANUE
9.85569134E-03 2 -1000012 12 # Z4SS --> ANUEL NUE
9.85569134E-03 2 1000014 -14 # Z4SS --> NUML ANUM
9.85569134E-03 2 -1000014 14 # Z4SS --> ANUML NUM
1.02530960E-02 2 1000016 -16 # Z4SS --> NUTL ANUT
1.02530960E-02 2 -1000016 16 # Z4SS --> ANUTL NUT
2.31089923E-18 2 1000039 22 # Z4SS --> GVSS GM
5.23431200E-20 3 1000039 11 -11 # Z4SS --> GVSS E- E+
1.17628802E-16 2 1000039 23 # Z4SS --> GVSS Z0
5.44861553E-17 2 1000039 25 # Z4SS --> GVSS HL0
# PDG Width
DECAY 1000024 2.74252333E-02 # W1SS+ decays
# BR NDA ID1 ID2 ID3 ID4
4.60564763E-07 3 1000022 2 -1 # W1SS+ --> Z1SS UP DB
4.60564195E-07 3 1000022 4 -3 # W1SS+ --> Z1SS CH SB
3.10645497E-04 3 1000022 -11 12 # W1SS+ --> Z1SS E+ NUE
3.10645439E-04 3 1000022 -13 14 # W1SS+ --> Z1SS MU+ NUM
3.16078134E-04 3 1000022 -15 16 # W1SS+ --> Z1SS TAU+ NUT
5.09333432E-01 2 1000022 24 # W1SS+ --> Z1SS W+
4.02256055E-13 3 1000023 -11 12 # W1SS+ --> Z2SS E+ NUE
4.02256028E-13 3 1000023 -13 14 # W1SS+ --> Z2SS MU+ NUM
4.89728302E-01 2 -1000015 16 # W1SS+ --> TAU1+ NUT
# PDG Width
DECAY 1000037 1.89320457E+00 # W2SS+ decays
# BR NDA ID1 ID2 ID3 ID4
5.26969011E-08 3 1000022 2 -1 # W2SS+ --> Z1SS UP DB
5.26968478E-08 3 1000022 4 -3 # W2SS+ --> Z1SS CH SB
2.55078703E-07 3 1000022 -15 16 # W2SS+ --> Z1SS TAU+ NUT
1.01918742E-01 2 1000022 24 # W2SS+ --> Z1SS W+
7.45283941E-08 3 1000023 2 -1 # W2SS+ --> Z2SS UP DB
7.45283444E-08 3 1000023 4 -3 # W2SS+ --> Z2SS CH SB
1.99299237E-07 3 1000023 -15 16 # W2SS+ --> Z2SS TAU+ NUT
3.11031610E-01 2 1000023 24 # W2SS+ --> Z2SS W+
7.50685388E-07 3 1000025 2 -1 # W2SS+ --> Z3SS UP DB
7.50685388E-07 3 1000025 4 -3 # W2SS+ --> Z3SS CH SB
2.50198951E-07 3 1000025 -11 12 # W2SS+ --> Z3SS E+ NUE
2.50198951E-07 3 1000025 -13 14 # W2SS+ --> Z3SS MU+ NUM
2.50199861E-07 3 1000025 -15 16 # W2SS+ --> Z3SS TAU+ NUT
1.05458433E-02 2 1000012 -11 # W2SS+ --> NUEL E+
1.05458349E-02 2 1000014 -13 # W2SS+ --> NUML MU+
1.71406157E-02 2 1000016 -15 # W2SS+ --> NUTL TAU+
1.78969409E-02 2 -1000011 12 # W2SS+ --> EL+ NUE
1.78969335E-02 2 -1000013 14 # W2SS+ --> MUL+ NUM
2.03690995E-02 2 -1000015 16 # W2SS+ --> TAU1+ NUT
2.00152602E-02 2 -2000015 16 # W2SS+ --> TAU2+ NUT
2.70409793E-01 2 1000024 23 # W2SS+ --> W1SS+ Z0
9.01657131E-08 3 1000024 1 -1 # W2SS+ --> W1SS+ DN DB
9.01653792E-08 3 1000024 3 -3 # W2SS+ --> W1SS+ ST SB
1.73596064E-07 3 1000024 2 -2 # W2SS+ --> W1SS+ UP UB
1.73596064E-07 3 1000024 4 -4 # W2SS+ --> W1SS+ CH CB
2.02225879E-01 2 1000024 25 # W2SS+ --> W1SS+ HL0
# PDG Width
DECAY 25 3.14349518E-03 # HL0 decays
# BR NDA ID1 ID2 ID3 ID4
7.02421721E-09 2 11 -11 # HL0 --> E- E+
2.96573562E-04 2 13 -13 # HL0 --> MU- MU+
8.48168954E-02 2 15 -15 # HL0 --> TAU- TAU+
8.81886808E-06 2 1 -1 # HL0 --> DN DB
3.56326415E-03 2 3 -3 # HL0 --> ST SB
7.62523592E-01 2 5 -5 # HL0 --> BT BB
2.44499006E-06 2 2 -2 # HL0 --> UP UB
4.61725593E-02 2 4 -4 # HL0 --> CH CB
2.18242197E-03 2 22 22 # HL0 --> GM GM
4.73928303E-02 2 21 21 # HL0 --> GL GL
2.77047884E-03 3 24 11 -12 # HL0 --> W+ E- ANUE
2.77047884E-03 3 24 13 -14 # HL0 --> W+ MU- ANUM
2.77047884E-03 3 24 15 -16 # HL0 --> W+ TAU- ANUT
8.31143651E-03 3 24 -2 1 # HL0 --> W+ UB DN
8.31143651E-03 3 24 -4 3 # HL0 --> W+ CB ST
2.77047884E-03 3 -24 -11 12 # HL0 --> W- E+ NUE
2.77047884E-03 3 -24 -13 14 # HL0 --> W- MU+ NUM
2.77047884E-03 3 -24 -15 16 # HL0 --> W- TAU+ NUT
8.31143651E-03 3 -24 2 -1 # HL0 --> W- UP DB
8.31143651E-03 3 -24 4 -3 # HL0 --> W- CH SB
2.16942033E-04 3 23 12 -12 # HL0 --> Z0 NUE ANUE
2.16942033E-04 3 23 14 -14 # HL0 --> Z0 NUM ANUM
2.16942033E-04 3 23 16 -16 # HL0 --> Z0 NUT ANUT
1.09184744E-04 3 23 11 -11 # HL0 --> Z0 E- E+
1.09184744E-04 3 23 13 -13 # HL0 --> Z0 MU- MU+
1.09184744E-04 3 23 15 -15 # HL0 --> Z0 TAU- TAU+
3.74057679E-04 3 23 2 -2 # HL0 --> Z0 UP UB
3.74057679E-04 3 23 4 -4 # HL0 --> Z0 CH CB
4.81878466E-04 3 23 1 -1 # HL0 --> Z0 DN DB
4.81878466E-04 3 23 3 -3 # HL0 --> Z0 ST SB
4.81878466E-04 3 23 5 -5 # HL0 | |
# Ops-Test
#Code to try and incorporate manual flight
####################################################
##Commander's Challenge Program for Drone Automation
##Starts Drone
## Flies to multiple waypoints
## Returns to starting location, lands/shutdown - Press "L" to land, "P" to acquire another target
#####################################
#####################################
## Imports
from __future__ import division
import math
import datetime
import msvcrt
import dronekit_sitl
from pymavlink import mavutil
from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command
import time
import serial
import signal
#import RPi.GPIO as gpio
#####################################
## Global Variables and initial values
global x, y, z, key, vel, accel, correction_x, correction_y, correction_z, trkx, trky
global distance, elat, elon, ealt, submode, distance, edist, between, safe
key = 76
trkx = 7
trky = 7
correction_x = 0
correction_y = 0
correction_z = 0
accel = .9
s_lat = .00001
s_lon = .00001
b_lat = .00001
b_lon = .00001
f_lat = .00001
f_lon = .00001
safe = 4
dist1 = 1
between1 = 1
meh = 3
loft = 1
TIMEOUT = 3
find = None
#need to uncomment GPIO
"""
#GPIO Setup
LEDPin = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LEDPin, GPIO.OUT)
pwm = GPIO.PWM(LEDPin, 50)
"""
##########################################
##########Boots Simulator#################
print "Start simulator (SITL)"
sitl = dronekit_sitl.start_default()
connection_string = sitl.connection_string()
print("Connecting to vehicle on: %s" % (connection_string,))
vehicle = connect(connection_string, wait_ready=True)
##########################################
#############################################
##########Start up code for real test########
##Connect to XBee
#ser = serial.Serial('com7', 9600, timeout = 0.5)
#ser = serial.Serial('/dev/ttyUSB1', 9600, timeout = 0.5)
#vehicle = connect("/dev/ttyUSB0", wait_ready=True, 57600) #Connected via RPi
#ser.write("Connecting...\n")
#############################################
##########Connect through Cord###############
#vehicle = connect('com5', wait_ready=True, baud =57600)
#time.sleep(2)
#print "Autopilot Firmware version: %s" % vehicle.version
#############################################
## Functions
#Arms and rises to given Altitude
def arm_and_takeoff(aTargetAltitude):
"""
Arms vehicle and fly to aTargetAltitude.
"""
#armingTS = time.time()
while True:
if not x == None and not y == None and not z == None:
####################################################
print "Basic pre-arm checks"
####Don't try to arm until autopilot is ready
#while not vehicle.is_armable:
#print " Waiting for vehicle to initialise..."
#time.sleep(1)
#######################Remove above "While" condition for real testing
print "Arming motors"
# Copter should arm in GUIDED mode
vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True
# Confirm vehicle armed before attempting to take off
while not vehicle.armed:
print " Waiting for arming..."
time.sleep(1)
print "Taking off!"
vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude
# Wait until the vehicle reaches a safe height before processing the goto (otherwise the command
# after Vehicle.simple_takeoff will execute immediately).
while True:
print " Altitude: ", vehicle.location.global_relative_frame.alt
#Break and return from function just below target altitude.
if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95:
print "Reached target altitude"
break
time.sleep(1)
break
else:
print "False Coords Received"
time.sleep(2)
"""
[Name, x, y, z] = rec_full_data("WP")
print "Latitude is: ", x
print "Longitude is: ", y
print "Altitude is: ", z
print "Type is: ", Name
[Name, elat, elon, ealt] = rec_full_data("EnemyWP")
print "Enemy Latitude is: ", elat
print "Enemy Longitude is: ", elon
print "Enemy Altitude is: ", ealt
print "Type is: ", Name
"""
#Needed only for conditionyaw action
def send_global_velocity(velocity_x,velocity_y,velocity_z):
msg = vehicle.message_factory.set_position_target_global_int_encode(0,0,0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, 0b0000111111000111,0,0,0,velocity_x,velocity_y,velocity_z,0,0,0,0,0)
vehicle.send_mavlink(msg)
vehicle.flush()
#Turns drone on z access
def conditionyaw(heading, relative = False):
is_relative = 0
# ^ states that heading is not relative to flight path
send_global_velocity(0,0,0)
msg = vehicle.message_factory.command_long_encode(0,0,mavutil.mavlink.MAV_CMD_CONDITION_YAW, 0,heading,0,1,is_relative, 0,0,0)
vehicle.send_mavlink(msg)
#Flies drone to a given set of coords and alt
def gotoGPS(location):
global x
global y
global z
global key
global correction_x
global correction_y
global correction_z
vehicle.simple_goto(location, airspeed=None, groundspeed=None)
#Distance to waypoint
def distance():
#global x, y, z
dist1 = 100
dist1 = math.sqrt(((x*100000)-((100000*vehicle.location.global_relative_frame.lat)))**2+((100000*y)-((100000*vehicle.location.global_relative_frame.lon)))**2+(z-(vehicle.location.global_relative_frame.alt))**2)
return dist1
#Distance to enemy
def between():
global elat, elon, ealt, between
between1 = 100
between1 = math.sqrt(((elat*100000)-((100000*vehicle.location.global_relative_frame.lat)))**2+((100000*elon)-((100000*vehicle.location.global_relative_frame.lon)))**2+(ealt-(vehicle.location.global_relative_frame.alt))**2)
return between1
#Sends vehicle home
def gotoHome(location): ###Note: Groundspeed must be set via missionplanner
print "I'm coming home!"
vehicle.simple_goto(location)
while True:
print " Location: Lat:%s, Lon:%s, Alt: %s" % (vehicle.location.global_relative_frame.lat, vehicle.location.global_relative_frame.lon, vehicle.location.global_relative_frame.alt)
print " Distance to Waypoint: %s" % (math.sqrt(((home_lat*100000)-((100000*vehicle.location.global_relative_frame.lat)))**2+((100000*home_lon)-((100000*vehicle.location.global_relative_frame.lon)))**2+(home_alt-(vehicle.location.global_relative_frame.alt))**2))
#if vehicle.location.global_relative_frame.alt>= z*0.95 and vehicle.location.global_relative_frame.lat>= x*0.80 and vehicle.location.global_relative_frame.lon>= y*0.80:
if math.sqrt(((100000*home_lat)-(100000*vehicle.location.global_relative_frame.lat))**2+((100000*home_lon)-(100000*vehicle.location.global_relative_frame.lon))**2+(home_alt-(vehicle.location.global_relative_frame.alt))**2)<=1:
#if math.sqrt((x-(d*(-1)))**2+(y-(e*(-1)))**2+(z-(f*-(1))**2))<=2:
print "The Drone is Back."
break
time.sleep(1)
#Returns vehicle to ground
def RTL(landingAlt):
print "Landing"
vehicle.mode = VehicleMode("LAND")
while vehicle.location.global_relative_frame.alt>=landingAlt:
print " Altitude: ", vehicle.location.global_relative_frame.alt
time.sleep(1)
#Attempt to control drone directly from visual imputs
def tracking(velocity_x, velocity_y, velocity_z, duration):
"""
Move vehicle in direction based on specified velocity vectors.
"""
msg = vehicle.message_factory.set_position_target_global_int_encode(
0, # time_boot_ms (not used)
0, 0, # target system, target component
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame
0b0000111111000111, # type_mask (only speeds enabled)
0, # lat_int - X Position in WGS84 frame in 1e7 * meters
0, # lon_int - Y Position in WGS84 frame in 1e7 * meters
0, # alt - Altitude in meters in AMSL altitude(not WGS84 if absolute or relative)
# altitude above terrain if GLOBAL_TERRAIN_ALT_INT
velocity_x, # X velocity in NED frame in m/s
velocity_y, # Y velocity in NED frame in m/s
velocity_z, # Z velocity in NED frame in m/s
0, 0, 0, # afx, afy, afz acceleration (not supported yet, ignored in GCS_Mavlink)
0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)
# send command to vehicle on 1 Hz cycle
for x in range(0,duration):
vehicle.send_mavlink(msg)
time.sleep(1)
#Setting for drone to fly based on heading
def track(heading):
global trkx
global trky
if vehicle.heading == 0:
trkx = -1
trky = 0
elif vehicle.heading < 15:
trkx = -1
trky = -.25
elif vehicle.heading>=15 and vehicle.heading<=30:
trkx = -1
trky = -.5
elif vehicle.heading>30 and vehicle.heading<37.5:
trkx = -1
trky = -.75
elif vehicle.heading>=37.5 and vehicle.heading<=52.5:
trkx = -1
trky = -1
elif vehicle.heading>52.5 and vehicle.heading<60:
trkx = -.75
trky = -1
elif vehicle.heading>=60 and vehicle.heading<=75:
trkx = -.5
trky = -1
elif vehicle.heading>75 and vehicle.heading<90:
trkx = -.25
trky = -1
elif vehicle.heading == 90:
trkx = -0
trky = -1
elif vehicle.heading>90 and vehicle.heading < 105:
trkx = .25
trky = -1
elif vehicle.heading>=105 and vehicle.heading<=120:
trkx = .5
trky = -1
elif vehicle.heading>120 and vehicle.heading<127.5:
trkx = .75
trky = -1
elif vehicle.heading>=127.5 and vehicle.heading<=142.5:
trkx = 1
trky = -1
elif vehicle.heading>142.5 and vehicle.heading<150:
trkx = 1
trky = -.75
elif vehicle.heading>=150 and vehicle.heading<=165:
trkx = 1
trky = -.5
elif vehicle.heading>165 and vehicle.heading<180:
trkx = 1
trky = -.25
elif vehicle.heading == 180:
trkx = 1
trky = 0
elif vehicle.heading>180 and vehicle.heading < 195:
trkx = 1
trky = .25
elif vehicle.heading>=195 and vehicle.heading<=210:
trkx = 1
trky = .5
elif vehicle.heading>210 and vehicle.heading<217.5:
trkx = 1
trky = .75
elif vehicle.heading>=217.5 and vehicle.heading<=232.5:
trkx = 1
trky = 1
elif vehicle.heading>232.5 and vehicle.heading<240:
trkx = .75
trky = 1
elif vehicle.heading>=240 and vehicle.heading<=255:
trkx = .5
trky = 1
elif vehicle.heading>255 and vehicle.heading<270:
trkx = .25
trky = 1
elif vehicle.heading == 270:
trkx = 0
trky = 1
elif vehicle.heading > 270 and vehicle.heading< 285:
trkx = -.25
trky = 1
elif vehicle.heading>=285 and vehicle.heading<=300:
trkx = -.5
trky = 1
elif vehicle.heading>300 and vehicle.heading<307.5:
trkx = -.75
trky = 1
elif vehicle.heading>=307.5 and vehicle.heading<=322.5:
trkx = -1
trky = 1
elif vehicle.heading>322.5 and vehicle.heading<330:
trkx = -1
trky = .75
elif vehicle.heading>=330 and vehicle.heading<345:
trkx = -1
trky = .5
elif vehicle.heading>345:
trkx = -1
trky = .25
#Glide is the base code for shifting the drone left and right...further comments can be found where "keys" "A" and "D" are utilized
def strafe():
global s_lat, s_lon, b_lat, b_lon, f_lat, f_lon
#@ heading = 0, drone goes East
s_lat = math.sin(math.radians(vehicle.heading))
s_lon = math.cos(math.radians(vehicle.heading))
f_lat = math.cos(math.radians(vehicle.heading))
f_lon = math.sin(math.radians(vehicle.heading))
b_lat = -math.cos(math.radians(vehicle.heading))
b_lon = -math.sin(math.radians(vehicle.heading))
#main function
def killingjoke():
print "Holding Position"
#########################
## Starts loop for recieving and flying to multiple coords
while True:
global x
global y
global z
global key
global vel
global accel
global correction_x
global correction_y
global correction_z
global trkx
global trky
##Will ask user if a threat is identified; if not, will update coords and try again, otherwise will switch to manual
print "Pilot Takeover"
time.sleep(5)
while True:
if not vehicle.mode == VehicleMode("GUIDED"):
start = time.time()
print "other mode"
if vehicle.mode == VehicleMode("GUIDED"):
end = time.time()
print "Pilot controlled A/C for %s" % (end-start)
break
print "Do you want to land? Press(Y or N)"
key=msvcrt.getch()
#uncomment for XBee
#print "Do you see the threat Y/N"
#while True:
#[Name, key] = rec_char("Threat Seen Y/N?")
#break
#print "key is %s" % key
if key == "Y" or key == "y":
break
else:
pass
#How to send data thru XBee
def send_full_data(Name, arg1, arg2, arg3):
while True:
ser.write("%s\n" % Name)
print Name
time.sleep(.5)
incoming = ser.readline().strip()
if incoming == "Go":
print "writing arg1"
time.sleep(.5)
ser.write("%s\n" % arg1)
time.sleep(.5)
becoming = ser.readline().strip()
print becoming
if becoming == "Received arg1":
print "writing arg2"
time.sleep(.5)
ser.write("%s\n" % arg2)
time.sleep(.5)
#print "I got to here"
becoming = ser.readline().strip()
print becoming
if becoming == "Received arg2":
print "writing arg3"
time.sleep(.5)
ser.write("%s\n" % arg3)
#print "I got to here"
time.sleep(.5)
becoming = ser.readline().strip()
print becoming
if becoming == "Received arg3":
break
print "woohoo"
break
#How to receive data thru XBee
def rec_full_data(Name):
while True:
ser.write("%s\n" % Name)
time.sleep(1)
if ser.readline().strip() == Name:
time.sleep(.5)
ser.write("Go\n")
print "ready for arg1"
time.sleep(1)
incoming = ser.readline().strip()
while True:
try:
incoming = ser.readline().strip()
print "incoming is: %s" % incoming
arg1 = float(incoming)
time.sleep(.5)
ser.write("Received arg1\n")
print "Arg1 worked!"
break
except ValueError, e:
print "error", e
time.sleep(1)
#ready for arg2
time.sleep(.5)
incoming = ser.readline().strip()
print incoming
while True:
try:
incoming = ser.readline().strip()
print "incoming is: %s" % incoming
arg2 = float(incoming)
time.sleep(.5)
ser.write("Received arg2\n")
print "Arg2 worked!"
break
except ValueError, e:
print "error", e
time.sleep(1)
#ready for arg3
time.sleep(.5)
incoming = ser.readline().strip()
print incoming
while True:
try:
incoming = ser.readline().strip()
print "incoming is: %s" % incoming
arg3 = float(incoming)
time.sleep(.5)
ser.write("Received arg3\n")
print "Arg3 worked!"
break
except ValueError, e:
print "error", e
time.sleep(1)
return Name, arg1, arg2, arg3
#How to receive chars thru XBee
def rec_key(Name):
while True:
ser.write("%s\n" % Name)
time.sleep(1)
if ser.readline().strip() == Name:
time.sleep(.5)
print Name
ser.write("Go\n")
print "ready for arg1"
time.sleep(.5)
incoming = ser.readline().strip()
print "incoming is: %s" % incoming
while True:
if incoming == Name:
print "still failing"
bc = ser.readline().strip()
if bc != Name:
arg1 = bc
print "got it"
ser.write("Received arg1\n")
break
else:
arg1 = incoming
print "got it"
ser.write("Received arg1\n")
break
return Name, arg1
#How to send chars thru XBee
def send_key(Name, arg1):
while True:
ser.write("%s\n" % Name)
time.sleep(.5)
incoming = ser.readline().strip()
if incoming == "Go":
print "writing arg1"
time.sleep(.5)
while True:
ser.write("%s\n" % arg1)
print "wrote"
time.sleep(.5)
becoming = ser.readline().strip()
print "becoming is: %s" % becoming
if becoming == "Received arg1":
return
def traveling():
while True:
global x, y, z, key, vel, accel, | |
<filename>test/quantization/core/test_quantized_tensor.py
# Owner(s): ["oncall: quantization"]
import numpy as np
import math
import torch
import io
import unittest
from copy import deepcopy
from hypothesis import given
from hypothesis import strategies as st
from torch.testing._internal.common_utils import TemporaryFileName
from torch.testing._internal.common_cuda import TEST_CUDA
from torch.testing._internal.common_utils import TestCase, TEST_WITH_ROCM
import torch.testing._internal.hypothesis_utils as hu
hu.assert_deadline_disabled()
import itertools
import tempfile
class Foo(torch.nn.Module):
def __init__(self):
super(Foo, self).__init__()
self.qscheme = torch.per_tensor_symmetric
def _calculate_dynamic_qparams(X, dtype, reduce_range=False):
"""Calculate the dynamic quantization parameters (scale, zero_point)
according to the min and max element of the tensor"""
if isinstance(X, torch.Tensor):
X = X.cpu().data.numpy()
if dtype == torch.qint8:
if reduce_range:
qmin, qmax = -64, 63
else:
qmin, qmax = -128, 127
else: # dtype == torch.quint8
if reduce_range:
qmin, qmax = 0, 127
else:
qmin, qmax = 0, 255
min_val = X.min().astype(dtype=np.float32)
max_val = X.max().astype(dtype=np.float32)
min_val = min(0.0, min_val)
max_val = max(0.0, max_val)
scale = (np.float64(max_val) - min_val) / (qmax - qmin)
if scale == 0.0 or math.isinf(1.0 / scale):
scale = np.float64(0.1)
zero_point = 0
zero_point_from_min = qmin - min_val / float(scale)
zero_point_from_max = qmax - max_val / float(scale)
zero_point_from_min_error = abs(qmin) - abs(min_val / float(scale))
zero_point_from_max_error = abs(qmax) - abs(max_val / float(scale))
if zero_point_from_min_error < zero_point_from_max_error:
initial_zero_point = zero_point_from_min
else:
initial_zero_point = zero_point_from_max
nudged_zero_point = 0
if initial_zero_point < qmin:
nudged_zero_point = qmin
elif initial_zero_point > qmax:
nudged_zero_point = qmax
else:
nudged_zero_point = int(round(initial_zero_point))
return [scale.astype(np.float32), int(nudged_zero_point)]
def get_supported_device_types():
return ['cpu', 'cuda'] if torch.cuda.is_available() and not TEST_WITH_ROCM else ['cpu']
# Note we explicitly cast variables to np.float32 in a couple of places to avoid
# the default casting in Python often resuling in double precision and to make
# sure we're doing the same numerics as C++ code.
def param_search_greedy(x, bit_rate, n_bins=200, ratio=0.16):
xmin, xmax = np.min(x), np.max(x)
stepsize = (xmax - xmin) / np.float32(n_bins)
min_bins = np.float32(n_bins) * (np.float32(1) - np.float32(ratio))
xq, loss = _compress_uniform_simplified(x, bit_rate, xmin, xmax)
solutions = [] # [(left, right, loss)] # local optima solution
cur_min, cur_max, cur_loss = xmin, xmax, loss
thr = min_bins * stepsize
while cur_min + thr < cur_max:
# move left
xq, loss1 = _compress_uniform_simplified(
x, bit_rate, cur_min + stepsize, cur_max
)
# move right
xq, loss2 = _compress_uniform_simplified(
x, bit_rate, cur_min, cur_max - stepsize
)
if cur_loss < loss1 and cur_loss < loss2:
# found a local optima
solutions.append((cur_min, cur_max, cur_loss))
if loss1 < loss2:
cur_min, cur_max, cur_loss = cur_min + stepsize, cur_max, loss1
else:
cur_min, cur_max, cur_loss = cur_min, cur_max - stepsize, loss2
if len(solutions):
best = solutions[0]
for solution in solutions:
if solution[-1] < best[-1]:
best = solution
return best[1], best[0] # xmax, xmin
return xmax, xmin
def _compress_uniform_simplified(X, bit_rate, xmin, xmax, fp16_scale_bias=True):
# affine transform to put Xq in [0,2**bit_rate - 1]
# Xq = (2 ** bit_rate - 1) * (Xq - xmin) / data_range
if fp16_scale_bias:
xmin = xmin.astype(np.float16).astype(np.float32)
data_range = xmax - xmin
scale = np.where(
data_range == 0, np.float32(1), data_range / np.float32(2 ** bit_rate - 1)
)
if fp16_scale_bias:
scale = scale.astype(np.float16).astype(np.float32)
inverse_scale = np.float32(1) / scale
Xq = np.clip(np.round((X - xmin) * inverse_scale), 0, np.float32(2 ** bit_rate - 1))
Xq = Xq * scale + xmin
# Manually compute loss instead of using np.linalg.norm to use the same
# accumulation order used by C++ code
vlen = 8
loss_v = np.zeros(vlen).astype(np.float32)
for i in range(len(Xq) // vlen * vlen):
loss_v[i % vlen] += (X[i] - Xq[i]) * (X[i] - Xq[i])
loss = np.float32(0)
for i in range(vlen):
loss += loss_v[i]
for i in range(len(Xq) // vlen * vlen, len(Xq)):
loss += (X[i] - Xq[i]) * (X[i] - Xq[i])
loss = np.sqrt(loss)
return Xq, loss
class TestQuantizedTensor(TestCase):
def test_per_tensor_qtensor_to_memory_format(self):
n = np.random.randint(1, 10)
c = np.random.randint(2, 10)
h = np.random.randint(2, 10)
w = np.random.randint(2, 10)
x = torch.rand(n, c, h, w)
scale = np.random.uniform(0.1, 1.0)
zero_point = np.random.randint(0.0, 10)
qints = [torch.qint8, torch.quint8, torch.qint32]
dtype = qints[np.random.randint(0, len(qints))]
qx = torch.quantize_per_tensor(x, scale=scale, zero_point=zero_point, dtype=dtype)
x_nhwc = x.to(memory_format=torch.channels_last)
qx_nhwc_using_to = qx.to(memory_format=torch.channels_last)
qx_nhwc_using_contiguous = qx.contiguous(memory_format=torch.channels_last)
self.assertEqual(qx_nhwc_using_to.stride(), qx_nhwc_using_contiguous.stride())
self.assertEqual(qx_nhwc_using_to.stride(), x_nhwc.stride())
# When the last two dimensions of a 4D tensor are both size 1 or if c == 1, we have a degenerate case
# see https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html
# In this case, the output of torch.Tensor.to and torch.Tensor.contiguous should not be the same
x = torch.rand(10, 2, 1, 1)
qx = torch.quantize_per_tensor(x, scale=scale, zero_point=zero_point, dtype=dtype)
qx_nhwc_using_to = qx.to(memory_format=torch.channels_last)
qx_nhwc_using_contiguous = qx.contiguous(memory_format=torch.channels_last)
self.assertNotEqual(qx_nhwc_using_to.stride(), qx_nhwc_using_contiguous.stride())
x = torch.rand(10, 1, 2, 2)
qx = torch.quantize_per_tensor(x, scale=scale, zero_point=zero_point, dtype=dtype)
qx_nhwc_using_to = qx.to(memory_format=torch.channels_last)
qx_nhwc_using_contiguous = qx.contiguous(memory_format=torch.channels_last)
self.assertNotEqual(qx_nhwc_using_to.stride(), qx_nhwc_using_contiguous.stride())
def test_per_channel_qtensor_to_memory_format(self):
n = np.random.randint(1, 10)
c = np.random.randint(2, 10)
h = np.random.randint(2, 10)
w = np.random.randint(2, 10)
x = torch.rand(n, c, h, w)
x_nhwc = x.to(memory_format=torch.channels_last)
scale = np.random.uniform(0.1, 1.0)
zero_point = np.random.randint(0.0, 10)
qints = [torch.qint8, torch.quint8, torch.qint32]
dtype = qints[np.random.randint(0, len(qints))]
for axis in range(x.ndim):
scales = torch.rand(x.size(axis)) + 0.00001
zero_points = torch.randint(low=0, high=10, size=(x.size(axis), ))
qx = torch.quantize_per_channel(x, scales=scales, zero_points=zero_points, dtype=dtype, axis=axis)
qx_nhwc_using_to = qx.to(memory_format=torch.channels_last)
self.assertEqual(qx_nhwc_using_to.stride(), x_nhwc.stride())
@unittest.skipIf(not TEST_CUDA, "No gpu is available.")
def test_qtensor_cuda(self):
self._test_qtensor(torch.device('cuda'))
self._test_qtensor_dynamic(torch.device('cuda'))
def test_qtensor_cpu(self):
self._test_qtensor(torch.device('cpu'))
self._test_qtensor_dynamic(torch.device('cpu'))
def _test_qtensor_dynamic(self, device):
# max number of tensor dimensions
max_tensor_order = 4
# max size for any tensor dimension
max_dim_sz = 20
num_dim = np.random.randint(low=1, high=max_tensor_order)
dims = np.random.randint(low=1, high=max_dim_sz, size=num_dim)
mat2quant = torch.randn(*dims, dtype=torch.float, device=device)
reduce_flag = False
for dtype in [torch.qint8, torch.quint8]:
q_d = torch.quantize_per_tensor_dynamic(mat2quant, dtype, reduce_flag)
scale, zero_pt = _calculate_dynamic_qparams(mat2quant, dtype, reduce_flag)
q_s = torch.quantize_per_tensor(mat2quant, scale, zero_pt, dtype)
self.assertEqual(q_d, q_s)
def _test_qtensor(self, device):
device = str(device)
num_elements = 10
scale = 1.0
zero_point = 2
for dtype in [torch.qint8, torch.quint8, torch.qint32]:
r = torch.ones(num_elements, dtype=torch.float, device=device)
qr = torch.quantize_per_tensor(r, scale, zero_point, dtype)
self.assertEqual(qr.q_scale(), scale)
self.assertEqual(qr.q_zero_point(), zero_point)
self.assertTrue(qr.is_quantized)
self.assertFalse(r.is_quantized)
self.assertEqual(qr.qscheme(), torch.per_tensor_affine)
self.assertTrue(isinstance(qr.qscheme(), torch.qscheme))
# slicing and int_repr
int_repr = qr.int_repr()
for num in int_repr:
self.assertEqual(num, 3)
for num in qr[2:].int_repr():
self.assertEqual(num, 3)
# dequantize
rqr = qr.dequantize()
for i in range(num_elements):
self.assertEqual(r[i], rqr[i])
# we can also print a qtensor
empty_r = torch.ones((0, 1), dtype=torch.float, device=device)
empty_qr = torch.quantize_per_tensor(empty_r, scale, zero_point, dtype)
device_msg = "" if device == 'cpu' else "device='" + device + ":0', "
dtype_msg = str(dtype) + ", "
self.assertEqual(' '.join(str(empty_qr).split()),
"tensor([], " + device_msg + "size=(0, 1), dtype=" + dtype_msg +
"quantization_scheme=torch.per_tensor_affine, " +
"scale=1.0, zero_point=2)")
def test_qtensor_int_repr(self):
# to catch edge case when num elements * bit rate < 8, make sure at lease allocate one byte to hold the int repr
num_elements = 1
device = torch.device('cpu')
scale = 1.0
zero_point = 2
dtype = torch.quint2x4
r = torch.ones(num_elements, dtype=torch.float, device=device)
qr = torch.quantize_per_tensor(r, scale, zero_point, dtype)
int_repr = qr.int_repr()
self.assertEqual(int_repr.numel(), 1)
# Packed one entry looks like 00000011
self.assertEqual(int_repr[0], 3)
def test_qtensor_sub_byte_aligned_cols(self):
# Packed 4 entries, each of value 3, look like 00110011, 00110011 for torch.qunit4x2, or 11111111 for torch.quint2x4
self._test_qtensor_sub_byte(1, 4, torch.quint4x2, 2, [51, 51])
self._test_qtensor_sub_byte(1, 4, torch.quint2x4, 4, [255])
def test_qtensor_sub_byte_not_aligned_cols(self):
# Packed 5 entries, each of value 3, look like 00110011, 00110011, 00000011 for torch.qunit4x2,
# or 11111111, 00000011 for torch.quint2x4
self._test_qtensor_sub_byte(1, 5, torch.quint4x2, 2, [51, 51, 3])
self._test_qtensor_sub_byte(1, 5, torch.quint2x4, 4, [255, 3])
def _test_qtensor_sub_byte(self, rows, cols, dtype, elements_per_byte, expected_packed_vals):
num_elements = rows * cols
scale = 1.0
zero_point = 2
r = torch.ones((rows, cols), dtype=torch.float)
qr = torch.quantize_per_tensor(r, scale, zero_point, dtype)
self.assertEqual(qr.q_scale(), scale)
self.assertEqual(qr.q_zero_point(), zero_point)
self.assertTrue(qr.is_quantized)
self.assertFalse(r.is_quantized)
self.assertEqual(qr.storage().size(), rows * math.ceil(cols / elements_per_byte), f"with {dtype}, {elements_per_byte}")
int_repr = qr.int_repr()
self.assertEqual(int_repr.numel(), len(expected_packed_vals))
for num, expected in zip(int_repr, expected_packed_vals):
self.assertEqual(num, expected, f"with dtype={dtype}, elements_per_byte={elements_per_byte}, rows={rows}, cols={cols}")
# Test tensor creation
q = torch._empty_affine_quantized([num_elements], scale=scale, zero_point=zero_point, dtype=dtype)
self.assertEqual(q.storage().size(), math.ceil(num_elements / elements_per_byte), f"with {dtype}, {elements_per_byte}")
# Test save/load
with tempfile.NamedTemporaryFile() as f:
torch.save(qr, f)
f.seek(0)
loaded_q = torch.load(f)
loaded_int_repr = loaded_q.int_repr()
self.assertEqual(int_repr, loaded_int_repr)
def test_qtensor_channel_float_assignment(self):
t1 = torch.rand(2, 3, 5, 5)
t2 = torch.rand(2, 3, 5, 5)
for axis in range(t1.ndim):
scales = np.random.rand(t1.size()[axis])
zero_points = np.random.randint(low=0, high=50, size=t1.size()[axis])
for dtype in [torch.qint8, torch.quint8, torch.qint32]:
qt1 = torch.quantize_per_channel(t1, scales=torch.tensor(scales),
zero_points=torch.tensor(zero_points), dtype=dtype, axis=axis)
qt2 = torch.quantize_per_channel(t2, scales=torch.tensor(scales),
zero_points=torch.tensor(zero_points), dtype=dtype, axis=axis)
i = 0
j = 1
k = 2
l = 4
# scalar assignment verification
qt1[i][j][k][l] | |
import signal
import sys
import unittest
import warnings
from unittest import mock
import asyncio
from asyncio import base_subprocess
from asyncio import subprocess
from test.test_asyncio import utils as test_utils
from test import support
if sys.platform != 'win32':
from asyncio import unix_events
# Program blocking
PROGRAM_BLOCKED = [sys.executable, '-c', 'import time; time.sleep(3600)']
# Program copying input to output
PROGRAM_CAT = [
sys.executable, '-c',
';'.join(('import sys',
'data = sys.stdin.buffer.read()',
'sys.stdout.buffer.write(data)'))]
class TestSubprocessTransport(base_subprocess.BaseSubprocessTransport):
def _start(self, *args, **kwargs):
self._proc = mock.Mock()
self._proc.stdin = None
self._proc.stdout = None
self._proc.stderr = None
self._proc.pid = -1
class SubprocessTransportTests(test_utils.TestCase):
def setUp(self):
super().setUp()
self.loop = self.new_test_loop()
self.set_event_loop(self.loop)
def create_transport(self, waiter=None):
protocol = mock.Mock()
protocol.connection_made._is_coroutine = False
protocol.process_exited._is_coroutine = False
transport = TestSubprocessTransport(
self.loop, protocol, ['test'], False,
None, None, None, 0, waiter=waiter)
return (transport, protocol)
def test_proc_exited(self):
waiter = asyncio.Future(loop=self.loop)
transport, protocol = self.create_transport(waiter)
transport._process_exited(6)
self.loop.run_until_complete(waiter)
self.assertEqual(transport.get_returncode(), 6)
self.assertTrue(protocol.connection_made.called)
self.assertTrue(protocol.process_exited.called)
self.assertTrue(protocol.connection_lost.called)
self.assertEqual(protocol.connection_lost.call_args[0], (None,))
self.assertFalse(transport.is_closing())
self.assertIsNone(transport._loop)
self.assertIsNone(transport._proc)
self.assertIsNone(transport._protocol)
# methods must raise ProcessLookupError if the process exited
self.assertRaises(ProcessLookupError,
transport.send_signal, signal.SIGTERM)
self.assertRaises(ProcessLookupError, transport.terminate)
self.assertRaises(ProcessLookupError, transport.kill)
transport.close()
def test_subprocess_repr(self):
waiter = asyncio.Future(loop=self.loop)
transport, protocol = self.create_transport(waiter)
transport._process_exited(6)
self.loop.run_until_complete(waiter)
self.assertEqual(
repr(transport),
"<TestSubprocessTransport pid=-1 returncode=6>"
)
transport._returncode = None
self.assertEqual(
repr(transport),
"<TestSubprocessTransport pid=-1 running>"
)
transport._pid = None
transport._returncode = None
self.assertEqual(
repr(transport),
"<TestSubprocessTransport not started>"
)
transport.close()
class SubprocessMixin:
def test_stdin_stdout(self):
args = PROGRAM_CAT
async def run(data):
proc = await asyncio.create_subprocess_exec(
*args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
loop=self.loop)
# feed data
proc.stdin.write(data)
await proc.stdin.drain()
proc.stdin.close()
# get output and exitcode
data = await proc.stdout.read()
exitcode = await proc.wait()
return (exitcode, data)
task = run(b'some data')
task = asyncio.wait_for(task, 60.0, loop=self.loop)
exitcode, stdout = self.loop.run_until_complete(task)
self.assertEqual(exitcode, 0)
self.assertEqual(stdout, b'some data')
def test_communicate(self):
args = PROGRAM_CAT
async def run(data):
proc = await asyncio.create_subprocess_exec(
*args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
loop=self.loop)
stdout, stderr = await proc.communicate(data)
return proc.returncode, stdout
task = run(b'some data')
task = asyncio.wait_for(task, 60.0, loop=self.loop)
exitcode, stdout = self.loop.run_until_complete(task)
self.assertEqual(exitcode, 0)
self.assertEqual(stdout, b'some data')
def test_shell(self):
create = asyncio.create_subprocess_shell('exit 7',
loop=self.loop)
proc = self.loop.run_until_complete(create)
exitcode = self.loop.run_until_complete(proc.wait())
self.assertEqual(exitcode, 7)
def test_start_new_session(self):
# start the new process in a new session
create = asyncio.create_subprocess_shell('exit 8',
start_new_session=True,
loop=self.loop)
proc = self.loop.run_until_complete(create)
exitcode = self.loop.run_until_complete(proc.wait())
self.assertEqual(exitcode, 8)
def test_kill(self):
args = PROGRAM_BLOCKED
create = asyncio.create_subprocess_exec(*args, loop=self.loop)
proc = self.loop.run_until_complete(create)
proc.kill()
returncode = self.loop.run_until_complete(proc.wait())
if sys.platform == 'win32':
self.assertIsInstance(returncode, int)
# expect 1 but sometimes get 0
else:
self.assertEqual(-signal.SIGKILL, returncode)
def test_terminate(self):
args = PROGRAM_BLOCKED
create = asyncio.create_subprocess_exec(*args, loop=self.loop)
proc = self.loop.run_until_complete(create)
proc.terminate()
returncode = self.loop.run_until_complete(proc.wait())
if sys.platform == 'win32':
self.assertIsInstance(returncode, int)
# expect 1 but sometimes get 0
else:
self.assertEqual(-signal.SIGTERM, returncode)
@unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP")
def test_send_signal(self):
# bpo-31034: Make sure that we get the default signal handler (killing
# the process). The parent process may have decided to ignore SIGHUP,
# and signal handlers are inherited.
old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL)
try:
code = 'import time; print("sleeping", flush=True); time.sleep(3600)'
args = [sys.executable, '-c', code]
create = asyncio.create_subprocess_exec(*args,
stdout=subprocess.PIPE,
loop=self.loop)
proc = self.loop.run_until_complete(create)
async def send_signal(proc):
# basic synchronization to wait until the program is sleeping
line = await proc.stdout.readline()
self.assertEqual(line, b'sleeping\n')
proc.send_signal(signal.SIGHUP)
returncode = await proc.wait()
return returncode
returncode = self.loop.run_until_complete(send_signal(proc))
self.assertEqual(-signal.SIGHUP, returncode)
finally:
signal.signal(signal.SIGHUP, old_handler)
def prepare_broken_pipe_test(self):
# buffer large enough to feed the whole pipe buffer
large_data = b'x' * support.PIPE_MAX_SIZE
# the program ends before the stdin can be feeded
create = asyncio.create_subprocess_exec(
sys.executable, '-c', 'pass',
stdin=subprocess.PIPE,
loop=self.loop)
proc = self.loop.run_until_complete(create)
return (proc, large_data)
def test_stdin_broken_pipe(self):
proc, large_data = self.prepare_broken_pipe_test()
async def write_stdin(proc, data):
await asyncio.sleep(0.5, loop=self.loop)
proc.stdin.write(data)
await proc.stdin.drain()
coro = write_stdin(proc, large_data)
# drain() must raise BrokenPipeError or ConnectionResetError
with test_utils.disable_logger():
self.assertRaises((BrokenPipeError, ConnectionResetError),
self.loop.run_until_complete, coro)
self.loop.run_until_complete(proc.wait())
def test_communicate_ignore_broken_pipe(self):
proc, large_data = self.prepare_broken_pipe_test()
# communicate() must ignore BrokenPipeError when feeding stdin
with test_utils.disable_logger():
self.loop.run_until_complete(proc.communicate(large_data))
self.loop.run_until_complete(proc.wait())
def test_pause_reading(self):
limit = 10
size = (limit * 2 + 1)
async def test_pause_reading():
code = '\n'.join((
'import sys',
'sys.stdout.write("x" * %s)' % size,
'sys.stdout.flush()',
))
connect_read_pipe = self.loop.connect_read_pipe
async def connect_read_pipe_mock(*args, **kw):
transport, protocol = await connect_read_pipe(*args, **kw)
transport.pause_reading = mock.Mock()
transport.resume_reading = mock.Mock()
return (transport, protocol)
self.loop.connect_read_pipe = connect_read_pipe_mock
proc = await asyncio.create_subprocess_exec(
sys.executable, '-c', code,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
limit=limit,
loop=self.loop)
stdout_transport = proc._transport.get_pipe_transport(1)
stdout, stderr = await proc.communicate()
# The child process produced more than limit bytes of output,
# the stream reader transport should pause the protocol to not
# allocate too much memory.
return (stdout, stdout_transport)
# Issue #22685: Ensure that the stream reader pauses the protocol
# when the child process produces too much data
stdout, transport = self.loop.run_until_complete(test_pause_reading())
self.assertEqual(stdout, b'x' * size)
self.assertTrue(transport.pause_reading.called)
self.assertTrue(transport.resume_reading.called)
def test_stdin_not_inheritable(self):
# asyncio issue #209: stdin must not be inheritable, otherwise
# the Process.communicate() hangs
async def len_message(message):
code = 'import sys; data = sys.stdin.read(); print(len(data))'
proc = await asyncio.create_subprocess_exec(
sys.executable, '-c', code,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
close_fds=False,
loop=self.loop)
stdout, stderr = await proc.communicate(message)
exitcode = await proc.wait()
return (stdout, exitcode)
output, exitcode = self.loop.run_until_complete(len_message(b'abc'))
self.assertEqual(output.rstrip(), b'3')
self.assertEqual(exitcode, 0)
def test_empty_input(self):
async def empty_input():
code = 'import sys; data = sys.stdin.read(); print(len(data))'
proc = await asyncio.create_subprocess_exec(
sys.executable, '-c', code,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
close_fds=False,
loop=self.loop)
stdout, stderr = await proc.communicate(b'')
exitcode = await proc.wait()
return (stdout, exitcode)
output, exitcode = self.loop.run_until_complete(empty_input())
self.assertEqual(output.rstrip(), b'0')
self.assertEqual(exitcode, 0)
def test_cancel_process_wait(self):
# Issue #23140: cancel Process.wait()
async def cancel_wait():
proc = await asyncio.create_subprocess_exec(
*PROGRAM_BLOCKED,
loop=self.loop)
# Create an internal future waiting on the process exit
task = self.loop.create_task(proc.wait())
self.loop.call_soon(task.cancel)
try:
await task
except asyncio.CancelledError:
pass
# Cancel the future
task.cancel()
# Kill the process and wait until it is done
proc.kill()
await proc.wait()
self.loop.run_until_complete(cancel_wait())
def test_cancel_make_subprocess_transport_exec(self):
async def cancel_make_transport():
coro = asyncio.create_subprocess_exec(*PROGRAM_BLOCKED,
loop=self.loop)
task = self.loop.create_task(coro)
self.loop.call_soon(task.cancel)
try:
await task
except asyncio.CancelledError:
pass
# ignore the log:
# "Exception during subprocess creation, kill the subprocess"
with test_utils.disable_logger():
self.loop.run_until_complete(cancel_make_transport())
def test_cancel_post_init(self):
async def cancel_make_transport():
coro = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
*PROGRAM_BLOCKED)
task = self.loop.create_task(coro)
self.loop.call_soon(task.cancel)
try:
await task
except asyncio.CancelledError:
pass
# ignore the log:
# "Exception during subprocess creation, kill the subprocess"
with test_utils.disable_logger():
self.loop.run_until_complete(cancel_make_transport())
test_utils.run_briefly(self.loop)
def test_close_kill_running(self):
async def kill_running():
create = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
*PROGRAM_BLOCKED)
transport, protocol = await create
kill_called = False
def kill():
nonlocal kill_called
kill_called = True
orig_kill()
proc = transport.get_extra_info('subprocess')
orig_kill = proc.kill
proc.kill = kill
returncode = transport.get_returncode()
transport.close()
await transport._wait()
return (returncode, kill_called)
# Ignore "Close running child process: kill ..." log
with test_utils.disable_logger():
returncode, killed = self.loop.run_until_complete(kill_running())
self.assertIsNone(returncode)
# transport.close() must kill the process if it is still running
self.assertTrue(killed)
test_utils.run_briefly(self.loop)
def test_close_dont_kill_finished(self):
async def kill_running():
create = self.loop.subprocess_exec(asyncio.SubprocessProtocol,
*PROGRAM_BLOCKED)
transport, protocol = await create
proc = transport.get_extra_info('subprocess')
# kill the process (but asyncio is not notified immediately)
proc.kill()
proc.wait()
proc.kill = mock.Mock()
proc_returncode = proc.poll()
transport_returncode = transport.get_returncode()
transport.close()
return (proc_returncode, transport_returncode, proc.kill.called)
# Ignore "Unknown child process pid ..." log of SafeChildWatcher,
# emitted because the test already consumes the exit status:
# proc.wait()
with test_utils.disable_logger():
result = self.loop.run_until_complete(kill_running())
test_utils.run_briefly(self.loop)
proc_returncode, transport_return_code, killed = result
self.assertIsNotNone(proc_returncode)
self.assertIsNone(transport_return_code)
# transport.close() must not kill the process if it finished, even if
# the transport was not notified yet
self.assertFalse(killed)
# Unlike SafeChildWatcher, FastChildWatcher does not pop the
# callbacks if waitpid() is called elsewhere. Let's clear them
# manually to avoid a warning when the watcher is detached.
if (sys.platform != 'win32' and
isinstance(self, SubprocessFastWatcherTests)):
asyncio.get_child_watcher()._callbacks.clear()
def _test_popen_error(self, stdin):
if sys.platform == 'win32':
target = 'asyncio.windows_utils.Popen'
else:
target = 'subprocess.Popen'
with mock.patch(target) as popen:
exc = ZeroDivisionError
popen.side_effect = exc
create = asyncio.create_subprocess_exec(sys.executable, '-c',
'pass', stdin=stdin,
loop=self.loop)
with warnings.catch_warnings(record=True) as warns:
with self.assertRaises(exc):
self.loop.run_until_complete(create)
self.assertEqual(warns, [])
def test_popen_error(self):
# Issue #24763: check that the subprocess transport is closed
# when BaseSubprocessTransport fails
self._test_popen_error(stdin=None)
def test_popen_error_with_stdin_pipe(self):
# Issue #35721: check that newly created socket pair is closed when
# Popen fails
self._test_popen_error(stdin=subprocess.PIPE)
def test_read_stdout_after_process_exit(self):
async def execute():
code = '\n'.join(['import sys',
'for _ in range(64):',
' sys.stdout.write("x" * 4096)',
'sys.stdout.flush()',
'sys.exit(1)'])
fut = asyncio.create_subprocess_exec(
sys.executable, '-c', code,
stdout=asyncio.subprocess.PIPE,
loop=self.loop)
process = await fut
while True:
data = await process.stdout.read(65536)
if data:
await asyncio.sleep(0.3, loop=self.loop)
else:
break
self.loop.run_until_complete(execute())
if sys.platform != 'win32':
# Unix
class SubprocessWatcherMixin(SubprocessMixin):
Watcher = None
def setUp(self):
super().setUp()
policy | |
1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_181 = [_sedlex_rnd_179, _sedlex_rnd_180]
_sedlex_rnd_178 = [_sedlex_rnd_177]
_sedlex_DT_table_20 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_176 = [_sedlex_rnd_174, _sedlex_rnd_175]
_sedlex_DT_table_19 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_173 = [_sedlex_rnd_171, _sedlex_rnd_172]
_sedlex_DT_table_18 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_170 = [_sedlex_rnd_168, _sedlex_rnd_169]
_sedlex_DT_table_17 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_167 = [_sedlex_rnd_165, _sedlex_rnd_166]
_sedlex_rnd_164 = [_sedlex_rnd_163]
_sedlex_DT_table_16 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_162 = [_sedlex_rnd_160, _sedlex_rnd_161]
_sedlex_DT_table_15 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_159 = [_sedlex_rnd_157, _sedlex_rnd_158]
_sedlex_rnd_156 = [_sedlex_rnd_154, _sedlex_rnd_155]
_sedlex_rnd_153 = [_sedlex_rnd_151, _sedlex_rnd_152]
_sedlex_rnd_150 = [_sedlex_rnd_148, _sedlex_rnd_149]
_sedlex_rnd_147 = [_sedlex_rnd_145, _sedlex_rnd_146]
_sedlex_rnd_144 = [_sedlex_rnd_142, _sedlex_rnd_143]
_sedlex_rnd_141 = [_sedlex_rnd_139, _sedlex_rnd_140]
_sedlex_rnd_138 = [_sedlex_rnd_136, _sedlex_rnd_137]
_sedlex_rnd_135 = [_sedlex_rnd_133, _sedlex_rnd_134]
_sedlex_rnd_132 = [_sedlex_rnd_130, _sedlex_rnd_131]
_sedlex_DT_table_14 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3]
_sedlex_rnd_129 = [_sedlex_rnd_126, _sedlex_rnd_127, _sedlex_rnd_128]
_sedlex_DT_table_13 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
_sedlex_rnd_125 = [_sedlex_rnd_123, _sedlex_rnd_124]
_sedlex_DT_table_12 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
_sedlex_rnd_122 = [_sedlex_rnd_120, _sedlex_rnd_121]
_sedlex_DT_table_11 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3]
_sedlex_rnd_119 = [_sedlex_rnd_116, _sedlex_rnd_117, _sedlex_rnd_118]
_sedlex_DT_table_10 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
_sedlex_rnd_115 = [_sedlex_rnd_113, _sedlex_rnd_114]
_sedlex_rnd_112 = [_sedlex_rnd_111]
_sedlex_DT_table_9 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_110 = [_sedlex_rnd_109]
_sedlex_rnd_108 = [_sedlex_rnd_106, _sedlex_rnd_107]
_sedlex_rnd_105 = [_sedlex_rnd_104]
_sedlex_DT_table_8 = [1, 2]
_sedlex_rnd_103 = [_sedlex_rnd_101, _sedlex_rnd_102]
_sedlex_rnd_100 = [_sedlex_rnd_99]
_sedlex_rnd_98 = [_sedlex_rnd_95, _sedlex_rnd_96, _sedlex_rnd_97]
_sedlex_rnd_94 = [_sedlex_rnd_93]
_sedlex_DT_table_7 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_sedlex_rnd_92 = [_sedlex_rnd_91]
_sedlex_DT_table_6 = [1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3]
_sedlex_rnd_90 = [_sedlex_rnd_87, _sedlex_rnd_88, _sedlex_rnd_89]
_sedlex_rnd_86 = [_sedlex_rnd_85]
_sedlex_rnd_84 = [_sedlex_rnd_83]
_sedlex_DT_table_5 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
_sedlex_rnd_82 = [_sedlex_rnd_80, _sedlex_rnd_81]
_sedlex_rnd_79 = [_sedlex_rnd_78]
_sedlex_DT_table_4 = [1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
@ x_rot[0]
errs = single_npjpe_not_mean(gt_pose_cam0, cam0_rot_pred, allow_mirror)
pck = tf.reduce_mean(tf.cast(errs < threshold, tf.float32)) * 100
return pck
pck_batch = vmap.vmap(pck, ['gt_pose_cam0', 'cur_x'])
return pck_batch
def resh_mse(x_gt, fwd):
fwd_re = tf.reshape(fwd, tf.shape(x_gt))
return tfk.losses.mse(fwd_re, x_gt)
def print_single_view_stats(opt_stats_ds):
"""Prints pose estimation metrics of monocular 3D estimates."""
def _map_pmpjpe_nmpjpe_pck(key, rec):
del key
output = []
for i in range(_N_CAM.value):
epi_cam_f32 = tf.cast(rec['pose3d_epi_pred'][i], tf.float64)
rot = tf.cast(tf.transpose(rec['cam_rot'][i]), tf.float64)
npje = single_npjpe_not_mean(
rec['pose3d'] @ rot, epi_cam_f32, _DEBUG_ALLOW_MIRROR_IN_NMPJES.value)
errs = [
single_pmpjpe(rec['pose3d'], epi_cam_f32),
tf.reduce_mean(npje),
tf.reduce_mean(tf.cast(npje < 150, tf.float64)) * 100
]
output.append(errs)
per_cam_scores = [tf.reduce_mean(x) for x in zip(*output)]
return per_cam_scores
init_scores_ds = opt_stats_ds.map(_map_pmpjpe_nmpjpe_pck)
score = tf.reduce_mean(list(init_scores_ds), axis=0)
print('per-frame init pmpje/npjpe/pck: %.3f %.3f %.3f' % tuple(score.numpy()))
def get_datasets():
"""Get MetaPose training/validation/test datasets and original data shapes."""
validate_on_eval = _VALID_FIRST_N.value < 0
dataset_root = os.path.join(_DATA_ROOT.value, _DATASET.value)
train_opt_stats_ds, eval_opt_stats_ds = [
data_utils.read_tfrec_feature_dict_ds(os.path.join(dataset_root, split))
for split in _DATA_SPLITS.value]
if _DEBUG_SHOW_SINGLE_FRAME_PMPJES.value:
for opt_stats_ds in [train_opt_stats_ds, eval_opt_stats_ds]:
print_single_view_stats(opt_stats_ds)
train_val_pose_task_ds, problem_shapes = get_pose_task_dataset(
train_opt_stats_ds, _N_CAM.value, _N_JOINT.value, _N_MIX_COMP.value,
cam_permute_aug=_PERMUTE_CAMS_AUG.value, use_bone_len=_USE_BONE_LEN.value,
standardize_init_best=_STANDARDIZE_INIT_BEST.value)
eval_pose_task_ds, _ = get_pose_task_dataset(
eval_opt_stats_ds, _N_CAM.value, _N_JOINT.value, _N_MIX_COMP.value,
cam_permute_aug=False, use_bone_len=_USE_BONE_LEN.value,
standardize_init_best=_STANDARDIZE_INIT_BEST.value)
if validate_on_eval:
train_ds = (
train_val_pose_task_ds
.batch(_TRAIN_BATCH_SIZE.value)
.take(_DEBUG_TAKE_N_TRAIN_BATCHES.value))
eval_ds = (
eval_pose_task_ds
.batch(_EVAL_BATCH_SIZE.value)
.take(_DEBUG_TAKE_N_EVAL_BATCHES.value))
valid_ds = eval_ds
else:
train_ds = (
train_val_pose_task_ds
.skip(_VALID_FIRST_N.value)
.repeat(_TRAIN_REPEAT_K.value)
.shuffle(_SHUFFLE_SIZE.value, seed=0, reshuffle_each_iteration=True)
.batch(_TRAIN_BATCH_SIZE.value)
.take(_DEBUG_TAKE_N_TRAIN_BATCHES.value))
valid_ds = (
train_val_pose_task_ds
.take(_VALID_FIRST_N.value)
.repeat(_TRAIN_REPEAT_K.value)
.batch(_EVAL_BATCH_SIZE.value)
.take(_DEBUG_TAKE_N_EVAL_BATCHES.value))
eval_ds = (
eval_pose_task_ds
.batch(_EVAL_BATCH_SIZE.value)
.take(_DEBUG_TAKE_N_EVAL_BATCHES.value))
if _DEBUG_CACHE_DATASET.value:
train_ds, valid_ds, eval_ds = [
x.cache() for x in [train_ds, valid_ds, eval_ds]]
datasets = {'eval': eval_ds, 'train': train_ds, 'valid': valid_ds}
pack_specs = get_pack_specs_from_opt_stats_ds(
eval_opt_stats_ds, use_bone_len=_USE_BONE_LEN.value)
return datasets, problem_shapes, pack_specs
def get_losses_and_metrics(
datasets, pack_specs,
soln_loss_weights
):
"""Get all metrics/losses. Optimally compute them for the initial guess."""
# pylint:disable=g-long-lambda
logp_re_evaluate_batch = get_logp_re_evaluate_batch(pack_specs)
pose_forward_batch = get_pose_forward_fn_batch(pack_specs)
soln_opt_loss_fn = get_soln_optimizer_loss(soln_loss_weights, pack_specs)
pmpjpe_metric = get_pmpjpe_metric(pack_specs)
nmpjpe_metric = get_nmpjpe_metric(
pack_specs, allow_mirror=_DEBUG_ALLOW_MIRROR_IN_NMPJES.value)
pck_metric = get_percentage_of_correct_keypoints(
pack_specs, allow_mirror=_DEBUG_ALLOW_MIRROR_IN_NMPJES.value)
bone_len_fn = get_bone_length_fn(pack_specs)
funcs = {
'logp_re_evaluate': logp_re_evaluate_batch,
'pose_forward': pose_forward_batch,
'soln_opt_loss': soln_opt_loss_fn,
'pmpjpe': pmpjpe_metric,
'nmpjpe': nmpjpe_metric,
'pck': pck_metric,
'bone_len': bone_len_fn
}
if not _DATASET_WARMUP.value:
return funcs
# and we also need this to warm up the ds cache
# x['x_init']: epipolar init for 3d pose + cameras
# x['task_vec']: heatmaps [+ bone length]
# y['x_opt']: sgd optimal for 3d pose + cameras
# y['fwd']: ground truth 2d projections
# y['pred']: ground truth 3d pose
# y['pred_cam0']: ground truth 3d pose rotated to camera 0
warmup_funcs = {
'initial task loss': lambda x, y: logp_re_evaluate_batch(
pose_forward_batch(x['x_init'], x['task_vec']), x['task_vec']),
'optimal task loss': lambda x, y: logp_re_evaluate_batch(
pose_forward_batch(y['x_opt'], x['task_vec']), x['task_vec']),
'gt task loss': lambda x, y: logp_re_evaluate_batch(
y['fwd'], x['task_vec']),
'initial pmpjpe': lambda x, y: pmpjpe_metric(y['pred'], x['x_init']),
'optimal pmpjpe': lambda x, y: pmpjpe_metric(y['pred'], y['x_opt']),
'initial nmpjpe': lambda x, y: nmpjpe_metric(y['pred_cam0'], x['x_init']),
'optimal nmpjpe': lambda x, y: nmpjpe_metric(y['pred_cam0'], y['x_opt']),
'initial pck': lambda x, y: pck_metric(y['pred_cam0'], x['x_init']),
'optimal pck': lambda x, y: pck_metric(y['pred_cam0'], y['x_opt']),
'initial mse 2d': lambda x, y: resh_mse(
y['fwd'], pose_forward_batch(x['x_init'], x['task_vec'])),
'optimal mse 2d': lambda x, y: resh_mse(
y['fwd'], pose_forward_batch(y['x_opt'], x['task_vec']))
}
if _USE_BONE_LEN.value:
warmup_funcs.update({
'initial normalized bone len loss': lambda x, y: resh_mse(
y['pred_bone_len'], bone_len_fn(x['x_init'])),
'optimal normalized bone len loss': lambda x, y: resh_mse(
y['pred_bone_len'], bone_len_fn(y['x_opt']))
})
for split, ds in datasets.items():
print(split, 'len', len(list(ds)))
for name, fn in warmup_funcs.items():
print(split, name, '%.4f' % tf.reduce_mean(list(ds.map(fn).unbatch())))
return funcs
def get_callbacks(log_dir,
datasets,
stage_i,
best_val_score):
"""Get all MetaPose callbacks for the stage i."""
# pylint:disable=protected-access
tb_cb = tfk.callbacks.TensorBoard(log_dir)
# to disable very slow evaluation_*_vs_iteration reporting
tb_cb.on_test_end = lambda *argv, **kwargs: None
ds_writer_getters = {
# not created yet, so passing getters instead of actual writers
'train': (lambda: tb_cb._train_writer, datasets['train']),
'validation': (lambda: tb_cb._val_writer, datasets['valid']),
}
if _VALID_FIRST_N.value < 0:
# valid = eval, no further actions needed
eval_cbs = []
else:
eval_cb = EvaluteOnDatasetCallback(
log_dir, datasets['eval'], ds_name='test')
ds_writer_getters['test'] = (lambda: eval_cb.writer, datasets['eval'])
eval_cbs = [eval_cb]
cbs = [
TensorflowSaveWeightsFix(),
*eval_cbs,
tfk.callbacks.ModelCheckpoint(
'/tmp/best-model', monitor='val_pred_pmpjpe',
save_best_only=True, save_weights_only=True,
verbose=True),
tfk.callbacks.EarlyStopping(
monitor='val_pred_pmpjpe',
patience=_EARLY_STOPPING_PATIENCE.value,
verbose=True),
]
cbs.extend([
# this order to ensure summary writers are not closed
WriteStageMetrics(ds_writer_getters, stage_i,
'val_pred_pmpjpe', best_val_score),
tb_cb
])
return cbs
def get_simple_stage_model(mlp_sizes, x_shape,
task_shape, fwd_shape):
input_dim = x_shape + task_shape + fwd_shape + 2
model = tfk.Sequential([
tfkl.Dense(mlp_sizes[0], _ACTIVATION_FN.value, input_shape=(input_dim,)),
*[tfkl.Dense(k, _ACTIVATION_FN.value) for k in mlp_sizes[1:]],
tfkl.Dense(x_shape)
])
return model
def _unpack_tensor_batch(batch, spec):
# pylint:disable=protected-access
return tf.vectorized_map(
lambda x: vmap._unpack_single_tensor(x, spec), batch)
# % ---
class ContextNormalization(tfk.Model):
"""A permutation-eqvivariant layer standardizing feature maps.
See "Learning to Find Good Correspondences" by Yi et al.
"""
def call(self, inputs):
tf.assert_rank(inputs, 3)
average = tf.reduce_mean(inputs, axis=1)[:, None, :]
std = tf.math.reduce_std(inputs, axis=1)[:, None, :]
normalized = (inputs - average) / (std + 1e-10)
return normalized
class ContextConcatenation(tfk.Model):
"""A permutation-eqvivariant layer concatenating moments to feature maps."""
def call(self, inputs):
tf.assert_rank(inputs, 3)
ctx_size = tf.shape(inputs)[1]
average = tf.reduce_mean(inputs, axis=1)[:, None, :]
std = tf.math.reduce_std(inputs, axis=1)[:, None, :]
average, std = [tf.repeat(x, ctx_size, axis=1) for x in [average, std]]
concated = tf.concat([inputs, average, std], axis=2)
return concated
EquivariantMLPSpec = Sequence[Union[int, Literal['cn'], Literal['ccat']]]
def EquivariantMLP(input_shape, # pylint: disable=invalid-name
output_dim,
mlp_spec,
activation):
"""Produces a permutation-eqvivariant MLP."""
assert isinstance(mlp_spec[0], int)
layers = [tfkl.Dense(mlp_spec[0], activation, input_shape=input_shape)]
for size_or_cn in mlp_spec:
if size_or_cn == 'cn':
layers.append(ContextNormalization())
elif size_or_cn == 'ccat':
layers.append(ContextConcatenation())
elif isinstance(size_or_cn, int):
layers.append(tfkl.Dense(size_or_cn, _ACTIVATION_FN.value))
else:
raise ValueError('unsupported eqvivar mlp spec %s' % mlp_spec)
layers.append(tfkl.Dense(output_dim))
return tfk.Sequential(layers)
class InvariantStageModel(tfk.Model):
"""A permutation-equivariant model compatible with `DeepInverseSolver`."""
def __init__(self, main_mlp_spec, pose_emb_size,
pose_mlp_sizes, pack_specs,
**kwargs):
super().__init__(**kwargs)
self.main_equiv_mlp_spec = main_mlp_spec
self.pack_specs = pack_specs
self.pose_emb_size = pose_emb_size
n_cam, n_joint, n_comp = pack_specs[1][0][:3]
fwd_shape = n_cam * n_joint * 2
x_shape = n_joint*3 + n_cam*(6 + 1 + 3)
task_shape = n_cam * n_joint * n_comp * 4
if _USE_BONE_LEN.value:
task_shape += _BONE_COUNT.value
used_bone_count = _BONE_COUNT.value
else:
used_bone_count = 0
self.x_shape = x_shape
self.task_shape = task_shape
self.fwd_shape = fwd_shape
mlp_input_data_dim = 0
input_data_parts_dims = {
'pose': n_joint * 3,
'cams': 10, # 6 + 3 + 1
'heatmaps': n_joint * n_comp * 4,
'projs': n_joint * 2,
'loss': 2
}
drop_mlp_inputs = _DEBUG_DROP_MLP_INPUTS.value
if any(x not in input_data_parts_dims for x in drop_mlp_inputs):
raise ValueError('unknown droppable %s' % drop_mlp_inputs)
for name, input_part_size in input_data_parts_dims.items():
if name not in drop_mlp_inputs:
mlp_input_data_dim += input_part_size
if _USE_BONE_LEN.value:
mlp_input_data_dim += used_bone_count
assert mlp_input_data_dim > 0
main_mlp_input_shape = (n_cam, mlp_input_data_dim)
main_mlp_output_dim = pose_emb_size + (6 + 1 + 3)
print('Eqvivariant spec: ',
[main_mlp_spec, pose_emb_size, pose_mlp_sizes, _ACTIVATION_FN.value,
main_mlp_input_shape, main_mlp_output_dim,
drop_mlp_inputs])
# can't change the name or checkpoints will break
self.main_mlp = EquivariantMLP(
main_mlp_input_shape, main_mlp_output_dim,
main_mlp_spec, _ACTIVATION_FN.value)
self.pose_mlp = tfk.Sequential([
tfkl.Dense(pose_mlp_sizes[0], _ACTIVATION_FN.value,
input_shape=(pose_emb_size,)),
*[tfkl.Dense(k, _ACTIVATION_FN.value) for k in pose_mlp_sizes[1:]],
tfkl.Dense(n_joint*3)
])
def call(self, inputs):
# inputs: [B, x_shape + task_shape + fwd_shape + 2]
x_spec, task_spec = self.pack_specs
n_cam, n_joint = task_spec[0][0], task_spec[0][1]
batch_size = tf.shape(inputs)[0]
cur_x, task_vec, cur_fwd, loss_stage = tf.split(
inputs, [self.x_shape, self.task_shape, self.fwd_shape, 2], axis=1)
# [B, x_shape] = [B, J*3 + ...]
# [B, J, 3], [B, C, 2, 3], [B, C], [B, C, 3]
x_pose, x_rot_re, x_scale_re, x_shift = _unpack_tensor_batch(cur_x, x_spec)
# [B, C, J, K, 4]
heatmaps_arr = _unpack_tensor_batch(task_vec, task_spec)[0]
# [B, C, J, 2]
cur_fwd_resh = tf.reshape(cur_fwd, (batch_size, n_cam, n_joint, 2))
mlp_inputs = {
'invariant': {
'pose': [x_pose],
'loss': [loss_stage]
},
'eqvivariant': {
'cams': [x_rot_re, x_scale_re, x_shift],
'heatmaps': [heatmaps_arr],
'projs': [cur_fwd_resh]
}
}
mlp_inputs_filtered = {k: [] for k in mlp_inputs}
for kind, kind_input_dict in mlp_inputs.items():
for input_name, input_arrs in kind_input_dict.items():
if input_name not in _DEBUG_DROP_MLP_INPUTS.value:
mlp_inputs_filtered[kind].extend(input_arrs)
if _USE_BONE_LEN.value:
bone_len_arr = _unpack_tensor_batch(task_vec, task_spec)[1]
mlp_inputs_filtered['invariant'].append(bone_len_arr) # [B, S]
glob_vecs = mlp_inputs_filtered['invariant']
cam_vecs = mlp_inputs_filtered['eqvivariant']
for cam_dep_vec in cam_vecs:
tf.assert_equal(tf.shape(cam_dep_vec)[1], n_cam)
# [B, J*3 + 2 + S]
# glob_concated = tf.concat(
# [tf.reshape(x, (batch_size, -1)) for x in glob_vecs], axis=1)
# [B, C, J*3 + 2 + S]
# glob_concated_repeated = tf.repeat(glob_concated[:, None], n_cam, axis=1)
# # [B, C, 6 + 1 + 3 + J*K*4 + J*2]
# cam_vecs_concated = tf.concat([
# tf.reshape(x, (batch_size, n_cam, -1)) for x in cam_vecs], axis=2)
# [[B, C, J*3], [B, C, 2], [B, C, S]]
# where S = _BONE_COUNT.value or zero
glob_flat_repeated = [
tf.repeat(tf.reshape(x, (batch_size, 1, -1)), n_cam, axis=1)
for x in glob_vecs
]
# [B, C, 6 + 1 + 3], [B, C, J*K*4], [B, C, J*2]]
cam_vecs_flat = [tf.reshape(x, (batch_size, n_cam, -1)) for | |
pore or throat labels are returned. If empty then
both are returned (default).
pores (or throats) : array_like
The pores (or throats) whose labels are sought. If left empty a
list containing all pore and throat labels is returned.
mode : string, optional
Controls how the query should be performed. Only applicable
when ``pores`` or ``throats`` are specified:
**'or', 'union', 'any'**: (default) Returns the labels that are
assigned to *any* of the given locations.
**'and', 'intersection', 'all'**: Labels that are present on *all*
the given locations.
**'xor', 'exclusive_or'** : Labels that are present on *only one*
of the given locations.
**'nor', 'none', 'not'**: Labels that are *not* present on any of
the given locations.
**'nand'**: Labels that are present on *all but one* of the given
locations
**'xnor'**: Labels that are present on *more than one* of the given
locations. 'nxor' is also accepted.
Returns
-------
A list containing the labels on the object. If ``pores`` or
``throats`` are given, the results are filtered according to the
specified ``mode``.
See Also
--------
props
keys
Notes
-----
Technically, *'nand'* and *'xnor'* should also return pores with *none*
of the labels but these are not included. This makes the returned list
more useful.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> pn.labels(pores=[11, 12])
['pore.all', 'pore.front', 'pore.internal', 'pore.surface']
"""
# Short-circuit query when no pores or throats are given
if (sp.size(pores) == 0) and (sp.size(throats) == 0):
labels = PrintableList(self.keys(element=element, mode='labels'))
elif (sp.size(pores) > 0) and (sp.size(throats) > 0):
raise Exception('Cannot perform label query on pores and ' +
'throats simultaneously')
elif sp.size(pores) > 0:
labels = self._get_labels(element='pore', locations=pores,
mode=mode)
elif sp.size(throats) > 0:
labels = self._get_labels(element='throat', locations=throats,
mode=mode)
return labels
def _get_indices(self, element, labels='all', mode='or'):
r"""
This is the actual method for getting indices, but should not be called
directly. Use ``pores`` or ``throats`` instead.
"""
# Parse and validate all input values.
element = self._parse_element(element, single=True)
labels = self._parse_labels(labels=labels, element=element)
if element+'.all' not in self.keys():
raise Exception('Cannot proceed without {}.all'.format(element))
# Begin computing label array
if mode in ['or', 'any', 'union']:
union = sp.zeros_like(self[element+'.all'], dtype=bool)
for item in labels: # Iterate over labels and collect all indices
union = union + self[element+'.'+item.split('.')[-1]]
ind = union
elif mode in ['and', 'all', 'intersection']:
intersect = sp.ones_like(self[element+'.all'], dtype=bool)
for item in labels: # Iterate over labels and collect all indices
intersect = intersect*self[element+'.'+item.split('.')[-1]]
ind = intersect
elif mode in ['xor', 'exclusive_or']:
xor = sp.zeros_like(self[element+'.all'], dtype=int)
for item in labels: # Iterate over labels and collect all indices
info = self[element+'.'+item.split('.')[-1]]
xor = xor + sp.int8(info)
ind = (xor == 1)
elif mode in ['nor', 'not', 'none']:
nor = sp.zeros_like(self[element+'.all'], dtype=int)
for item in labels: # Iterate over labels and collect all indices
info = self[element+'.'+item.split('.')[-1]]
nor = nor + sp.int8(info)
ind = (nor == 0)
elif mode in ['nand']:
nand = sp.zeros_like(self[element+'.all'], dtype=int)
for item in labels: # Iterate over labels and collect all indices
info = self[element+'.'+item.split('.')[-1]]
nand = nand + sp.int8(info)
ind = (nand < len(labels)) * (nand > 0)
elif mode in ['xnor', 'nxor']:
xnor = sp.zeros_like(self[element+'.all'], dtype=int)
for item in labels: # Iterate over labels and collect all indices
info = self[element+'.'+item.split('.')[-1]]
xnor = xnor + sp.int8(info)
ind = (xnor > 1)
else:
raise Exception('Unsupported mode: '+mode)
# Extract indices from boolean mask
ind = sp.where(ind)[0]
ind = ind.astype(dtype=int)
return ind
def pores(self, labels='all', mode='or', asmask=False):
r"""
Returns pore indicies where given labels exist, according to the logic
specified by the ``mode`` argument.
Parameters
----------
labels : string or list of strings
The label(s) whose pores locations are requested. This argument
also accepts '*' for wildcard searches.
mode : string
Specifies how the query should be performed. The options are:
**'or', 'union', 'any'** : (default) Pores with *one or more* of
the given labels are returned.
**'and', 'intersection', 'all'** : Pores with *all* of the given
labels are returned.
**'xor', 'exclusive_or'** : Pores with *only one* of the given
labels are returned.
**'nor', 'none', 'not'** : Pores with *none* of the given labels
are returned.
**'nand'** : Pores with *not all* of the given labels are
returned.
**'xnor'** : Pores with *more than one* of the given labels are
returned.
asmask : boolean
If ``True`` then a boolean array of length Np is returned with
``True`` values indicating the pores that satisfy the query.
Returns
-------
A Numpy array containing pore indices filtered by the logic specified
in ``mode``.
See Also
--------
throats
Notes
-----
Technically, *nand* and *xnor* should also return pores with *none* of
the labels but these are not included. This makes the returned list
more useful.
To perform more complex or compound queries, you can opt to receive
the result a a boolean mask (``asmask=True``), then manipulate the
arrays manually.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ps = pn.pores(labels=['top', 'front'], mode='union')
>>> Ps[:5] # Look at first 5 pore indices
array([0, 1, 2, 3, 4])
>>> pn.pores(labels=['top', 'front'], mode='xnor')
array([ 4, 9, 14, 19, 24])
"""
ind = self._get_indices(element='pore', labels=labels, mode=mode)
if asmask:
ind = self.tomask(pores=ind)
return ind
@property
def Ps(self):
r"""
A shortcut to get a list of all pores on the object
"""
return sp.arange(0, self.Np)
def throats(self, labels='all', mode='or', asmask=False):
r"""
Returns throat locations where given labels exist, according to the
logic specified by the ``mode`` argument.
Parameters
----------
labels : string or list of strings
The throat label(s) whose locations are requested. If omitted,
'all' throat inidices are returned. This argument also accepts
'*' for wildcard searches.
mode : string
Specifies how the query should be performed. The options are:
**'or', 'union', 'any'** : (default) Throats with *one or more* of
the given labels are returned.
**'and', 'intersection', 'all'** : Throats with *all* of the given
labels are returned.
**'xor', 'exclusive_or'** : Throats with *only one* of the given
labels are returned.
**'nor', 'none', 'not'** : Throats with *none* of the given labels
are returned.
**'nand'** : Throats with *not all* of the given labels are
returned.
**'xnor'** : Throats with *more than one* of the given labels are
returned.
asmask : boolean
If ``True`` then a boolean array of length Nt is returned with
``True`` values indicating the throats that satisfy the query.
Returns
-------
A Numpy array containing throat indices filtered by the logic specified
in ``mode``.
See Also
--------
pores
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[3, 3, 3])
>>> Ts = pn.throats()
>>> Ts[0:5] # Look at first 5 throat indices
array([0, 1, 2, 3, 4])
"""
ind = self._get_indices(element='throat', labels=labels, mode=mode)
if asmask:
ind = self.tomask(throats=ind)
return ind
@property
def Ts(self):
r"""
A shortcut to get a list of all throats on the object
"""
return sp.arange(0, self.Nt)
def _map(self, ids, element, filtered):
ids = sp.array(ids, dtype=sp.int64)
locations = self._get_indices(element=element)
self_in_ids = sp.isin(ids, self[element+'._id'], assume_unique=True)
ids_in_self = sp.isin(self[element+'._id'], ids, assume_unique=True)
mask = sp.zeros(shape=ids.shape, dtype=bool)
mask[self_in_ids] = True
ind = sp.ones_like(mask, dtype=sp.int64) * -1
ind[self_in_ids] = locations[ids_in_self]
if filtered:
return ind[mask]
else:
t = namedtuple('index_map', ('indices', 'mask'))
return t(ind, mask)
def map_pores(self, pores, origin, filtered=True):
r"""
Given a list of pore on a target object, finds indices of those pores
on the calling object
Parameters
----------
pores : array_like
The indices of the pores on the object specifiedin ``origin``
origin : OpenPNM Base object
The object corresponding to the indices given in ``pores``
filtered : boolean (default is ``True``)
If ``True`` then a ND-array of indices is returned with missing
indices removed, otherwise a named-tuple containing both the
``indices`` and a boolean ``mask`` with ``False`` indicating
which locations were not found.
Returns
-------
Pore indices on the calling object corresponding to the same pores
on the ``origin`` object. Can be | |
= PerlTreeEvaluator(ctlr, buf, trg, citdl_expr,
line, filter)
buf.mgr.request_eval(evalr)
def libs_from_buf(self, buf):
env = buf.env
# A buffer's libs depend on its env and the buf itself so
# we cache it on the env and key off the buffer.
if "perl-buf-libs" not in env.cache:
env.cache["perl-buf-libs"] = weakref.WeakKeyDictionary()
cache = env.cache["perl-buf-libs"] # <buf-weak-ref> -> <libs>
if buf not in cache:
# - curdirlib
# Using the dirname of this buffer isn't always right, but
# hopefully is a good first approximation.
cwd = dirname(buf.path)
if cwd == "<Unsaved>":
libs = []
else:
libs = [self.mgr.db.get_lang_lib("Perl", "curdirlib", [cwd])]
libs += self._buf_indep_libs_from_env(env)
cache[buf] = libs
return cache[buf]
def perl_info_from_env(self, env):
# Return an array of [perl_ver, config_dirs, import_path]
cache_key = self.lang + "-info"
info = env.cache.get(cache_key)
if info is None:
perlInterpreter = self._perl_from_env(env)
if not perlInterpreter:
log.warn("no Perl interpreter was found from which to determine the "
"codeintel information")
info = None, None, None
else:
info = self._perl_info_from_perl(perlInterpreter, env)
env.cache[cache_key] = info
return info
def _perl_from_env(self, env):
import which
path = [d.strip()
for d in env.get_envvar("PATH", "").split(os.pathsep)
if d.strip()]
try:
return which.which("perl", path=path)
except which.WhichError:
return None
def _perl_info_from_perl(self, perl, env):
"""Call the given Perl and return:
(<version>, <config_dirs>, <import_path>)
where <config_dirs> is a dict with (relevant) dirs from
Config.pm.
"""
import process
info_cmd = (r'use Config;'
r'print "version:$Config{version}\n";'
r'print "siteprefix:$Config{siteprefix}\n";'
r'print "archlib:$Config{archlib}\n";'
r'print "privlib:$Config{privlib}\n";'
r'print "vendorarch:$Config{vendorarch}\n";'
r'print "vendorlib:$Config{vendorlib}\n";'
r'print join("\n", @INC);')
argv = [perl, "-e", info_cmd]
log.debug("run `%s -e ...'", perl)
p = process.ProcessOpen(argv, env=env.get_all_envvars(), stdin=None)
stdout, stderr = p.communicate()
stdout_lines = stdout.splitlines(0)
retval = p.returncode
if retval:
log.warn("failed to determine Perl info:\n"
" path: %s\n"
" retval: %s\n"
" stdout:\n%s\n"
" stderr:\n%s\n",
perl, retval, indent('\n'.join(stdout_lines)),
indent(stderr))
perl_ver = stdout_lines[0].split(':', 1)[1]
config_dirs = dict(
siteprefix=stdout_lines[1].split(':', 1)[1],
archlib=stdout_lines[2].split(':', 1)[1],
privlib=stdout_lines[3].split(':', 1)[1],
vendorarch=stdout_lines[4].split(':', 1)[1],
vendorlib=stdout_lines[5].split(':', 1)[1],
)
import_path = stdout_lines[6:]
return perl_ver, config_dirs, import_path
#def _extra_dirs_from_env(self, env):
# extra_dirs = set()
# for pref in env.get_all_prefs("perlExtraPaths"):
# if not pref:
# continue
# extra_dirs.update(d.strip() for d in pref.split(os.pathsep)
# if exists(d.strip()))
# return tuple(extra_dirs)
def _buf_indep_libs_from_env(self, env):
"""Create the buffer-independent list of libs."""
cache_key = "perl-libs"
if cache_key not in env.cache:
env.add_pref_observer("perl", self._invalidate_cache)
env.add_pref_observer("perlExtraPaths",
self._invalidate_cache_and_rescan_extra_dirs)
env.add_pref_observer("codeintel_selected_catalogs",
self._invalidate_cache)
db = self.mgr.db
# Gather information about the current perl.
perl = None
if env.has_pref("perl"):
perl = env.get_pref("perl").strip() or None
if not perl or not exists(perl):
perl = self._perl_from_env(env)
if not perl:
log.warn("no Perl was found from which to determine the "
"import path")
perl_ver, config_dirs, import_path = None, {}, []
else:
perl_ver, config_dirs, import_path \
= self._perl_info_from_perl(perl, env)
libs = []
# - extradirslib
extra_dirs = self._extra_dirs_from_env(env)
if extra_dirs:
log.debug("Perl extra lib dirs: %r", extra_dirs)
libs.append(db.get_lang_lib("Perl", "extradirslib",
extra_dirs))
# Figuring out where the lib and sitelib dirs are is hard --
# or at least complex from my P.O.V.
# - For ActivePerl (on Linux, at least):
# $ perl -e 'print join "\n", @INC'
# /home/trentm/opt/ActivePerl-5.8.8.818/site/lib
# (sitearch, sitelib, siteprefix)
# /home/trentm/opt/ActivePerl-5.8.8.818/lib
# (archlib, privlib)
# . (???, we'll handle with curdirlib)
# - For /usr/bin/perl on skink (ubuntu 6):
# $ /usr/bin/perl -e 'print join "\n", @INC'
# /etc/perl (???)
# /usr/local/lib/perl/5.8.7 (sitearch, siteprefix)
# /usr/local/share/perl/5.8.7 (sitelib, siteprefix)
# /usr/lib/perl5 (vendorarch)
# /usr/share/perl5 (vendorlib)
# /usr/lib/perl/5.8 (archlib)
# /usr/share/perl/5.8 (privlib)
# /usr/local/lib/site_perl (???, siteprefix)
paths_from_libname = {"sitelib": [], "envlib": [], "stdlib": []}
for dir in import_path:
dir = normpath(dir)
if dir == ".": # -> curdirlib (handled separately)
continue
if islink(dir):
# Note: this doesn't handle multiple levels of
# links.
link_value = os.readlink(dir)
if isabs(link_value):
dir = link_value
else:
dir = normpath(join(dirname(dir), link_value))
if not isdir(dir):
log.debug("perl @INC value '%s' is not a dir: dropping it",
dir)
continue
for config_dir_name in ("archlib", "privlib",
"vendorarch", "vendorlib"):
if config_dirs[config_dir_name] \
and dir.startswith(config_dirs[config_dir_name]):
paths_from_libname["stdlib"].append(dir)
break
else:
if config_dirs["siteprefix"] \
and dir.startswith(config_dirs["siteprefix"]):
paths_from_libname["sitelib"].append(dir)
else:
paths_from_libname["envlib"].append(dir)
log.debug("Perl %s paths for each lib:\n%s",
perl_ver, indent(pformat(paths_from_libname)))
# - envlib, sitelib, cataloglib, stdlib
if paths_from_libname["envlib"]:
libs.append(db.get_lang_lib("Perl", "envlib",
paths_from_libname["envlib"]))
if paths_from_libname["sitelib"]:
libs.append(db.get_lang_lib("Perl", "sitelib",
paths_from_libname["sitelib"]))
catalog_selections = env.get_pref("codeintel_selected_catalogs")
libs += [
db.get_catalog_lib("Perl", catalog_selections),
db.get_stdlib("Perl", perl_ver)
]
env.cache[cache_key] = libs
return env.cache[cache_key]
def _invalidate_cache(self, env, pref_name):
for key in ("perl-buf-libs", "perl-libs"):
if key in env.cache:
log.debug("invalidate '%s' cache on %r", key, env)
del env.cache[key]
def _invalidate_cache_and_rescan_extra_dirs(self, env, pref_name):
self._invalidate_cache(env, pref_name)
extra_dirs = self._extra_dirs_from_env(env)
if extra_dirs:
extradirslib = self.mgr.db.get_lang_lib(
"Perl", "extradirslib", extra_dirs)
request = PreloadLibRequest(extradirslib)
self.mgr.idxr.stage_request(request, 1.0)
#---- code browser integration
cb_import_group_title = "Uses and Requires"
def cb_import_data_from_elem(self, elem):
alias = elem.get("alias")
symbol = elem.get("symbol")
module = elem.get("module")
if symbol:
if symbol == "*":
name = module
detail = "use %s" % module
elif symbol == "**":
name = module
detail = "use %s qw(:<tag>)" % module
else:
name = "::".join([module, symbol])
detail = "use %s qw(%s)" % (module, symbol)
else:
name = module
# This is either "use Foo ();" or "require Foo;". A search
# the of the Perl 5.8 site lib should that the latter is about
# 6 times more likely -- lets use that.
detail = "require %s" % module
return {"name": name, "detail": detail}
class PerlBuffer(CitadelBuffer):
lang = "Perl"
sce_prefixes = ["SCE_PL_"]
cb_show_if_empty = True
# 'cpln_fillup_chars' exclusions for Perl:
# - cannot be '-' for "complete-*-subs" because:
# attributes::->import(__PACKAGE__, \$x, 'Bent');
# - cannot be '{' for "complete-object-subs" because:
# my $d = $self->{'escape'};
# - shouldn't be ')' because:
# $dumper->dumpValue(\*::);
# - shouldn't be ':' (bug 65292)
cpln_fillup_chars = "~`!@#$%^&*(=+}[]|\\;'\",.<>?/ "
cpln_stop_chars = "-~`!@#$%^&*()=+{}[]|\\;:'\",.<>?/ "
def __init__(self, *args, **kwargs):
CitadelBuffer.__init__(self, *args, **kwargs)
# Some Perl styles in addition to the usual comment and string styles
# in which completion triggering should not happen.
self.completion_skip_styles[ScintillaConstants.SCE_PL_REGEX] = True
@property
def libs(self):
return self.langintel.libs_from_buf(self)
@property
def stdlib(self):
return self.libs[-1]
class PerlImportHandler(ImportHandler):
PATH_ENV_VAR = "PERL5LIB"
sep = "::"
def _shellOutForPath(self, compiler):
import process
sep = "--WomBa-woMbA--"
argv = [compiler, "-e", "print join('%s', @INC);" % sep]
env = dict(os.environ)
if "PERL5LIB" in env:
del env["PERL5LIB"]
if "PERLLIB" in env:
del env["PERLLIB"]
p = process.ProcessOpen(argv, env=env, stdin=None)
output, error = p.communicate()
retval = p.returncode
if retval:
raise CodeIntelError("could not determine Perl import path: %s"
% error)
path = [normpath(d) for d in output.split(sep)]
# cwd handled separately
path = [p for p in path if p not in (os.curdir, os.getcwd())]
return path
def setCorePath(self, compiler=None, extra=None):
if compiler is None:
import which
compiler = which.which("perl")
self.corePath = self._shellOutForPath(compiler)
def _findScannableFiles(self, xxx_todo_changeme,
dirname, names):
(files, searchedDirs,
skipTheseDirs, skipRareImports) = xxx_todo_changeme
if sys.platform.startswith("win"):
cpath = dirname.lower()
else:
cpath = dirname
if cpath in searchedDirs:
while names:
del names[0]
return
else:
searchedDirs[cpath] = 1
if skipRareImports:
# Skip .pl files when scanning a Perl lib/sitelib.
scannableExts = (".pm",)
else:
scannableExts = (".pl", ".pm")
for i in range(len(names)-1, -1, -1): # backward so can del from list
path = join(dirname, names[i])
if isdir(path):
if normcase(path) in skipTheseDirs:
del names[i]
elif skipRareImports and not ('A' <= names[i][0] <= 'Z'):
# Perl good practice dictates that all module directories
# begin with a capital letter. Therefore, we skip dirs
# that start with a lower case.
del names[i]
elif splitext(names[i])[1] in scannableExts:
# XXX The list of extensions should be settable on
# the ImportHandler and Komodo should set whatever is
# set in prefs.
# XXX This check for files should probably include
# scripts, which might likely not have the
# extension: need to grow filetype-from-content smarts.
files.append(path)
def find_importables_in_dir(self, dir):
"""See citadel.py::ImportHandler.find_importables_in_dir() for
details.
Importables for Perl look like this:
{"Shell": ("Shell.pm", None, False),
"LWP": ("LWP.pm", None, True),
"XML": (None, None, True)}
Notes:
- Drop the "auto" dir (it holds the binary module bits).
- Keep non-capitalized dirs and modules (e.g. want "strict" in
cplns for "use <|>").
"""
from os.path import join, isdir, splitext
if dir == "<Unsaved>":
# TODO: stop these getting in here.
return {}
# TODO: log the fs-stat'ing a la codeintel.db logging.
try:
names = os.listdir(dir)
except OSError as ex:
return {}
| |
'''
Copyright (c) 2017-2018, wezu (<EMAIL>)
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
import sys
if sys.version_info >= (3, 0):
import builtins
else:
import __builtin__ as builtins
import math
import random
import string
import datetime
import os
import copy
from contextlib import contextmanager
#this is the template string for formating the info in the 'stats' frame
stat_template='''
Armor Class: {ac:>3} Hit Points: {max_hp:>3} Crit. Power/CC:{crit_power:>3}/{crit_power_cc:>3} Bonus Damage: {bonus_dmg:>2}% HEX for 95% vs AC50 (eye aim):
Action Points: {ap:>3} HP/Level: {hp_per_level:>3} Critical Res.: {crit_res:>3} Bonus Fire Dmg.:{bonus_fire_dmg:>2}% SG: {sg_range:>4}({sg_range_aim:>3})
Carry Weight: {carry_weight:>3} Skill Points: {sp:>3} Crit. Res. Head: {crit_res_head:>3} Target DR: {target_dr:>2} SG long range: {sg_longrange:>4}({sg_longrange_aim:>3})
Melee Damage: {melee:>3} SP/Level: {sp_per_level:>3} Normal DT/DR: {normal_dt}/{normal_dr:>3}% Bonus XP: {bonus_xp:>2}% BG: {bg_range:>4}({bg_range_aim:>3})
Poison Res.: {poision_res:>3} Party Points: {pp:>3} Laser DT/DR: {laser_dt}/{laser_dr:>3}% Drug time: {drug_duration:>3}% BG long range: {bg_longrange:>4}({bg_longrange_aim:>3})
Radiation Res.: {radiation_res:>3} Total Perks: {max_perks:>3} Fire DT/DR: {fire_dt}/{fire_dr:>3}% Drug heal: {drug_heal:>3}% EW: {ew_range:>4}({ew_range_aim:>3})
Healing Rate: {healing_rate:>3} Unused Perks: {free_perks:>3} Plasma DT/DR: {plasma_dt}/{plasma_dr:>3}% FA healed: ~{fa_healed:>3} EW long range: {ew_longrange:>4}({ew_longrange_aim:>3})
Crit. Chance: {crit_chance:>3} Sight: {sight_a}/{sight_b}/{sight_c}/{sight_d:>2} Explode DT/DR: {explode_dt}/{explode_dr:>3}% FA cooldown: {fa_cooldown:>3} Throwing: {tw_range:>4}({tw_range_aim:>3})
CC. Crit. Chance:{crit_chance_cc:>3} Level: {lvl:>3} Electric DT/DR: {electrical_dt}/{electrical_dr:>3}% Doc cooldown: {doc_cooldown:>3}
'''
#this is the template string for formating the info in the 'target' frame
target_template='''Armor Class: 30
DT: DR:
NORMAL: {normal_dt:>2} {normal_dr:>2}
LASER: {laser_dt:>2} {laser_dr:>2}
FIRE: {fire_dt:>2} {fire_dr:>2}
PLASMA: {plasma_dt:>2} {plasma_dr:>2}
EXPLODE: {explode_dt:>2} {explode_dr:>2}
ELECTRIC: {electric_dt:>2} {electric_dr:>2}
CRITICAL RESISTANCE:
POWER: {crit_pow:>2}
CHANCE: {crit_c:>2}
ENDURANCE: {e:>2}
LUCK: {l:>2}
STRENGTH: {s:>2}
'''
class Stats():
'''
This calss handels calculating all Fonline stats
'''
def __init__(self):
#create some data structures used later
self.memory=[]
self.bonuses={}
self.perks={}
self.traits={}
self.skills={}
self.last_level_skills={}
self.tags={}
#fill in some data structures
self.current_gun=None
self.level=1
self.aim_mode='UNAIMED'
self.special={'s':5,'p':5,'e':5,'c':5,'i':5,'a':5,'l':5,'none':5}
self.target_stats={ 'ac':0, 'normal_dr':0, 'normal_dt':0, 'laser_dr':0,
'laser_dt': 0, 'fire_dr':0, 'fire_dt':0,
'plasma_dr':0, 'plasma_dt': 0, 'explode_dr': 0,
'explode_dt': 0, 'electric_dr':0, 'electric_dt':0,
'crit_c':0 ,'crit_pow':0, 'l':5, 's':5, 'e':5, None:0}
#bonus for aim modes critical chance and also to-hit penalty
self.aim_bonus={'EYE':60,
'HEAD':40,
'TORSO':0,
'GROIN':30,
'HANDS':30,
'LEGS':20,
'UNAIMED':0,
'BURST':0}
self.derived={'max_hp':0,'hp_per_level':0, 'sp':0, 'sp_per_level':0,'pp':0,
'max_perks':8, 'free_perks':0, 'sight':0, 'sequence':0,'lvl':0,
'ac':0, 'ap':0, 'carry_weight':0, 'melee':0, 'poision_res':0,
'radiation_res':0, 'healing_rate':0, 'crit_chance':0}
#some traits change SPECIAL, they are listed here
self.trait_special={'Bruiser':{'s':4},'Bonehead':{'i':-1}}
#maximum level of skills
self.skill_limits={'Small Guns':300,'Big Guns':300,'Energy Guns':300,
'Close Combat':300,'Throwing':300,'First Aid':200,
'Doctor':200,'Lockpick':150,'Repair':125,'Science':125,
'Outdoorsman':175,'Scavenging':0,'Sneak':270,'Steal':150,
'Traps':150,'Speech':300,'Gambling':150,'Barter':150}
#requirements for perks:
# perk_point -1 or 0, if 0 then the perk is a 'free' support perk
# level - minimum character level to buy perk
# skill - dictionary of minimum required skill levels to buy perk
# min_special - dictionary of minimum required special to buy perk (empty dict for no requirements)
# max_special- dictionary of maximum special to buy perk (empty dict for no requirements)
# perks - list of perk names required to buy this perk
self.perk_req={
'More Critical':{'perk_point':1, 'level':3, 'skill':{'Small Guns':100,'Big Guns':100,'Energy Guns':100,'Close Combat':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Quick Pockets':{'perk_point':1, 'level':3, 'skill':{}, 'min_special':{'a':5}, 'max_special':{}, 'perks':[]},
'Adrenaline Rush':{'perk_point':1, 'level':3, 'skill':{}, 'min_special':{'s':5}, 'max_special':{}, 'perks':[]},
'Quick Recovery':{'perk_point':1, 'level':3, 'skill':{}, 'min_special':{'s':6}, 'max_special':{}, 'perks':[]},
'Weapon Handling':{'perk_point':1, 'level':3, 'skill':{'Small Guns':100,'Big Guns':100,'Energy Guns':100,'Close Combat':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'In Your Face!':{'perk_point':1, 'level':6, 'skill':{'Close Combat':125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Even More Criticals':{'perk_point':1, 'level':6, 'skill':{'Small Guns':125,'Big Guns':125,'Energy Guns':125,'Close Combat':125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Silent Running':{'perk_point':1, 'level':6, 'skill':{'Sneak':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Toughness':{'perk_point':1, 'level':6, 'skill':{}, 'min_special':{'e':4}, 'max_special':{}, 'perks':[]},
'Sharpshooter':{'perk_point':1, 'level':9, 'skill':{'Small Guns':150,'Big Guns':150,'Energy Guns':150,'Close Combat':150}, 'min_special':{'i':3}, 'max_special':{}, 'perks':[]},
'Pyromaniac':{'perk_point':1, 'level':9, 'skill':{'Small Guns':100,'Big Guns':100,'Energy Guns':100,'Close Combat':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Close Combat Master':{'perk_point':1, 'level':9, 'skill':{'Close Combat':150}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Even Tougher':{'perk_point':1, 'level':9, 'skill':{}, 'min_special':{'e':6}, 'max_special':{}, 'perks':[]},
'Stonewall':{'perk_point':1, 'level':9, 'skill':{}, 'min_special':{'s':6}, 'max_special':{}, 'perks':[]},
'Medic':{'perk_point':1, 'level':9, 'skill':{'Doctor':125, 'First Aid':125}, 'min_special':{'i':3}, 'max_special':{}, 'perks':[]},
'Heave Ho!':{'perk_point':1, 'level':9, 'skill':{'Throwing':125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Bonus Ranged Dmg.':{'perk_point':1, 'level':9, 'skill':{'Small Guns':150,'Big Guns':150,'Energy Guns':150}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Lifegiver 1':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Gain ST':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'s':9}, 'perks':[]},
'Gain PE':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'p':9}, 'perks':[]},
'Gain EN':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'e':9}, 'perks':[]},
'Gain CH':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'c':9}, 'perks':[]},
'Gain IN':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'i':9}, 'perks':[]},
'Gain AG':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'a':9}, 'perks':[]},
'Gain LK':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{}, 'max_special':{'l':9}, 'perks':[]},
'Better Critical':{'perk_point':1, 'level':12, 'skill':{'Small Guns':175,'Big Guns':175,'Energy Guns':175,'Close Combat':175}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Ghost':{'perk_point':1, 'level':12, 'skill':{'Sneak':150}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Action Boy 1':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{'a':6}, 'max_special':{}, 'perks':[]},
'Action Boy 2':{'perk_point':1, 'level':12, 'skill':{}, 'min_special':{'a':6}, 'max_special':{}, 'perks':[]},
'Lifegiver 2':{'perk_point':1, 'level':15, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Dodger 1':{'perk_point':1, 'level':15, 'skill':{'Close Combat':150 }, 'min_special':{'a':8}, 'max_special':{}, 'perks':[]},
'Dodger 2':{'perk_point':1, 'level':18, 'skill':{'Close Combat':175 }, 'min_special':{'a':10}, 'max_special':{}, 'perks':['Dodger 1']},
'Livewire':{'perk_point':1, 'level':15, 'skill':{}, 'min_special':{'a':6}, 'max_special':{}, 'perks':[]},
'Man of Steel':{'perk_point':15, 'level':3, 'skill':{}, 'min_special':{'e':8}, 'max_special':{}, 'perks':[]},
'Field Medic':{'perk_point':1, 'level':15, 'skill':{'Doctor':175, 'First Aid':175}, 'min_special':{}, 'max_special':{}, 'perks':['Medic']},
'Iron Limbs':{'perk_point':1, 'level':15, 'skill':{}, 'min_special':{'s':6, 'e':6}, 'max_special':{}, 'perks':[]},
'Silent Death':{'perk_point':1, 'level':15, 'skill':{'Sneak':175}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'More Ranged Dmg.':{'perk_point':1, 'level':15, 'skill':{'Small Guns':200,'Big Guns':200,'Energy Guns':200}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Lifegiver 3':{'perk_point':1, 'level':18, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Bonus Rate of Attack':{'perk_point':1, 'level':18, 'skill':{'Small Guns':180,'Big Guns':180,'Energy Guns':180,'Close Combat':180}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Boneyard Guard SG':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Boneyard Guard BG':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Boneyard Guard EW':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Boneyard Guard CC':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Boneyard Guard THW':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Cautious Nature':{'perk_point':0, 'level':2, 'skill':{'Outdoorsman':100}, 'min_special':{'p':6}, 'max_special':{}, 'perks':[]},
'Dead Man Walking':{'perk_point':0, 'level':2, 'skill':{'Doctor':50}, 'min_special':{'i':5}, 'max_special':{}, 'perks':[]},
'Demolition Expert':{'perk_point':0, 'level':2, 'skill':{'Traps':125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Dismantler':{'perk_point':0, 'level':2, 'skill':{'Science':120}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Educated':{'perk_point':0, 'level':2, 'skill':{'Science':100}, 'min_special':{'i':8}, 'max_special':{}, 'perks':[]},
'Explorer':{'perk_point':0, 'level':2, 'skill':{'Outdoorsman':150}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Faster Healing':{'perk_point':0, 'level':2, 'skill':{'Doctor':75}, 'min_special':{'i':6}, 'max_special':{}, 'perks':[]},
'Gecko Skinning':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Harmless':{'perk_point':0, 'level':2, 'skill':{'Steal':125}, 'min_special':{'c':6}, 'max_special':{}, 'perks':[]},
'Light Step':{'perk_point':0, 'level':2, 'skill':{'Traps': 100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Magnetic Personality':{'perk_point':0, 'level':2, 'skill':{'Speech':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Master Thief':{'perk_point':0, 'level':2, 'skill':{'Steal':125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Mr. Fixit':{'perk_point':0, 'level':2, 'skill':{'Repair':120}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Negotiator':{'perk_point':0, 'level':2, 'skill':{'Barter': 125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Pack Rat':{'perk_point':0, 'level':3, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Pathfinder':{'perk_point':0, 'level':2, 'skill':{'Outdoorsman':150}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Pickpocket':{'perk_point':0, 'level':2, 'skill':{'Steal': 125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Rad Resistance':{'perk_point':0, 'level':2, 'skill':{'Doctor':100}, 'min_special':{'i':7}, 'max_special':{}, 'perks':[]},
'Ranger':{'perk_point':0, 'level':2, 'skill':{'Outdoorsman':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Scout':{'perk_point':0, 'level':2, 'skill':{'Outdoorsman':150}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Sex Appeal':{'perk_point':0, 'level':2, 'skill':{'Speech':75}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Snakeater':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{'e':6}, 'max_special':{}, 'perks':[]},
'Speaker':{'perk_point':0, 'level':2, 'skill':{'Speech': 125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Stealth Girl':{'perk_point':0, 'level':2, 'skill':{'Sneak':100, 'Repair':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Strong Back':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{'e':6}, 'max_special':{}, 'perks':[]},
'Swift Learner':{'perk_point':0, 'level':2, 'skill':{'Science':50}, 'min_special':{'i':6}, 'max_special':{}, 'perks':[]},
'Thief':{'perk_point':0, 'level':2, 'skill':{'Steal':100}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Treasure Hunter':{'perk_point':0, 'level':2, 'skill':{'Lockpick':125}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Repair x10':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'First Aid x10':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Small Guns x10':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Outdoorsman x10':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Barter x10':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]},
'Science x10':{'perk_point':0, 'level':2, 'skill':{}, 'min_special':{}, 'max_special':{}, 'perks':[]}
}
#some perks give skill bonus, this dict tell how much and of what skill
#the values are in 'skill points' not raw points
self.perk_skill_bonus={'Repair x10':{'Repair':60},
'First Aid x10':{'First Aid':60},
'Small Guns x10':{'Small Guns':60},
'Outdoorsman x10':{'Outdoorsman':60},
'Barter x10':{'Barter':60},
'Science x10':{'Science':60},
'Boneyard Guard SG':{'Small Guns':10},
'Boneyard Guard BG':{'Big Guns':10},
'Boneyard Guard CC':{'Close Combat':10},
'Boneyard Guard THW':{'Throwing':10},
'Boneyard Guard EW':{'Energy Guns':10}}
#some perks give special bonuses,this dict tell how much
self.perk_special_bonus={'Gain ST':{'s':2},
'Gain PE':{'p':2},
'Gain EN':{'e':2},
'Gain CH':{'c':2},
'Gain IN':{'i':2},
'Gain AG':{'a':2},
'Gain LK':{'l':2}}
#known guns (or other weapons)
#min_dmg and max_dmg - damage dealt by gun
#max_range - maximum gun range
#min_burst - minimum number of bullets hitting a target when using burst mode, or 0 if gun can't burst
#max_burst - maximum number of bullets hitting a target when using burst mode, or 0 if gun can't burst
#skill - name of the skill used by this gun
#ammo_dr - ammunition DR modifier (should be negative)
#ammo_ac- ammunition AC modifier
#ammo_dmg - ammunition DM modifier (or damage adjustment), should be float if !=1 (eg. 1.5 not 3/2 unless running py3+)
#min_st - minimum | |
<gh_stars>0
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright <NAME> 2014 <EMAIL> |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import socket, time, re
# Python 2.3 does not have 'set' in normal namespace.
# But it can be imported from 'sets'
try:
set()
except NameError:
from sets import Set as set
"""MK Livestatus Python API
This module allows easy access to Nagios via MK Livestatus.
It supports persistent connections via the connection class.
If you want single-shot connections, just initialize a
connection object on-the-fly, e.g.:
r = connection("/var/lib/nagios/rw/live").query_table_assoc("GET hosts")
For persistent connections create and keep an object:
conn = connection("/var/lib/nagios/rw/live")
r1 = conn.query_table_assoc("GET hosts")
r2 = conn.query_row("GET status")
"""
# Keep a global array of persistant connections
persistent_connections = {}
# Regular expression for removing Cache: headers if caching is not allowed
remove_cache_regex = re.compile("\nCache:[^\n]*")
# DEBUGGING PERSISTENT CONNECTIONS
# import os
# hirn_debug = file("/tmp/live.log", "a")
# def hirn(x):
# pid = os.getpid()
# hirn_debug.write("[\033[1;3%d;4%dm%d\033[0m] %s\n" % (pid%7+1, (pid/7)%7+1, pid, x))
# hirn_debug.flush()
class MKLivestatusException(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return str(self.parameter)
class MKLivestatusSocketError(MKLivestatusException):
def __init__(self, reason):
MKLivestatusException.__init__(self, reason)
class MKLivestatusSocketClosed(MKLivestatusSocketError):
def __init__(self, reason):
MKLivestatusSocketError.__init__(self, reason)
class MKLivestatusConfigError(MKLivestatusException):
def __init__(self, reason):
MKLivestatusException.__init__(self, reason)
class MKLivestatusQueryError(MKLivestatusException):
def __init__(self, code, reason):
MKLivestatusException.__init__(self, "%s: %s" % (code, reason))
self.code = code
class MKLivestatusNotFoundError(MKLivestatusException):
def __init__(self, query):
MKLivestatusException.__init__(self, query)
self.query = query
# We need some unique value here
NO_DEFAULT = lambda: None
class Helpers:
def query_value(self, query, deflt = NO_DEFAULT):
"""Issues a query that returns exactly one line and one columns and returns
the response as a single value"""
result = self.query(query, "ColumnHeaders: off\n")
try:
return result[0][0]
except:
if deflt == NO_DEFAULT:
raise MKLivestatusNotFoundError(query)
else:
return deflt
def query_row(self, query):
"""Issues a query that returns one line of data and returns the elements
of that line as list"""
return self.query(query, "ColumnHeaders: off\n")[0]
def query_row_assoc(self, query):
"""Issues a query that returns one line of data and returns the elements
of that line as a dictionary from column names to values"""
r = self.query(query, "ColumnHeaders: on\n")[0:2]
return dict(zip(r[0], r[1]))
def query_column(self, query):
"""Issues a query that returns exactly one column and returns the values
of all lines in that column as a single list"""
return [ l[0] for l in self.query(query, "ColumnHeaders: off\n") ]
def query_column_unique(self, query):
"""Issues a query that returns exactly one column and returns the values
of all lines with duplicates removed"""
result = []
for line in self.query(query, "ColumnHeaders: off\n"):
if line[0] not in result:
result.append(line[0])
return result
def query_table(self, query):
"""Issues a query that may return multiple lines and columns and returns
a list of lists"""
return self.query(query, "ColumnHeaders: off\n")
def query_table_assoc(self, query):
"""Issues a query that may return multiple lines and columns and returns
a dictionary from column names to values for each line. This can be
very ineffective for large response sets."""
response = self.query(query, "ColumnHeaders: on\n")
headers = response[0]
result = []
for line in response[1:]:
result.append(dict(zip(headers, line)))
return result
def query_summed_stats(self, query, add_headers = ""):
"""Conveniance function for adding up numbers from Stats queries
Adds up results column-wise. This is useful for multisite queries."""
data = self.query(query, add_headers)
if len(data) == 1:
return data[0]
elif len(data) == 0:
raise MKLivestatusNotFoundError("Empty result to Stats-Query")
result = []
for x in range(0, len(data[0])):
result.append(sum([row[x] for row in data]))
return result
class BaseConnection:
def __init__(self, socketurl, persist = False, allow_cache = False):
"""Create a new connection to a MK Livestatus socket"""
self.add_headers = ""
self.persist = persist
self.allow_cache = allow_cache
self.socketurl = socketurl
self.socket = None
self.timeout = None
self.successful_persistence = False
def successfully_persisted(self):
return self.successful_persistence
def add_header(self, header):
self.add_headers += header + "\n"
def set_timeout(self, timeout):
self.timeout = timeout
if self.socket:
self.socket.settimeout(float(timeout))
def connect(self):
if self.persist and self.socketurl in persistent_connections:
self.socket = persistent_connections[self.socketurl]
self.successful_persistence = True
return
self.successful_persistence = False
# Create new socket
self.socket = None
url = self.socketurl
parts = url.split(":")
if parts[0] == "unix":
if len(parts) != 2:
raise MKLivestatusConfigError("Invalid livestatus unix URL: %s. "
"Correct example is 'unix:/var/run/nagios/rw/live'" % url)
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
target = parts[1]
elif parts[0] == "tcp":
try:
host = parts[1]
port = int(parts[2])
except:
raise MKLivestatusConfigError("Invalid livestatus tcp URL '%s'. "
"Correct example is 'tcp:somehost:6557'" % url)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target = (host, port)
else:
raise MKLivestatusConfigError("Invalid livestatus URL '%s'. "
"Must begin with 'tcp:' or 'unix:'" % url)
# If a timeout is set, then we retry after a failure with mild
# a binary backoff.
if self.timeout:
before = time.time()
sleep_interval = 0.1
while True:
try:
if self.timeout:
self.socket.settimeout(float(sleep_interval))
self.socket.connect(target)
break
except Exception, e:
if self.timeout:
time_left = self.timeout - (time.time() - before)
# only try again, if there is substantial time left
if time_left > sleep_interval:
time.sleep(sleep_interval)
sleep_interval *= 1.5
continue
self.socket = None
raise MKLivestatusSocketError("Cannot connect to '%s': %s" % (self.socketurl, e))
if self.persist:
persistent_connections[self.socketurl] = self.socket
def disconnect(self):
self.socket = None
if self.persist:
del persistent_connections[self.socketurl]
def receive_data(self, size):
result = ""
# Timeout is only honored when connecting
self.socket.settimeout(None)
while size > 0:
packet = self.socket.recv(size)
if len(packet) == 0:
raise MKLivestatusSocketClosed("Read zero data from socket, nagios server closed connection")
size -= len(packet)
result += packet
return result
def do_query(self, query, add_headers = ""):
self.send_query(query, add_headers)
return self.recv_response(query, add_headers)
def send_query(self, query, add_headers = "", do_reconnect=True):
if not self.allow_cache:
query = remove_cache_regex.sub("", query)
orig_query = query
if self.socket == None:
self.connect()
if not query.endswith("\n"):
query += "\n"
query += self.auth_header + self.add_headers
query += "Localtime: %d\nOutputFormat: python\nKeepAlive: on\nResponseHeader: fixed16\n" % int(time.time())
query += add_headers
if not query.endswith("\n"):
query += "\n"
query += "\n"
try:
# socket.send() will implicitely cast to str(), we need ot
# convert to UTF-8 in order to avoid exceptions
if type(query) == unicode:
query = query.encode("utf-8")
self.socket.send(query)
except IOError, e:
if self.persist:
del persistent_connections[self.socketurl]
self.successful_persistence = False
self.socket = None
if do_reconnect:
# Automatically try to reconnect in case of an error, but
# only once.
self.connect()
self.send_query(orig_query, add_headers, False)
return
raise MKLivestatusSocketError("RC1:" + str(e))
# Reads a response from the livestatus socket. If the socket is closed
# by the livestatus server, we automatically make a reconnect and send
# the query again (once). This is due to timeouts during keepalive.
def recv_response(self, query = None, add_headers = "", timeout_at = None):
try:
resp = self.receive_data(16)
code = resp[0:3]
try:
length = int(resp[4:15].lstrip())
except:
raise MKLivestatusSocketError("Malformed output. Livestatus TCP socket might be unreachable.")
data = self.receive_data(length)
if code == "200":
try:
return eval(data)
except:
raise MKLivestatusSocketError("Malformed output")
else:
raise MKLivestatusQueryError(code, data.strip())
# In case of an IO error or the other side having
# closed the socket do a reconnect and try again, but
# only once
except (MKLivestatusSocketClosed, IOError), e:
self.disconnect()
now = time.time()
if query and (not timeout_at or timeout_at > now):
if timeout_at == None:
timeout_at = now + self.timeout
time.sleep(0.1)
self.connect()
self.send_query(query, add_headers)
return self.recv_response(query, add_headers, timeout_at) # do not send query again -> danger of infinite loop
| |
# Copyright 2012 Nicira Networks, Inc.
#
# 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.
#
# @author: <NAME>, Nicira Networks, Inc.
# @author: <NAME>, Nicira Networks, Inc.
import ConfigParser
import logging
import os
import sys
import NvpApiClient
import nvplib
from quantum.common import exceptions as exception
from quantum.plugins.nicira.nicira_nvp_plugin.api_client.client_eventlet \
import (
DEFAULT_CONCURRENT_CONNECTIONS,
DEFAULT_FAILOVER_TIME,
)
from quantum.plugins.nicira.nicira_nvp_plugin.api_client.request_eventlet \
import (
DEFAULT_REQUEST_TIMEOUT,
DEFAULT_HTTP_TIMEOUT,
DEFAULT_RETRIES,
DEFAULT_REDIRECTS,
)
LOG = logging.getLogger("QuantumPlugin")
CONFIG_FILE = "nvp.ini"
CONFIG_FILE_PATHS = []
if os.environ.get('QUANTUM_HOME', None):
CONFIG_FILE_PATHS.append('%s/etc' % os.environ['QUANTUM_HOME'])
CONFIG_FILE_PATHS.append("/etc/quantum/plugins/nicira")
CONFIG_KEYS = ["DEFAULT_TZ_UUID", "NVP_CONTROLLER_IP", "PORT", "USER",
"PASSWORD"]
def initConfig(cfile=None):
config = ConfigParser.ConfigParser()
if cfile is None:
if os.path.exists(CONFIG_FILE):
cfile = CONFIG_FILE
else:
cfile = find_config(os.path.abspath(os.path.dirname(__file__)))
if cfile is None:
raise Exception("Configuration file \"%s\" doesn't exist" % (cfile))
LOG.info("Using configuration file: %s" % cfile)
config.read(cfile)
LOG.debug("Config: %s" % config)
return config
def find_config(basepath):
LOG.info("Looking for %s in %s" % (CONFIG_FILE, basepath))
for root, dirs, files in os.walk(basepath, followlinks=True):
if CONFIG_FILE in files:
return os.path.join(root, CONFIG_FILE)
for alternate_path in CONFIG_FILE_PATHS:
p = os.path.join(alternate_path, CONFIG_FILE)
if os.path.exists(p):
return p
return None
def parse_config(config):
"""Backwards compatible parsing.
:param config: ConfigParser object initilized with nvp.ini.
:returns: A tuple consisting of a control cluster object and a
plugin_config variable.
raises: In general, system exceptions are not caught but are propagated
up to the user. Config parsing is still very lightweight.
At some point, error handling needs to be significantly
enhanced to provide user friendly error messages, clean program
exists, rather than exceptions propagated to the user.
"""
# Extract plugin config parameters.
try:
failover_time = config.get('NVP', 'failover_time')
except ConfigParser.NoOptionError, e:
failover_time = str(DEFAULT_FAILOVER_TIME)
try:
concurrent_connections = config.get('NVP', 'concurrent_connections')
except ConfigParser.NoOptionError, e:
concurrent_connections = str(DEFAULT_CONCURRENT_CONNECTIONS)
plugin_config = {
'failover_time': failover_time,
'concurrent_connections': concurrent_connections,
}
LOG.info('parse_config(): plugin_config == "%s"' % plugin_config)
cluster = NVPCluster('cluster1')
# Extract connection information.
try:
defined_connections = config.get('NVP', 'NVP_CONTROLLER_CONNECTIONS')
for conn_key in defined_connections.split():
args = [config.get('NVP', 'DEFAULT_TZ_UUID')]
args.extend(config.get('NVP', conn_key).split(':'))
try:
cluster.add_controller(*args)
except Exception, e:
LOG.fatal('Invalid connection parameters: %s' % str(e))
sys.exit(1)
return cluster, plugin_config
except Exception, e:
LOG.info('No new style connections defined: %s' % e)
# Old style controller specification.
args = [config.get('NVP', k) for k in CONFIG_KEYS]
try:
cluster.add_controller(*args)
except Exception, e:
LOG.fatal('Invalid connection parameters.')
sys.exit(1)
return cluster, plugin_config
class NVPCluster(object):
"""Encapsulates controller connection and api_client.
Initialized within parse_config().
Accessed within the NvpPlugin class.
Each element in the self.controllers list is a dictionary that
contains the following keys:
ip, port, user, password, default_tz_uuid
There may be some redundancy here, but that has been done to provide
future flexibility.
"""
def __init__(self, name):
self._name = name
self.controllers = []
self.api_client = None
def __repr__(self):
ss = ['{ "NVPCluster": [']
ss.append('{ "name" : "%s" }' % self.name)
ss.append(',')
for c in self.controllers:
ss.append(str(c))
ss.append(',')
ss.append('] }')
return ''.join(ss)
def add_controller(self, default_tz_uuid, ip, port, user, password,
request_timeout=DEFAULT_REQUEST_TIMEOUT,
http_timeout=DEFAULT_HTTP_TIMEOUT,
retries=DEFAULT_RETRIES, redirects=DEFAULT_REDIRECTS):
"""Add a new set of controller parameters.
:param ip: IP address of controller.
:param port: port controller is listening on.
:param user: user name.
:param password: <PASSWORD>.
:param request_timeout: timeout for an entire API request.
:param http_timeout: timeout for a connect to a controller.
:param retries: maximum number of request retries.
:param redirects: maximum number of server redirect responses to
follow.
:param default_tz_uuid: default transport zone uuid.
"""
keys = ['ip', 'port', 'user', 'password', 'default_tz_uuid']
controller_dict = dict([(k, locals()[k]) for k in keys])
int_keys = ['request_timeout', 'http_timeout', 'retries', 'redirects']
for k in int_keys:
controller_dict[k] = int(locals()[k])
self.controllers.append(controller_dict)
def get_controller(self, idx):
return self.controllers[idx]
@property
def name(self):
return self._name
@name.setter
def name(self, val=None):
self._name = val
@property
def host(self):
return self.controllers[0]['ip']
@property
def port(self):
return self.controllers[0]['port']
@property
def user(self):
return self.controllers[0]['user']
@property
def password(self):
return self.controllers[0]['password']
@property
def request_timeout(self):
return self.controllers[0]['request_timeout']
@property
def http_timeout(self):
return self.controllers[0]['http_timeout']
@property
def retries(self):
return self.controllers[0]['retries']
@property
def redirects(self):
return self.controllers[0]['redirects']
@property
def default_tz_uuid(self):
return self.controllers[0]['default_tz_uuid']
class NvpPlugin(object):
"""
NvpPlugin is a Quantum plugin that provides L2 Virtual Network
functionality using NVP.
"""
supported_extension_aliases = ["portstats"]
def __init__(self, configfile=None, loglevel=None, cli=False):
if loglevel:
logging.basicConfig(level=loglevel)
nvplib.LOG.setLevel(loglevel)
NvpApiClient.LOG.setLevel(loglevel)
config = initConfig(configfile)
self.controller, self.plugin_config = parse_config(config)
c = self.controller
api_providers = [(x['ip'], x['port'], True) for x in c.controllers]
c.api_client = NvpApiClient.NVPApiHelper(
api_providers, c.user, c.password,
request_timeout=c.request_timeout, http_timeout=c.http_timeout,
retries=c.retries, redirects=c.redirects,
failover_time=int(self.plugin_config['failover_time']),
concurrent_connections=int(
self.plugin_config['concurrent_connections']))
c.api_client.login()
# For testing..
self.api_client = self.controller.api_client
def get_all_networks(self, tenant_id, **kwargs):
"""
Returns a dictionary containing all <network_uuid, network_name> for
the specified tenant.
:returns: a list of mapping sequences with the following signature:
[{'net-id': uuid that uniquely identifies
the particular quantum network,
'net-name': a human-readable name associated
with network referenced by net-id
},
....
{'net-id': uuid that uniquely identifies the
particular quantum network,
'net-name': a human-readable name associated
with network referenced by net-id
}
]
:raises: None
"""
networks = nvplib.get_all_networks(self.controller, tenant_id, [])
LOG.debug("get_all_networks() completed for tenant %s: %s" %
(tenant_id, networks))
return networks
def create_network(self, tenant_id, net_name, **kwargs):
"""
Creates a new Virtual Network, and assigns it a symbolic name.
:returns: a sequence of mappings with the following signature:
{'net-id': uuid that uniquely identifies the
particular quantum network,
'net-name': a human-readable name associated
with network referenced by net-id
}
:raises:
"""
kwargs["controller"] = self.controller
return nvplib.create_network(tenant_id, net_name, **kwargs)
def create_custom_network(self, tenant_id, net_name, transport_zone,
controller):
return self.create_network(tenant_id, net_name,
network_type="custom",
transport_zone=transport_zone,
controller=controller)
def delete_network(self, tenant_id, netw_id):
"""
Deletes the network with the specified network identifier
belonging to the specified tenant.
:returns: a sequence of mappings with the following signature:
{'net-id': uuid that uniquely identifies the
particular quantum network
}
:raises: exception.NetworkInUse
:raises: exception.NetworkNotFound
"""
if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
raise exception.NetworkNotFound(net_id=netw_id)
nvplib.delete_network(self.controller, netw_id)
LOG.debug("delete_network() completed for tenant: %s" % tenant_id)
return {'net-id': netw_id}
def get_network_details(self, tenant_id, netw_id):
"""
Retrieves a list of all the remote vifs that
are attached to the network.
:returns: a sequence of mappings with the following signature:
{'net-id': uuid that uniquely identifies the
particular quantum network
'net-name': a human-readable name associated
with network referenced by net-id
'net-ifaces': ['vif1_on_network_uuid',
'vif2_on_network_uuid',...,'vifn_uuid']
}
:raises: exception.NetworkNotFound
:raises: exception.QuantumException
"""
if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
raise exception.NetworkNotFound(net_id=netw_id)
result = None
remote_vifs = []
switch = netw_id
lports = nvplib.query_ports(self.controller, switch,
relations="LogicalPortAttachment")
for port in lports:
relation = port["_relations"]
vic = relation["LogicalPortAttachment"]
if "vif_uuid" in vic:
remote_vifs.append(vic["vif_uuid"])
if not result:
result = nvplib.get_network(self.controller, switch)
d = {
"net-id": netw_id,
"net-ifaces": remote_vifs,
"net-name": result["display_name"],
"net-op-status": "UP",
}
LOG.debug("get_network_details() completed for tenant %s: %s" %
(tenant_id, d))
return d
def update_network(self, tenant_id, netw_id, **kwargs):
"""
Updates the properties of a particular Virtual Network.
:returns: a sequence of mappings representing the new network
attributes, with the following signature:
{'net-id': uuid that uniquely identifies the
particular quantum network
'net-name': the new human-readable name
associated with network referenced by net-id
}
:raises: exception.NetworkNotFound
"""
if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
raise exception.NetworkNotFound(net_id=netw_id)
result = nvplib.update_network(self.controller, netw_id, **kwargs)
LOG.debug("update_network() completed for tenant: %s" % tenant_id)
return {
'net-id': netw_id,
'net-name': result["display_name"],
'net-op-status': "UP",
}
def get_all_ports(self, tenant_id, netw_id, **kwargs):
"""
Retrieves all port identifiers belonging to the
specified Virtual Network.
:returns: a list of mapping sequences with the following signature:
[{'port-id': uuid representing a particular port
on the specified quantum network
},
....
{'port-id': uuid representing a particular port
on the specified quantum network
}
]
:raises: exception.NetworkNotFound
"""
ids = []
filters = kwargs.get("filter_opts") or {}
if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
raise exception.NetworkNotFound(net_id=netw_id)
LOG.debug("Getting logical ports on lswitch: %s" % netw_id)
lports = nvplib.query_ports(self.controller, netw_id, fields="uuid",
filters=filters)
for port in lports:
ids.append({"port-id": port["uuid"]})
# Delete from the filter so that Quantum doesn't attempt to filter on
# this too
if filters and "attachment" in filters:
del filters["attachment"]
LOG.debug("get_all_ports() completed for tenant: %s" % tenant_id)
LOG.debug("returning port listing:")
LOG.debug(ids)
return ids
def create_port(self, tenant_id, netw_id, port_init_state=None, **params):
"""
Creates a | |
configuration of the run agent.
:type agent_configuration:
~azure.mgmt.containerregistry.v2019_06_01_preview.models.AgentProperties
:param source_registry_auth: The scope of the credentials that were used to login to the source
registry during this run.
:type source_registry_auth: str
:param custom_registries: The list of custom registries that were logged in during this run.
:type custom_registries: list[str]
:ivar run_error_message: The error message received from backend systems after the run is
scheduled.
:vartype run_error_message: str
:param update_trigger_token: The update trigger token passed for the Run.
:type update_trigger_token: str
:ivar log_artifact: The image description for the log artifact.
:vartype log_artifact: ~azure.mgmt.containerregistry.v2019_06_01_preview.models.ImageDescriptor
:param provisioning_state: The provisioning state of a run. Possible values include:
"Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled".
:type provisioning_state: str or
~azure.mgmt.containerregistry.v2019_06_01_preview.models.ProvisioningState
:param is_archive_enabled: The value that indicates whether archiving is enabled or not.
:type is_archive_enabled: bool
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'system_data': {'readonly': True},
'run_error_message': {'readonly': True},
'log_artifact': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'system_data': {'key': 'systemData', 'type': 'SystemData'},
'run_id': {'key': 'properties.runId', 'type': 'str'},
'status': {'key': 'properties.status', 'type': 'str'},
'last_updated_time': {'key': 'properties.lastUpdatedTime', 'type': 'iso-8601'},
'run_type': {'key': 'properties.runType', 'type': 'str'},
'agent_pool_name': {'key': 'properties.agentPoolName', 'type': 'str'},
'create_time': {'key': 'properties.createTime', 'type': 'iso-8601'},
'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'},
'finish_time': {'key': 'properties.finishTime', 'type': 'iso-8601'},
'output_images': {'key': 'properties.outputImages', 'type': '[ImageDescriptor]'},
'task': {'key': 'properties.task', 'type': 'str'},
'image_update_trigger': {'key': 'properties.imageUpdateTrigger', 'type': 'ImageUpdateTrigger'},
'source_trigger': {'key': 'properties.sourceTrigger', 'type': 'SourceTriggerDescriptor'},
'timer_trigger': {'key': 'properties.timerTrigger', 'type': 'TimerTriggerDescriptor'},
'platform': {'key': 'properties.platform', 'type': 'PlatformProperties'},
'agent_configuration': {'key': 'properties.agentConfiguration', 'type': 'AgentProperties'},
'source_registry_auth': {'key': 'properties.sourceRegistryAuth', 'type': 'str'},
'custom_registries': {'key': 'properties.customRegistries', 'type': '[str]'},
'run_error_message': {'key': 'properties.runErrorMessage', 'type': 'str'},
'update_trigger_token': {'key': 'properties.updateTriggerToken', 'type': 'str'},
'log_artifact': {'key': 'properties.logArtifact', 'type': 'ImageDescriptor'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'is_archive_enabled': {'key': 'properties.isArchiveEnabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(Run, self).__init__(**kwargs)
self.run_id = kwargs.get('run_id', None)
self.status = kwargs.get('status', None)
self.last_updated_time = kwargs.get('last_updated_time', None)
self.run_type = kwargs.get('run_type', None)
self.agent_pool_name = kwargs.get('agent_pool_name', None)
self.create_time = kwargs.get('create_time', None)
self.start_time = kwargs.get('start_time', None)
self.finish_time = kwargs.get('finish_time', None)
self.output_images = kwargs.get('output_images', None)
self.task = kwargs.get('task', None)
self.image_update_trigger = kwargs.get('image_update_trigger', None)
self.source_trigger = kwargs.get('source_trigger', None)
self.timer_trigger = kwargs.get('timer_trigger', None)
self.platform = kwargs.get('platform', None)
self.agent_configuration = kwargs.get('agent_configuration', None)
self.source_registry_auth = kwargs.get('source_registry_auth', None)
self.custom_registries = kwargs.get('custom_registries', None)
self.run_error_message = None
self.update_trigger_token = kwargs.get('update_trigger_token', None)
self.log_artifact = None
self.provisioning_state = kwargs.get('provisioning_state', None)
self.is_archive_enabled = kwargs.get('is_archive_enabled', False)
class RunFilter(msrest.serialization.Model):
"""Properties that are enabled for Odata querying on runs.
:param run_id: The unique identifier for the run.
:type run_id: str
:param run_type: The type of run. Possible values include: "QuickBuild", "QuickRun",
"AutoBuild", "AutoRun".
:type run_type: str or ~azure.mgmt.containerregistry.v2019_06_01_preview.models.RunType
:param status: The current status of the run. Possible values include: "Queued", "Started",
"Running", "Succeeded", "Failed", "Canceled", "Error", "Timeout".
:type status: str or ~azure.mgmt.containerregistry.v2019_06_01_preview.models.RunStatus
:param create_time: The create time for a run.
:type create_time: ~datetime.datetime
:param finish_time: The time the run finished.
:type finish_time: ~datetime.datetime
:param output_image_manifests: The list of comma-separated image manifests that were generated
from the run. This is applicable if the run is of
build type.
:type output_image_manifests: str
:param is_archive_enabled: The value that indicates whether archiving is enabled or not.
:type is_archive_enabled: bool
:param task_name: The name of the task that the run corresponds to.
:type task_name: str
:param agent_pool_name: The name of the agent pool that the run corresponds to.
:type agent_pool_name: str
"""
_attribute_map = {
'run_id': {'key': 'runId', 'type': 'str'},
'run_type': {'key': 'runType', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'finish_time': {'key': 'finishTime', 'type': 'iso-8601'},
'output_image_manifests': {'key': 'outputImageManifests', 'type': 'str'},
'is_archive_enabled': {'key': 'isArchiveEnabled', 'type': 'bool'},
'task_name': {'key': 'taskName', 'type': 'str'},
'agent_pool_name': {'key': 'agentPoolName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RunFilter, self).__init__(**kwargs)
self.run_id = kwargs.get('run_id', None)
self.run_type = kwargs.get('run_type', None)
self.status = kwargs.get('status', None)
self.create_time = kwargs.get('create_time', None)
self.finish_time = kwargs.get('finish_time', None)
self.output_image_manifests = kwargs.get('output_image_manifests', None)
self.is_archive_enabled = kwargs.get('is_archive_enabled', None)
self.task_name = kwargs.get('task_name', None)
self.agent_pool_name = kwargs.get('agent_pool_name', None)
class RunGetLogResult(msrest.serialization.Model):
"""The result of get log link operation.
:param log_link: The link to logs for a run on a azure container registry.
:type log_link: str
:param log_artifact_link: The link to logs in registry for a run on a azure container registry.
:type log_artifact_link: str
"""
_attribute_map = {
'log_link': {'key': 'logLink', 'type': 'str'},
'log_artifact_link': {'key': 'logArtifactLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RunGetLogResult, self).__init__(**kwargs)
self.log_link = kwargs.get('log_link', None)
self.log_artifact_link = kwargs.get('log_artifact_link', None)
class RunListResult(msrest.serialization.Model):
"""Collection of runs.
:param value: The collection value.
:type value: list[~azure.mgmt.containerregistry.v2019_06_01_preview.models.Run]
:param next_link: The URI that can be used to request the next set of paged results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Run]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RunListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RunUpdateParameters(msrest.serialization.Model):
"""The set of run properties that can be updated.
:param is_archive_enabled: The value that indicates whether archiving is enabled or not.
:type is_archive_enabled: bool
"""
_attribute_map = {
'is_archive_enabled': {'key': 'isArchiveEnabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(RunUpdateParameters, self).__init__(**kwargs)
self.is_archive_enabled = kwargs.get('is_archive_enabled', None)
class SecretObject(msrest.serialization.Model):
"""Describes the properties of a secret object value.
:param value: The value of the secret. The format of this value will be determined
based on the type of the secret object. If the type is Opaque, the value will be
used as is without any modification.
:type value: str
:param type: The type of the secret object which determines how the value of the secret object
has to be
interpreted. Possible values include: "Opaque", "Vaultsecret".
:type type: str or ~azure.mgmt.containerregistry.v2019_06_01_preview.models.SecretObjectType
"""
_attribute_map = {
'value': {'key': 'value', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecretObject, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.type = kwargs.get('type', None)
class SetValue(msrest.serialization.Model):
"""The properties of a overridable value that can be passed to a task template.
All required parameters must be populated in order to send to Azure.
:param name: Required. The name of the overridable value.
:type name: str
:param value: Required. The overridable value.
:type value: str
:param is_secret: Flag to indicate whether the value represents a secret or not.
:type is_secret: bool
"""
_validation = {
'name': {'required': True},
'value': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
'is_secret': {'key': 'isSecret', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(SetValue, self).__init__(**kwargs)
self.name = kwargs['name']
self.value = kwargs['value']
self.is_secret = kwargs.get('is_secret', False)
class SourceProperties(msrest.serialization.Model):
"""The properties of the source code repository.
All required parameters must be populated in order to send to Azure.
:param source_control_type: Required. The type of source control service. Possible values
include: "Github", "VisualStudioTeamService".
:type source_control_type: str or
~azure.mgmt.containerregistry.v2019_06_01_preview.models.SourceControlType
:param repository_url: Required. The full URL to the source code repository.
:type repository_url: str
:param branch: The branch name of the source code.
:type branch: str
:param source_control_auth_properties: The authorization properties for accessing the source
code repository and to set up
webhooks for notifications.
:type source_control_auth_properties:
~azure.mgmt.containerregistry.v2019_06_01_preview.models.AuthInfo
"""
_validation = {
'source_control_type': {'required': True},
'repository_url': {'required': True},
}
_attribute_map = {
'source_control_type': {'key': 'sourceControlType', 'type': 'str'},
'repository_url': {'key': 'repositoryUrl', 'type': 'str'},
'branch': {'key': 'branch', 'type': 'str'},
'source_control_auth_properties': {'key': 'sourceControlAuthProperties', 'type': 'AuthInfo'},
}
def __init__(
self,
**kwargs
):
super(SourceProperties, self).__init__(**kwargs)
self.source_control_type = kwargs['source_control_type']
self.repository_url = kwargs['repository_url']
self.branch = kwargs.get('branch', None)
self.source_control_auth_properties = kwargs.get('source_control_auth_properties', None)
class SourceRegistryCredentials(msrest.serialization.Model):
"""Describes the credential parameters for accessing the source registry.
:param login_mode: The authentication mode which determines the source registry login scope.
The credentials for the source registry
will be generated using the given scope. These credentials will be used to login to
the source registry during the run. Possible values include: "None", "Default".
:type login_mode: str or
~azure.mgmt.containerregistry.v2019_06_01_preview.models.SourceRegistryLoginMode
"""
_attribute_map = {
'login_mode': {'key': 'loginMode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SourceRegistryCredentials, self).__init__(**kwargs)
self.login_mode = kwargs.get('login_mode', None)
class SourceTrigger(msrest.serialization.Model):
"""The properties of a source based trigger.
All required parameters must be populated in order to send to Azure.
:param source_repository: Required. The properties that describes the source(code) | |
as exc:
try:
# Try to parse with formatting with day first
return dateutil_parser.parse(cleaned_date, dayfirst=True, fuzzy=True)
except ValueError as exc:
# If failed, try with year first
try:
m = re.search('\d+', s, re.UNICODE)
if len(m.group(0)) == 4:
return dateutil_parser.parse(cleaned_date, yearfirst=True, fuzzy=True)
else:
raise
except Exception as exc:
# Else we print an error but we pass (we just don't use this date)
print('Warning: Failed parsing this date: %s' % s)
return None
def df_date_clean(df_in, col):
"""Apply fuzzy date cleaning (and datetype conversion) to a dataframe's column"""
# Make a copy to avoid tampering the original
df = df_in.copy()
df[col] = df[col].apply(date_clean).astype('datetime64')
return df
def clean_integer_score(x):
"""Converts x from potentially a float or string into a clean integer, and replace NA and NP values with one string character"""
try:
x = str(int(float(x)))
except Exception as exc:
if isinstance(x, basestring):
pass
else:
raise
x = x.lower().strip()
return 'A' if x == 'na (not assesible)' else 'P' if x == 'np (not performed)' else x
def df_subscores_concat(df, cols=None, col_out='subscore'):
"""Create CRS-R subscores summary (eg, S123456)"""
if cols is None:
raise ValueError('Must specify which columns we take the CRS-R subscores from!')
if len(cols) != 6:
raise ValueError('The number of columns specified does not correspond to CRS-R, we need 6 columns (6 categories of items)!')
# We extract only the subscores in the correct order and we clean up the special values (not assesible NA and not performed NP) to replace by a single character (A and P respectively) and we replace NAN by X
df_subscores = df[cols].fillna('X').applymap(clean_integer_score)
# Make a copy to avoid side effects
df2 = df.copy()
# Then we concatenate all subscores in one string, prefixing 'S' before, and add the result as a new column
df2[col_out] = df_subscores.apply(lambda x: concat_strings(x, 'S'), axis=1)
# Return!
return df2
def df_unify(df, cols, unicol):
"""Unify multiple columns by recursively filling blanks from the specified list of columns.
cols is the list of columns from which to copy (the first will be the most copied, the last the least and only if other columns did not contain any info)
unicol is the name of the new unified column"""
# Make a copy to avoid side effects
df2 = df.copy()
# Copy the first column as reference
df2[unicol] = df2[cols[0]]
# Then each subsequent column will be used to fill the blank parts
for col in cols[1:]:
df2.loc[df2[unicol].isnull() | (df2[unicol] == ''), unicol] = df2[col]
# Return the Dataframe with the new unified column
return df2
def df_replace_nonnull(x, repmap, cleanup=False):
if cleanup and isinstance(x, str):
x = cleanup_name(replace_buggy_accents(x))
if x in repmap:
replacement = repmap[x]
return replacement if replacement is not None else x
else:
return x
def df_translate(df, col, mapping, cleanup=False, partial=False):
"""Translate a list of strings on a Dataframe's column
This can for example be used to simplify all the values to a reduced set, for more comprehensible graphs or easier data organization
If partial=True, if a cell contains the matching pattern, it will be replaced by the target. Use an OrderedDict to take advantage of the sequential order (to make sure that the first pattern is replaced first, then the rest)."""
df2 = df.copy()
if not partial:
# Exact match required
df2[col] = df2[col].apply(lambda x: df_replace_nonnull(x, mapping, cleanup=cleanup))
else:
# Partial match OK
for pattern, replacement in mapping.items():
df2.loc[df2[col].str.contains(pattern), col] = replacement
return df2
def filter_nan_str(x):
"""Filter 'nan' values as string from a list of strings"""
if not isinstance(x, list):
return x
else:
return [y for y in x if y.lower() != 'nan']
def df_filter_nan_str(df_col):
"""Filter all 'nan' values as strings from a Dataframe column containing lists"""
return df_col.apply(df_literal_eval).apply(filter_nan_str).astype('str')
def df_squash_lists(df_col_in, func=None, aggressive=False):
"""Filter lists enclosed in Dataframe column by first evaluating the strings as a list and then applying the supplied function to choose which element to return"""
if func is None:
# By default, take the first item when squashing
func = lambda x: next(iter(x))
df_col = df_col_in.copy()
if aggressive:
df_col = df_col.astype('str').str.replace("[\[\]{}']", '')
return df_col.apply(df_literal_eval).apply(lambda x: func(x) if isinstance(x, (list, set, tuple)) else x).astype('str')
def df_fillnastr(df_col_in, replacement=None):
"""Replace null values hidden in strings with the provided replacement value"""
df_col = df_col_in.copy()
df_col[df_col.isna() | (df_col == 'None') | (df_col == 'NONE') | (df_col == 'none') | (df_col == 'NaN') | (df_col == 'nan') | (df_col == 'NaT') | (df_col == 'nat') | (df_col == 'na') | (df_col == 'NA') | (df_col == 'N/A') | (df_col == '#VALUE!')] = replacement
return df_col
######################## DICOMS #############################
def generate_path_from_dicom_fields(output_dir, dcmdata, key_dicom_fields, cleanup_dicom_fields=True, placeholder_value='unknown'):
pathparts = []
# For each outer list elements (will be concatenated with a directory separator like '/')
for dfields in key_dicom_fields:
if not isinstance(dfields, list):
dfields = [dfields]
innerpathparts = []
# For each inner list elements (will be concatenated with '_')
for dfield in dfields:
# Extract the dicom field's value
if dfield in dcmdata:
if isinstance(dfield, str):
# If string (a named field)
dcmfieldval = dcmdata[dcmdata.data_element(dfield).tag].value
else:
# Else it's a coordinate field (no name, like (0010, 2020))
dcmfieldval = dcmdata[dfield].value
else:
dcmfieldval = placeholder_value
# Cleanup the dicom field is enabled (this will replace accentuated characters, most english softwares do not support those)
if cleanup_dicom_fields:
dcmfieldval = cleanup_name(dcmfieldval)
# Add the path parts to the list
innerpathparts.append(dcmfieldval)
# Concatenate the inner path parts and add to the outer path parts list
pathparts.append('_'.join(innerpathparts))
# Build the full path from the outer path parts list
pathpartsassembled = os.path.join(*pathparts)
# Replace all spaces by dashes (so that programs that do not support spaces well won't be bothered)
pathpartsassembled = re.sub(r'\s+', r'-', pathpartsassembled, count=0)
# Join with output dir to get final path
finalpathdir = os.path.join(output_dir, pathpartsassembled)
return finalpathdir
def recwalk_dcm(*args, **kwargs):
"""Recursive DICOM metadata reader, supporting zipfiles.
Yields for each dicom file (whether normal or inside a zipfile) a dictionary filled with DICOM file metadata, path and zip handler if it is inside a zipfile.
Comes with an integrated progress bar."""
if 'verbose' in kwargs:
verbose = kwargs['verbose']
del kwargs['verbose']
else:
verbose = False
if 'nobar' in kwargs:
nobar = kwargs['nobar']
del kwargs['nobar']
else:
nobar = False
if not 'filetype' in kwargs:
kwargs['filetype'] = ['.dcm', '', '.zip']
# Make list of filetypes for zipfile
# Process no extension separately (because else endswith() will accept any extension if we supply '')
noextflag = False
filetypes = list(kwargs['filetype']) # make a copy
if '' in filetypes:
filetypes.remove('')
filetypes = tuple(filetypes) # endswith() only supports tuples
noextflag = True
# Counting total number of files (to show a progress bar)
filescount = 0
if not nobar:
for dirpath, filename in _tqdm(recwalk(*args, **kwargs), desc='PRECOMP', unit='files'):
if not filename.endswith('.zip'):
filescount +=1
else:
try:
zfilepath = os.path.join(dirpath, filename)
with zipfile.ZipFile(zfilepath, 'r') as zipfh:
zfilescount = sum(1 for item in zipfh.namelist() if not item.endswith('/'))
filescount += zfilescount
except zipfile.BadZipfile as exc:
# If the zipfile is unreadable, just pass
if verbose:
print('Error: Bad zip file: %s' % os.path.join(dirpath, filename))
pass
pbar = _tqdm(total=filescount, desc='REORG', unit='files', disable=nobar)
for dirpath, filename in recwalk(*args, **kwargs):
try:
if not filename.endswith('.zip'):
if filename.lower() == 'dicomdir': # pass DICOMDIR files
continue
try:
if verbose:
print('* Try to read fields from dicom file: %s' % os.path.join(dirpath, filename))
# Update progress bar
pbar.update()
# Read the dicom data in memory (via StringIO)
dcmdata = pydicom.read_file(os.path.join(dirpath, filename), stop_before_pixels=True, defer_size="512 KB", force=True) # stop_before_pixels allow for faster processing since we do not read the full dicom data, and here we can use it because we do not modify the dicom, we only read it to extract the dicom patient name. defer_size avoids reading everything into memory, which workarounds issues with some malformatted fields that are too long (OverflowError: Python int too large to convert to C long)
yield {'data': dcmdata, 'dirpath': dirpath, 'filename': filename}
except (InvalidDicomError, AttributeError, OverflowError) as exc:
pass
else:
try:
zfilepath = os.path.join(dirpath, filename)
with zipfile.ZipFile(zfilepath, 'r') as zipfh:
#zfolders = (item for item in zipfh.namelist() if item.endswith('/'))
| |
in systemdlls:
print "System DLL: " + file
continue
dllpath = ""
for path in extrapaths:
if os.path.exists(path + "/" + file):
dllpath = re.sub(r"\\", r"/", path + "/" + file)
print file + ": found at " + dllpath
dllpaths.append(dllpath)
break
if dllpath == "":
try:
dllpath = re.sub(r"\\", r"/", which(file))
print file + ": found at " + dllpath
dllpaths.append(dllpath)
except:
print "MISSING DLL: " + file
return dllpaths
def zipball(programfiles, versionstring, buildfolder, platform=sys.platform):
'''package created binary'''
print "Creating binary zipball."
archivebase = program + "-" + versionstring
outfolder = buildfolder + "/" + archivebase
archivename = archivebase + ".zip"
# create output folder
os.mkdir(outfolder)
# move program files to output folder
for f in programfiles:
if re.match(r'^(/|[a-zA-Z]:)', f) != None:
shutil.copy(f, outfolder)
else:
shutil.copy(buildfolder + "/" + f, outfolder)
# create zipball from output folder
zf = zipfile.ZipFile(archivename, mode='w', compression=zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(outfolder):
for name in files:
physname = os.path.normpath(os.path.join(root, name))
filename = os.path.relpath(physname, buildfolder)
zf.write(physname, filename)
zf.close()
# remove output folder
shutil.rmtree(outfolder)
return archivename
def tarball(programfiles, versionstring, buildfolder):
'''package created binary'''
print "Creating binary tarball."
archivebase = program + "-" + versionstring
outfolder = buildfolder + "/" + archivebase
archivename = archivebase + ".tar.bz2"
# create output folder
os.mkdir(outfolder)
# move program files to output folder
for f in programfiles:
shutil.copy(buildfolder + "/" + f, outfolder)
# create tarball from output folder
tf = tarfile.open(archivename, mode='w:bz2')
tf.add(outfolder, archivebase)
tf.close()
# remove output folder
shutil.rmtree(outfolder)
return archivename
def macdeploy(versionstring, buildfolder, platform=sys.platform):
'''package created binary to dmg'''
dmgfile = program + "-" + versionstring + ".dmg"
appbundle = buildfolder + "/" + progexe[platform]
# workaround to Qt issues when building out-of-tree. Copy files into bundle.
sourcebase = buildfolder + re.sub('[^/]+.pro$', '', project) + "/"
print sourcebase
for src in bundlecopy:
shutil.copy(sourcebase + src, appbundle + "/" + bundlecopy[src])
# end of Qt workaround
output = subprocess.Popen(["macdeployqt", progexe[platform], "-dmg"], \
stdout=subprocess.PIPE, cwd=buildfolder)
output.communicate()
if not output.returncode == 0:
print "macdeployqt failed!"
return -1
# copy dmg to output folder
shutil.copy(buildfolder + "/" + program + ".dmg", dmgfile)
return dmgfile
def filehashes(filename):
'''Calculate md5 and sha1 hashes for a given file.'''
if not os.path.exists(filename):
return ["", ""]
m = hashlib.md5()
s = hashlib.sha1()
f = open(filename, 'rb')
while True:
d = f.read(65536)
if d == "":
break
m.update(d)
s.update(d)
return [m.hexdigest(), s.hexdigest()]
def filestats(filename):
if not os.path.exists(filename):
return
st = os.stat(filename)
print filename, "\n", "-" * len(filename)
print "Size: %i bytes" % st.st_size
h = filehashes(filename)
print "md5sum: %s" % h[0]
print "sha1sum: %s" % h[1]
print "-" * len(filename), "\n"
def tempclean(workfolder, nopro):
if nopro == True:
print "Cleaning up working folder %s" % workfolder
shutil.rmtree(workfolder)
else:
print "Project file specified or cleanup disabled!"
print "Temporary files kept at %s" % workfolder
def deploy():
startup = time.time()
try:
opts, args = getopt.getopt(sys.argv[1:], "q:p:t:a:n:sbdkx:i:h",
["qmake=", "project=", "tag=", "add=", "makensis=", "source-only",
"binary-only", "dynamic", "keep-temp", "cross=", "buildid=", "help"])
except getopt.GetoptError, err:
print str(err)
usage(sys.argv[0])
sys.exit(1)
qt = ""
proj = ""
svnbase = svnserver + "trunk/"
tag = ""
addfiles = []
cleanup = True
binary = True
source = True
keeptemp = False
makensis = ""
cross = ""
buildid = None
platform = sys.platform
treehash = gitscraper.get_refs(gitrepo)['refs/remotes/origin/HEAD']
if sys.platform != "darwin":
static = True
else:
static = False
for o, a in opts:
if o in ("-q", "--qmake"):
qt = a
if o in ("-p", "--project"):
proj = a
cleanup = False
if o in ("-a", "--add"):
addfiles.append(a)
if o in ("-n", "--makensis"):
makensis = a
if o in ("-s", "--source-only"):
binary = False
if o in ("-b", "--binary-only"):
source = False
if o in ("-d", "--dynamic") and sys.platform != "darwin":
static = False
if o in ("-k", "--keep-temp"):
keeptemp = True
if o in ("-t", "--tree"):
treehash = a
if o in ("-x", "--cross") and sys.platform != "win32":
cross = a
platform = "win32"
if o in ("-i", "--buildid"):
buildid = a
if o in ("-h", "--help"):
usage(sys.argv[0])
sys.exit(0)
if source == False and binary == False:
print "Building build neither source nor binary means nothing to do. Exiting."
sys.exit(1)
print "Building " + progexe[platform] + " for " + platform
# search for qmake
if qt == "":
qm = findqt(cross)
else:
qm = checkqt(qt)
if qm == "":
print "ERROR: No suitable Qt installation found."
sys.exit(1)
# create working folder. Use current directory if -p option used.
if proj == "":
w = tempfile.mkdtemp()
# make sure the path doesn't contain backslashes to prevent issues
# later when running on windows.
workfolder = re.sub(r'\\', '/', w)
revision = gitscraper.describe_treehash(gitrepo, treehash)
# try to find a version number from describe output.
# WARNING: this is broken and just a temporary workaround!
v = re.findall('([\d\.a-f]+)', revision)
if v:
if v[-1].find('.') >= 0:
revision = "v" + v[-1]
else:
revision = v[-1]
if buildid == None:
versionextra = ""
else:
versionextra = "-" + buildid
sourcefolder = workfolder + "/" + program + "-" + str(revision) + versionextra + "/"
archivename = program + "-" + str(revision) + versionextra + "-src.tar.bz2"
ver = str(revision)
os.mkdir(sourcefolder)
print "Version: %s" % revision
else:
workfolder = "."
sourcefolder = "."
archivename = ""
# check if project file explicitly given. If yes, don't get sources from svn
if proj == "":
proj = sourcefolder + project
# get sources and pack source tarball
if not getsources(treehash, svnpaths, sourcefolder) == 0:
tempclean(workfolder, cleanup and not keeptemp)
sys.exit(1)
# replace version strings.
print "Updating version information in sources"
for f in regreplace:
infile = open(sourcefolder + "/" + f, "r")
incontents = infile.readlines()
infile.close()
outfile = open(sourcefolder + "/" + f, "w")
for line in incontents:
newline = line
for r in regreplace[f]:
# replacements made on the replacement string:
# %REVISION% is replaced with the revision number
replacement = re.sub("%REVISION%", str(revision), r[1])
newline = re.sub(r[0], replacement, newline)
# %BUILD% is replaced with buildid as passed on the command line
if buildid != None:
replacement = re.sub("%BUILDID%", "-" + str(buildid), replacement)
else:
replacement = re.sub("%BUILDID%", "", replacement)
newline = re.sub(r[0], replacement, newline)
outfile.write(newline)
outfile.close()
if source == True:
print "Creating source tarball %s\n" % archivename
tf = tarfile.open(archivename, mode='w:bz2')
tf.add(sourcefolder, os.path.basename(re.subn('/$', '', sourcefolder)[0]))
tf.close()
if binary == False:
shutil.rmtree(workfolder)
sys.exit(0)
else:
# figure version from sources. Need to take path to project file into account.
versionfile = re.subn('[\w\.]+$', "version.h", proj)[0]
ver = findversion(versionfile) + "-dev" + datetime.now().strftime('%Y%m%d%H%M%S')
# append buildid if any.
if buildid != None:
ver += "-" + buildid
# check project file
if not os.path.exists(proj):
print "ERROR: path to project file wrong."
sys.exit(1)
# copy specified (--add) files to working folder
for f in addfiles:
shutil.copy(f, sourcefolder)
buildstart = time.time()
header = "Building %s %s" % (program, ver)
print header
print len(header) * "="
# build it.
if not qmake(qm, proj, platform, sourcefolder, static, cross) == 0:
tempclean(workfolder, cleanup and not keeptemp)
sys.exit(1)
if not build(sourcefolder, platform, cross) == 0:
tempclean(workfolder, cleanup and not keeptemp)
sys.exit(1)
buildtime = time.time() - buildstart
progfiles = programfiles
progfiles.append(progexe[platform])
if platform == "win32":
if useupx == True:
if not upxfile(sourcefolder, platform) == 0:
tempclean(workfolder, cleanup and not keeptemp)
sys.exit(1)
dllfiles = finddlls(sourcefolder + "/" + progexe[platform], \
[os.path.dirname(qm)], cross)
if len(dllfiles) > 0:
progfiles.extend(dllfiles)
archive = zipball(progfiles, ver, sourcefolder, platform)
# only when running native right now.
if nsisscript != "" and makensis != "":
nsisfileinject(sourcefolder + "/" + nsisscript, sourcefolder \
+ "/" + nsisscript + ".tmp", dllfiles)
runnsis(ver, makensis, nsisscript + ".tmp", sourcefolder)
elif platform == "darwin":
archive = macdeploy(ver, sourcefolder, platform)
else:
if platform == "linux2":
for p in progfiles:
prog = sourcefolder + "/" + p
output = subprocess.Popen(["file", prog],
stdout=subprocess.PIPE)
res = output.communicate()
if re.findall("ELF 64-bit", res[0]):
ver += "-64bit"
break
archive = tarball(progfiles, ver, sourcefolder)
# remove temporary files
tempclean(workfolder, cleanup)
# display summary
| |
# Find a suitable (writable) location for the index database
if writeIndex:
for indexPath in possibleIndexFilePaths:
try:
folder = os.path.dirname( indexPath )
os.makedirs( folder, exist_ok = True )
f = open( indexPath, 'wb' )
f.write( b'\0' * 1024 * 1024 )
f.close()
os.remove( indexPath )
self.indexFileName = indexPath
break
except IOError:
if printDebug >= 2:
print( "Could not create file:", indexPath )
self.createIndex( self.tarFileObject )
self._loadOrStoreCompressionOffsets()
self._storeTarMetadata()
if printDebug >= 1 and writeIndex:
# The 0-time is legacy for the automated tests
print( "Writing out TAR index to", self.indexFileName, "took 0s",
"and is sized", os.stat( self.indexFileName ).st_size, "B" )
def _storeTarMetadata( self ):
"""Adds some consistency meta information to recognize the need to update the cached TAR index"""
metadataTable = """
/* empty table whose sole existence specifies that we finished iterating the tar */
CREATE TABLE "metadata" (
"key" VARCHAR(65535) NOT NULL, /* e.g. "tarsize" */
"value" VARCHAR(65535) NOT NULL /* e.g. size in bytes as integer */
);
"""
try:
tarStats = os.stat( self.tarFileName )
self.sqlConnection.executescript( metadataTable )
serializedTarStats = json.dumps( { attr : getattr( tarStats, attr )
for attr in dir( tarStats ) if attr.startswith( 'st_' ) } )
self.sqlConnection.execute( 'INSERT INTO "metadata" VALUES (?,?)', ( "tarstats", serializedTarStats ) )
self.sqlConnection.commit()
except Exception as exception:
if printDebug >= 2:
print( exception )
print( "[Warning] There was an error when adding file metadata information." )
print( "[Warning] Automatic detection of changed TAR files during index loading might not work." )
def _openSqlDb( self, filePath ):
self.sqlConnection = sqlite3.connect( filePath )
self.sqlConnection.row_factory = sqlite3.Row
self.sqlConnection.executescript( """
PRAGMA LOCKING_MODE = EXCLUSIVE;
PRAGMA TEMP_STORE = MEMORY;
PRAGMA JOURNAL_MODE = OFF;
PRAGMA SYNCHRONOUS = OFF;
""" )
def createIndex( self, fileObject, progressBar = None, pathPrefix = '', streamOffset = 0 ):
if printDebug >= 1:
print( "Creating offset dictionary for",
"<file object>" if self.tarFileName is None else self.tarFileName, "..." )
t0 = timer()
# 1. If no SQL connection was given (by recursive call), open a new database file
openedConnection = False
if not self.indexIsLoaded():
if printDebug >= 1:
print( "Creating new SQLite index database at", self.indexFileName )
createTables = """
CREATE TABLE "files" (
"path" VARCHAR(65535) NOT NULL,
"name" VARCHAR(65535) NOT NULL,
"offsetheader" INTEGER, /* seek offset from TAR file where these file's contents resides */
"offset" INTEGER, /* seek offset from TAR file where these file's contents resides */
"size" INTEGER,
"mtime" INTEGER,
"mode" INTEGER,
"type" INTEGER,
"linkname" VARCHAR(65535),
"uid" INTEGER,
"gid" INTEGER,
/* True for valid TAR files. Internally used to determine where to mount recursive TAR files. */
"istar" BOOL ,
"issparse" BOOL , /* for sparse files the file size refers to the expanded size! */
/* See SQL benchmarks for decision on the primary key.
* See also https://www.sqlite.org/optoverview.html
* (path,name) tuples might appear multiple times in a TAR if it got updated.
* In order to also be able to show older versions, we need to add
* the offsetheader column to the primary key. */
PRIMARY KEY (path,name,offsetheader)
);
/* "A table created using CREATE TABLE AS has no PRIMARY KEY and no constraints of any kind"
* Therefore, it will not be sorted and inserting will be faster! */
CREATE TABLE "filestmp" AS SELECT * FROM "files" WHERE 0;
CREATE TABLE "parentfolders" (
"path" VARCHAR(65535) NOT NULL,
"name" VARCHAR(65535) NOT NULL,
PRIMARY KEY (path,name)
);
"""
openedConnection = True
self._openSqlDb( self.indexFileName if self.indexFileName else ':memory:' )
tables = self.sqlConnection.execute( 'SELECT name FROM sqlite_master WHERE type = "table";' )
if set( [ "files", "filestmp", "parentfolders" ] ).intersection( set( [ t[0] for t in tables ] ) ):
raise Exception( "[Error] The index file {} already seems to contain a table. "
"Please specify --recreate-index." )
self.sqlConnection.executescript( createTables )
# 2. Open TAR file reader
try:
streamed = ( 'IndexedBzip2File' in globals() and isinstance( fileObject, IndexedBzip2File ) ) or \
( 'IndexedGzipFile' in globals() and isinstance( fileObject, IndexedGzipFile ) )
# r: uses seeks to skip to the next file inside the TAR while r| doesn't do any seeks.
# r| might be slower but for compressed files we have to go over all the data once anyways
# and I had problems with seeks at this stage. Maybe they are gone now after the bz2 bugfix though.
loadedTarFile = tarfile.open( fileobj = fileObject, mode = 'r|' if streamed else 'r:', ignore_zeros = True )
except tarfile.ReadError as exception:
print( "Archive can't be opened! This might happen for compressed TAR archives, "
"which currently is not supported." )
raise exception
if progressBar is None:
progressBar = ProgressBar( os.fstat( fileObject.fileno() ).st_size )
# 3. Iterate over files inside TAR and add them to the database
try:
for tarInfo in loadedTarFile:
loadedTarFile.members = []
globalOffset = streamOffset + tarInfo.offset_data
globalOffsetHeader = streamOffset + tarInfo.offset
if 'IndexedBzip2File' in globals() and isinstance( fileObject, IndexedBzip2File ):
# We will have to adjust the global offset to a rough estimate of the real compressed size.
# Note that tell_compressed is always one bzip2 block further, which leads to underestimated
# file compression ratio especially in the beginning.
progressBar.update( int( globalOffset * fileObject.tell_compressed() / 8 / fileObject.tell() ) )
elif 'IndexedGzipFile' in globals() and isinstance( fileObject, IndexedGzipFile ):
try:
progressBar.update( int( globalOffset * fileObject.fileobj().tell() / fileObject.tell() ) )
except:
progressBar.update( globalOffset )
else:
progressBar.update( globalOffset )
mode = tarInfo.mode
if tarInfo.isdir() : mode |= stat.S_IFDIR
if tarInfo.isfile(): mode |= stat.S_IFREG
if tarInfo.issym() : mode |= stat.S_IFLNK
if tarInfo.ischr() : mode |= stat.S_IFCHR
if tarInfo.isfifo(): mode |= stat.S_IFIFO
# Add a leading '/' as a convention where '/' represents the TAR root folder
# Partly, done because fusepy specifies paths in a mounted directory like this
# os.normpath does not delete duplicate '/' at beginning of string!
fullPath = pathPrefix + "/" + os.path.normpath( tarInfo.name ).lstrip( '/' )
# 4. Open contained TARs for recursive mounting
isTar = False
if self.mountRecursively and tarInfo.isfile() and tarInfo.name.endswith( ".tar" ):
oldPos = fileObject.tell()
fileObject.seek( globalOffset )
oldPrintName = self.tarFileName
try:
self.tarFileName = tarInfo.name.lstrip( '/' ) # This is for output of the recursive call
self.createIndex( fileObject, progressBar, fullPath, globalOffset if streamed else 0 )
# if the TAR file contents could be read, we need to adjust the actual
# TAR file's metadata to be a directory instead of a file
mode = ( mode & 0o777 ) | stat.S_IFDIR
if mode & stat.S_IRUSR != 0: mode |= stat.S_IXUSR
if mode & stat.S_IRGRP != 0: mode |= stat.S_IXGRP
if mode & stat.S_IROTH != 0: mode |= stat.S_IXOTH
isTar = True
except tarfile.ReadError:
None
self.tarFileName = oldPrintName
fileObject.seek( oldPos )
path, name = fullPath.rsplit( "/", 1 )
fileInfo = (
path , # 0
name , # 1
globalOffsetHeader , # 2
globalOffset , # 3
tarInfo.size , # 4
tarInfo.mtime , # 5
mode , # 6
tarInfo.type , # 7
tarInfo.linkname , # 8
tarInfo.uid , # 9
tarInfo.gid , # 10
isTar , # 11
tarInfo.issparse() , # 12
)
self._setFileInfo( fileInfo )
except tarfile.ReadError as e:
if 'unexpected end of data' in str( e ):
print( "[Warning] The TAR file is incomplete. Ratarmount will work but some files might be cut off. "
"If the TAR file size changes, ratarmount will recreate the index during the next mounting." )
# 5. Resort by (path,name). This one-time resort is faster than resorting on each INSERT (cache spill)
if openedConnection:
if printDebug >= 2:
print( "Resorting files by path ..." )
cleanupDatabase = """
INSERT OR REPLACE INTO "files" SELECT * FROM "filestmp" ORDER BY "path","name",rowid;
DROP TABLE "filestmp";
INSERT OR IGNORE INTO "files"
/* path name offsetheader offset size mtime mode type linkname uid gid istar issparse */
SELECT path,name,0,0,1,0,{},{},"",0,0,0,0
FROM "parentfolders" ORDER BY "path","name";
DROP TABLE "parentfolders";
""".format( int( 0o555 | stat.S_IFDIR ), | |
self.__dict__ == other.__dict__
def __ne__(self, other: 'GetPublicSettingsResponseVERSIONS') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class ImportCaBodyMsp():
"""
ImportCaBodyMsp.
:attr ImportCaBodyMspCa ca:
:attr ImportCaBodyMspTlsca tlsca:
:attr ImportCaBodyMspComponent component:
"""
def __init__(self,
ca: 'ImportCaBodyMspCa',
tlsca: 'ImportCaBodyMspTlsca',
component: 'ImportCaBodyMspComponent') -> None:
"""
Initialize a ImportCaBodyMsp object.
:param ImportCaBodyMspCa ca:
:param ImportCaBodyMspTlsca tlsca:
:param ImportCaBodyMspComponent component:
"""
self.ca = ca
self.tlsca = tlsca
self.component = component
@classmethod
def from_dict(cls, _dict: Dict) -> 'ImportCaBodyMsp':
"""Initialize a ImportCaBodyMsp object from a json dictionary."""
args = {}
if 'ca' in _dict:
args['ca'] = ImportCaBodyMspCa.from_dict(_dict.get('ca'))
else:
raise ValueError('Required property \'ca\' not present in ImportCaBodyMsp JSON')
if 'tlsca' in _dict:
args['tlsca'] = ImportCaBodyMspTlsca.from_dict(_dict.get('tlsca'))
else:
raise ValueError('Required property \'tlsca\' not present in ImportCaBodyMsp JSON')
if 'component' in _dict:
args['component'] = ImportCaBodyMspComponent.from_dict(_dict.get('component'))
else:
raise ValueError('Required property \'component\' not present in ImportCaBodyMsp JSON')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a ImportCaBodyMsp 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, 'ca') and self.ca is not None:
_dict['ca'] = self.ca.to_dict()
if hasattr(self, 'tlsca') and self.tlsca is not None:
_dict['tlsca'] = self.tlsca.to_dict()
if hasattr(self, 'component') and self.component is not None:
_dict['component'] = self.component.to_dict()
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 ImportCaBodyMsp object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'ImportCaBodyMsp') -> 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: 'ImportCaBodyMsp') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class ImportCaBodyMspCa():
"""
ImportCaBodyMspCa.
:attr str name: The "name" to distinguish this CA from the TLS CA.
:attr List[str] root_certs: (optional) An array that contains one or more base
64 encoded PEM root certificates for the CA.
"""
def __init__(self,
name: str,
*,
root_certs: List[str] = None) -> None:
"""
Initialize a ImportCaBodyMspCa object.
:param str name: The "name" to distinguish this CA from the TLS CA.
:param List[str] root_certs: (optional) An array that contains one or more
base 64 encoded PEM root certificates for the CA.
"""
self.name = name
self.root_certs = root_certs
@classmethod
def from_dict(cls, _dict: Dict) -> 'ImportCaBodyMspCa':
"""Initialize a ImportCaBodyMspCa object from a json dictionary."""
args = {}
if 'name' in _dict:
args['name'] = _dict.get('name')
else:
raise ValueError('Required property \'name\' not present in ImportCaBodyMspCa JSON')
if 'root_certs' in _dict:
args['root_certs'] = _dict.get('root_certs')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a ImportCaBodyMspCa 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, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'root_certs') and self.root_certs is not None:
_dict['root_certs'] = self.root_certs
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 ImportCaBodyMspCa object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'ImportCaBodyMspCa') -> 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: 'ImportCaBodyMspCa') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class ImportCaBodyMspComponent():
"""
ImportCaBodyMspComponent.
:attr str tls_cert: The TLS certificate as base 64 encoded PEM. Certificate is
used to secure/validate a TLS connection with this component.
"""
def __init__(self,
tls_cert: str) -> None:
"""
Initialize a ImportCaBodyMspComponent object.
:param str tls_cert: The TLS certificate as base 64 encoded PEM.
Certificate is used to secure/validate a TLS connection with this
component.
"""
self.tls_cert = tls_cert
@classmethod
def from_dict(cls, _dict: Dict) -> 'ImportCaBodyMspComponent':
"""Initialize a ImportCaBodyMspComponent object from a json dictionary."""
args = {}
if 'tls_cert' in _dict:
args['tls_cert'] = _dict.get('tls_cert')
else:
raise ValueError('Required property \'tls_cert\' not present in ImportCaBodyMspComponent JSON')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a ImportCaBodyMspComponent 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, 'tls_cert') and self.tls_cert is not None:
_dict['tls_cert'] = self.tls_cert
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 ImportCaBodyMspComponent object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'ImportCaBodyMspComponent') -> 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: 'ImportCaBodyMspComponent') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class ImportCaBodyMspTlsca():
"""
ImportCaBodyMspTlsca.
:attr str name: The "name" to distinguish this CA from the other CA.
:attr List[str] root_certs: (optional) An array that contains one or more base
64 encoded PEM root certificates for the TLS CA.
"""
def __init__(self,
name: str,
*,
root_certs: List[str] = None) -> None:
"""
Initialize a ImportCaBodyMspTlsca object.
:param str name: The "name" to distinguish this CA from the other CA.
:param List[str] root_certs: (optional) An array that contains one or more
base 64 encoded PEM root certificates for the TLS CA.
"""
self.name = name
self.root_certs = root_certs
@classmethod
def from_dict(cls, _dict: Dict) -> 'ImportCaBodyMspTlsca':
"""Initialize a ImportCaBodyMspTlsca object from a json dictionary."""
args = {}
if 'name' in _dict:
args['name'] = _dict.get('name')
else:
raise ValueError('Required property \'name\' not present in ImportCaBodyMspTlsca JSON')
if 'root_certs' in _dict:
args['root_certs'] = _dict.get('root_certs')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a ImportCaBodyMspTlsca 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, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'root_certs') and self.root_certs is not None:
_dict['root_certs'] = self.root_certs
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 ImportCaBodyMspTlsca object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'ImportCaBodyMspTlsca') -> 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: 'ImportCaBodyMspTlsca') -> bool:
"""Return `true` when self and other are not equal, false otherwise."""
return not self == other
class LogSettingsResponse():
"""
The logging settings for the client and server.
:attr LoggingSettingsClient client: (optional) The client side (browser) logging
settings. _Changes to this field will restart the IBP console server(s)_.
:attr LoggingSettingsServer server: (optional) The server side logging settings.
_Changes to this field will restart the IBP console server(s)_.
"""
def __init__(self,
*,
client: 'LoggingSettingsClient' = None,
server: 'LoggingSettingsServer' = None) -> None:
"""
Initialize a LogSettingsResponse object.
:param LoggingSettingsClient client: (optional) The client side (browser)
logging settings. _Changes to this field will restart the IBP console
server(s)_.
:param LoggingSettingsServer server: (optional) The server side logging
settings. _Changes to this field will restart the IBP console server(s)_.
"""
self.client = client
self.server = server
@classmethod
def from_dict(cls, _dict: Dict) -> 'LogSettingsResponse':
"""Initialize a LogSettingsResponse object from a json dictionary."""
args = {}
if 'client' in _dict:
args['client'] = LoggingSettingsClient.from_dict(_dict.get('client'))
if 'server' in _dict:
args['server'] = LoggingSettingsServer.from_dict(_dict.get('server'))
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a LogSettingsResponse 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, 'client') and self.client is not None:
_dict['client'] = self.client.to_dict()
if hasattr(self, 'server') and self.server is not None:
_dict['server'] = self.server.to_dict()
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 LogSettingsResponse object."""
return json.dumps(self.to_dict(), indent=2)
def __eq__(self, other: 'LogSettingsResponse') -> 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: 'LogSettingsResponse') -> | |
<filename>direct/src/tkpanels/ParticlePanel.py
"""PANDA3D Particle Panel"""
__all__ = ['ParticlePanel']
# Import Tkinter, Pmw, and the floater code from this directory tree.
from direct.tkwidgets.AppShell import *
from direct.showbase.TkGlobal import *
from direct.tkwidgets import Dial
from direct.tkwidgets import Floater
from direct.tkwidgets import Slider
from direct.tkwidgets import VectorWidgets
from direct.tkpanels import Placer
from direct.particles import ForceGroup
from direct.particles import Particles
from direct.particles import ParticleEffect
import Pmw, os, sys
if sys.version_info >= (3, 0):
from tkinter.filedialog import *
from tkinter.simpledialog import askstring
else:
from tkFileDialog import *
from tkSimpleDialog import askstring
from panda3d.core import *
from panda3d.physics import *
from panda3d.direct import getParticlePath
class ParticlePanel(AppShell):
# Override class variables
appname = 'Particle Panel'
frameWidth = 375
frameHeight = 675
usecommandarea = 0
usestatusarea = 0
balloonState = 'both'
def __init__(self, particleEffect = None, **kw):
INITOPT = Pmw.INITOPT
optiondefs = (
('title', self.appname, None),
)
self.defineoptions(kw, optiondefs)
# Record particle effect
if particleEffect != None:
self.particleEffect = particleEffect
else:
# Make sure particles are enabled
base.enableParticles()
# Or create a new one if none given
particles = Particles.Particles()
particles.setBirthRate(0.02)
particles.setLitterSize(10)
particles.setLitterSpread(0)
particles.setFactory("PointParticleFactory")
particles.setRenderer("PointParticleRenderer")
particles.setEmitter("SphereVolumeEmitter")
particles.enable()
pe = ParticleEffect.ParticleEffect('effect-1', particles)
self.particleEffect = pe
pe.reparentTo(render)
pe.enable()
# Initialize application specific info
AppShell.__init__(self)
# Initialize panel Pmw options
self.initialiseoptions(ParticlePanel)
# Update panel values to reflect particle effect's state
self.selectEffectNamed(next(iter(self.effectsDict)))
# Make sure labels/menus reflect current state
self.updateMenusAndLabels()
# Make sure there is a page for each forceGroup objects
for forceGroup in self.particleEffect.getForceGroupList():
self.addForceGroupNotebookPage(self.particleEffect, forceGroup)
def appInit(self):
# Create dictionaries to keep track of panel objects
self.widgetDict = {}
self.variableDict = {}
self.effectsDict = {}
self.effectsDict[self.particleEffect.getName()] = (
self.particleEffect)
self.forcePagesDict = {}
def createInterface(self):
# Handle to the toplevels hull
interior = self.interior()
# Create particle panel menu items
## MENUBAR ENTRIES ##
# FILE MENU
# Get a handle on the file menu so commands can be inserted
# before quit item
fileMenu = self.menuBar.component('File-menu')
# MRM: Need to add load and save effects methods
fileMenu.insert_command(
fileMenu.index('Quit'),
label = 'Load Params',
command = self.loadParticleEffectFromFile)
fileMenu.insert_command(
fileMenu.index('Quit'),
label = 'Save Params',
command = self.saveParticleEffectToFile)
fileMenu.insert_command(
fileMenu.index('Quit'),
label = 'Print Params',
command = lambda s = self: s.particles.printParams())
# PARTICLE MANAGER MENU
self.menuBar.addmenu('ParticleMgr', 'ParticleMgr Operations')
self.particleMgrActive = IntVar()
self.particleMgrActive.set(base.isParticleMgrEnabled())
self.menuBar.addmenuitem(
'ParticleMgr', 'checkbutton',
'Enable/Disable ParticleMgr',
label = 'Active',
variable = self.particleMgrActive,
command = self.toggleParticleMgr)
## MENUBUTTON LABELS ##
# Menubutton/label to identify the current objects being configured
labelFrame = Frame(interior)
# Current effect
self.effectsLabel = Menubutton(labelFrame, width = 10,
relief = RAISED,
borderwidth = 2,
font=('MSSansSerif', 12, 'bold'),
activebackground = '#909090')
self.effectsLabelMenu = Menu(self.effectsLabel, tearoff = 0)
self.effectsLabel['menu'] = self.effectsLabelMenu
self.effectsLabel.pack(side = LEFT, fill = 'x', expand = 1)
self.bind(self.effectsLabel,
'Select effect to configure or create new effect')
self.effectsLabelMenu.add_command(label = 'Create New Effect',
command = self.createNewEffect)
self.effectsLabelMenu.add_command(
label = 'Select Particle Effect',
command = lambda s = self: base.direct.select(s.particleEffect))
self.effectsLabelMenu.add_command(
label = 'Place Particle Effect',
command = lambda s = self: Placer.place(s.particleEffect))
def togglePEVis(s = self):
if s.particleEffect.isHidden():
s.particleEffect.show()
else:
s.particleEffect.hide()
self.effectsLabelMenu.add_command(
label = 'Toggle Effect Vis',
command = togglePEVis)
self.effectsEnableMenu = Menu(self.effectsLabelMenu, tearoff = 0)
self.effectsLabelMenu.add_cascade(label = 'Enable/Disable',
menu = self.effectsEnableMenu)
self.effectsLabelMenu.add_separator()
# Current particles
self.particlesLabel = Menubutton(labelFrame, width = 10,
relief = RAISED,
borderwidth = 2,
font=('MSSansSerif', 12, 'bold'),
activebackground = '#909090')
self.particlesLabelMenu = Menu(self.particlesLabel, tearoff = 0)
self.particlesLabel['menu'] = self.particlesLabelMenu
self.particlesLabel.pack(side = LEFT, fill = 'x', expand = 1)
self.bind(self.particlesLabel,
('Select particles object to configure ' +
'or add new particles object to current effect'))
self.particlesLabelMenu.add_command(label = 'Create New Particles',
command = self.createNewParticles)
self.particlesEnableMenu = Menu(self.particlesLabelMenu, tearoff = 0)
self.particlesLabelMenu.add_cascade(label = 'Enable/Disable',
menu = self.particlesEnableMenu)
self.particlesLabelMenu.add_separator()
# Current force
self.forceGroupLabel = Menubutton(labelFrame, width = 10,
relief = RAISED,
borderwidth = 2,
font=('MSSansSerif', 12, 'bold'),
activebackground = '#909090')
self.forceGroupLabelMenu = Menu(self.forceGroupLabel, tearoff = 0)
self.forceGroupLabel['menu'] = self.forceGroupLabelMenu
self.forceGroupLabel.pack(side = LEFT, fill = 'x', expand = 1)
self.bind(self.forceGroupLabel,
('Select force group to configure ' +
'or add a new force group to current effect'))
self.forceGroupLabelMenu.add_command(
label = 'Create New ForceGroup',
command = self.createNewForceGroup)
self.forceGroupEnableMenu = Menu(self.forceGroupLabelMenu, tearoff = 0)
self.forceGroupLabelMenu.add_cascade(label = 'Enable/Disable',
menu = self.forceGroupEnableMenu)
self.forceGroupLabelMenu.add_separator()
# Pack labels
labelFrame.pack(fill = 'x', expand = 0)
# Create the toplevel notebook pages
self.mainNotebook = Pmw.NoteBook(interior)
self.mainNotebook.pack(fill = BOTH, expand = 1)
systemPage = self.mainNotebook.add('System')
factoryPage = self.mainNotebook.add('Factory')
emitterPage = self.mainNotebook.add('Emitter')
rendererPage = self.mainNotebook.add('Renderer')
forcePage = self.mainNotebook.add('Force')
# Put this here so it isn't called right away
self.mainNotebook['raisecommand'] = self.updateInfo
## SYSTEM PAGE WIDGETS ##
# Create system floaters
systemFloaterDefs = (
('System', 'Pool Size',
'Max number of simultaneous particles',
self.setSystemPoolSize,
1.0, 1.0),
('System', 'Birth Rate',
'Seconds between particle births',
self.setSystemBirthRate,
0.0, None),
('System', 'Litter Size',
'Number of particle created at each birth',
self.setSystemLitterSize,
1.0, 1.0),
('System', 'Litter Spread',
'Variation in litter size',
self.setSystemLitterSpread,
0.0, 1.0),
('System', 'Lifespan',
'Age in seconds at which the system (vs. particles) should die',
self.setSystemLifespan,
0.0, None)
)
self.createFloaters(systemPage, systemFloaterDefs)
# Checkboxes
self.createCheckbutton(
systemPage, 'System', 'Render Space Velocities',
('On: velocities are in render space; ' +
'Off: velocities are in particle local space'),
self.toggleSystemLocalVelocity, 0)
self.createCheckbutton(
systemPage, 'System', 'System Grows Older',
'On: system has a lifespan',
self.toggleSystemGrowsOlder, 0)
# Vector widgets
pos = self.createVector3Entry(systemPage, 'System', 'Pos',
'Particle system position',
command = self.setSystemPos)
pos.addMenuItem('Popup Placer Panel', Placer.Placer)
hpr = self.createVector3Entry(systemPage, 'System', 'Hpr',
'Particle system orientation',
fGroup_labels = ('H', 'P', 'R'),
command = self.setSystemHpr)
hpr.addMenuItem('Popup Placer Panel', Placer.Placer)
## FACTORY PAGE WIDGETS ##
self.createOptionMenu(
factoryPage,
'Factory', 'Factory Type',
'Select type of particle factory',
('PointParticleFactory', 'ZSpinParticleFactory',
#'OrientedParticleFactory'
),
self.selectFactoryType)
factoryWidgets = (
('Factory', 'Life Span',
'Average particle lifespan in seconds',
self.setFactoryLifeSpan,
0.0, None),
('Factory', 'Life Span Spread',
'Variation in lifespan',
self.setFactoryLifeSpanSpread,
0.0, None),
('Factory', 'Mass',
'Average particle mass',
self.setFactoryParticleMass,
0.001, None),
('Factory', 'Mass Spread',
'Variation in particle mass',
self.setFactoryParticleMassSpread,
0.0, None),
('Factory', 'Terminal Velocity',
'Cap on average particle velocity',
self.setFactoryTerminalVelocity,
0.0, None),
('Factory', 'Terminal Vel. Spread',
'Variation in terminal velocity',
self.setFactoryTerminalVelocitySpread,
0.0, None),
)
self.createFloaters(factoryPage, factoryWidgets)
self.factoryNotebook = Pmw.NoteBook(factoryPage, tabpos = None)
# Point page #
factoryPointPage = self.factoryNotebook.add('PointParticleFactory')
# Z spin page #
zSpinPage = self.factoryNotebook.add('ZSpinParticleFactory')
self.createCheckbutton(
zSpinPage, 'Z Spin Factory', 'Enable Angular Velocity',
("On: angular velocity is used; " +
"Off: final angle is used"),
self.toggleAngularVelocity, 0, side = TOP),
self.createFloater(
zSpinPage, 'Z Spin Factory', 'Angular Velocity',
'How fast sprites rotate',
command = self.setFactoryZSpinAngularVelocity)
self.createFloater(
zSpinPage, 'Z Spin Factory', 'Angular Velocity Spread',
'Variation in how fast sprites rotate',
command = self.setFactoryZSpinAngularVelocitySpread)
self.createAngleDial(zSpinPage, 'Z Spin Factory', 'Initial Angle',
'Starting angle in degrees',
fRollover = 1,
command = self.setFactoryZSpinInitialAngle)
self.createAngleDial(
zSpinPage, 'Z Spin Factory',
'Initial Angle Spread',
'Spread of the initial angle',
fRollover = 1,
command = self.setFactoryZSpinInitialAngleSpread)
self.createAngleDial(zSpinPage, 'Z Spin Factory', 'Final Angle',
'Final angle in degrees',
fRollover = 1,
command = self.setFactoryZSpinFinalAngle)
self.createAngleDial(
zSpinPage, 'Z Spin Factory',
'Final Angle Spread',
'Spread of the final angle',
fRollover = 1,
command = self.setFactoryZSpinFinalAngleSpread)
# Oriented page #
orientedPage = self.factoryNotebook.add('OrientedParticleFactory')
Label(orientedPage, text = 'Not implemented').pack(expand = 1,
fill = BOTH)
self.factoryNotebook.pack(expand = 1, fill = BOTH)
## EMITTER PAGE WIDGETS ##
self.createOptionMenu(
emitterPage, 'Emitter',
'Emitter Type',
'Select type of particle emitter',
('BoxEmitter', 'DiscEmitter', 'LineEmitter', 'PointEmitter',
'RectangleEmitter', 'RingEmitter', 'SphereVolumeEmitter',
'SphereSurfaceEmitter', 'TangentRingEmitter'),
self.selectEmitterType)
# Emitter modes
self.emissionType = IntVar()
self.emissionType.set(BaseParticleEmitter.ETRADIATE)
emissionFrame = Frame(emitterPage)
self.createRadiobutton(
emissionFrame, 'left',
'Emitter', 'Explicit Emission',
('particles are all emitted in parallel, direction is based ' +
'on explicit velocity vector'),
self.emissionType, BaseParticleEmitter.ETEXPLICIT,
self.setEmissionType)
self.createRadiobutton(
emissionFrame, 'left',
'Emitter', 'Radiate Emission',
'particles are emitted away from a specific point',
self.emissionType, BaseParticleEmitter.ETRADIATE,
self.setEmissionType)
self.createRadiobutton(
emissionFrame, 'left',
'Emitter', 'Custom Emission',
('particles are emitted with a velocity that ' +
'is determined by the particular emitter'),
self.emissionType, BaseParticleEmitter.ETCUSTOM,
self.setEmissionType)
emissionFrame.pack(fill = 'x', expand = 0)
self.createFloater(
emitterPage, 'Emitter', 'Velocity Multiplier',
'launch velocity multiplier (all emission modes)',
command = self.setEmitterAmplitude,
min = None)
self.createFloater(
emitterPage, 'Emitter', 'Velocity Multiplier Spread',
'spread for launch velocity multiplier (all emission modes)',
command = self.setEmitterAmplitudeSpread)
self.createVector3Entry(
emitterPage, 'Emitter', 'Offset Velocity',
'Velocity vector applied to all particles',
command = self.setEmitterOffsetForce)
self.createVector3Entry(
emitterPage, 'Emitter', 'Explicit Velocity',
'all particles launch with this velocity in Explicit mode',
command = self.setEmitterExplicitLaunchVector)
self.createVector3Entry(
emitterPage, 'Emitter', 'Radiate Origin',
'particles launch away from this point in Radiate mode',
command | |
<gh_stars>1-10
#
# Autogenerated by Thrift Compiler (0.9.2)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class OrderingType:
ASCENDING = 1
DESCENDING = 2
_VALUES_TO_NAMES = {
1: "ASCENDING",
2: "DESCENDING",
}
_NAMES_TO_VALUES = {
"ASCENDING": 1,
"DESCENDING": 2,
}
class DataPoint:
"""
Attributes:
- dimensions
- metrics
"""
thrift_spec = (
None, # 0
(1, TType.MAP, 'dimensions', (TType.STRING,None,TType.STRING,None), None, ), # 1
(2, TType.MAP, 'metrics', (TType.STRING,None,TType.I64,None), None, ), # 2
)
def __init__(self, dimensions=None, metrics=None,):
self.dimensions = dimensions
self.metrics = metrics
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.MAP:
self.dimensions = {}
(_ktype1, _vtype2, _size0 ) = iprot.readMapBegin()
for _i4 in xrange(_size0):
_key5 = iprot.readString();
_val6 = iprot.readString();
self.dimensions[_key5] = _val6
iprot.readMapEnd()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.MAP:
self.metrics = {}
(_ktype8, _vtype9, _size7 ) = iprot.readMapBegin()
for _i11 in xrange(_size7):
_key12 = iprot.readString();
_val13 = iprot.readI64();
self.metrics[_key12] = _val13
iprot.readMapEnd()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('DataPoint')
if self.dimensions is not None:
oprot.writeFieldBegin('dimensions', TType.MAP, 1)
oprot.writeMapBegin(TType.STRING, TType.STRING, len(self.dimensions))
for kiter14,viter15 in self.dimensions.items():
oprot.writeString(kiter14)
oprot.writeString(viter15)
oprot.writeMapEnd()
oprot.writeFieldEnd()
if self.metrics is not None:
oprot.writeFieldBegin('metrics', TType.MAP, 2)
oprot.writeMapBegin(TType.STRING, TType.I64, len(self.metrics))
for kiter16,viter17 in self.metrics.items():
oprot.writeString(kiter16)
oprot.writeI64(viter17)
oprot.writeMapEnd()
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.dimensions)
value = (value * 31) ^ hash(self.metrics)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class DimensionFilter:
"""
Attributes:
- dimension
- value
"""
thrift_spec = (
None, # 0
(1, TType.STRING, 'dimension', None, None, ), # 1
(2, TType.STRING, 'value', None, None, ), # 2
)
def __init__(self, dimension=None, value=None,):
self.dimension = dimension
self.value = value
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.dimension = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.value = iprot.readString();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('DimensionFilter')
if self.dimension is not None:
oprot.writeFieldBegin('dimension', TType.STRING, 1)
oprot.writeString(self.dimension)
oprot.writeFieldEnd()
if self.value is not None:
oprot.writeFieldBegin('value', TType.STRING, 2)
oprot.writeString(self.value)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.dimension)
value = (value * 31) ^ hash(self.value)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class Response:
"""
Attributes:
- data
"""
thrift_spec = (
None, # 0
(1, TType.LIST, 'data', (TType.STRUCT,(DataPoint, DataPoint.thrift_spec)), None, ), # 1
)
def __init__(self, data=None,):
self.data = data
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.LIST:
self.data = []
(_etype21, _size18) = iprot.readListBegin()
for _i22 in xrange(_size18):
_elem23 = DataPoint()
_elem23.read(iprot)
self.data.append(_elem23)
iprot.readListEnd()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('Response')
if self.data is not None:
oprot.writeFieldBegin('data', TType.LIST, 1)
oprot.writeListBegin(TType.STRUCT, len(self.data))
for iter24 in self.data:
iter24.write(oprot)
oprot.writeListEnd()
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.data)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class Sort:
"""
Attributes:
- dimension
- metric
- ordering
"""
thrift_spec = (
None, # 0
(1, TType.STRING, 'dimension', None, None, ), # 1
(2, TType.STRING, 'metric', None, None, ), # 2
(3, TType.I32, 'ordering', None, None, ), # 3
)
def __init__(self, dimension=None, metric=None, ordering=None,):
self.dimension = dimension
self.metric = metric
self.ordering = ordering
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.dimension = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.metric = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.I32:
self.ordering = iprot.readI32();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('Sort')
if self.dimension is not None:
oprot.writeFieldBegin('dimension', TType.STRING, 1)
oprot.writeString(self.dimension)
oprot.writeFieldEnd()
if self.metric is not None:
oprot.writeFieldBegin('metric', TType.STRING, 2)
oprot.writeString(self.metric)
oprot.writeFieldEnd()
if self.ordering is not None:
oprot.writeFieldBegin('ordering', TType.I32, 3)
oprot.writeI32(self.ordering)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.dimension)
value = (value * 31) ^ hash(self.metric)
value = (value * 31) ^ hash(self.ordering)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class Request:
"""
Attributes:
- dimensions
- metrics
- filters
- sorts
"""
thrift_spec = (
None, # 0
(1, TType.LIST, 'dimensions', (TType.STRING,None), None, ), # 1
(2, TType.LIST, 'metrics', (TType.STRING,None), None, ), # 2
(3, TType.LIST, 'filters', (TType.STRUCT,(DimensionFilter, DimensionFilter.thrift_spec)), None, ), # 3
(4, TType.LIST, 'sorts', (TType.STRUCT,(Sort, Sort.thrift_spec)), None, ), # 4
)
def __init__(self, dimensions=None, metrics=None, filters=None, sorts=None,):
self.dimensions = dimensions
self.metrics = metrics
self.filters = filters
self.sorts = sorts
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.LIST:
self.dimensions = []
(_etype28, _size25) = iprot.readListBegin()
for _i29 in xrange(_size25):
_elem30 = iprot.readString();
self.dimensions.append(_elem30)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.LIST:
self.metrics = []
(_etype34, _size31) = iprot.readListBegin()
for _i35 in xrange(_size31):
_elem36 = iprot.readString();
self.metrics.append(_elem36)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.LIST:
self.filters = []
(_etype40, _size37) = iprot.readListBegin()
for _i41 in xrange(_size37):
_elem42 = DimensionFilter()
_elem42.read(iprot)
self.filters.append(_elem42)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.LIST:
self.sorts = []
(_etype46, _size43) = iprot.readListBegin()
for _i47 in xrange(_size43):
_elem48 = Sort()
_elem48.read(iprot)
self.sorts.append(_elem48)
iprot.readListEnd()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('Request')
if self.dimensions is not None:
oprot.writeFieldBegin('dimensions', TType.LIST, 1)
oprot.writeListBegin(TType.STRING, len(self.dimensions))
for iter49 in self.dimensions:
oprot.writeString(iter49)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.metrics is not None:
oprot.writeFieldBegin('metrics', TType.LIST, 2)
oprot.writeListBegin(TType.STRING, len(self.metrics))
for iter50 in self.metrics:
oprot.writeString(iter50)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.filters is | |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import uuid
from datetime import datetime
from xml.etree import cElementTree as ElementTree
from django.test.utils import override_settings
from django.test import TestCase
from mock import patch
from casexml.apps.case.util import post_case_blocks
from casexml.apps.phone.exceptions import RestoreException
from casexml.apps.phone.restore_caching import RestorePayloadPathCache
from casexml.apps.case.mock import CaseBlock, CaseStructure, CaseIndex
from casexml.apps.phone.tests.utils import create_restore_user
from casexml.apps.phone.utils import get_restore_config, MockDevice
from casexml.apps.phone.models import OwnershipCleanlinessFlag
from corehq.apps.domain.models import Domain
from corehq.apps.domain.tests.test_utils import delete_all_domains
from corehq.apps.groups.models import Group
from corehq.apps.users.dbaccessors.all_commcare_users import delete_all_users
from corehq.apps.receiverwrapper.util import submit_form_locally
from corehq.blobs import get_blob_db
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from corehq.form_processor.tests.utils import (
FormProcessorTestUtils,
use_sql_backend,
)
from corehq.util.test_utils import flag_enabled
from casexml.apps.case.tests.util import TEST_DOMAIN_NAME
from casexml.apps.phone.models import (
AbstractSyncLog,
get_properly_wrapped_sync_log,
LOG_FORMAT_LIVEQUERY,
LOG_FORMAT_SIMPLIFIED,
SimplifiedSyncLog,
)
from casexml.apps.phone.restore import (
CachedResponse,
CLEAN_OWNERS,
LIVEQUERY,
RestoreConfig,
RestoreParams,
RestoreCacheSettings,
)
from casexml.apps.case.xml import V2, V1
from casexml.apps.case.sharedmodels import CommCareCaseIndex
from six.moves import range
from io import open
USERNAME = "syncguy"
OTHER_USERNAME = "ferrel"
PARENT_TYPE = "mother"
CHILD_RELATIONSHIP = "child"
class BaseSyncTest(TestCase):
"""
Shared functionality among tests
"""
restore_options = {'case_sync': CLEAN_OWNERS}
@classmethod
def setUpClass(cls):
super(BaseSyncTest, cls).setUpClass()
delete_all_users()
cls.project = Domain(name=TEST_DOMAIN_NAME)
cls.project.save()
cls.user = create_restore_user(
cls.project.name,
USERNAME,
)
cls.user_id = cls.user.user_id
# this creates the initial blank sync token in the database
def setUp(self):
super(BaseSyncTest, self).setUp()
FormProcessorTestUtils.delete_all_cases()
FormProcessorTestUtils.delete_all_xforms()
FormProcessorTestUtils.delete_all_sync_logs()
self.device = self.get_device()
self.device.sync(overwrite_cache=True, version=V1)
def tearDown(self):
restore_config = RestoreConfig(
project=self.project,
restore_user=self.user,
**self.restore_options
)
restore_config.restore_payload_path_cache.invalidate()
super(BaseSyncTest, self).tearDown()
@classmethod
def tearDownClass(cls):
delete_all_users()
delete_all_domains()
super(BaseSyncTest, cls).tearDownClass()
def get_device(self, **kw):
kw.setdefault("project", self.project)
kw.setdefault("user", self.user)
kw.setdefault("restore_options", self.restore_options)
kw.setdefault("default_case_type", PARENT_TYPE)
return MockDevice(**kw)
def _checkLists(self, l1, l2, msg=None):
self.assertEqual(set(l1), set(l2), msg)
def _testUpdate(self, sync_log_or_id, case_id_map, dependent_case_id_map=None):
dependent_case_id_map = dependent_case_id_map or {}
if isinstance(sync_log_or_id, AbstractSyncLog):
sync_log = sync_log_or_id
else:
sync_log = get_properly_wrapped_sync_log(sync_log_or_id)
if isinstance(sync_log, SimplifiedSyncLog):
all_ids = {}
all_ids.update(case_id_map)
all_ids.update(dependent_case_id_map)
self.assertEqual(set(all_ids), sync_log.case_ids_on_phone)
# livequery sync does not use or populate sync_log.index_tree
if self.restore_options['case_sync'] == LIVEQUERY:
self.assertEqual(sync_log.log_format, LOG_FORMAT_LIVEQUERY)
else:
self.assertEqual(sync_log.log_format, LOG_FORMAT_SIMPLIFIED)
self.assertEqual(set(dependent_case_id_map.keys()), sync_log.dependent_case_ids_on_phone)
for case_id, indices in case_id_map.items():
if indices:
index_ids = [i.referenced_id for i in case_id_map[case_id]]
self._checkLists(index_ids, list(sync_log.index_tree.indices[case_id].values()),
'case {} has unexpected indices'.format(case_id))
for case_id, indices in dependent_case_id_map.items():
if indices:
index_ids = [i.referenced_id for i in case_id_map[case_id]]
self._checkLists(index_ids, list(sync_log.index_tree.indices[case_id].values()))
else:
# check case map
self.assertEqual(len(case_id_map), len(sync_log.cases_on_phone))
for case_id, indices in case_id_map.items():
self.assertTrue(sync_log.phone_has_case(case_id))
state = sync_log.get_case_state(case_id)
self._checkLists(indices, state.indices)
# check dependent case map
self.assertEqual(len(dependent_case_id_map), len(sync_log.dependent_cases_on_phone))
for case_id, indices in dependent_case_id_map.items():
self.assertTrue(sync_log.phone_has_dependent_case(case_id))
state = sync_log.get_dependent_case_state(case_id)
self._checkLists(indices, state.indices)
# test migration of old to new by migrating and testing again.
# this is a lazy way of running tests on a variety of edge cases
# without having to write explicit tests for the migration
migrated_sync_log = SimplifiedSyncLog.from_other_format(sync_log)
self.assertEqual(sync_log.get_state_hash(), migrated_sync_log.get_state_hash())
self._testUpdate(migrated_sync_log, case_id_map, dependent_case_id_map)
class DeprecatedBaseSyncTest(BaseSyncTest):
"""DEPRECATED use BaseSyncTest when making new subclasses
This base class has `self.factory` and `self.sync_log`, which
are superseded by `self.device` (`MockDevice`).
"""
def setUp(self):
super(DeprecatedBaseSyncTest, self).setUp()
self.sync_log = self.device.last_sync.log
self.factory = self.device.case_factory
self.factory.form_extras = {
'last_sync_token': self.sync_log._id,
}
class SyncTokenUpdateTest(BaseSyncTest):
"""
Tests sync token updates on submission related to the list of cases
on the phone and the footprint.
"""
def testInitialEmpty(self):
"""
Tests that a newly created sync token has no cases attached to it.
"""
self._testUpdate(self.device.last_sync.log.get_id, {}, {})
def testOwnUpdatesDontSync(self):
case_id = "own_updates_dont_sync"
self.device.change_cases(case_id=case_id, create=True)
self.assertEqual(self.device.sync().cases, {})
self.device.change_cases(
CaseStructure(case_id=case_id, attrs={'update': {"greeting": "hello"}}),
)
self.assertEqual(self.device.sync().cases, {})
self.device.change_cases(
CaseStructure(case_id=case_id, attrs={'owner_id': 'do-not-own-this'}),
)
self.assertEqual(self.device.sync().cases, {})
def test_change_index_type(self):
"""
Test that changing an index type updates the sync log
"""
child_id, parent_id, index_id, parent_ref = self._initialize_parent_child()
# update the child's index (parent type)
updated_type = "updated_type"
self.device.post_changes(CaseBlock(
create=False, case_id=child_id, user_id=self.user_id,
index={index_id: (updated_type, parent_id)},
))
parent_ref.referenced_type = updated_type
self._testUpdate(self.device.last_sync.log._id,
{parent_id: [], child_id: [parent_ref]})
def test_change_index_id(self):
"""
Test that changing an index ID updates the sync log
"""
child_id, parent_id, index_id, parent_ref = self._initialize_parent_child()
# update the child's index (parent id)
updated_id = 'changed_index_id'
self.device.post_changes(CaseStructure(
case_id=child_id,
indices=[CaseIndex(
CaseStructure(case_id=updated_id, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=index_id,
)],
))
parent_ref.referenced_id = updated_id
self._testUpdate(self.device.last_sync.log.get_id,
{parent_id: [], updated_id: [], child_id: [parent_ref]})
def test_add_multiple_indices(self):
"""
Test that adding multiple indices works as expected
"""
child_id, parent_id, index_id, parent_ref = self._initialize_parent_child()
# add new index
new_case_id = 'new_case_id'
new_index_identifier = 'new_index_id'
self.device.post_changes(CaseStructure(
case_id=child_id,
indices=[CaseIndex(
CaseStructure(case_id=new_case_id, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=new_index_identifier,
)],
))
new_index_ref = CommCareCaseIndex(
identifier=new_index_identifier,
referenced_type=PARENT_TYPE,
referenced_id=new_case_id,
)
self._testUpdate(self.device.last_sync.log.get_id,
{parent_id: [], new_case_id: [], child_id: [parent_ref, new_index_ref]})
def test_delete_only_index(self):
child_id, parent_id, index_id, parent_ref = self._initialize_parent_child()
# delete the first index
self.device.post_changes(CaseBlock(
create=False,
case_id=child_id,
user_id=self.user_id,
index={index_id: (PARENT_TYPE, "")},
))
self._testUpdate(self.device.last_sync.log.get_id, {parent_id: [], child_id: []})
def test_delete_one_of_multiple_indices(self):
# make IDs both human readable and globally unique to this test
uid = uuid.uuid4().hex
child_id = 'child_id-{}'.format(uid)
parent_id_1 = 'parent_id-{}'.format(uid)
index_id_1 = 'parent_index_id-{}'.format(uid)
parent_id_2 = 'parent_id_2-{}'.format(uid)
index_id_2 = 'parent_index_id_2-{}'.format(uid)
self.device.post_changes(CaseStructure(
case_id=child_id,
attrs={'create': True},
indices=[
CaseIndex(
CaseStructure(case_id=parent_id_1, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=index_id_1,
),
CaseIndex(
CaseStructure(case_id=parent_id_2, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=index_id_2,
),
],
))
parent_ref_1 = CommCareCaseIndex(
identifier=index_id_1, referenced_type=PARENT_TYPE, referenced_id=parent_id_1)
parent_ref_2 = CommCareCaseIndex(
identifier=index_id_2, referenced_type=PARENT_TYPE, referenced_id=parent_id_2)
self._testUpdate(self.device.last_sync.log.get_id, {parent_id_1: [], parent_id_2: [],
child_id: [parent_ref_1, parent_ref_2]})
# delete the first index
self.device.post_changes(CaseBlock(
create=False,
case_id=child_id,
user_id=self.user_id,
index={index_id_1: (PARENT_TYPE, "")},
))
self._testUpdate(self.device.last_sync.log.get_id,
{parent_id_1: [], parent_id_2: [], child_id: [parent_ref_2]})
def _initialize_parent_child(self):
child_id = "child_id"
parent_id = "parent_id"
index_id = 'parent_index_id'
self.device.post_changes(CaseStructure(
case_id=child_id,
attrs={'create': True},
indices=[CaseIndex(
CaseStructure(case_id=parent_id, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=index_id,
)],
))
parent_ref = CommCareCaseIndex(
identifier=index_id,
referenced_type=PARENT_TYPE,
referenced_id=parent_id,
)
self._testUpdate(self.device.last_sync.log._id, {parent_id: [], child_id: [parent_ref]})
return (child_id, parent_id, index_id, parent_ref)
def testClosedParentIndex(self):
"""
Tests that things work properly when you have a reference to the parent
case in a child, even if it's closed.
"""
parent_id = "mommy"
child_id = "baby"
index_id = 'my_mom_is'
self.device.post_changes([
CaseStructure(
case_id=child_id,
attrs={'create': True},
indices=[CaseIndex(
CaseStructure(case_id=parent_id, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=index_id,
)],
)
])
index_ref = CommCareCaseIndex(identifier=index_id,
referenced_type=PARENT_TYPE,
referenced_id=parent_id)
self._testUpdate(self.device.last_sync.log.get_id,
{parent_id: [], child_id: [index_ref]})
# close the mother case
close = CaseBlock(create=False, case_id=parent_id, user_id=self.user_id, close=True)
self.device.post_changes(close)
self._testUpdate(self.device.last_sync.log.get_id, {child_id: [index_ref]},
{parent_id: []})
# try a clean restore again
self.device.last_sync = None
self.assertEqual(set(self.device.sync().cases), {parent_id, child_id})
def testAssignToNewOwner(self):
# create parent and child
parent_id = "mommy"
child_id = "baby"
index_id = 'my_mom_is'
self.device.post_changes([
CaseStructure(
case_id=child_id,
attrs={'create': True},
indices=[CaseIndex(
CaseStructure(case_id=parent_id, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=index_id,
)],
)
])
index_ref = CommCareCaseIndex(identifier=index_id,
referenced_type=PARENT_TYPE,
referenced_id=parent_id)
# should be there
self._testUpdate(self.device.last_sync.log.get_id,
{parent_id: [], child_id: [index_ref]})
# assign the child to a new owner
new_owner = "not_mine"
self.device.post_changes(
CaseBlock(create=False, case_id=child_id, user_id=self.user_id, owner_id=new_owner),
)
# child should be moved, parent should still be there
self._testUpdate(self.device.last_sync.log.get_id, {parent_id: []}, {})
def testArchiveUpdates(self):
"""
Tests that archiving a form (and changing a case) causes the
case to be included in the next sync.
"""
case_id = "archive_syncs"
self.device.change_cases(case_id=case_id, create=True)
self.assertEqual(self.device.sync().cases, {})
self.device.change_cases(CaseBlock(
create=False,
case_id=case_id,
user_id=self.user_id,
update={"greeting": "hello"}
))
sync = self.device.sync()
self.assertEqual(sync.cases, {})
sync.form.archive()
RestorePayloadPathCache(
domain=self.project.name,
user_id=self.user_id,
sync_log_id=sync.restore_id,
device_id=None,
).invalidate()
self.assertEqual(set(self.device.sync().cases), {case_id})
def testUserLoggedIntoMultipleDevices(self):
# test that a child case created by the same user from a different device
# gets included in the sync
parent_id = "parent"
child_id = "child"
self.device.post_changes(case_id=parent_id, create=True)
# create child case using a different sync log ID
device2 = self.get_device(sync=True)
device2.post_changes(
create=True,
case_id=child_id,
index={'mother': ('mother', parent_id)}
)
# ensure child case is included in sync using original sync log ID
self.assertIn(child_id, self.device.sync().cases)
def test_tiered_parent_closing(self):
all_ids = [uuid.uuid4().hex for i in range(3)]
[grandparent_id, parent_id, child_id] = all_ids
self.device.post_changes([
CaseStructure(
case_id=child_id,
attrs={'create': True},
indices=[CaseIndex(
CaseStructure(
case_id=parent_id,
attrs={'create': True},
indices=[CaseIndex(
CaseStructure(case_id=grandparent_id, attrs={'create': True}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
)],
),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
)],
)
])
self.device.post_changes(case_id=grandparent_id, close=True)
sync_log = self.device.last_sync.get_log()
for id in all_ids:
self.assertTrue(sync_log.phone_is_holding_case(id))
self.device.post_changes(case_id=parent_id, close=True)
sync_log = self.device.last_sync.get_log()
for id in all_ids:
self.assertTrue(sync_log.phone_is_holding_case(id))
self.device.post_changes(case_id=child_id, close=True)
sync_log = self.device.last_sync.get_log()
for id in all_ids:
# once the child is closed, all three are no longer relevant
self.assertFalse(sync_log.phone_is_holding_case(id))
def test_create_immediately_irrelevant_parent_case(self):
"""
Make a case that is only relevant through a dependency at the same
time as the dependency is made. Make sure it is relevant.
"""
# create a parent and child case (with index) from one user
parent_id, child_id = [uuid.uuid4().hex for i in range(2)]
self.device.post_changes([
CaseStructure(
case_id=child_id,
attrs={'create': True},
indices=[CaseIndex(
CaseStructure(case_id=parent_id, attrs={
'create': True,
'owner_id': uuid.uuid4().hex,
}),
relationship=CHILD_RELATIONSHIP,
related_type=PARENT_TYPE,
identifier=PARENT_TYPE,
)],
)
])
index_ref = CommCareCaseIndex(identifier=PARENT_TYPE,
referenced_type=PARENT_TYPE,
referenced_id=parent_id)
self._testUpdate(self.device.last_sync.log._id,
{child_id: [index_ref]}, {parent_id: []})
def test_closed_case_not_in_next_sync(self):
# create a case
case_id = uuid.uuid4().hex
self.device.change_cases(case_id=case_id, create=True)
# sync
sync = self.device.sync()
self.assertTrue(sync.log.phone_is_holding_case(case_id))
# close the case on the second sync
self.device.change_cases(case_id=case_id, close=True)
self.device.sync()
# sync again
sync = self.device.sync()
self.assertFalse(sync.log.phone_is_holding_case(case_id))
def test_sync_by_user_id(self):
# create a case with an empty owner but | |
"TO_CHAR(A, 'VW', 'NLS_DATE_LANGUAGE=GERMAN')")
self.completeFunctionTest("A", 't_datetime', "TO_DATE(TO_CHAR(A)", 'WHERE A < TO_DATE(TO_CHAR(A))')
self.completeFunctionTest("A", 't_datetime', "TO_DATE(TO_CHAR(A), 'YYYY-MM-DD')", "WHERE A < TO_DATE(TO_CHAR(A), 'YYYY-MM-DD')")
self.completeFunctionTest("TO_DSINTERVAL(A||' 10:59:59')", 't', "TO_DSINTERVAL(CONCAT(A, ' 10:59:59'))", "WHERE A IS NOT NULL")
self.completeFunctionTest("A", 't_datetime', "TO_TIMESTAMP(TO_CHAR(A, 'HH24:MI:SS DDD-YYYY'), 'HH24:MI:SS DDD-YYYY')", "WHERE A < TO_TIMESTAMP(TO_CHAR(A, 'HH24:MI:SS DDD-YYYY'), 'HH24:MI:SS DDD-YYYY')")
self.completeFunctionTest("TO_YMINTERVAL(A || '-' || A)", 't', "TO_YMINTERVAL(CONCAT(A, CONCAT('-', A)))", "WHERE A IS NOT NULL")
self.completeFunctionTest("TRUNC(A)", 't_datetime', "TRUNC(A)")
self.completeFunctionTest("TRUNC(A, 'W')", 't_datetime', "TRUNC(A, 'W')")
self.completeFunctionTest("TRUNCATE(A)", 't_datetime', "TRUNC(A)")
self.completeFunctionTest("TRUNCATE(A, 'W')", 't_datetime', "TRUNC(A, 'W')")
self.completeFunctionTest("WEEK(A)", 't_datetime', "WEEK(A)")
self.completeFunctionTest("YEAR(A)", 't_datetime', "YEAR(A)")
self.completeFunctionTest("YEARS_BETWEEN(A, A)", 't_datetime', "YEARS_BETWEEN(A, A)")
def testGeospatialFunctions(self):
self.completeFunctionTest("ST_AREA(A)", 't_geometry', "ST_AREA(A)")
self.completeFunctionTest("ST_BOUNDARY(A)", 't_geometry', "ST_BOUNDARY(A)", "WHERE id < 3")
self.completeFunctionTest("ST_BUFFER(A, 1)", 't_geometry', "ST_BUFFER(A, 1)")
self.completeFunctionTest("ST_CENTROID(A)", 't_geometry', "ST_CENTROID(A)")
self.completeFunctionTest("ST_CONTAINS(A, A)", 't_geometry', "ST_CONTAINS(A, A)")
self.completeFunctionTest("ST_CONVEXHULL(A)", 't_geometry', "ST_CONVEXHULL(A)")
self.completeFunctionTest("ST_CROSSES(A, A)", 't_geometry', "ST_CROSSES(A, A)")
self.completeFunctionTest("ST_DIFFERENCE(A, A)", 't_geometry', "ST_DIFFERENCE(A, A)")
self.completeFunctionTest("ST_DIMENSION(A)", 't_geometry', "ST_DIMENSION(A)")
self.completeFunctionTest("ST_DISJOINT(A, A)", 't_geometry', "ST_DISJOINT(A, A)")
self.completeFunctionTest("ST_DISTANCE(A, A)", 't_geometry', "ST_DISTANCE(A, A)")
self.completeFunctionTest("ST_ENDPOINT(A)", 't_geometry', "ST_ENDPOINT(A)", "WHERE id = 2")
self.completeFunctionTest("ST_ENVELOPE(A)", 't_geometry', "ST_ENVELOPE(A)")
self.completeFunctionTest("ST_EQUALS(A, A)", 't_geometry', "ST_EQUALS(A, A)")
self.completeFunctionTest("ST_EXTERIORRING(A)", 't_geometry', "ST_EXTERIORRING(A)", "WHERE id = 1")
self.completeFunctionTest("ST_FORCE2D('POINT(1 2 '||a||')')", 't', "ST_FORCE2D(CONCAT('POINT(1 2 ', CONCAT(A, ')')))")
self.completeFunctionTest("ST_GEOMETRYN(A, 1)", 't_geometry', "ST_GEOMETRYN(A, 1)", "WHERE id = 3")
self.completeFunctionTest("ST_GEOMETRYTYPE(A)", 't_geometry', "ST_GEOMETRYTYPE(A)")
self.completeFunctionTest("ST_INTERIORRINGN(A, 1)", 't_geometry', "ST_INTERIORRINGN(A, 1)", "WHERE id = 1")
self.completeFunctionTest("ST_INTERSECTION(A)", 't_geometry', "ST_INTERSECTION(A)")
self.completeFunctionTest("ST_INTERSECTION(A, A)", 't_geometry', "ST_INTERSECTION(A, A)")
self.completeFunctionTest("ST_INTERSECTS(A, A)", 't_geometry', "ST_INTERSECTS(A, A)")
self.completeFunctionTest("ST_ISCLOSED(A)", 't_geometry', "ST_ISCLOSED(A)", "WHERE id = 2")
self.completeFunctionTest("ST_ISEMPTY(A)", 't_geometry', "ST_ISEMPTY(A)")
self.completeFunctionTest("ST_ISRING(A)", 't_geometry', "ST_ISRING(A)", "WHERE id = 2")
self.completeFunctionTest("ST_ISSIMPLE(A)", 't_geometry', "ST_ISSIMPLE(A)", "WHERE id < 3")
self.completeFunctionTest("ST_LENGTH(A)", 't_geometry', "ST_LENGTH(A)")
self.completeFunctionTest("ST_NUMGEOMETRIES(A)", 't_geometry', "ST_NUMGEOMETRIES(A)", "WHERE id = 3")
self.completeFunctionTest("ST_NUMINTERIORRINGS(A)", 't_geometry', "ST_NUMINTERIORRINGS(A)", "WHERE id = 1")
self.completeFunctionTest("ST_NUMPOINTS(A)", 't_geometry', "ST_NUMPOINTS(A)", "WHERE id = 2")
self.completeFunctionTest("ST_OVERLAPS(A, A)", 't_geometry', "ST_OVERLAPS(A, A)")
self.completeFunctionTest("ST_POINTN(A, 1)", 't_geometry', "ST_POINTN(A, 1)", "WHERE id = 2")
self.completeFunctionTest("ST_SETSRID(A, 5)", 't_geometry', "ST_SETSRID(A, 5)")
self.completeFunctionTest("ST_STARTPOINT(A)", 't_geometry', "ST_STARTPOINT(A)", "WHERE id = 2")
self.completeFunctionTest("ST_SYMDIFFERENCE(A, A)", 't_geometry', "ST_SYMDIFFERENCE(A, A)")
self.completeFunctionTest("ST_TRANSFORM(ST_SETSRID(A, 2000), 2001)", 't_geometry', "ST_TRANSFORM(ST_SETSRID(A, 2000), 2001)")
self.completeFunctionTest("ST_TOUCHES(A, A)", 't_geometry', "ST_TOUCHES(A, A)")
self.completeFunctionTest("ST_UNION(A)", 't_geometry', "ST_UNION(A)")
self.completeFunctionTest("ST_UNION(A, A)", 't_geometry', "ST_UNION(A, A)")
self.completeFunctionTest("ST_WITHIN(A, A)", 't_geometry', "ST_WITHIN(A, A)")
self.completeFunctionTest("ST_X(ST_STARTPOINT(A))", 't_geometry', "ST_X(ST_STARTPOINT(A))", "WHERE id = 2")
self.completeFunctionTest("ST_Y(ST_STARTPOINT(A))", 't_geometry', "ST_Y(ST_STARTPOINT(A))", "WHERE id = 2")
def testBitwiseFunctions(self):
self.completeFunctionTest('BIT_AND(A, A)', 't', 'BIT_AND(A, A)')
self.completeFunctionTest('BIT_CHECK(A, 0)', 't', 'BIT_CHECK(A, 0)')
self.completeFunctionTest('BIT_NOT(A)', 't', 'BIT_NOT(A)')
self.completeFunctionTest('BIT_OR(A, A)', 't', 'BIT_OR(A, A)')
self.completeFunctionTest('BIT_SET(A, 0)', 't', 'BIT_SET(A, 0)')
self.completeFunctionTest('A + BIT_TO_NUM(A,0,0)', 't', 'BIT_TO_NUM(A, 0, 0)', "WHERE A=1")
self.completeFunctionTest('BIT_XOR(A, A)', 't', 'BIT_XOR(A, A)')
def testConversionFunctions(self):
self.completeFunctionTest('CAST(A as CHAR(15))', 't', 'CAST(A AS CHAR(15) UTF8)')
self.completeFunctionTest('CAST(CAST(A > 0 as VARCHAR(15)) as BOOLEAN)', 't', 'CAST(CAST(0 < A AS VARCHAR(15) UTF8) AS BOOLEAN)')
self.completeFunctionTest('CAST(CAST(A as VARCHAR(30)) as DATE)', 't_datetime', 'CAST(CAST(A AS VARCHAR(30) UTF8) AS DATE)')
self.completeFunctionTest('CAST(CAST(A as VARCHAR(15)) as DECIMAL(8,1))', 't', 'CAST(CAST(A AS VARCHAR(15) UTF8) AS DECIMAL(8, 1))')
self.completeFunctionTest('CAST(CAST(C as VARCHAR(15)) as DOUBLE)', 't', 'CAST(CAST(C AS VARCHAR(15) UTF8) AS DOUBLE)')
self.completeFunctionTest('CAST(CAST(A as VARCHAR(100)) as GEOMETRY(5))', 't_geometry', 'CAST(CAST(A AS VARCHAR(100) UTF8) AS GEOMETRY(5))')
self.completeFunctionTest('CAST(CAST(B as VARCHAR(100)) as INTERVAL DAY(5) TO SECOND(2))', 't_interval', 'CAST(CAST(B AS VARCHAR(100) UTF8) AS INTERVAL DAY (5) TO SECOND (2))')
self.completeFunctionTest('CAST(CAST(A as VARCHAR(100)) as INTERVAL YEAR (5) TO MONTH)', 't_interval', 'CAST(CAST(A AS VARCHAR(100) UTF8) AS INTERVAL YEAR (5) TO MONTH)')
self.completeFunctionTest('CAST(CAST(A as VARCHAR(100)) as TIMESTAMP)', 't_datetime', 'CAST(CAST(A AS VARCHAR(100) UTF8) AS TIMESTAMP)')
self.completeFunctionTest('CAST(CAST(A as VARCHAR(100)) as TIMESTAMP WITH LOCAL TIME ZONE)', 't_datetime', 'CAST(CAST(A AS VARCHAR(100) UTF8) AS TIMESTAMP WITH LOCAL TIME ZONE)')
self.completeFunctionTest('CAST(A as VARCHAR(15))', 't', 'CAST(A AS VARCHAR(15) UTF8)')
self.completeFunctionTest('CONVERT(CHAR(15), A)', 't', 'CAST(A AS CHAR(15) UTF8)')
self.completeFunctionTest('IS_NUMBER(TO_CHAR(A))', 't', 'IS_NUMBER(TO_CHAR(A))')
self.completeFunctionTest("IS_NUMBER(TO_CHAR(A), '99999.999')", 't', "IS_NUMBER(TO_CHAR(A), '99999.999')")
self.completeFunctionTest('IS_DATE(TO_CHAR(A))', 't_datetime', 'IS_DATE(TO_CHAR(A))')
self.completeFunctionTest("IS_DATE(TO_CHAR(A), 'YYYY-MM-DD')", 't_datetime', "IS_DATE(TO_CHAR(A), 'YYYY-MM-DD')")
self.completeFunctionTest('IS_TIMESTAMP(TO_CHAR(A))', 't_datetime', 'IS_TIMESTAMP(TO_CHAR(A))')
self.completeFunctionTest("IS_TIMESTAMP(TO_CHAR(A), 'HH24:MI:SS DDD-YYYY')", 't_datetime', "IS_TIMESTAMP(TO_CHAR(A), 'HH24:MI:SS DDD-YYYY')")
self.completeFunctionTest('IS_BOOLEAN(B)', 't', 'IS_BOOLEAN(B)')
self.completeFunctionTest('IS_DSINTERVAL(B)', 't', 'IS_DSINTERVAL(B)')
self.completeFunctionTest('IS_YMINTERVAL(B)', 't', 'IS_YMINTERVAL(B)')
def testOtherFunctions(self):
self.completeFunctionTest("CASE A WHEN 1 THEN 'YES' WHEN 2 THEN 'FOO' ELSE 'NO' END", 't', "CASE A WHEN 1 THEN 'YES' WHEN 2 THEN 'FOO' ELSE 'NO' END")
self.completeFunctionTest("CASE WHEN A > 1 THEN 'YES' ELSE 'NO' END", 't', "CASE WHEN 1 < A THEN 'YES' ELSE 'NO' END")
self.completeFunctionTest('COALESCE(A, B, C)', 't', 'WHEN A IS NOT NULL THEN A WHEN B IS NOT NULL THEN B ELSE C')
self.completeFunctionTest('a', 't', 'CURRENT_SCHEMA', "WHERE A > CURRENT_SCHEMA")
self.completeFunctionTest('a', 't', 'CURRENT_SESSION', "WHERE A < CURRENT_SESSION")
self.completeFunctionTest('a', 't', 'CURRENT_STATEMENT', "WHERE A > CURRENT_STATEMENT")
self.completeFunctionTest('v2', 'g', 'CURRENT_USER', "WHERE v2 > CURRENT_USER")
self.completeFunctionTest("DECODE(v2, 'xyz', 1, 'abc', 2, 3)", 'g', "CASE V2 WHEN 'xyz' THEN 1 WHEN 'abc' THEN 2 ELSE 3 END")
self.completeFunctionTest('GREATEST(A, C)', 't', 'GREATEST(A, C)')
self.completeFunctionTest('HASH_MD5(A)', 't', 'HASH_MD5(A)')
self.completeFunctionTest('HASH_SHA(A)', 't', 'HASH_SHA1(A)')
self.completeFunctionTest('HASH_SHA1(A)', 't', 'HASH_SHA1(A)')
self.completeFunctionTest('HASH_TIGER(A)', 't', 'HASH_TIGER(A)')
self.completeFunctionTest('LEAST(A, C)', 't', 'LEAST(A, C)')
self.completeFunctionTest('NULLIF(A, 1)', 't', 'CASE A WHEN 1 THEN NULL ELSE A')
self.completeFunctionTest('NULLIFZERO(A)', 't', 'NULLIFZERO(A)')
self.completeFunctionTest('NVL(A, C)', 't', 'CASE WHEN A IS NOT NULL THEN A ELSE C')
self.completeFunctionTest('NVL2(A, C, NULL)', 't', 'CASE WHEN A IS NOT NULL THEN C ELSE NULL')
self.completeFunctionTest('A', 't', 'SELECT A FROM NATIVE.T', 'WHERE ROWNUM < 3')
self.completeFunctionTest('*', 't', 'SELECT * FROM NATIVE.T', 'WHERE ROWNUM < 3')
self.completeFunctionTest('A, C, ROWNUM', 't', 'SELECT A, C FROM NATIVE.T', 'WHERE ROWNUM < 3')
self.completeFunctionTest('A, ROW_NUMBER() OVER (ORDER BY C DESC) ROW_NUMBER', 't', 'SELECT A, C FROM NATIVE.T')
with self.assertRaisesRegexp(Exception, 'ROWID is invalid for virtual tables.'):
self.completeFunctionTest('ROWID', 't', 'SELECT true')
self.completeFunctionTest('v2', 'g', 'SYS_GUID()', "WHERE v2 > SYS_GUID()")
self.completeFunctionTest('v2', 'g', 'USER', "WHERE v2 > USER")
self.completeFunctionTest('ZEROIFNULL(A)', 't', 'ZEROIFNULL(A)')
def testAggregateFunctions(self):
self.completeFunctionTest('APPROXIMATE_COUNT_DISTINCT(A)', 't', 'APPROXIMATE_COUNT_DISTINCT(A)')
self.completeFunctionTest('AVG(A)', 't', 'AVG(A)')
self.completeFunctionTest('AVG(ALL A)', 't', 'AVG(A)')
self.completeFunctionTest('AVG(DISTINCT A)', 't', 'AVG(DISTINCT A)')
self.completeFunctionTest('CORR(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('COUNT(A)', 't', 'COUNT(A)')
self.completeFunctionTest('COUNT(*)', 't', 'COUNT(*)')
self.completeFunctionTest('COUNT(DISTINCT A)', 't', 'COUNT(DISTINCT A)')
self.completeFunctionTest('COUNT(ALL (A, C))', 't', 'SELECT A, C FROM')
self.completeFunctionTest('COVAR_POP(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('COVAR_SAMP(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('FIRST_VALUE(A)', 't', 'FIRST_VALUE(A)')
self.completeFunctionTest('GROUP_CONCAT(A)', 't', 'GROUP_CONCAT(A)')
self.completeFunctionTest('GROUP_CONCAT(DISTINCT A)', 't', 'GROUP_CONCAT(DISTINCT A)')
self.completeFunctionTest('GROUP_CONCAT(A ORDER BY C)', 't', 'GROUP_CONCAT(A ORDER BY C)')
self.completeFunctionTest('GROUP_CONCAT(A ORDER BY C DESC)', 't', 'GROUP_CONCAT(A ORDER BY C DESC)')
self.completeFunctionTest('GROUP_CONCAT(A ORDER BY C DESC NULLS LAST)', 't', 'GROUP_CONCAT(A ORDER BY C DESC NULLS LAST)')
self.completeFunctionTest("GROUP_CONCAT(A SEPARATOR ';'||' ')", 't', "GROUP_CONCAT(A SEPARATOR '; ')")
self.completeFunctionTest('GROUPING(A)', 't', 'SELECT A FROM', 'GROUP BY A')
self.completeFunctionTest('GROUPING(A, C)', 't', 'SELECT A, C FROM', 'GROUP BY A, C')
self.completeFunctionTest('GROUPING_ID(A)', 't', 'SELECT A FROM', 'GROUP BY A')
self.completeFunctionTest('GROUPING_ID(A, C)', 't', 'SELECT A, C FROM', 'GROUP BY A, C')
self.completeFunctionTest('LAST_VALUE(A)', 't', 'LAST_VALUE(A)')
self.completeFunctionTest('MAX(A)', 't', 'MAX(A)')
self.completeFunctionTest('MAX(ALL A)', 't', 'MAX(A)')
self.completeFunctionTest('MAX(DISTINCT A)', 't', 'MAX(A)')
self.completeFunctionTest('MEDIAN(A)', 't', 'MEDIAN(A)')
self.completeFunctionTest('MIN(A)', 't', 'MIN(A)')
self.completeFunctionTest('MIN(ALL A)', 't', 'MIN(A)')
self.completeFunctionTest('MIN(DISTINCT A)', 't', 'MIN(A)')
self.completeFunctionTest('PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY A)', 't', 'SELECT A FROM')
self.completeFunctionTest('PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY A)', 't', 'SELECT A FROM')
self.completeFunctionTest('REGR_AVGX(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_AVGY(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_COUNT(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_INTERCEPT(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_R2(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_SLOPE(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_SXX(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_SXY(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('REGR_SYY(A, C)', 't', 'SELECT A, C FROM')
self.completeFunctionTest('STDDEV(A)', 't', 'STDDEV(A)')
self.completeFunctionTest('STDDEV(ALL A)', 't', 'STDDEV(A)')
self.completeFunctionTest('STDDEV(DISTINCT A)', 't', 'STDDEV(DISTINCT A)')
self.completeFunctionTest('STDDEV_POP(A)', 't', 'STDDEV_POP(A)')
self.completeFunctionTest('STDDEV_POP(ALL A)', 't', 'STDDEV_POP(A)')
self.completeFunctionTest('STDDEV_POP(DISTINCT A)', 't', 'STDDEV_POP(DISTINCT A)')
self.completeFunctionTest('STDDEV_SAMP(A)', 't', 'STDDEV_SAMP(A)')
self.completeFunctionTest('STDDEV_SAMP(ALL A)', 't', 'STDDEV_SAMP(A)')
self.completeFunctionTest('STDDEV_SAMP(DISTINCT A)', 't', 'STDDEV_SAMP(DISTINCT A)')
self.completeFunctionTest('SUM(A)', 't', 'SUM(A)')
self.completeFunctionTest('SUM(ALL A)', 't', 'SUM(A)')
self.completeFunctionTest('SUM(DISTINCT A)', 't', 'SUM(DISTINCT A)')
self.completeFunctionTest('VAR_POP(A)', 't', 'VAR_POP(A)')
self.completeFunctionTest('VAR_POP(ALL A)', 't', 'VAR_POP(A)')
self.completeFunctionTest('VAR_POP(DISTINCT A)', 't', 'VAR_POP(DISTINCT A)')
self.completeFunctionTest('VAR_SAMP(A)', 't', 'VAR_SAMP(A)')
self.completeFunctionTest('VAR_SAMP(ALL A)', 't', 'VAR_SAMP(A)')
self.completeFunctionTest('VAR_SAMP(DISTINCT A)', 't', 'VAR_SAMP(DISTINCT A)')
self.completeFunctionTest('VARIANCE(A)', 't', 'VARIANCE(A)')
self.completeFunctionTest('VARIANCE(ALL A)', 't', 'VARIANCE(A)')
self.completeFunctionTest('VARIANCE(DISTINCT A)', 't', 'VARIANCE(DISTINCT A)')
class IllegalResponses(VSchemaTest):
def setUp(self):
self.query('DROP SCHEMA IF EXISTS NATIVE CASCADE')
self.query('CREATE SCHEMA NATIVE')
self.query('CREATE VIEW my_view as select 1 c1, 2 c2 from dual')
def testViewInPushdownResponse(self):
self.createViewAdapter(schemaName="ADAPTER", adapterName="VIEW_ADAPTER")
self.query('DROP FORCE VIRTUAL SCHEMA IF EXISTS VS1 CASCADE')
self.query('CREATE VIRTUAL SCHEMA VS1 USING ADAPTER.VIEW_ADAPTER')
self.query('''SELECT * FROM VS1.DUMMY''')
def testVirtualTableInPushdownResponse(self):
self.createRecursiveAdapter(schemaName="ADAPTER", adapterName="RECURSIVE_ADAPTER")
self.query('DROP FORCE VIRTUAL SCHEMA IF EXISTS VS1 CASCADE')
self.query('CREATE VIRTUAL SCHEMA VS1 USING ADAPTER.RECURSIVE_ADAPTER')
with self.assertRaisesRegexp(Exception, 'The pushdown query returned by the Adapter contains a virtual table \\(DUMMY\\). This is currently not supported.'):
self.query('''
SELECT * FROM VS1.DUMMY
''')
def testViewInPushdownResponseWithSubSelect(self):
self.createExtendedViewAdapter(schemaName="ADAPTER", adapterName="EXTENDED_VIEW_ADAPTER")
self.query('DROP FORCE VIRTUAL SCHEMA IF EXISTS VS1 CASCADE')
self.query('CREATE VIRTUAL SCHEMA VS1 USING ADAPTER.EXTENDED_VIEW_ADAPTER')
self.query('''SELECT * FROM VS1.DUMMY''')
def testVirtualTableInPushdownResponseWithSubSelect(self):
self.createExtendedRecursiveAdapter(schemaName="ADAPTER", adapterName="EXTENDED_RECURSIVE_ADAPTER")
self.query('DROP FORCE VIRTUAL SCHEMA IF EXISTS VS1 CASCADE')
| |
import math
from krrt.utils import get_opts, write_file
from krrt.stats.plots import plot
from run_example import *
POP_FILE = "testing/cog-pop"
def experiment1():
print "Running experiment to compute the time savings"
print "for precomputing the temporal network.\n"
print "Building the policy..."
(pol, P) = build_policy(POP_FILE)
max_profile = {'prob_unlaundry':0.5,
'prob_hungry':0.4,
'prob_full':0.16,
'prob_laundry':0.16,
'prob_read':0.16,
'prob_movie':0.16,
'prob_groc':0.16}
print "Running the simulation..."
current_state = P.init.adds
current_time = 0.0
pol.reset()
going = True
max_profile['laundryok'] = True
max_profile['fullok'] = True
pre_times = []
unpre_times = []
while going:
((act, l, u), time_pre, time_unpre) = pol.get_action(current_time, current_state, 'timings')
pre_times.append(time_pre)
unpre_times.append(time_unpre)
if 'startA_do_laundry' == act.operator:
max_profile['laundryok'] = False
elif 'check_at_home' == act.operator:
max_profile['laundryok'] = True
elif 'goto_sleep' == act.operator:
max_profile['laundryok'] = False
max_profile['fullok'] = False
#print "Execute %s between %.2f and %.2f" % (str(act), l, u)
if act == P.goal:
going = False
else:
current_state = progress_state(current_state, act)
general_dynamics(current_state, P.F_map, True, max_profile)
current_time += (l + u) / 2
print "Executing %s at %d:%02d (%f)\n\n-------------\n" % (str(act), int(current_time/60), int(current_time % 60), current_time)
pol.add_action(current_time, act)
current_time += TemporalConstraint.epsilon
print "Processing the data..."
x = []
y = []
for i in range(len(pre_times)):
x.append(i+1)
y.append(unpre_times[i] / pre_times[i])
plot(x, y, x_label='Execution Trace', y_label='Ratio of Effort', col=False, xyline=False, y_log=True, x1line=True)
#############################################
def experiment2():
print "Running experiment to see the number of causally and"
print "temporally viable contexts that match at each step.\n"
print "Building the policy..."
(pol, P) = build_policy(POP_FILE)
print "Running the simulation for early behaviour..."
(lower_counts_causal, lower_counts_temporal, lower_counts_checked, lower_times) = exp_2_sim(pol, P, 'lower', pessimistic_dynamics)
print "Running the simulation for late behaviour..."
(upper_counts_causal, upper_counts_temporal, upper_counts_checked, upper_times) = exp_2_sim(pol, P, 'upper')
print "Running the simulation for average behaviour..."
(mid_counts_causal, mid_counts_temporal, mid_counts_checked, mid_times) = exp_2_sim(pol, P, 'mid')
print
print "Processing the lower behaviour data..."
exp_2_proc(lower_counts_causal, lower_counts_temporal, lower_counts_checked, lower_times)
print "Processing the upper behaviour data..."
exp_2_proc(upper_counts_causal, upper_counts_temporal, upper_counts_checked, upper_times)
print "Processing the average behaviour data..."
exp_2_proc(mid_counts_causal, mid_counts_temporal, mid_counts_checked, mid_times)
def exp_2_sim(pol, P, mode, alter_state = None):
alter_state = alter_state or static_dynamics
current_state = P.init.adds
current_time = 0.0
pol.reset()
going = True
laundryok = True
fullok = True
counts_causal = []
counts_temporal = []
counts_checked = []
times = []
while going:
#print pol.get_action(current_time, current_state, 'viable_counts')
((act, l, u), causal_count, temporal_count, checked_count) = pol.get_action(current_time, current_state, 'viable_counts')
counts_causal.append(causal_count)
counts_temporal.append(temporal_count)
counts_checked.append(checked_count)
if 'startA_do_laundry' == act.operator:
laundryok = False
elif 'check_at_home' == act.operator:
laundryok = True
elif 'goto_sleep' == act.operator:
laundryok = False
fullok = False
#print "%d / %d / %d" % (causal_count, temporal_count, checked_count)
#print "Execute %s between %.2f and %.2f" % (str(act), l, u)
if act == P.goal:
times.append(1440.0)
going = False
else:
current_state = alter_state(progress_state(current_state, act), P.F_map, fullok=fullok, laundryok=laundryok)
if 'lower' == mode:
current_time += l
elif 'upper' == mode:
current_time += u
elif 'mid' == mode:
current_time += (l + u) / 2
#print "Executing %s at %d:%02d (%f)\n\n-------------\n" % (str(act), int(current_time/60), int(current_time % 60), current_time)
times.append(current_time)
pol.add_action(current_time, act)
current_time += TemporalConstraint.epsilon
return (counts_causal, counts_temporal, counts_checked, times)
def exp_2_proc_xy_ploy(counts_causal, counts_temporal, counts_checked):
xs = [counts_causal, counts_causal]
ys = [counts_temporal, counts_checked]
plot(xs, ys, x_label='\# of Causal Contexts', y_label='\# of Temporal and Computed Contexts', col=False, xyline=True, no_scatter=False, x_log=True, y_log=True)#,names=['Temporal Contexts', 'Checked Contexts'])
def exp_2_proc(counts_causal, counts_temporal, counts_checked, times):
xs = [range(1,len(counts_causal)+1)] * 3
#xs = [[(t / 60) for t in times]] * 3
ys = [counts_causal, counts_temporal, counts_checked]
print "\n".join(["%d,%d,%d" % (ys[0][i], ys[1][i], ys[2][i]) for i in range(len(ys[0]))])
plot(xs, ys, x_label='Execution Trace', y_label='\# of Contexts', col=False, xyline=False, y_log=False, no_scatter=True, names=['Causally Viable', 'Temporally Viable', 'Checked'])
#############################################
def experiment3():
print "Running experiment to try and profile the code usage during execution\n"
print "Profile step:\n python -m cProfile -o output.pstats evaluation.py exp3\n"
print "Compilation:\n python ~/Scripts/gprof2dot.py -f pstats output.pstats | dot -Tpng > profile.png\n\n"
print "Building the policy..."
(pol, P) = build_policy(POP_FILE)
sim_num = 10000
print "Running %d simulations..." % sim_num
for i in range(sim_num):
run_static(pol, P, mode = 'mid', silent = True)
#############################################
def experiment4():
print "Running experiment to test the impact of having a long execution trace"
print "Building the policy..."
(pol, P) = build_policy(POP_FILE)
print "Simulation a partial execution trace...\n"
pol.add_action(360,P.A_map['wakeup'])
pol.add_action(360.00001,P.A_map['serve_breakfast'])
pol.add_action(360.00002,P.A_map['check_full'])
pol.add_action(480,P.A_map['startA_drive_kids_school'])
pol.add_action(510,P.A_map['endA_drive_kids_school'])
pol.add_action(510.00001,P.A_map['startA_drive_mall'])
pol.add_action(530.00001,P.A_map['endA_drive_mall'])
pol.add_action(530.00002,P.A_map['check_at_mall'])
pol.add_action(530.00003,P.A_map['startA_get_groceries'])
pol.add_action(590.00003,P.A_map['endA_get_groceries'])
pol.add_action(590.00004,P.A_map['startA_watch_movie'])
pol.add_action(680.00004,P.A_map['endA_watch_movie'])
pol.add_action(680.00005,P.A_map['startA_drive_home'])
pol.add_action(700.00005,P.A_map['endA_drive_home'])
pol.add_action(700.00006,P.A_map['startA_read_book'])
print "Adding a number of start laundry actions (to pump up the force follow)..."
s1 = set(map(P.F_map.get, ['f1', 'f4', 'f6', 'f7', 'f9', 'f10', 'f12', 'f14', 'noexec_do_laundry', 'exec_read_book',
'noexec_drive_school', 'noexec_drive_kids_school', 'noexec_drive_kids_home',
'noexec_drive_home', 'noexec_cook_meal', 'noexec_get_groceries', 'noexec_watch_movie',
'noexec_clean_kitchen', 'noexec_drive_mall']))
s2 = set(map(P.F_map.get, ['f1', 'f4', 'f6', 'f7', 'f9', 'f10', 'f12', 'f14', 'exec_do_laundry', 'exec_read_book',
'noexec_drive_school', 'noexec_drive_kids_school', 'noexec_drive_kids_home',
'noexec_drive_home', 'noexec_cook_meal', 'noexec_get_groceries', 'noexec_watch_movie',
'noexec_clean_kitchen', 'noexec_drive_mall']))
t = 701
pre_times = []
unpre_times = []
for i in range(3):
t += 20
((act, l, u), time_pre, time_unpre) = pol.get_action(t, s1, 'timings')
pre_times.append(time_pre)
unpre_times.append(time_unpre)
print "%s, %f, %f" % (str(act), l, u)
print "%f / %f" % (time_pre, time_unpre)
print "Doing startA_read_book at %f\n\n#########################\n" % t
pol.add_action(t,P.A_map['startA_read_book'])
t += 15
((act, l, u), time_pre, time_unpre) = pol.get_action(t, s1, 'timings')
pre_times.append(time_pre)
unpre_times.append(time_unpre)
print "%s, %f, %f" % (str(act), l, u)
print "%f / %f" % (time_pre, time_unpre)
print "Doing startA_do_laundry at %f\n\n#########################\n" % t
pol.add_action(t,P.A_map['startA_do_laundry'])
for i in range(6):
((act, l, u), time_pre, time_unpre) = pol.get_action(t, s2, 'timings')
pre_times.append(time_pre)
unpre_times.append(time_unpre)
t += (l+u) / 2
print "%s, %f, %f" % (str(act), l, u)
print "%f / %f" % (time_pre, time_unpre)
print "Doing startA_do_laundry at %f\n\n#########################\n" % t
pol.add_action(t,P.A_map['startA_do_laundry'])
print "Processing the data..."
xs = [[], []]
ys = [[], []]
for i in range(len(pre_times)):
xs[0].append(i+1)
xs[1].append(i+1)
ys[1].append(pre_times[i] / 100)
ys[0].append(unpre_times[i] / 100)
plot(xs, ys, x_label='Execution Trace', y_label='Time Required (s)', col=False, xyline=False, y_log=True, no_scatter=True, names=['Not Preprocessed', 'Preprocessed'])
#############################################
def experiment5():
print "Running experiment to test success rate over a range of alteration probabilities\n"
print "Building the policy..."
(pol, P) = build_policy(POP_FILE)
steps = 20
prob_start = 0.0
prob_end = 0.5
prob_step = (prob_end - prob_start) / steps
prob_laundry = prob_start
x = []
y = []
sim_num = 100
print "Running %d simulations for %d steps..." % (sim_num, steps)
while prob_laundry < prob_end:
worked = 0
for i in range(sim_num):
if run_static(pol, P, mode = 'mid', silent = True, alter_state=pessimistic_dynamics,
alter_settings={'prob_unlaundry':prob_laundry, 'prob_hungry':0.0})[0]:
worked += 1
x.append(prob_laundry)
y.append(float(worked) / float(sim_num))
print "\nProbability, Success Rate = %.2f,%.2f" % (x[-1], y[-1])
prob_laundry += prob_step
plot(x, y, x_label='Probability of Change', y_label='Success Rate', col=False, xyline=False)
#############################################
def experiment6():
print "Running experiment to test various approaches in increasingly dynamic environments\n"
print "Building the policy..."
(pol, P) = build_policy(POP_FILE)
prob_profiles = [
{'prob_unlaundry':0.0,
'prob_hungry':0.0,
'prob_full':0.0,
'prob_laundry':0.0,
'prob_read':0.0,
'prob_movie':0.0,
'prob_groc':0.0},
{'prob_unlaundry':0.05,
'prob_hungry':0.1,
'prob_full':0.04,
'prob_laundry':0.04,
'prob_read':0.04,
'prob_movie':0.04,
'prob_groc':0.04},
{'prob_unlaundry':0.13,
'prob_hungry':0.15,
'prob_full':0.07,
'prob_laundry':0.07,
'prob_read':0.07,
'prob_movie':0.07,
'prob_groc':0.07},
{'prob_unlaundry':0.21,
'prob_hungry':0.2,
'prob_full':0.1,
'prob_laundry':0.1,
'prob_read':0.1,
'prob_movie':0.1,
'prob_groc':0.1},
{'prob_unlaundry':0.28,
'prob_hungry':0.25,
'prob_full':0.13,
'prob_laundry':0.13,
'prob_read':0.13,
'prob_movie':0.13,
'prob_groc':0.13},
{'prob_unlaundry':0.35,
'prob_hungry':0.3,
'prob_full':0.16,
'prob_laundry':0.16,
'prob_read':0.16,
'prob_movie':0.16,
'prob_groc':0.16}
]
# Means
finish_times = {'us': [], 'seren': [], 'stn': []}
action_counts = {'us': [], 'seren': [], 'stn': []}
number_changes = {'us': [], 'seren': [], 'stn': []}
# Computed
success_rates = {'us': 0, 'seren': 0, 'stn': 0}
sim_num = 1000
first_run = True
print "Running %d simulation profiles for %d iterations..." % (len(prob_profiles), sim_num)
for settings in prob_profiles:
if first_run:
first_run = False
sims = 1
else:
sims = sim_num
for approach in ['us', 'seren', 'stn']:
pol.mode = approach
for i in range(sims):
(success, f_time, a_count, n_changes, n_replans) = run_static(pol, P, mode = 'lower', silent = True,
alter_state=general_dynamics, alter_settings=settings)
finish_times[approach].append(f_time)
if -1 == a_count:
a_count = 55
action_counts[approach].append(a_count)
number_changes[approach].append(n_changes)
if success:
success_rates[approach] += 1
#print finish_times
#print action_counts
#print number_changes
print "\nSuccess rates: %s\n" % str(success_rates)
print "Processing the data..."
xs1 = [[], [], []]
ys1 = [[], [], []]
num_trials = len(finish_times['stn'])
for i in range(num_trials):
xs1[2].append(number_changes['stn'][i])
ys1[2].append(action_counts['stn'][i])
xs1[0].append(number_changes['us'][i])
ys1[0].append(action_counts['us'][i])
xs1[1].append(number_changes['seren'][i])
ys1[1].append(action_counts['seren'][i])
stn_success = []
seren_success = []
us_success = []
stn_unsuccess = []
seren_unsuccess = []
us_unsuccess = []
stn_change_counts = {}
seren_change_counts = {}
us_change_counts = {}
for i in range(num_trials):
if number_changes['stn'][i] not in stn_change_counts:
stn_change_counts[number_changes['stn'][i]] = [0,0]
if -1 == finish_times['stn'][i]:
stn_unsuccess.append(number_changes['stn'][i])
stn_change_counts[number_changes['stn'][i]][1] += 1
else:
stn_success.append(number_changes['stn'][i])
stn_change_counts[number_changes['stn'][i]][0] += 1
stn_change_counts[number_changes['stn'][i]][1] += 1
if number_changes['us'][i] not in us_change_counts:
us_change_counts[number_changes['us'][i]] = [0,0]
if -1 == finish_times['us'][i]:
us_unsuccess.append(number_changes['us'][i])
us_change_counts[number_changes['us'][i]][1] += 1
else:
us_success.append(number_changes['us'][i])
| |
<reponame>jlk9/wavelet_xcorr<gh_stars>1-10
# Written by <NAME>, <EMAIL>
# Last modified 3/4/2021
import numpy as np
import math
from scipy.signal import correlate
# First, we need a few C related libraries:
from ctypes import c_void_p, c_double, c_int, cdll
from numpy.ctypeslib import ndpointer
# This loads the compiled C code and the function, getting its path relative to this module:
lib = cdll.LoadLibrary(__file__[:-62] + 'bin/diag_helper_sparse.so')
sparse_xcorr_sum_void = lib.sparse_xcorr_sum_void
# Now we need to load our function, which was already compiled with the following command:
# cc -fPIC -shared -o ../../bin/diag_helper_sparse.so ./diag_helper_sparse.c
""" Given two signals of the same level from coeffs1 and coeffs2, along with a set number of time lags and
interior right and left entries, this will compute all of the required diagonals for our basic levelx -
levelx component of our xcorr.
Inputs:
coeff1 the wavelet coefficients for the first (longer) signal
coeff2 the wavelet coefficients for the second (shorter) signal, same level as coeff1
right_length the number of lags we need to compute pushing coeff2 forward, including the main diagonal,
for this weight matrix
left_length the number of lags we need to compute pushing coeff2 backward for this weight matrix
lags the number of time lags we need
Returns
left_diags the left diagonals for each timelag
right_diags the right diagonals for each timelag
"""
def compute_all_diags_sparse(sparse_coeff1, sparse_coeff2, left_length, right_length, offsets):
left_diags = np.zeros((left_length, offsets))
right_diags = np.zeros((right_length, offsets))
len_coeff2 = sparse_coeff2[2]
# First we'll deal with the main diagonals, the first upper diagonals, and the last lower diagonals. These are the sliding
# inner products of the two sets of wavelet coefficients against each other - we use C code to speed up the required for loops:
# Note: might need to truncate the end of sparse_coeff1 here.
diags = sparse_xcorr_calc_C_void((sparse_coeff1[0] + right_length-1, sparse_coeff1[1], sparse_coeff1[2]), sparse_coeff2, offsets + left_length + right_length-1)
# The first few upper diagonals are the first sliding inner products:
right_diags[::-1,0] = diags[:right_length]
# Most of the sliding inner products make up the main diagonals:
right_diags[0] = diags[right_length-1:offsets+right_length-1]
# The last few sliding inner products are the end lower diagonals:
left_diags[:,offsets-1] = diags[-left_length:]
# We can get the rest of the upper diagonals by slightly changing our main diagonals.
# First, we need to determine which entries of the sparse vector must be added to each lower/upper diagonal.
# These entries correspond to the end of what to remove from the uppers, then the begin/end of what to
# remove from the lowers, respectively.
# This determines what entries of coeff1 are needed to modify our upper and lower (right and left) diagonals:
lower_upper_bounds = np.searchsorted(sparse_coeff1[0], [offsets-1, len_coeff2, len_coeff2+offsets-1], side='left', sorter=None)
# This determines what entries of coeff2 modify our right diagonals:
upper_begins = np.searchsorted(sparse_coeff2[0], list(range(right_length-1)), side='left', sorter=None)
# This is the term from coeff1 we subtract from our upper diagonals:
modify_diag = sparse_coeff1[1][:lower_upper_bounds[0]]
# This gives us the indexing of the entries which are decremented by modify_diag:
indexing = sparse_coeff1[0][:lower_upper_bounds[0]] + 1
for i in range(1, right_length):
# First, we know this upper diagonal almost equals the previous offset's previous upper diagonal:
right_diags[i,1:] = right_diags[i-1,:offsets-1]
# If our sparse vector contains the value to be removed, then we need to remove it to get the exact upper diagonal:
if sparse_coeff2[0][upper_begins[i-1]] == i-1:
right_diags[i, indexing] -= sparse_coeff2[1][upper_begins[i-1]] * modify_diag
# Now we'll deal with the lower diagonals, first determining what part of coeff2 to remove:
lower_ends = np.searchsorted(sparse_coeff2[0], list(range(len_coeff2-1, len_coeff2 - left_length-1, -1)), side='left', sorter=None)
# This is the term from coeff1 we subtract from our lower diagonals:
modify_diag = sparse_coeff1[1][lower_upper_bounds[1]:lower_upper_bounds[2]]
# This gives us the indexing of the entries which are decremented by modify_diag:
indexing = sparse_coeff1[0][lower_upper_bounds[1]:lower_upper_bounds[2]] - len_coeff2
# Here we'll establish the first lower subdiagonal:
left_diags[0,:-1] = right_diags[0,1:]
if (lower_ends[0] < len(sparse_coeff2[0])) and (sparse_coeff2[0][lower_ends[0]] == len_coeff2 - 1):
left_diags[0, indexing] -= sparse_coeff2[1][lower_ends[0]] * modify_diag
# And here we'll establish subsequent diagonals:
for i in range(1, left_length):
left_diags[i,:-1] = left_diags[i-1,1:]
if (lower_ends[i] < len(sparse_coeff2[0])) and (sparse_coeff2[0][lower_ends[i]] == len_coeff2 - 1 - i):
left_diags[i, indexing] -= sparse_coeff2[1][lower_ends[i]] * modify_diag
return np.transpose(left_diags), np.transpose(right_diags)
""" Given two signals of the same level from coeffs1 and coeffs2, along with a set number of time lags and
interior right and left entries, this will compute all of the required diagonals for our mixed level1 -
level2 component of our xcorr.
Inputs:
coeff1 the wavelet coefficients for the first (longer) signal
coeff2 the wavelet coefficients for the second (shorter) signal, same level as coeff1
scale_diff
endpoint_ind
offsets
length_diag the number of lags we need to compute pushing coeff2 forward for this weight matrix
len_coeff1 the length of coeff1
Returns
diags the diagonals for each timelag
"""
def mixed_compute_all_diags_sparse(sparse_coeff1, sparse_coeff2, scale_diff, endpoint_ind, offsets, length_diag, len_coeff1):
# We'll get the first column by padding some extra 0s to our timelags and applying redundancy rules:
padding = math.ceil(length_diag / scale_diff) * scale_diff
# Here we allocate the memory:
diags = np.zeros((length_diag, offsets + padding))
# The coeff2 endpoints are dependent on signal length, so we need to compute them here:
coeff2_ends = endpoint_ind[2,:] + scale_diff * (len_coeff1 - endpoint_ind[1,:] - endpoint_ind[0,:])
main_length = (offsets + padding) // scale_diff
# We'll get the first diagonals here:
# IDEA: break sparse_coeff2 up into parts, based on which part goes into which correlate call.
# Then call sparse_xcorr_calc_C on those separate xcorr calculations
# FIRST, call searchsorted out here to get the beginning and end indices of both coeffs for each i (begin will be coeff2[endpoint_ind[2,0]-i, end will be coeff2_ends[0]-i)
coeff1_padded = sparse_coeff1[0] + (padding // scale_diff)
coeff1_endpoints = np.searchsorted(coeff1_padded, [endpoint_ind[0,0], len_coeff1-endpoint_ind[1,0]+main_length-1], side='left', sorter=None)
coeff2_endpoints = np.searchsorted(sparse_coeff2[0], [endpoint_ind[2,0]-scale_diff+1, coeff2_ends[0]], side='left', sorter=None)
# Here, we determine what portions of coeff1 and coeff2 we need to operate on:
coeff1_to_compute = (coeff1_padded[coeff1_endpoints[0]:coeff1_endpoints[1]] - endpoint_ind[0,0], sparse_coeff1[1][coeff1_endpoints[0]:coeff1_endpoints[1]], sparse_coeff1[2])
coeff2_to_compute_indices = sparse_coeff2[0][coeff2_endpoints[0]:coeff2_endpoints[1]]
coeff2_to_compute_values = sparse_coeff2[1][coeff2_endpoints[0]:coeff2_endpoints[1]]
for i in range(scale_diff):
# HERE, use np.where to find which entries of sparse_coeff2[0][begin for this i:end for this i] are divisible by scale_diff
this_scale = ((coeff2_to_compute_indices % scale_diff) == (scale_diff - 1 - i))
# LAST, call sparse_xcorr_calc_C here, with the sparse vectors filtered using work from above. The lagmax should be
# main_length
diags[0,i::scale_diff] = sparse_xcorr_calc_C_void(coeff1_to_compute, (coeff2_to_compute_indices[this_scale] // scale_diff, coeff2_to_compute_values[this_scale]), main_length)
# Here we'll get subsequent rows based on the previous rows. Since we padded the front entries, we now use the redundancy rules to generate the
# first column:
for i in range(1, length_diag):
# The basic rule is that the next diagonals is equal to the previous diagonal from the previous row:
diags[i,1:] = diags[i-1,:-1]
# TODO, for better accuracy:
# Need to ADD element to front, if endpoint indices coeff1 start went down:
# Need to REMOVE element from back, if endpoint indices coeff1 end went up:
return diags[:,padding:]
""" In general, diagonals will go down one and to left because of how the signals slide across each other.
Let's try that, make sure the overall error isn't too extreme, and test the savings:
ASSUMPTION: the endpoint indices of our correlation matrix coeff1 will always either increment or decrement
by 1 only. This affects how we fill in entries from the previous row of diagonals.
Inputs:
coeff1 the series of longer wavelets, from the shorter signal
coeff2 the series of shorter wavelets, from the longer signal
scale_diff the difference between the scale of coeff1 and coeff2, 2 ^ (level 1 - level 2)
endpoint_ind the endpoint coordinates for this mixed-wavelet xcorr
offsets the number of diagonals we need, based on the strides of these wavelets and our
number of timelags
length_diag the number of diagonals we need to compute
len_coeff1 the number of terms from coeff1 we use for 1 diagonal
Returns:
diags the sliding xcorrs we need for interior points
"""
def mixed_compute_all_diags_case2_sparse(sparse_coeff1, sparse_coeff2, scale_diff, endpoint_ind, offsets, length_diag, len_coeff1):
# We'll get the last column by padding some extra 0s to our timelags and applying redundancy rules:
padding = math.ceil(length_diag / scale_diff) * scale_diff
# Here we allocate the memory and get the coeff2 endpoints:
diags = np.zeros((length_diag, offsets | |
<reponame>MyPyDavid/ECpy<filename>src/elchempy/_todo_PostEC/plotting.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 25 11:04:07 2020
@author: zmg
"""
import itertools
from pathlib import Path
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import seaborn as sns
try:
import SampleSelection
except ModuleNotFoundError:
SampleSelection = lambda x: x
class PlotAnalysis:
"""Some properties of electrochemical experiments collected and reference values"""
def __init__():
pass
@staticmethod
def LinearTrend(df, x_col, y_col):
data = pd.DataFrame([])
# colX,colY = OCP_DATA['Elapsed Time(s)'],OCP_DATA['E(V)']
data["x"] = x_col
data["y"] = y_col
res = smf.ols("data.y ~ data.x", data=data).fit()
# X = sm.add_constant(x), mod = sm.OLS(y,X),res = mod.fit()
intercept, slope, rsquared = res.params[0], res.params[1], res.rsquared
if np.abs(slope) < 1e-5:
check = True
else:
check = False
return intercept, slope, rsquared, check
def heatmap(x, y, **kwargs):
if "color" in kwargs:
color = kwargs["color"]
else:
color = [1] * len(x)
if "palette" in kwargs:
palette = kwargs["palette"]
n_colors = len(palette)
else:
n_colors = 256 # Use 256 colors for the diverging color palette
palette = sns.color_palette("Blues", n_colors)
if "color_range" in kwargs:
color_min, color_max = kwargs["color_range"]
else:
color_min, color_max = min(color), max(
color
) # Range of values that will be mapped to the palette, i.e. min and max possible correlation
def value_to_color(val):
if color_min == color_max:
return palette[-1]
else:
val_position = float((val - color_min)) / (
color_max - color_min
) # position of value in the input range, relative to the length of the input range
val_position = min(
max(val_position, 0), 1
) # bound the position betwen 0 and 1
ind = int(
val_position * (n_colors - 1)
) # target index in the color palette
return palette[ind]
if "size" in kwargs:
size = kwargs["size"]
else:
size = [1] * len(x)
if "size_range" in kwargs:
size_min, size_max = kwargs["size_range"][0], kwargs["size_range"][1]
else:
size_min, size_max = min(size), max(size)
size_scale = kwargs.get("size_scale", 500)
def value_to_size(val):
if size_min == size_max:
return 1 * size_scale
else:
val_position = (val - size_min) * 0.99 / (
size_max - size_min
) + 0.01 # position of value in the input range, relative to the length of the input range
val_position = min(
max(val_position, 0), 1
) # bound the position betwen 0 and 1
return val_position * size_scale
if "x_order" in kwargs:
x_names = [t for t in kwargs["x_order"]]
else:
x_names = [t for t in sorted(set([v for v in x]))]
x_to_num = {p[1]: p[0] for p in enumerate(x_names)}
if "y_order" in kwargs:
y_names = [t for t in kwargs["y_order"]]
else:
y_names = [t for t in sorted(set([v for v in y]))]
y_to_num = {p[1]: p[0] for p in enumerate(y_names)}
plot_grid = plt.GridSpec(1, 15, hspace=0.2, wspace=0.1) # Setup a 1x10 grid
ax = plt.subplot(
plot_grid[:, :-1]
) # Use the left 14/15ths of the grid for the main plot
marker = kwargs.get("marker", "s")
kwargs_pass_on = {
k: v
for k, v in kwargs.items()
if k
not in [
"color",
"palette",
"color_range",
"size",
"size_range",
"size_scale",
"marker",
"x_order",
"y_order",
]
}
ax.scatter(
x=[x_to_num[v] for v in x],
y=[y_to_num[v] for v in y],
marker=marker,
s=[value_to_size(v) for v in size],
c=[value_to_color(v) for v in color],
**kwargs_pass_on,
)
ax.set_xticks([v for k, v in x_to_num.items()])
ax.set_xticklabels(
[k for k in x_to_num], rotation=45, horizontalalignment="right"
)
ax.set_yticks([v for k, v in y_to_num.items()])
ax.set_yticklabels([k for k in y_to_num])
ax.grid(False, "major")
ax.grid(True, "minor")
ax.set_xticks([t + 0.5 for t in ax.get_xticks()], minor=True)
ax.set_yticks([t + 0.5 for t in ax.get_yticks()], minor=True)
ax.set_xlim([-0.5, max([v for v in x_to_num.values()]) + 0.5])
ax.set_ylim([-0.5, max([v for v in y_to_num.values()]) + 0.5])
ax.set_facecolor("#F1F1F1")
# Add color legend on the right side of the plot
if color_min < color_max:
ax = plt.subplot(plot_grid[:, -1]) # Use the rightmost column of the plot
col_x = [0] * len(palette) # Fixed x coordinate for the bars
bar_y = np.linspace(
color_min, color_max, n_colors
) # y coordinates for each of the n_colors bars
bar_height = bar_y[1] - bar_y[0]
ax.barh(
y=bar_y,
width=[5] * len(palette), # Make bars 5 units wide
left=col_x, # Make bars start at 0
height=bar_height,
color=palette,
linewidth=0,
)
ax.set_xlim(
1, 2
) # Bars are going from 0 to 5, so lets crop the plot somewhere in the middle
ax.grid(False) # Hide grid
ax.set_facecolor("white") # Make background white
ax.set_xticks([]) # Remove horizontal ticks
ax.set_yticks(
np.linspace(min(bar_y), max(bar_y), 3)
) # Show vertical ticks for min, middle and max
ax.yaxis.tick_right() # Show vertical ticks on the right
def corrplot(data, size_scale=500, marker="s"):
# data = rcorr
corr = pd.melt(data.reset_index(), id_vars="index").dropna()
# corr = corr.loc[corr.x.isin(SampleSelection.EC_EIS_par_cols)]
corr.columns = ["x", "y", "value"]
PlotAnalysis.heatmap(
corr["x"],
corr["y"],
color=corr["value"],
color_range=[-1, 1],
palette=sns.diverging_palette(20, 220, n=256),
size=corr["value"].abs(),
size_range=[0, 1],
marker=marker,
x_order=data.columns,
y_order=data.columns[::-1],
size_scale=size_scale,
)
def plot_spectra_SampleIDs(xc, yc, spectras, destdir):
# stgr = EIS_O2_065_acid1_no
# stgr = grE
# fig,ax = plt.subplots()
# spdf_char.plot(x=['DATA_Yre'],y=['DATA_Yim'],kind='scatter',ax=ax)
# spdf_char.plot(x=['FIT2_Yre'],y=['FIT2_Yim'],kind='scatter',ax=ax)
spdf_char = spectras
x_col, y_col = "DATA_Yre", "DATA_Yim"
x_fit2, y_fit2 = "FIT2_Yre", "FIT2_Yim"
# Y_adm = {'x_data' : }
AdmImp = eisplot.AmdImp()
# x_col, y_col = 'N_content','Rct_kin'
# x_col, y_col = 'Qad','Rct'
# 'BET_Area_RPT', 'BET_SA m2/g_RAW'
#%%
for ZY in AdmImp:
ZYinfo = AdmImp[ZY]
fig, ax = plt.subplots()
EC_exp_nuniq = [
i
for i in SampleSelection.EC_exp_cols + ["E_RHE"]
if spdf_char[i].nunique() == 1
]
EC_exp_nuniq_non = [
i
for i in SampleSelection.EC_exp_cols + ["E_RHE"]
if spdf_char[i].nunique() != 1
]
EC_exp_cond1 = [
"{0} : {1}".format(i, spdf_char[i].unique()[0]) for i in EC_exp_nuniq[0:3]
]
EC_exp_cond_png = "_".join(
["{0}".format(spdf_char[i].unique()[0]) for i in EC_exp_nuniq]
)
EC_exp_cond2 = [
"{0} : {1}".format(i, spdf_char[i].unique()[0]) for i in EC_exp_nuniq[3::]
]
if "pH" in EC_exp_nuniq_non:
extra_pH = "pH : {0}".format(
" & ".join([str(i) for i in list(spdf_char["pH"].unique())])
)
EC_exp_cond2.append(extra_pH)
ax.text(
0.4,
1.1,
"{0} with {1} \n in {2}\n {3}".format(
xc, yc, ", ".join(EC_exp_cond1), ", ".join(EC_exp_cond2)
),
horizontalalignment="center",
transform=ax.transAxes,
)
# fig.suptitle('{0} with {1}\n in {2}'.format(x_col,y_col,', '.join(EC_exp_cond)))
# ym = stgr[y_col].max()*1.3 if stgr[y_col].max() < 2*stgr[y_col].mean() else stgr[y_col].mean()*1.5
x_col, y_col = ZYinfo["x_data"], ZYinfo["y_data"]
x_fit2, y_fit2 = ZYinfo["x_fit"], ZYinfo["y_fit"]
ymean, ystd = spdf_char[y_col].mean(), spdf_char[y_col].std()
y_fltr = spdf_char.loc[spdf_char[y_col] < ymean + 4 * ystd, y_col]
yfltrmean, yfltrstd, yfltrmax = y_fltr.mean(), y_fltr.std(), y_fltr.max()
xmean, xstd = spdf_char[x_col].mean(), spdf_char[x_col].std()
x_fltr = spdf_char.loc[spdf_char[x_col] < xmean + 4 * xstd, x_col]
xfltrmean, xfltrstd, xfltrmax, xfltrmin = (
x_fltr.mean(),
x_fltr.std(),
x_fltr.max(),
x_fltr.min(),
)
ymin, ymax = spdf_char[y_col].min(), spdf_char[y_col].max()
ymax_set = (
yfltrmax * 1.1
) # if not yfltrmax < yfltrmean+3*yfltrstd else yfltrmean*2
ymin_set = ymin * 0.9
if np.abs(xfltrmean) - 5 * np.abs(xfltrstd) < 0:
if spdf_char.loc[spdf_char[x_col] < 0].empty:
xmin_set = 0
else:
xmin_set = xfltrmin * 0.9
else:
xmin_set = xfltrmin * 0.9
# xmin_set = xfltrmin*0.9 if not stgr.loc[stgr[x_col] < 0].empty and not xfltrmean-6*xfltrstd < 0 else 0
xmax_set = xfltrmax * 1.1
# MLmax = stgr.ML.max()*1.2
EC_st_out = []
OriginColors = Characterization_TypeSetting.OriginColorList()
xls_path = "{0}_{1}_{2}.xlsx".format(x_col, y_col, ZY).replace("/", "")
png_path = "{0}_{1}_{2}_{3}_spectra.png".format(
xc, yc, EC_exp_cond_png, ZY
).replace("/", "")
print(xls_path)
for Parf, IDgr in spdf_char.groupby(by=["PAR_file"]):
ID_cl1 = [i for i in IDgr.Colorcode.unique() if str(i) != "nan"]
IDnm = IDgr.SampleID.unique()[0]
if ID_cl1:
ID_colorcode = ID_cl1[0]
else:
ID_colorcode = 1
RGB = [
float(i) / 255
for i in (
OriginColors.loc[
OriginColors.OriginCode == ID_colorcode, "RGB"
].values[0]
).split(",")
]
x, y = IDgr[x_col].values, IDgr[y_col].values
xfit2, yfit2 = IDgr[x_fit2].values, IDgr[y_fit2].values
alpha_val_ML = IDgr.ML.unique()[0] / 21.4 + 0.2
alpha_val_ML_set = alpha_val_ML if not alpha_val_ML > 1 else 1
alpha_val_ML_set = alpha_val_ML_set if not alpha_val_ML_set < 0 else 0.1
try:
ax.scatter(
x,
y,
label="{0} ({1})".format(
IDgr.SampleLabel.unique()[0], IDgr.SampleID.unique()[0]
),
color=RGB,
s=50,
alpha=alpha_val_ML_set,
)
except Exception as e:
print("No plot for: {0}, because {1}".format(IDnm, e))
if "RGB" in e:
print("RGB: {}, alpha = {:.3f} ".format(RGB, alpha_val_ML))
try:
alpha_val_ML_fit_set = (
alpha_val_ML_set + 0.2 if alpha_val_ML < 0.7 else alpha_val_ML_set
)
fit_label = "{0} ({1})".format(
IDgr.SampleLabel.unique()[0], IDgr.SampleID.unique()[0]
)
ax.plot(xfit2, yfit2, color=RGB, lw=2, alpha=alpha_val_ML_fit_set)
except Exception as e:
print("No plot for: {0}, because {1}".format(IDnm, e))
if "RGB" in e:
print("RGB: {}, alpha = {:.3f} ".format(RGB, alpha_val_ML))
# EC_st_out.append(IDgr)
# XLS file already there, otherwise: pd.concat([i for i in EC_st_out]).to_excel(destdir.joinpath(xls_path))
ax.set_ylim(0, ymax_set)
ax.set_xlim(0, xmax_set)
ax.set_xlabel(ZYinfo["x_label"])
ax.set_ylabel(ZYinfo["y_label"])
ax.legend(
bbox_to_anchor=(-0.35, 1.45, 1.7, 0.102),
loc="lower left",
ncol=2,
mode="expand",
borderaxespad=0.0,
)
#%%
plt.savefig(destdir.joinpath(png_path), dpi=300, bbox_inches="tight")
| |
# -*- coding: utf-8 -*-
"""Classes and functions that create the bandwidth measurements document
(v3bw) used by bandwidth authorities."""
# flake8: noqa: E741
# (E741 ambiguous variable name), when using l.
import copy
import logging
import math
import os
from itertools import combinations
from statistics import median, mean
from stem.descriptor import parse_file
from sbws import __version__
from sbws.globals import (SPEC_VERSION, BW_LINE_SIZE, SBWS_SCALE_CONSTANT,
TORFLOW_SCALING, SBWS_SCALING, TORFLOW_BW_MARGIN,
TORFLOW_OBS_LAST, TORFLOW_OBS_MEAN,
PROP276_ROUND_DIG, MIN_REPORT, MAX_BW_DIFF_PERC)
from sbws.lib import scaling
from sbws.lib.resultdump import ResultSuccess, _ResultType
from sbws.util.filelock import DirectoryLock
from sbws.util.timestamp import (now_isodt_str, unixts_to_isodt_str,
now_unixts, isostr_to_dt_obj,
dt_obj_to_isodt_str)
from sbws.util.state import State
log = logging.getLogger(__name__)
LINE_SEP = '\n'
KEYVALUE_SEP_V1 = '='
KEYVALUE_SEP_V2 = ' '
# NOTE: in a future refactor make make all the KeyValues be a dictionary
# with their type, so that it's more similar to stem parser.
# Header KeyValues
# =================
# KeyValues that need to be in a specific order in the Bandwidth File.
HEADER_KEYS_V1_1_ORDERED = ['version']
# KeyValues that are not initialized from the state file nor the measurements.
# They can also be pass as an argument to `Header` to overwrite default values,
# what is done in unit tests.
# `latest bandwidth` is special cause it gets its value from timestamp, which
# is not a KeyValue, but it's always pass as an agument.
# It could be separaed in other list, but so far there is no need, cause:
# 1. when it's pass to the Header to initialize it, it's just ignored.
# 2. when the file is created, it's took into account.
HEADER_KEYS_V1_1_SELF_INITIALIZED = [
"software",
"software_version",
"file_created",
"latest_bandwidth",
]
# KeyValues that are initialized from arguments.
HEADER_KEYS_V1_1_TO_INIT = [
"earliest_bandwidth",
"generator_started",
]
# number_eligible_relays is the number that ends in the bandwidth file
# ie, have not been excluded by one of the filters in 4. below
# They should be call recent_measurement_included_count to be congruent
# with the other KeyValues.
HEADER_KEYS_V1_2 = [
"number_eligible_relays",
"minimum_number_eligible_relays",
"number_consensus_relays",
"percent_eligible_relays",
"minimum_percent_eligible_relays",
]
# KeyValues added in the Bandwidth File v1.3.0
HEADER_KEYS_V1_3 = [
"scanner_country",
"destinations_countries",
]
# KeyValues that count the number of relays that are in the bandwidth file,
# but ignored by Tor when voting, because they do not have a
# measured bandwidth.
HEADER_RECENT_MEASUREMENTS_EXCLUDED_KEYS = [
# Number of relays that were measured but all the measurements failed
# because of network failures or it was
# not found a suitable helper relay
'recent_measurements_excluded_error_count',
# Number of relays that have successful measurements but the measurements
# were not away from each other in X time (by default 1 day).
'recent_measurements_excluded_near_count',
# Number of relays that have successful measurements and they are away from
# each other but they are not X time recent.
# By default this is 5 days, which is the same time the older
# the measurements can be by default.
'recent_measurements_excluded_old_count',
# Number of relays that have successful measurements and they are away from
# each other and recent
# but the number of measurements are less than X (by default 2).
'recent_measurements_excluded_few_count',
]
# Added in #29591
# NOTE: recent_consensus_count, recent_priority_list_count,
# recent_measurement_attempt_count and recent_priority_relay_count
# are not reset when the scanner is stop.
# They will accumulate the values since the scanner was ever started.
HEADER_KEYS_V1_4 = [
# 1.1 header: the number of different consensuses, that sbws has seen,
# since the last 5 days
'recent_consensus_count',
# 2.4 Number of times a priority list has been created
'recent_priority_list_count',
# 2.5 Number of relays that there were in a priority list
# [50, number of relays in the network * 0.05]
'recent_priority_relay_count',
# 3.6 header: the number of times that sbws has tried to measure any relay,
# since the last 5 days
# This would be the number of times a relays were in a priority list
'recent_measurement_attempt_count',
# 3.7 header: the number of times that sbws has tried to measure any relay,
# since the last 5 days, but it didn't work
# This should be the number of attempts - number of ResultSuccess -
# something else we don't know yet
# So far is the number of ResultError
'recent_measurement_failure_count',
# The time it took to report about half of the network.
'time_to_report_half_network',
] + HEADER_RECENT_MEASUREMENTS_EXCLUDED_KEYS
# Tor version will be obtained from the state file, so it won't be pass as an
# argument, but will be self-initialized.
HEADER_KEYS_V1_4_TO_INIT = ['tor_version']
# KeyValues that are initialized from arguments, not self-initialized.
HEADER_INIT_KEYS = (
HEADER_KEYS_V1_1_TO_INIT
+ HEADER_KEYS_V1_3
+ HEADER_KEYS_V1_2
+ HEADER_KEYS_V1_4
+ HEADER_KEYS_V1_4_TO_INIT
)
HEADER_INT_KEYS = HEADER_KEYS_V1_2 + HEADER_KEYS_V1_4
# List of all unordered KeyValues currently being used to generate the file
HEADER_UNORDERED_KEYS = (
HEADER_KEYS_V1_1_SELF_INITIALIZED
+ HEADER_KEYS_V1_1_TO_INIT
+ HEADER_KEYS_V1_3
+ HEADER_KEYS_V1_2
+ HEADER_KEYS_V1_4
+ HEADER_KEYS_V1_4_TO_INIT
)
# List of all the KeyValues currently being used to generate the file
HEADER_ALL_KEYS = HEADER_KEYS_V1_1_ORDERED + HEADER_UNORDERED_KEYS
TERMINATOR = '====='
# Bandwidth Lines KeyValues
# =========================
# Num header lines in v1.X.X using all the KeyValues
NUM_LINES_HEADER_V1 = len(HEADER_ALL_KEYS) + 2
LINE_TERMINATOR = TERMINATOR + LINE_SEP
# KeyValue separator in Bandwidth Lines
BWLINE_KEYVALUES_SEP_V1 = ' '
# not inclding in the files the extra bws for now
BWLINE_KEYS_V0 = ['node_id', 'bw']
BWLINE_KEYS_V1_1 = [
"master_key_ed25519",
"nick",
"rtt",
"time",
"success",
"error_stream",
"error_circ",
"error_misc",
# Added in #292951
"error_second_relay",
"error_destination",
]
BWLINE_KEYS_V1_2 = [
"bw_median",
"bw_mean",
"desc_bw_avg",
"desc_bw_bur",
"desc_bw_obs_last",
"desc_bw_obs_mean",
"consensus_bandwidth",
"consensus_bandwidth_is_unmeasured",
]
# There were no bandwidth lines key added in the specification version 1.3
# Added in #292951
BWLINE_KEYS_V1_4 = [
# 1.2 relay: the number of different consensuses, that sbws has seen,
# since the last 5 days, that have this relay
'relay_in_recent_consensus_count',
# 2.6 relay: the number of times a relay was "prioritized" to be measured
# in the recent days (by default 5).
'relay_recent_priority_list_count',
# 3.8 relay: the number of times that sbws has tried to measure
# this relay, since the last 5 days
# This would be the number of times a relay was in a priority list (2.6)
# since once it gets measured, it either returns ResultError,
# ResultSuccess or something else happened that we don't know yet
'relay_recent_measurement_attempt_count',
# 3.9 relay: the number of times that sbws has tried to measure
# this relay, since the last 5 days, but it didn't work
# This should be the number of attempts - number of ResultSuccess -
# something else we don't know yet
# So far is the number of ResultError
'relay_recent_measurement_failure_count',
# Number of error results created in the last 5 days that are excluded.
# This is the sum of all the errors.
'relay_recent_measurements_excluded_error_count',
# The number of successful results, created in the last 5 days,
# that were excluded by a rule, for this relay.
# 'relay_recent_measurements_excluded_error_count' would be the
# sum of the following 3 + the number of error results.
# The number of successful measurements that are not X time away
# from each other (by default 1 day).
'relay_recent_measurements_excluded_near_count',
# The number of successful measurements that are away from each other
# but not X time recent (by default 5 days).
'relay_recent_measurements_excluded_old_count',
# The number of measurements excluded because they are not at least X
# (by default 2).
'relay_recent_measurements_excluded_few_count',
# `vote=0` is used for the relays that were excluded to
# be reported in the bandwidth file and now they are
# reported.
# It tells Tor to do not vote on the relay.
# `unmeasured=1` is used for the same relays and it is
# added in case Tor would vote on them in future versions.
# Maybe these keys should not be included for the relays
# in which vote=1 and unmeasured=0.
'vote', 'unmeasured',
# When there not enough eligible relays (not excluded)
# under_min_report is 1, `vote` is 0.
# Added in #29853.
'under_min_report',
]
BWLINE_KEYS_V1 = BWLINE_KEYS_V0 + BWLINE_KEYS_V1_1 + BWLINE_KEYS_V1_2 \
+ BWLINE_KEYS_V1_4
# NOTE: tech-debt: assign boolean type to vote and unmeasured,
# when the attributes are defined with a type, as stem does.
BWLINE_INT_KEYS = (
[
"bw",
"rtt",
"success",
"error_stream",
"error_circ",
"error_misc",
]
+ BWLINE_KEYS_V1_2
+ BWLINE_KEYS_V1_4
)
# This is boolean, not int.
BWLINE_INT_KEYS.remove('consensus_bandwidth_is_unmeasured')
def round_sig_dig(n, digits=PROP276_ROUND_DIG):
"""Round n to 'digits' significant digits in front of the decimal point.
Results less than or equal to 1 are rounded to 1.
Returns an integer.
digits must be greater than 0.
n must | |
# 要添加一个新单元,输入 '# %%'
# 要添加一个新的标记单元,输入 '# %% [markdown]'
# %%
from IPython import get_ipython
# %% [markdown]
# # Module 1: Using CNN for dogs vs cats
# %% [markdown]
# To illustrate the Deep Learning pipeline, we are going to use a pretrained model to enter the [Dogs vs Cats](https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition) competition at Kaggle.
# %% [markdown]
# There are 25,000 labelled dog and cat photos available for training, and 12,500 in the test set that we have to try to label for this competition. According to the Kaggle web-site, when this competition was launched (end of 2013): *"**State of the art**: The current literature suggests machine classifiers can score above 80% accuracy on this task"*. So if you can beat 80%, then you will be at the cutting edge as of 2013!
# %% [markdown]
# ## Imports
# %%
import numpy as np
import matplotlib.pyplot as plt
import os
import torch
import torch.nn as nn
import torchvision
from torchvision import models,transforms,datasets
import time
get_ipython().run_line_magic('matplotlib', 'inline')
# %% [markdown]
# Here you see that the latest version of PyTorch is installed by default.
# %%
torch.__version__
# %%
import sys
sys.version
# %% [markdown]
# Check if GPU is available and if not change the [runtime](https://jovianlin.io/pytorch-with-gpu-in-google-colab/).
# %%
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print('Using gpu: %s ' % torch.cuda.is_available())
# %% [markdown]
# ## Downloading the data
# %% [markdown]
# You can download the full dataset from Kaggle directly.
#
# Alternatively, <NAME> (fast.ai) provides a direct link to the catvsdogs [dataset](http://files.fast.ai/data/examples/). He's separated the cats and dogs into separate folders and created a validation folder as well.
#
# For test purpose (or if you run on cpu), you should use the (small) sample directory.
# %%
get_ipython().run_line_magic('mkdir', 'data')
# the following line should be modified if you run the notebook on your computer
# change directory to data where you will store the dataset
get_ipython().run_line_magic('cd', 'data')
# !wget http://files.fast.ai/data/examples/dogscats.tgz
# %%
# !tar -zxvf dogscats.tgz
# %%
get_ipython().run_line_magic('ls', '')
# %%
get_ipython().run_line_magic('cd', 'dogscats')
get_ipython().run_line_magic('ls', '')
# %% [markdown]
# The structure of the sub-folders inside the folder `dogscats` will be important for what follows:
# ```bash
# .
# ├── test1 # contains 12500 images of cats and dogs
# ├── train
# | └── cats # contains 11500 images of cats
# | └── dogs # contains 11500 images of dogs
# ├── valid
# | └── cats # contains 1000 images of cats
# | └── dogs # contains 1000 images of dogs
# ├── sample
# | └── train
# | └── cats # contains 8 images of cats
# | └── dogs # contains 8 images of dogs
# | └── valid
# | └── cats # contains 4 images of cats
# | └── dogs # contains 4 images of dogs
# ├── models # empty folder
# ```
#
# You see that the 12 500 images of the test are in the `test1` sub-folder; the dataset of 25 000 labelled images has been split into a train set and a validation set.
#
# The sub-folder `sample` is here only to make sure the code is running properly on a very small dataset.
# %% [markdown]
# ## Data processing
# %%
get_ipython().run_line_magic('cd', '..')
# %% [markdown]
# Below, we give the path where the data is stored. If you are running this code on your computer, you should modifiy this cell.
# %%
data_dir = '/home/zhangxuanming/notebooks/Module1/data/dogscats/'
# %% [markdown]
# ```datasets``` is a class of the ```torchvision``` package (see [torchvision.datasets](http://pytorch.org/docs/master/torchvision/datasets.html)) and deals with data loading. It integrates a multi-threaded loader that fetches images from the disk, groups them in mini-batches and serves them continously to the GPU right after each _forward_/_backward_ pass through the network.
#
# Images needs a bit of preparation before passing them throught the network. They need to have all the same size $224\times 224 \times 3$ plus some extra formatting done below by the normalize transform (explained later).
# %%
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
imagenet_format = transforms.Compose([
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
# %%
dsets = {x: datasets.ImageFolder(os.path.join(data_dir, x), imagenet_format)
for x in ['train', 'valid']}
# %%
os.path.join(data_dir,'train')
# %% [markdown]
# Interactive help on jupyter notebook thanks to `?`
# %%
datasets.ImageFolder(data_dir)
# %% [markdown]
# We see that `datasets.ImageFolder` has attributes: classes, class_to_idx, imgs.
#
# Let see what they are?
# %%
dsets['train'].classes
# %% [markdown]
# The name of the classes are directly inferred from the structure of the folder:
# ```bash
# ├── train
# | └── cats
# | └── dogs
# ```
# %%
dsets['train'].class_to_idx
# %% [markdown]
# The label 0 will correspond to cats and 1 to dogs.
#
# Below, you see that the first 5 imgs are pairs (location_of_the_image, label):
# %%
dsets['train'].imgs[:5]
# %%
dset_sizes = {x: len(dsets[x]) for x in ['train', 'valid']}
dset_sizes
# %% [markdown]
# As expected we have 23 000 images in the training set and 2 000 in the validation set.
#
# Below, we store the classes in the variable `dset_classes`:
# %%
dset_classes = dsets['train'].classes
# %% [markdown]
# The ```torchvision``` packages allows complex pre-processing/transforms of the input data (_e.g._ normalization, cropping, flipping, jittering). A sequence of transforms can be grouped in a pipeline with the help of the ```torchvision.transforms.Compose``` function, see [torchvision.transforms](http://pytorch.org/docs/master/torchvision/transforms.html)
# %% [markdown]
# The magic help `?` allows you to retrieve function you defined and forgot!
# %%
imagenet_format
# %% [markdown]
# Where is this normalization coming from?
#
# As explained in the [PyTorch doc](https://pytorch.org/docs/stable/torchvision/models.html), you will use a pretrained model. All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using `mean = [0.485, 0.456, 0.406]` and `std = [0.229, 0.224, 0.225]`.
# %%
loader_train = torch.utils.data.DataLoader(dsets['train'], batch_size=64, shuffle=True, num_workers=6)
# %%
torch.utils.data.DataLoader
# %%
loader_valid = torch.utils.data.DataLoader(dsets['valid'], batch_size=5, shuffle=False, num_workers=6)
# %% [markdown]
# Try to understand what the following cell is doing?
# %%
count = 1
for data in loader_valid:
print(count, end=',')
if count == 1:
inputs_try,labels_try = data
count +=1
# %%
labels_try
# %%
inputs_try.shape
# %% [markdown]
# Got it: the validation dataset contains 2 000 images, hence this is 400 batches of size 5. `labels_try` contains the labels of the first batch and `inputs_try` the images of the first batch.
#
# What is an image for your computer?
# %%
inputs_try[0]
# %% [markdown]
# A 3-channel RGB image is of shape (3 x H x W). Note that entries can be negative because of the normalization.
# %% [markdown]
# A small function to display images:
# %%
def imshow(inp, title=None):
# Imshow for Tensor.
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = np.clip(std * inp + mean, 0,1)
plt.imshow(inp)
if title is not None:
plt.title(title)
# %%
# Make a grid from batch from the validation data
out = torchvision.utils.make_grid(inputs_try)
imshow(out, title=[dset_classes[x] for x in labels_try])
# %%
# Get a batch of training data
inputs, classes = next(iter(loader_train))
n_images = 8
# Make a grid from batch
out = torchvision.utils.make_grid(inputs[0:n_images])
imshow(out, title=[dset_classes[x] for x in classes[0:n_images]])
# %% [markdown]
# ## Creating VGG Model
# %% [markdown]
# The torchvision module comes with a zoo of popular CNN architectures which are already trained on [ImageNet](http://www.image-net.org/) (1.2M training images). When called the first time, if ```pretrained=True``` the model is fetched over the internet and downloaded to ```~/.torch/models```.
# For next calls, the model will be directly read from there.
# %%
model_vgg = models.vgg16(pretrained=True)
# %% [markdown]
# We will first use VGG Model without any modification. In order to interpret the results, we need to import the 1000 ImageNet categories, available at: [https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json](https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json)
# %%
# !wget https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json
# %%
import json
fpath = './imagenet_class_index.json'
with open(fpath) as f:
class_dict = json.load(f)
dic_imagenet = [class_dict[str(i)][1] for i in range(len(class_dict))]
# %%
dic_imagenet[:4]
# %%
inputs_try , labels_try = inputs_try.to(device), labels_try.to(device)
model_vgg = model_vgg.to(device)
# %%
outputs_try = model_vgg(inputs_try)
# %%
outputs_try
# %%
outputs_try.shape
# %% [markdown]
# To translate the outputs of the network into 'probabilities', we pass it through a [Softmax function](https://en.wikipedia.org/wiki/Softmax_function)
# %%
m_softm = nn.Softmax(dim=1)
probs = m_softm(outputs_try)
vals_try,preds_try = torch.max(probs,dim=1)
# %% [markdown]
# Let check, that we obtain a probability!
# %%
torch.sum(probs,1)
# %%
vals_try
# %%
print([dic_imagenet[i] for i in preds_try.data])
# %%
out = torchvision.utils.make_grid(inputs_try.data.cpu())
imshow(out, title=[dset_classes[x] for x in labels_try.data.cpu()])
# %% [markdown]
# ### Modifying the last layer and setting the gradient false to all layers
# %%
print(model_vgg)
# %% [markdown]
# We'll learn about what these different blocks do later in the course. For now, it's enough to know that:
#
# - Convolution | |
<reponame>njw0709/ShapeY<filename>shapey/dataprocess/raw_data.py
from tqdm import tqdm
import numpy as np
from itertools import combinations
import cupy as cp
from cupyx.scipy.linalg import tri
import functools
from shapey.utils.customdataset import ImageFolderWithPaths, PermutationPairsDataset
from shapey.utils.modelutils import GetModelIntermediateLayer
from shapey.utils.customfunc import pearsonr_batch, ln_batch
import torchvision.transforms as transforms
import torch
import torchvision.models as models
from torch.utils.data import Subset
from typing import Tuple
from h5py import File
import logging
import traceback
log = logging.getLogger(__name__)
def extract_features_resnet50(datadir: str) -> Tuple[list, list]:
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
dataset = ImageFolderWithPaths(
datadir,
transforms.Compose([transforms.Resize(224), transforms.ToTensor(), normalize]),
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=1, shuffle=False, num_workers=0, pin_memory=True
)
resnet50 = models.resnet50(pretrained=True)
resnet50_gap = GetModelIntermediateLayer(resnet50, -1)
resnet50_gap.cuda().eval()
# compute features
original_stored_imgname = []
original_stored_feat = []
for s in tqdm(data_loader):
img1, _, fname1 = s
fname1 = fname1[0].split("/")[-1]
output1 = resnet50_gap(img1.cuda())
output1 = torch.flatten(output1)
output1_store = output1.cpu().data.numpy()
original_stored_imgname.append(fname1)
original_stored_feat.append(output1_store)
return original_stored_imgname, original_stored_feat
def compute_correlation_and_save(
permutation_dataset: PermutationPairsDataset,
hdfstore: File,
corrval_key: str,
batch_size: int = 20000,
num_workers: int = 8,
) -> None:
data_loader = torch.utils.data.DataLoader(
permutation_dataset,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=num_workers,
)
log.info("Computing feature correlations...")
completed = False
while not completed:
try:
for s1, s2 in tqdm(data_loader):
idx1, feat1 = s1
idx2, feat2 = s2
idx1 = idx1.data.numpy()
idx2 = idx2.data.numpy()
# feat1 = hdfstore[feature_output_key][idx1, :]
# feat2 = hdfstore[feature_output_key][idx2, :]
# feat1 = torch.tensor(feat1).cuda()
# feat2 = torch.tensor(feat2).cuda()
# compute correlation
rval = pearsonr_batch(feat1.cuda(), feat2.cuda())
data = hdfstore[corrval_key][idx1.min() : idx1.max() + 1, :]
data[idx1 - idx1.min(), idx2] = rval.cpu().data.numpy().flatten()
hdfstore[corrval_key][idx1.min() : idx1.max() + 1, :] = data
log.info("Last computed: idx1: {}, idx2: {}".format(idx1[-1], idx2[-1]))
completed = True
except Exception as e:
log.error(e)
log.error(traceback.format_exc())
log.info(
"Last batch computed: ({}, {}) ~ ({}, {})".format(
idx1[0], idx2[0], idx1[-1], idx2[-1]
)
)
finally:
del data_loader
if not completed:
log.info(
"Restarting data loader from ({}, {})...".format(idx1[0], idx2[0])
)
idx = idx1[0] * permutation_dataset.datalen + idx2[0]
new_dataset = Subset(
permutation_dataset, range(idx, len(permutation_dataset))
)
data_loader = torch.utils.data.DataLoader(
new_dataset,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=num_workers,
)
def compute_distance_and_save(
permutation_dataset: PermutationPairsDataset,
hdfstore: File,
corrval_key: str,
batch_size: int = 20000,
num_workers: int = 8,
distance: str = "correlation",
) -> None:
data_loader = torch.utils.data.DataLoader(
permutation_dataset,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=num_workers,
)
log.info("Computing distances using {}...".format(distance))
completed = False
error_idx = (0, 0, 0, 0)
repeat_count = 0
while not completed:
try:
for s1, s2 in tqdm(data_loader):
idx1, feat1 = s1
idx2, feat2 = s2
idx1 = idx1.data.numpy()
idx2 = idx2.data.numpy()
# feat1 = hdfstore[feature_output_key][idx1, :]
# feat2 = hdfstore[feature_output_key][idx2, :]
# feat1 = torch.tensor(feat1).cuda()
# feat2 = torch.tensor(feat2).cuda()
# compute correlation
if distance == "correlation":
rval = pearsonr_batch(feat1.cuda(), feat2.cuda())
elif distance == "l1":
rval = ln_batch(feat1.cuda(), feat2.cuda(), n=1)
elif distance == "l2":
rval = ln_batch(feat1.cuda(), feat2.cuda(), n=2)
data = hdfstore[corrval_key][idx1.min() : idx1.max() + 1, :]
data[idx1 - idx1.min(), idx2] = rval.cpu().data.numpy().flatten()
hdfstore[corrval_key][idx1.min() : idx1.max() + 1, :] = data
log.info("Last computed: idx1: {}, idx2: {}".format(idx1[-1], idx2[-1]))
completed = True
except Exception as e:
log.error(e)
log.error(traceback.format_exc())
log.info(
"Last batch computed: ({}, {}) ~ ({}, {})".format(
idx1[0], idx2[0], idx1[-1], idx2[-1]
)
)
if error_idx == (idx1[0], idx2[0], idx1[-1], idx2[-1]):
log.info("repeating the same batch...")
repeat_count += 1
finally:
del data_loader
if not completed:
if repeat_count > 1000:
log.error("repeating the same batch over and over...")
log.info("exiting...")
break
log.info(
"Restarting data loader from ({}, {})...".format(idx1[0], idx2[0])
)
error_idx = (idx1[0], idx2[0], idx1[-1], idx2[-1])
idx = idx1[0] * permutation_dataset.datalen + idx2[0]
new_dataset = Subset(
permutation_dataset, range(idx, len(permutation_dataset))
)
data_loader = torch.utils.data.DataLoader(
new_dataset,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=num_workers,
)
class ImgCorrelationDataProcessorV2:
def __init__(self, hdfstore: File) -> None:
self.imgnames = hdfstore["/feature_output/imgname"][:].astype("U")
self.axes_of_interest = self.generate_axes_of_interest()
self.objnames = np.unique(np.array([c.split("-")[0] for c in self.imgnames]))
@staticmethod
def generate_axes_of_interest() -> list:
axes = ["x", "y", "p", "r", "w"]
axis_of_interest = []
for choose in range(1, 7):
for comb in combinations(axes, choose):
axis_of_interest.append(functools.reduce(lambda a, b: a + b, comb))
axis_of_interest.sort()
return axis_of_interest
def cut_corrmat(
self,
hdfstore: File,
num_objs: int,
post_processed: bool = False,
pp_exclusion: str = "soft",
) -> None:
if not hasattr(self, "objnames_buffer"):
self.objnames_buffer = self.objnames
self.imgnames_buffer = self.imgnames
obj_per_category = int(num_objs / 20)
obj_idxs = np.array(
[
v + 10 * cat
for cat in range(20)
for v in np.sort(np.random.choice(10, obj_per_category, replace=False))
]
)
self.objnames = self.objnames_buffer[obj_idxs]
# cut image names
img_idxs_start = obj_idxs * 11 * 31
img_idxs_end = (obj_idxs + 1) * 11 * 31
img_idxs = np.array(
[np.array([range(a, b)]) for (a, b) in zip(img_idxs_start, img_idxs_end)]
).flatten()
self.imgnames = self.imgnames_buffer[img_idxs]
# cut corr matrix
if post_processed:
cval_matrix = hdfstore["/pairwise_correlation/postprocessed"]
key_head = "/pairwise_correlation/postprocessed/{}".format(pp_exclusion)
if pp_exclusion == "hard":
cval_orig = hdfstore["/pairwise_correlation/original"]
else:
cval_matrix = hdfstore["/pairwise_correlation/original"]
key_head = "/pairwise_correlation/original"
mat_list = []
for i in obj_idxs:
obj_mat_list = []
for j in obj_idxs:
obj_mat = cval_matrix[
i * 11 * 31 : (i + 1) * 11 * 31, j * 11 * 31 : (j + 1) * 11 * 31
]
obj_mat_list.append(obj_mat)
obj_mat_row = np.concatenate(obj_mat_list, axis=1)
mat_list.append(obj_mat_row)
mat = np.concatenate(mat_list)
try:
hdfstore[key_head + "_{}".format(num_objs)] = mat
hdfstore[key_head + "_{}_obj_idx".format(num_objs)] = obj_idxs
except RuntimeError:
pass
def excluded_to_zero(
self, corr_mat_sameobj: cp.ndarray, axis: str, exc_dist: int, pure: bool = True
) -> cp.ndarray:
# corr_mat_obj has to be a cut-out copy of the original matrix!!!
# create list with axis of interest in the alphabetical order
if exc_dist != 0:
# first create a 11x11 sampling mask per axis
sampling_mask = 1 - (
tri(11, 11, exc_dist - 1, dtype=float)
- tri(11, 11, -exc_dist, dtype=float)
)
sampling_mask[sampling_mask == 0] = cp.nan
# pure transform
if pure:
# cut out the axis of interest
idx = self.axes_of_interest.index(axis)
corr_mat_axis = cp.copy(
corr_mat_sameobj[idx * 11 : (idx + 1) * 11, idx * 11 : (idx + 1) * 11]
)
# sample with the sampling mask
if exc_dist != 0:
corr_mat_axis = cp.multiply(corr_mat_axis, sampling_mask)
return corr_mat_axis
elif exc_dist != 0:
contain_ax = cp.array(
[
[
cp.array([c in a for c in axis]).all()
for a in self.axes_of_interest
]
],
dtype=int,
)
# selects relevant axis
repeat_mask = contain_ax * contain_ax.T
# create sampling mask of size 11 (# image in each series) x 31 (total number of axes)
repeat_mask = cp.repeat(cp.repeat(repeat_mask, 11, axis=1), 11, axis=0)
sampling_mask_whole = cp.tile(sampling_mask, (31, 31))
sampling_mask_whole = cp.multiply(sampling_mask_whole, repeat_mask)
# sample from the correlation matrix using the sampling mask
corr_mat_sameobj = cp.multiply(sampling_mask_whole, corr_mat_sameobj)
# cut out only the samples where starting image is contained within the transformation series "axis"
idx = self.axes_of_interest.index(axis)
corr_mat_sameobj = corr_mat_sameobj[idx * 11 : (idx + 1) * 11, :]
return corr_mat_sameobj
else:
idx = self.axes_of_interest.index(axis)
corr_mat_sameobj = corr_mat_sameobj[idx * 11 : (idx + 1) * 11, :]
return corr_mat_sameobj
def get_coord_corrmat(self, obj_name: str, ax: str = "all") -> Tuple[int, int]:
idx = np.where(self.objnames == obj_name)[0][0]
if ax == "all":
return idx * 11 * 31, (idx + 1) * 11 * 31
else:
ax_idx = self.axes_of_interest.index(ax)
return idx * 11 * 31 + ax_idx * 11, idx * 11 * 31 + (ax_idx + 1) * 11
def get_top1_cval_other_object(
self,
cval_matrix_hdf: File,
obj: str,
ax: str,
cval_arr_sameobj: np.ndarray,
distance="correlation",
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
c1, c2 = self.get_coord_corrmat(obj, ax=ax)
cval_mat_np = cp.array(cval_matrix_hdf[c1:c2, :])
# zero masking the same object
c3, c4 = self.get_coord_corrmat(obj)
cval_mat_np[:, c3:c4] = 0
if distance == "correlation":
# get top1 cval per row
top1_cval = cval_mat_np.max(axis=1)
top1_idx = cval_mat_np.argmax(axis=1)
# get image rank
sameobj_imagerank = []
for col in cval_arr_sameobj.T:
comparison_mask = cp.tile(col, (cval_mat_np.shape[1], 1)).T
count_col = (cval_mat_np > comparison_mask).sum(axis=1)
count_col = count_col.get()
count_col = count_col.astype(np.float)
count_col[np.isnan(col)] = np.nan
sameobj_imagerank.append(count_col)
else:
# get top1 closest per row
top1_cval = cval_mat_np.min(axis=1)
top1_idx = cval_mat_np.argmin(axis=1)
# get image rank
sameobj_imagerank = []
for col in cval_arr_sameobj.T:
comparison_mask = cp.tile(col, (cval_mat_np.shape[1], 1)).T
count_col = (cval_mat_np < comparison_mask).sum(axis=1)
count_col = count_col.get()
count_col = count_col.astype(np.float)
count_col[np.isnan(col)] = np.nan
sameobj_imagerank.append(count_col)
return top1_idx.get(), top1_cval.get(), np.array(sameobj_imagerank).T
def get_top_per_object(
self, cval_matrix_hdf: File, obj: str, ax: str, distance: str = "correlation"
) -> Tuple[np.ndarray, np.ndarray]:
c1, c2 = self.get_coord_corrmat(obj, ax=ax)
cval_mat_np = cval_matrix_hdf[c1:c2, :]
top1_cvals = []
top1_idxs = []
for o in self.objnames:
if not o == obj:
c3, c4 = self.get_coord_corrmat(o)
cval_mat_obj = cval_mat_np[:, c3:c4]
if distance == "correlation":
top1_cvals.append(cval_mat_obj.max(axis=1))
| |
and smooth", 72],
["Wanyue", "婉约", "composed", 72],
["Kee", "可恶", "hateful", 72],
["Zhuojue", "卓绝", "outstanding", 72],
["Zuozuo", "做作", "artificial", 72],
["Yinxian", "阴险", "sinister", 71],
["Feimei", "肥美", "lush", 71],
["Jinglian", "精练", "concise", 71],
["Haohao", "浩浩", "vast", 71],
["Meijin", "没劲", "insipid", 71],
["Jieao", "桀骜", "unruly", 71],
["Modeng", "摩登", "modern", 71],
["Shuaiqi", "帅气", "charming", 71],
["Lawei", "辣味", "hot", 70],
["Zide", "自得", "contented", 70],
["Tengteng", "腾腾", "steaming", 70],
["Danran", "淡然", "indifferent", 70],
["Aosang", "懊丧", "depressed", 70],
["Gangjian", "刚健", "vigorous", 70],
["Zhuanheng", "专横", "despotic", 70],
["Yongrong", "雍容", "graceful", 69],
["Luomo", "落寞", "desolate", 69],
["Genggeng", "耿耿", "dedicated", 69],
["Laocheng", "老成", "experienced", 69],
["Gaishi", "盖世", "unparalleled", 69],
["Changliang", "敞亮", "bright", 69],
["Chouchang", "惆怅", "disconsolate", 69],
["Beiliang", "悲凉", "dismal", 69],
["Qiwei", "奇伟", "extraordinary", 69],
["Lisheng", "厉声", "fierce", 69],
["Zihong", "紫红", "purplish red", 68],
["Changda", "畅达", "smooth", 68],
["Anfen", "安分", "law-abiding", 68],
["Jianwang", "健忘", "forgetful", 68],
["Tanxin", "贪心", "greedy", 67],
["Fenyun", "纷纭", "diverse", 67],
["Zhibai", "直白", "straightforward", 67],
["Jiaozha", "狡诈", "deceitful", 67],
["Shenguang", "深广", "deep and broad", 67],
["Jiduo", "极多", "extremely numerous", 67],
["Xinzhi", "新制", "newly-made", 67],
["Xinzui", "心醉", "elated", 67],
["Pingshun", "平顺", "smooth", 67],
["Toumo", "偷摸", "suspicious", 67],
["Junqiao", "俊俏", "good-looking", 67],
["Xinla", "辛辣", "pungent", 66],
["Qiqi", "萋萋", "luxuriant", 66],
["Jinchi", "矜持", "reserved", 66],
["Kuangbao", "狂暴", "wild", 66],
["Kunjuan", "困倦", "sleepy", 66],
["Zichi", "自持", "self-sustaining", 65],
["Huanghuang", "惶惶", "fearful", 65],
["Jucu", "局促", "cramped", 65],
["Haoqiang", "好强", "strive to excel", 65],
["Kouke", "口渴", "thirsty", 65],
["Bogu", "博古", "well-informed in ancient learning", 65],
["Fengzu", "丰足", "plentiful", 65],
["Gaoao", "高傲", "arrogant", 64],
["Tieqing", "铁青", "pale", 64],
["Zhicheng", "至诚", "most sincere", 64],
["Zanduan", "暂短", "fleeting", 64],
["Xindao", "新到", "newly-arrived", 64],
["Wenruo", "文弱", "frail", 64],
["Naoren", "恼人", "irritating", 64],
["Nana", "娜娜", "gentle", 64],
["Jiaonen", "娇嫩", "tender and delicate", 64],
["Leiruo", "羸弱", "emaciated", 63],
["Jueshi", "绝世", "peerless", 63],
["Zaore", "燥热", "dry and hot", 63],
["Runze", "润泽", "favor", 63],
["Ganshang", "感伤", "sad", 63],
["Xinxu", "心虚", "afraid", 63],
["Jianzhi", "间质", "mesenchymal", 62],
["Zhenan", "镇安", "calm", 62],
["Mihu", "迷糊", "blurry", 62],
["Mili", "迷离", "blurred", 62],
["Danhan", "胆寒", "scared", 62],
["Bingruo", "病弱", "feeble", 62],
["Ehen", "恶狠", "wicked", 62],
["Xinsui", "心碎", "brokenhearted", 62],
["Qixiu", "奇秀", "wonderfully beautiful", 62],
["Heshen", "合身", "good-fitting", 62],
["Xiemen", "邪门", "weird", 61],
["Shutou", "熟透", "thoroughly ripe", 61],
["Duanxu", "断续", "off and on", 61],
["Kunjiong", "困窘", "embarrassed", 61],
["Qimei", "凄美", "sad touching", 61],
["Hanchang", "酣畅", "hearty", 60],
["Gengzhi", "耿直", "straightforward", 60],
["Zhishuang", "直爽", "frank", 60],
["Baijing", "白净", "fair and clear", 60],
["Lvzhi", "率直", "straightforward", 60],
["Boya", "博雅", "learned", 60],
["Taoran", "陶然", "carefree", 59],
["Leiren", "累人", "exhausting", 59],
["Hunyuan", "浑圆", "perfectly round", 59],
["Qianbao", "浅薄", "superficial", 59],
["Jianli", "尖厉", "sharp", 59],
["Naoteng", "闹腾", "restless", 58],
["Baixi", "白皙", "fair", 58],
["Fangsi", "放肆", "dissolute", 58],
["Pingyi", "平易", "amiable", 58],
["Guangxian", "光鲜", "attractive", 58],
["Huoran", "豁然", "broadminded", 57],
["Xiluo", "稀落", "scattered", 57],
["Baonve", "暴虐", "tyrannical", 57],
["Eran", "愕然", "stunned", 57],
["Jizhou", "急骤", "rapid", 57],
["Guya", "古雅", "classically elegant", 57],
["Bingshuang", "冰霜", "incorruptible", 57],
["Jingran", "井然", "orderly", 57],
["Xiangchun", "香醇", "mellow", 56],
["Qingpiao", "轻飘", "light", 56],
["Tanchi", "贪吃", "gluttonous", 56],
["Jianmo", "缄默", "silent", 56],
["Jianlve", "简略", "brief", 56],
["Xianggan", "相干", "coherent", 56],
["Xinxin", "欣欣", "happy", 56],
["Wumian", "无眠", "sleepless", 56],
["Haohe", "好喝", "tasty", 56],
["Tuqi", "土气", "rustic", 56],
["Tingdang", "停当", "ready", 56],
["Yian", "义安", "peaceful", 56],
["Fengya", "风雅", "elegant", 55],
["Chimu", "迟暮", "late in life", 55],
["Weiran", "蔚然", "magnificent", 55],
["Cuxin", "粗心", "careless", 55],
["Zhihuan", "滞缓", "slow", 55],
["Wuque", "无缺", "complete", 55],
["Dunshi", "敦实", "stocky", 55],
["Gouge", "够格", "qualified", 55],
["Gute", "古特", "antique", 55],
["Xumou", "蓄谋", "premeditated", 54],
["Quemiao", "缺苗", "sparse", 54],
["Chilie", "炽烈", "blazing", 54],
["Nuoruo", "懦弱", "spiritless", 54],
["Ansheng", "安生", "peaceful", 54],
["Guao", "古奥", "ancient and abstruse", 54],
["Jiuzui", "酒醉", "drunk", 53],
["Yuyu", "郁郁", "elegant", 53],
["Xushe", "虚设", "nominal", 53],
["Mishi", "密实", "dense", 53],
["Taxing", "塔形", "tower-shaped", 53],
["Xianhui", "贤惠", "virtuous", 52],
["Shaoduo", "稍多", "frequent", 52],
["Duanshao", "短少", "deficient", 52],
["Keshui", "瞌睡", "sleepy", 52],
["Huanyu", "欢愉", "happy", 52],
["Mingyan", "明艳", "bright-colored", 52],
["Shemi", "奢靡", "wasteful", 52],
["Xile", "喜乐", "pleasant", 52],
["Lilian", "历练", "informed and experienced", 52],
["Renxing", "任性", "willful", 52],
["Yinsen", "阴森", "gloomy", 51],
["Kuochao", "阔绰", "extravagant", 51],
["Jinhong", "金红", "yellowish red", 51],
["Guiyi", "诡异", "strange", 51],
["Zhizhuo", "稚拙", "simple and artless", 51],
["Lanshu", "烂熟", "thoroughly cooked", 51],
["Yisun", "易损", "vulnerable", 51],
["Zhiniu", "执拗", "obstinate", 51],
["Xinjiao", "心焦", "distressed", 51],
["Shunyan", "顺眼", "pleasing to the eyes", 50],
["Luqi", "陆栖", "terrestrial", 50],
["Mengdong", "懵懂", "ignorant", 50],
["Jiliao", "寂寥", "lonely", 50],
["Qijue", "奇绝", "wonderful", 50],
["Duoshi", "多事", "meddlesome", 50],
["Xiangnong", "香浓", "spicy", 49],
["Lanshan", "阑珊", "waning", 49],
["Tiezhu", "铁铸", "strong", 49],
["Yangqi", "洋气", "foreign style", 49],
["Dezhi", "得志", "successful", 49],
["Ganba", "干巴", "dry", 49],
["Hanxin", "寒心", "disappointed", 49],
["Yapao", "哑炮", "dud", 49],
["Aiwan", "哀婉", "sorrowful", 49],
["Guzhuo", "古拙", "unadorned", 49],
["Lengji", "冷寂", "cold and still", 49],
["Zhennu", "震怒", "furious", 48],
["Biejiao", "蹩脚", "inferior", 48],
["Yinu", "易怒", "testy", 48],
["Sujing", "肃静", "solemnly silent", 47],
["Chizhong", "持重", "prudent", 47],
["Daguan", "达观", "philosphical", 46],
["Zhenge", "真格", "real", 46],
["Danjing", "淡静", "quiescent", 46],
["Changlong", "昌隆", "prosperous", 46],
["Koumen", "抠门", "stingy", 46],
["Guaidan", "怪诞", "weird", 46],
["Gunang", "鼓囊", "bulging", 45],
["Xigui", "稀贵", "precious", 45],
["Kuangzao", "狂躁", "manic", 45],
["Qienuo", "怯懦", "timid", 45],
["Kuaiwei", "快慰", "pleased", 45],
["Shitai", "失态", "rude", 45],
["Shunliu", "顺流", "afloat", 44],
["Feihou", "肥厚", "plump", 44],
["Yaotiao", "窈窕", "slender", 44],
["Kandie", "看跌", "bearish", 44],
["Kankong", "看空", "bearish", 44],
["Muxuan", "目眩", "dizzy", 44],
["Shanqing", "煽情", "sensational", 44],
["Jianke", "尖刻", "caustic", 44],
["Tanghuang", "堂皇", "majestic", 44],
["Houcheng", "厚诚", "sincere", 44],
["Chushen", "出神", "lost", 44],
["Quanfu", "全副", "complete", 44],
["Gaisi", "该死", "damn", 43],
["Pengsong", "蓬松", "fluffy", 43],
["Laola", "老辣", "vicious", 43],
["Xisui", "细碎", "in broken bits", 43],
["Chunmei", "纯美", "fine", 43],
["Kuangye", "狂野", "wild", 43],
["Wufen", "无分", "unqualified", 43],
["Zhanjing", "战兢", "trembling", 43],
["Fenfen", "愤愤", "indignant", 43],
["Xinfan", "心烦", "annoyed", 43],
["Guangyuan", "广远", "far-reaching", 43],
["Meisu", "媚俗", "kitsch", 43],
["Houpu", "厚朴", "magnolol", 43],
["Bankai", "半开", "ajar", 43],
["Qiwan", "凄婉", "touching", 43],
["Heishou", "黑瘦", "dark and thin", 42],
["Shunhe", "顺和", "affable", 42],
["Tongzhi", "童稚", "childish", 42],
["Wenwen", "温文", "polite", 42],
["Wenwan", "温婉", "gentle", 42],
["Tiandan", "恬淡", "indifferent to fame or gain", 42],
["Tante", "忐忑", "disturbed", 42],
["Xinhan", "心寒", "fearful", 42],
["Biaohan", "彪悍", "valiant", 42],
["Mangcang", "莽苍", "vast and hazy", 41],
["Suoran", "索然", "dull", 41],
["Jiongkun", "窘困", "in distress", 41],
["Yingban", "硬板", "firm", 41],
["Qingtian", "清甜", "sweet", 41],
["Huiqi", "晦气", "unlucky", 41],
["Biemen", "憋闷", "oppressed", 41],
["Fenmen", "愤懑", "resentful", 41],
["Daipin", "待聘", "awaiting employment", 41],
["Tongshun", "通顺", "smooth", 40],
["Duqi", "赌气", "spiteful", 40],
["Qiangong", "谦恭", "courteous", 40],
["Jingjue", "精绝", "exquisite", 40],
["Huanyue", "欢悦", "joyous", 40],
["Weiqing", "未清", "not clear", 40],
["Zhayan", "扎眼", "garish", 40],
["Kaiwei", "开胃", "appetizing", 40],
["Zhouzheng", "周正", "proper", 40],
["Shiquan", "十全", "perfect", 40],
["Pinzui", "贫嘴", "loquacious", 39],
["Yaomu", "耀目", "eye-catching", 39],
["Jingwei", "精微", "subtle", 39],
["Kuangfang", "狂放", "wild", 39],
["Qianqiang", "牵强", "forced", 39],
["Fuhua", "浮华", "ostentatious", 39],
["Kangshen", "抗渗", "impervious", 39],
["Ganbie", "干瘪", "withered", 39],
["Hanchen", "寒碜", "shabby", 39],
["Jianzhen", "坚贞", "firm", 39],
["Juejiang", "倔犟", "stubborn", 39],
["Fenrao", "纷扰", "troubled", 38],
["Jingu", "紧固", "tight", 38],
["Jingzhuang", "精壮", "capable", 38],
["Qinggao", "清高", "aloof from worldly affairs", 38],
["Dula", "毒辣", "sinister", 38],
["Zasui", "杂碎", "mixed up", 38],
["Muran", "木然", "wooden", 38],
["Yibian", "易变", "instable", 38],
["Huimin", "慧敏", "intelligent", 38],
["Daizha", "待闸", "waiting", 38],
["Mijian", "弥坚", "strong", 38],
["Jiaogui", "娇贵", "pampered", 38],
["Lingding", "伶仃", "lonely", 38],
["Fengyu", "丰腴", "plentiful", 38],
["Xiangcui", "香脆", "cripy", 37],
["Piaoling", "飘零", "faded and fallen", 37],
["Manhao", "蛮好", "good", 37],
["Jingyong", "经用", "durable", 37],
["Baida", "白搭", "useless", 37],
["Xuanmiao", "玄妙", "mysterious", 37],
["Lianyan", "潋滟", "billowing", 37],
["Qingqu", "清癯", "thin", 37],
["Shaozhuang", "少壮", "young and strong", 37],
["Anhao", "安好", "well", 37],
["Qihan", "奇寒", "extraordinarily cold", 37],
["Fangsuo", "防缩", "shrinkproof", 36],
["Mimeng", "迷蒙", "hazy", 36],
["Jinju", "近距", "short-range", 36],
["Juemei", "绝美", "beautiful", 36],
["Zaotou", "糟透", "ruined", 36],
["Guku", "孤苦", "wretched", 36],
["Jiaomei", "娇美", "sweet and pretty", 36],
["Shanbian", "善变", "fickle", 36],
["Jiaoheng", "骄横", "overbearing", 35],
["Xiaer", "遐迩", "far and wide", 35],
["Xisong", "稀松", "sloppy", 35],
["Shouchang", "瘦长", "lanky", 35],
["Jiongjiong", "炯炯", "bright", 35],
["Lanshang", "滥伤", "excessively injurious", 35],
["Huashuang", "滑爽", "smooth", 35],
["Zhaoyao", "招摇", "free", 35],
["Duizhi", "对直", | |
= Returns(
window_length=returns_length,
mask=(AssetExists() | SingleAsset(asset=target)),
)
return super().__new__(
cls,
base_factor=returns,
target=returns[target],
correlation_length=correlation_length,
mask=mask,
)
class RollingLinearRegressionOfReturns(RollingLinearRegression):
"""
Perform an ordinary least-squares regression predicting the returns of all
other assets on the given asset.
Parameters
----------
target : zipline.assets.Asset
The asset to regress against all other assets.
returns_length : int >= 2
Length of the lookback window over which to compute returns. Daily
returns require a window length of 2.
regression_length : int >= 1
Length of the lookback window over which to compute each regression.
mask : zipline.pipeline.Filter, optional
A Filter describing which assets should be regressed against the target
asset each day.
Notes
-----
Computing this factor over many assets can be time consuming. It is
recommended that a mask be used in order to limit the number of assets over
which regressions are computed.
This factor is designed to return five outputs:
- alpha, a factor that computes the intercepts of each regression.
- beta, a factor that computes the slopes of each regression.
- r_value, a factor that computes the correlation coefficient of each
regression.
- p_value, a factor that computes, for each regression, the two-sided
p-value for a hypothesis test whose null hypothesis is that the slope is
zero.
- stderr, a factor that computes the standard error of the estimate of each
regression.
For more help on factors with multiple outputs, see
:class:`zipline.pipeline.CustomFactor`.
Examples
--------
Let the following be example 10-day returns for three different assets::
SPY MSFT FB
2017-03-13 -.03 .03 .04
2017-03-14 -.02 -.03 .02
2017-03-15 -.01 .02 .01
2017-03-16 0 -.02 .01
2017-03-17 .01 .04 -.01
2017-03-20 .02 -.03 -.02
2017-03-21 .03 .01 -.02
2017-03-22 .04 -.02 -.02
Suppose we are interested in predicting each stock's returns from SPY's
over rolling 5-day look back windows. We can compute rolling regression
coefficients (alpha and beta) from 2017-03-17 to 2017-03-22 by doing::
regression_factor = RollingRegressionOfReturns(
target=sid(8554),
returns_length=10,
regression_length=5,
)
alpha = regression_factor.alpha
beta = regression_factor.beta
The result of computing ``alpha`` from 2017-03-17 to 2017-03-22 gives::
SPY MSFT FB
2017-03-17 0 .011 .003
2017-03-20 0 -.004 .004
2017-03-21 0 .007 .006
2017-03-22 0 .002 .008
And the result of computing ``beta`` from 2017-03-17 to 2017-03-22 gives::
SPY MSFT FB
2017-03-17 1 .3 -1.1
2017-03-20 1 .2 -1
2017-03-21 1 -.3 -1
2017-03-22 1 -.3 -.9
Note that SPY's column for alpha is all 0's and for beta is all 1's, as the
regression line of SPY with itself is simply the function y = x.
To understand how each of the other values were calculated, take for
example MSFT's ``alpha`` and ``beta`` values on 2017-03-17 (.011 and .3,
respectively). These values are the result of running a linear regression
predicting MSFT's returns from SPY's returns, using values starting at
2017-03-17 and looking back 5 days. That is, the regression was run with
x = [-.03, -.02, -.01, 0, .01] and y = [.03, -.03, .02, -.02, .04], and it
produced a slope of .3 and an intercept of .011.
See Also
--------
:class:`zipline.pipeline.factors.RollingPearsonOfReturns`
:class:`zipline.pipeline.factors.RollingSpearmanOfReturns`
"""
window_safe = True
def __new__(cls,
target,
returns_length,
regression_length,
mask=NotSpecified):
# Use the `SingleAsset` filter here because it protects against
# inputting a non-existent target asset.
returns = Returns(
window_length=returns_length,
mask=(AssetExists() | SingleAsset(asset=target)),
)
return super().__new__(
cls,
dependent=returns,
independent=returns[target],
regression_length=regression_length,
mask=mask,
)
class SimpleBeta(CustomFactor, StandardOutputs):
"""
Factor producing the slope of a regression line between each asset's daily
returns to the daily returns of a single "target" asset.
Parameters
----------
target : zipline.Asset
Asset against which other assets should be regressed.
regression_length : int
Number of days of daily returns to use for the regression.
allowed_missing_percentage : float, optional
Percentage of returns observations (between 0 and 1) that are allowed
to be missing when calculating betas. Assets with more than this
percentage of returns observations missing will produce values of
NaN. Default behavior is that 25% of inputs can be missing.
"""
window_safe = True
dtype = float64_dtype
params = ('allowed_missing_count',)
@expect_types(
target=Asset,
regression_length=int,
allowed_missing_percentage=(int, float),
__funcname='SimpleBeta',
)
@expect_bounded(
regression_length=(3, None),
allowed_missing_percentage=(0.0, 1.0),
__funcname='SimpleBeta',
)
def __new__(cls,
target,
regression_length,
allowed_missing_percentage=0.25):
daily_returns = Returns(
window_length=2,
mask=(AssetExists() | SingleAsset(asset=target)),
)
allowed_missing_count = int(
allowed_missing_percentage * regression_length
)
return super().__new__(
cls,
inputs=[daily_returns, daily_returns[target]],
window_length=regression_length,
allowed_missing_count=allowed_missing_count,
)
def compute(self,
today,
assets,
out,
all_returns,
target_returns,
allowed_missing_count):
vectorized_beta(
dependents=all_returns,
independent=target_returns,
allowed_missing=allowed_missing_count,
out=out,
)
def graph_repr(self):
return "{}({!r}, {}, {})".format(
type(self).__name__,
str(self.target.symbol), # coerce from unicode to str in py2.
self.window_length,
self.params['allowed_missing_count'],
)
@property
def target(self):
"""Get the target of the beta calculation.
"""
return self.inputs[1].asset
def __repr__(self):
return "{}({}, length={}, allowed_missing={})".format(
type(self).__name__,
self.target,
self.window_length,
self.params['allowed_missing_count'],
)
def vectorized_beta(dependents, independent, allowed_missing, out=None):
"""
Compute slopes of linear regressions between columns of ``dependents`` and
``independent``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
independent : np.array[N, 1]
Independent variable of the regression
allowed_missing : int
Number of allowed missing (NaN) observations per column. Columns with
more than this many non-nan observations in either ``dependents`` or
``independents`` will output NaN as the regression coefficient.
out : np.array[M] or None, optional
Output array into which to write results. If None, a new array is
created and returned.
Returns
-------
slopes : np.array[M]
Linear regression coefficients for each column of ``dependents``.
"""
# Cache these as locals since we're going to call them multiple times.
nan = np.nan
isnan = np.isnan
N, M = dependents.shape
if out is None:
out = np.full(M, nan)
# Copy N times as a column vector and fill with nans to have the same
# missing value pattern as the dependent variable.
#
# PERF_TODO: We could probably avoid the space blowup by doing this in
# Cython.
# shape: (N, M)
independent = np.where(
isnan(dependents),
nan,
independent,
)
# Calculate beta as Cov(X, Y) / Cov(X, X).
# https://en.wikipedia.org/wiki/Simple_linear_regression#Fitting_the_regression_line # noqa
#
# NOTE: The usual formula for covariance is::
#
# mean((X - mean(X)) * (Y - mean(Y)))
#
# However, we don't actually need to take the mean of both sides of the
# product, because of the folllowing equivalence::
#
# Let X_res = (X - mean(X)).
# We have:
#
# mean(X_res * (Y - mean(Y))) = mean(X_res * (Y - mean(Y)))
# (1) = mean((X_res * Y) - (X_res * mean(Y)))
# (2) = mean(X_res * Y) - mean(X_res * mean(Y))
# (3) = mean(X_res * Y) - mean(X_res) * mean(Y)
# (4) = mean(X_res * Y) - 0 * mean(Y)
# (5) = mean(X_res * Y)
#
#
# The tricky step in the above derivation is step (4). We know that
# mean(X_res) is zero because, for any X:
#
# mean(X - mean(X)) = mean(X) - mean(X) = 0.
#
# The upshot of this is that we only have to center one of `independent`
# and `dependent` when calculating covariances. Since we need the centered
# `independent` to calculate its variance in the next step, we choose to
# center `independent`.
# shape: (N, M)
ind_residual = independent - nanmean(independent, axis=0)
# shape: (M,)
covariances = nanmean(ind_residual * dependents, axis=0)
# We end up with different variances in each column here because each
# column may have a different subset of the data dropped due to missing
# data in the corresponding dependent column.
# shape: (M,)
independent_variances = nanmean(ind_residual ** 2, axis=0)
# shape: (M,)
np.divide(covariances, independent_variances, out=out)
# Write nans back to locations where we have more then allowed number of
# missing entries.
nanlocs = isnan(independent).sum(axis=0) > allowed_missing
out[nanlocs] = nan
return out
def vectorized_pearson_r(dependents, independents, allowed_missing, out=None):
"""
Compute Pearson's r between columns of ``dependents`` and ``independents``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
independents : np.array[N, M] or np.array[N, 1]
Independent variable(s) of the regression. If a single | |
import csv
import h5py
import logging
import logging.config
import numpy as np
import os
from os import path
import pandas as pd
import pathlib
import re
import xlsxwriter
class CreateCsv:
"""Class combines csv linking IDs to csv containing feature info.
Merge linked track and object IDs to corresponding feature data to
produce a csv output file that can be visualized in FlowJo.
"""
def __init__(self, ims_filename, dir_name, meta_dir_name, logger=None):
"""Open .ims file for reading; h5py.File acts like a dictionary.
Args:
ims_filename (:obj:`str`): Name of the selected Imaris file
dir_name (:obj:`str`): Output csv collection
meta_dir_name (:obj:`str`): Output metadata directory
"""
#: Set up the logger
logging.basicConfig(
format='%(asctime)s-%(name)s-%(levelname)s-%(message)s',
datefmt='%b-%d-%y %H:%M:%S')
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
self.ims_filename = ims_filename
self.dir_name = dir_name
self.meta_dir_name = meta_dir_name
self.f = h5py.File(self.ims_filename, 'r')
def round_to_six(self, num):
"""Round values to six significant figures
Args:
num (:obj:`int`): Num to be rounded to 6 significant figures
Returns:
A number rounded to six significant figures
"""
if num != 0:
if np.isnan(num) != True:
num = np.round(num, -int(np.floor(np.log10(abs(num)))) + 5)
elif num == 0:
pass
return num
def get_df_from_csv(self, dirname, chan, chan_name, csv_substring):
"""Read intermediate csv files containing feature data
(``extract_ims_data.py`` output) or ID data (``link_ims_ids.py``
output) for each channel, and store in dataframes. ``chan``
represents attribute names within the ``Scene8/Content`` keys
of the .ims files with names ``MegaSurfaces0`` or ``Points0``.
Each attribute contains data belonging to particular channels.
The argument chan_name differs from chan because while chan
might have a more general name such as ``Points0``, chan_name is
extracted from the Imaris file's metadata, converted from byte to
string, and stored as **chan_name**. csv_substring is the
substring of the csv file that gets read in; can be `trackdf_`/
`objectdf_` for outputs of the first module
(``extract_ims_data.py``), or empty string for outputs of the
second module, ``link_ims_ids.py`` (links `ID_Object` and
`TrackID`).
Args:
dirname (:obj:`str`): Output csv collection provided by user
chan (:obj:`str`): attribute name in ``Scene8/Content``
chan_name (:obj:`str`): Channel name entered in Imaris
csv_substring (:obj:`str`): Temp .csv prefix (ex: trackdf_)
Returns:
Pandas dataframe created from intermediate csv files.
"""
keepsame = {'ID_Time'}
#: Read csv
temp_string = csv_substring + chan + ".csv"
temp_path = dirname/temp_string
df = pd.read_csv(temp_path)
#: Remove "Unnamed" columns:
df = df.loc[:, ~df.columns.str.contains('^Unnamed')]
#: suffix chan name to all headers except 'ID_Object, 'ID_Time'
if len(df.columns) > 0:
#: Suffix col names except some columns (keep same=ID_Time)
df.columns = ['{}{}'.format(
c, '' if c in keepsame else chan_name) for c in df.columns]
df.columns = df.columns.str.replace('__', '_')
#: Remove intermediate csv file
self.logger.debug("Remove line file_to_remove.unlink() to debug.")
self.logger.debug(
"CSV files can indicate where in the process an issue begins.")
file_to_remove = temp_path
file_to_remove.unlink()
return df
def get_overall(self, overall_df, chan_name):
"""Extract overall data from object data
This reads the output from the ``get_df_from_csv()`` function
and extracts overall data from the df containing non-track data.
Note that in the second module, ``extract_ims_data.py``,
data tagged `Overall` was assigned an `ID_Object` of -1
Args:
overall_df: Df obtained `ID_Object` of object df < 0.
chan_name (:obj:`str`): Channel name entered in Imaris
Returns:
DF containing overall data; formatted like Imaris version
"""
overall_df.dropna(axis=1, how='all', inplace=True)
#: All ID_Objects == -1 belong to Overall. Replace with np.NaN
overall_df['ID_Object' + chan_name] = \
overall_df['ID_Object'+chan_name].replace(
-1.0, np.NaN, inplace=True)
#: Replace time = -1.0 with np.NaN
overall_df['ID_Time'].replace(-1.0, np.NaN, inplace=True)
overall_df.reset_index()
#: Rearrange df to match exact format exported by Imaris file
overall_df = pd.melt(
overall_df, id_vars=['ID_Time', 'ID_Object' + chan_name],
var_name='Variable', value_name='Value')
overall_df = overall_df[
['Variable','Value','ID_Time','ID_Object'+chan_name]]
overall_df.rename(
{'ID_Time': 'Time', 'ID_Object' + chan_name: 'ID'},
axis='columns', inplace=True)
overall_df.dropna(subset=['Value'], inplace=True)
overall_df['Variable'] = overall_df['Variable'].str.replace('_', ' ')
overall_df=overall_df.dropna(axis=1,how='all')
return overall_df
def create_overall_xlsx(self,imaris_filename,meta_dirname,all_overall_dict):
"""Create overall xlsx. Each sheet represents one channel.
This function merges all Overall DFs together and write each
channel to an xlsx notebook that uses sheets to represent
individual channels
Args:
imaris_filename (:obj:`str`): Filename of Imaris file
meta_dirname (:obj:`str`): Output metadata directory
all_overall_dict: Dict key=Imaris channel, value=overall df
"""
#: Get basename from imaris filename, to prepend to Overall.xlsx
imaris_basename = imaris_filename.stem
#: Remove .ims extension
imaris_basename = imaris_basename[:-4]
#: Create a Pandas Excel writer using XlsxWriter as the engine
temp_string = imaris_basename + "_" + 'Overall.xlsx'
temp_path = meta_dirname/temp_string
writer = pd.ExcelWriter(temp_path, engine='xlsxwriter')
count = 1
for chan_name, overall_df_list in all_overall_dict.items():
for i in range(0, len(overall_df_list)):
str_i = "_"
if i >= 1:
str_i = "_" + str(i) + "_"
str_channel_name = re.sub('[^A-Za-z0-9]+', '_', chan_name)
#: Convert the dataframe to an XlsxWriter Excel object
str_channel_name_shortened = ""
if len(str_channel_name) > 25:
str_channel_name_shortened = str_channel_name[:25]
else:
str_channel_name_shortened = str_channel_name
#: Round Overall "Values" column to 6 significant digits
self.logger.debug("Converting data to 6 significant figures...")
overall_df_list[i]['Value'] = overall_df_list[i]\
['Value'].apply(self.round_to_six)
overall_df_list[i].to_excel(
writer,
sheet_name=str_channel_name_shortened + str_i + str(count),
index=False, startrow=2, startcol=0)
#: Get the xlsxwriter workbook and worksheet objects
worksheet = writer.sheets[
str_channel_name_shortened + str_i + str(count)]
#: Add original, unmodified channel name to first row
worksheet.write(0, 0, chan_name)
#: Set the column width and format.
worksheet.set_column(0, 0, 50) #: 1st, last col, width
#: Close the Pandas Excel writer and output the Excel file.
count = count + 1
writer.save()
def create_final_output(self, imaris_filename, non_overall_dfs, dirname):
"""Stores non-overall data in dataframes
Store remaining non-overall data with `TrackID` (if applicable),
`ID_Object` (if applicable), and feature data in a Pandas
dataframe.
Args:
imaris_filename (:obj:`str`): Filename of Imaris file
non_overall_dfs: dict key=channel name, value=non-overall df
dirname (:obj:`str`): Output csv collection provided by user
"""
#: Get basename from imaris filename, to prepend to channel.csv
imaris_basename = imaris_filename.stem
#: Remove .ims extension
imaris_basename = imaris_basename[:-4]
for chan_name, non_ov in non_overall_dfs.items():
#: Replace special characters from channel name (key) with _
chan_mod = re.sub('[^0-9a-zA-Z]+', '_', chan_name)
for i in range(0, len(non_ov)):
str_i = ""
if i == 1:
str_i = "_copy"
if i > 1:
str_i = "_copy " + str(i)
#: Remove _ from the front of file (due to some plugins)
for col in non_ov[i].columns:
if col[:1] == "_":
col_mod = col[1:]
non_ov[i].rename(columns={col:col_mod}, inplace=True)
#: Sort header names alphabetically
header_names = non_ov[i].columns
header_names = header_names.sort_values()
non_ov[i] = non_ov[i][header_names]
for c in non_ov[i].columns:
#: Round all but ID, TrackID, Time to 6 sigfigs
if c != "TrackID_"+chan_mod and c != "ID_Object_"+chan_mod:
if c!="ID_Time" and "TrackID" not in c:
non_ov[i][c]=non_ov[i][c].apply(self.round_to_six)
non_ov[i].columns = non_ov[i].columns.str.replace("___", "_")
non_ov[i].columns = non_ov[i].columns.str.replace("__", "_")
non_ov[i].columns = non_ov[i].columns.str.replace(
"ID_Time", "Time")
non_ov[i].columns = non_ov[i].columns.str.replace(
"ID_Object", "ID")
#: Display np.NaN values as as 'NaN' so FlowJo can view
temp_string = imaris_basename + "_" + chan_name + str_i + ".csv"
temp_path = dirname/temp_string
non_ov[i].to_csv(temp_path, index=False, na_rep='NaN')
def create_csv_fun(self):
"""Main function; combines intermediate files to produce output.
This function combines all intermediate files
(``extract_ims_data.py`` and ``link_ims_ids.py`` outputs)
to produce csv files that link IDs to features for each channel
and an xlsx file containing overall summary statistics.
It takes in as inputs the csv files created from
``link_ims_ids.py`` and ``extract_ims_data.py``. It outputs an
``Overall.xlsx`` file containing summary data for each channel.
The remaining feature data is exported within individual csv
files for each channel. For example: ``Red.csv``, ``Green.csv``,
and ``ColocSurfaces.csv``
"""
#: Open the file for reading; h5py.File acts like a dictionary
self.logger.debug(
"Opening .ims file {}...".format(str(self.ims_filename)))
self.f = h5py.File(self.ims_filename, 'r')
#: Determine # of groups (channel_names) in 'Scene8/Content'
logging.debug("Counting channel names in Scene8/Content...")
channel_names = list(self.f['Scene8']['Content'].keys())
# Ignore irrelevant channel types
channel_names = [
chan for chan in channel_names if chan.startswith(
"Points") or chan.startswith("MegaSurfaces")]
#: Combine objectdf, trackdf, track_id_object_df csv into 1 df
all_overall_dfs = {}
non_overall_dfs = {}
for i in range(0,len(channel_names)):
#: Loop through each attribute in Scene8/Content/
self.logger.debug(
"\n\nITERATION {}/{} OF FILE {}".format(
i+1, len(channel_names), self.ims_filename))
current_channel = channel_names[i]
self.logger.debug("Reading {}...".format(current_channel))
#: Read 'Name' attribute of each channel to get channel name
chan_name=self.f['Scene8']['Content'][current_channel].attrs['Name']
| |
<gh_stars>0
# Copyright 2020 Google LLC
# 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.
"""Wavefunction class for accessing and manipulation of the state of interest
"""
#zeros_like is incorrectly flagged by pylint
#pylint: disable=unsupported-assignment-operation
#there are many instances where access to protected members/methods simplify the
#code structure. They are not exposed to the users, and therefore, harmless
#pylint: disable=protected-access
import copy
import os
import math
from typing import (Any, Callable, cast, Dict, KeysView, List, Optional, Tuple,
Union)
import pickle
import numpy
from scipy import linalg
from scipy.special import factorial, jv
from fqe.fqe_decorators import wrap_apply, wrap_apply_generated_unitary
from fqe.fqe_decorators import wrap_time_evolve, wrap_rdm
from fqe.fqe_data import FqeData
from fqe.fqe_data_set import FqeDataSet
from fqe.util import alpha_beta_electrons
from fqe.util import map_broken_symmetry
from fqe.util import sort_configuration_keys
from fqe.util import vdot
from fqe.hamiltonians import hamiltonian, sparse_hamiltonian, \
diagonal_hamiltonian, diagonal_coulomb, \
restricted_hamiltonian
from fqe.bitstring import count_bits
from fqe.fqe_ops import fqe_operator, fqe_ops_utils
from fqe.wick import wick
class Wavefunction:
"""Wavefunction is the central object for manipulaion in the
OpenFermion-FQE.
"""
def __init__(self,
param: Optional[List[List[int]]] = None,
broken: Optional[Union[List[str], str]] = None) -> None:
"""
Args:
param (list[list[n, ms, norb]]): the constructor accepts a list of \
parameter lists. The parameter lists are comprised of
p[0] (integer) - number of particles;
p[1] (integer) - z component of spin angular momentum;
p[2] (integer) - number of spatial orbitals
broken (str): pass in the symmetries that should be preserved by \
the wavefunction.
Member Variables:
_conserve_spin (bool): When this flag is true, the wavefunction \
will maintain a constant m_s
_conserve_number (bool): When this flag is true, the wavefunction \
will maintain a constant nele
_civec (dict[(int, int)] -> FqeData): This is a dictionary for \
FqeData objects. The key is a tuple defined by the number of \
electrons and the spin projection of the system.
"""
self._symmetry_map: Dict[Tuple[int, int], Tuple[int, int]] = {}
self._conserved: Dict[str, int] = {}
self._conserve_spin: bool = False
if broken is None or 'spin' not in broken:
self._conserve_spin = True
self._conserve_number: bool = False
if broken is None or 'number' not in broken:
self._conserve_number = True
self._norb: int = 0
self._civec: Dict[Tuple[int, int], 'FqeData'] = {}
if not self._conserve_spin and not self._conserve_number:
raise TypeError('Number and spin non-conserving waveunfction is' \
' the complete Fock space.')
if param:
user_input_norbs = set([x[2] for x in param])
if len(user_input_norbs) != 1:
raise ValueError('Number of orbitals is not consistent')
self._norb = list(user_input_norbs)[0]
for i in param:
nalpha, nbeta = alpha_beta_electrons(i[0], i[1])
self._civec[(i[0], i[1])] = FqeData(nalpha, nbeta, self._norb)
if self._conserve_number:
self._conserved['n'] = param[0][0]
if self._conserve_spin:
self._conserved['s_z'] = param[0][1]
if not self._conserve_number:
self._symmetry_map = map_broken_symmetry(
param[0][1], param[0][2])
def __add__(self, other: 'Wavefunction') -> 'Wavefunction':
"""Intrinsic addition function to combine two wavefunctions. This acts \
to iterate through the wavefunctions, combine coefficients of \
configurations they have in common and add configurations that are \
unique to each one. The values are all combined into a new \
wavefunction object
Args:
other (wavefunction.Wavefunction): the second wavefunction to \
add with the local wavefunction
Returns:
wfn (wavefunction.Wavefunction): a new wavefunction with the \
values set by adding together values
"""
out = copy.deepcopy(self)
out.ax_plus_y(1.0, other)
return out
def __iadd__(self, wfn: 'Wavefunction') -> 'Wavefunction':
"""Same is __add___ but performed in-place
Args:
wfn (wavefunction.Wavefunction): the second wavefunction to \
add with the local wavefunction
Returns:
Wavefunction: self
"""
self.ax_plus_y(1.0, wfn)
return self
def __sub__(self, other: 'Wavefunction') -> 'Wavefunction':
"""Intrinsic subtraction function to combine two wavefunctions. This
acts to iterate through the wavefunctions, combine coefficients of
configurations they have in common and include configurations that are
unique to each one. The values are all combined into a new
wavefunction object
Args:
other (wavefunction.Wavefunction): the second wavefunction that \
will be subtracted from the first wavefunction
Returns:
wfn (wavefunction.Wavefunction): a new wavefunction with the
values set by subtracting the wfn from the first
"""
out = copy.deepcopy(self)
out.ax_plus_y(-1.0, other)
return out
def __getitem__(self, key: Tuple[int, int]) -> complex:
"""Element read access to the wave function.
Args:
key (Tuple[int, int]): a pair of strings for alpha and beta
Returns:
(complex): the value of the wave function
"""
astr, bstr = key[0], key[1]
sector = (count_bits(astr) + count_bits(bstr),
count_bits(astr) - count_bits(bstr))
return self._civec[sector][key]
def __setitem__(self, key: Tuple[int, int], value: complex) -> None:
"""Element write access to the wave function.
Args:
key (Tuple[int, int]): a pair of strings for alpha and beta
value (complex): the value to be set to the wave function
"""
astr, bstr = key[0], key[1]
sector = (count_bits(astr) + count_bits(bstr),
count_bits(astr) - count_bits(bstr))
self._civec[sector][key] = value
def empty_copy(self) -> 'Wavefunction':
"""create a copy of self with zero coefficients
Returns:
Wavefunction: a new object with zero coefficients
"""
out = Wavefunction()
out._norb = self._norb
out._conserved = self._conserved
out._symmetry_map = self._symmetry_map
for key, civec in self._civec.items():
out._civec[key] = civec.empty_copy()
return out
def _copy_beta_inversion(self) -> 'Wavefunction':
"""Return a copy of the wavefunction with the beta particle and hole
inverted.
Returns:
Wavefunction: wavefuction with beta particle/hole conjugation
"""
norb = self._norb
m_s = self._conserved['s_z']
nele = norb + m_s
param = []
maxb = min(norb, nele)
minb = nele - maxb
param = [
[nele, nele - nbeta * 2, norb] for nbeta in range(minb, maxb + 1)
]
inverted = Wavefunction(param, broken=['spin'])
data = {}
for key, sector in self._civec.items():
work = ((key[0] + key[1]) // 2, (key[0] - key[1]) // 2)
nkey = self._symmetry_map[work]
data[(nkey[0] + nkey[1],
nkey[0] - nkey[1])] = sector.beta_inversion()
inverted.set_wfn(strategy='from_data', raw_data=data)
return inverted
def ax_plus_y(self, sval: complex, wfn: 'Wavefunction') -> None:
"""Perform scale and add of the wavefunction. The result will be stored
in self.
Args:
sval (complex): a factor to be multiplied to wfn
wfn (Wavefunction): a wavefunction to be added to self
"""
if self._civec.keys() != wfn._civec.keys():
raise ValueError('inconsistent sectors in Wavefunction.ax_plus_y')
for sector in self._civec:
self._civec[sector].ax_plus_y(sval, wfn._civec[sector])
def sector(self, key: Tuple[int, int]) -> 'FqeData':
"""Return a specific sector of the wavefunction using a key.
Args:
key (Tuple[int, int]): key for ci vector
Returns:
FqeData: corresponding sector as an FqeData object
"""
return self._civec[key]
def sectors(self) -> KeysView[Tuple[int, int]]:
"""
Return:
KeysView[Tuple[int, int]]: a list of the configuration keys \
in the wavefunction
"""
return self._civec.keys()
def conserve_number(self) -> bool:
"""
Returns:
(bool): True if this wave function conserves the number symmetry
"""
return self._conserve_number
def conserve_spin(self) -> bool:
"""
Returns:
(bool): True if this wave function conserves the spin (Sz) \
symmetry. Otherwise False
"""
return self._conserve_spin
def norb(self) -> int:
"""
Returns:
(int): the number of orbitals
"""
return self._norb
def norm(self) -> float:
"""Calculate the norm of the wavefuntion
Returns:
(float): the norm
"""
normall = 0.0
for sector in self._civec.values():
normall += sector.norm()**2
normall = math.sqrt(normall)
return normall
def normalize(self) -> None:
"""Generte the wavefunction norm and then scale each element by that
value.
"""
self.scale(1.0 / self.norm())
@wrap_apply
def apply(self, hamil: 'hamiltonian.Hamiltonian') -> 'Wavefunction':
""" Returns a wavefunction subject to application of the Hamiltonian
(or more generally, the operator).
Args:
hamil (Hamiltonian): Hamiltonian to be applied
Returns:
(Wavefunction): resulting wave function array
"""
if not self._conserve_number or not hamil.conserve_number():
if self._conserve_number:
raise TypeError('Number non-conserving hamiltonian passed to'
' number conserving wavefunction')
if hamil.conserve_number():
raise TypeError('Number conserving hamiltonian passed to'
' number non-conserving wavefunction')
if isinstance(hamil, sparse_hamiltonian.SparseHamiltonian):
transformed = self._apply_few_nbody(hamil)
else:
if self._conserve_spin and not self._conserve_number:
out = self._copy_beta_inversion()
else:
out = self
if isinstance(hamil, diagonal_hamiltonian.Diagonal):
transformed = out._apply_diagonal(hamil)
elif isinstance(hamil, diagonal_coulomb.DiagonalCoulomb):
transformed = out._apply_diagonal_coulomb(hamil)
else:
if isinstance(hamil,
restricted_hamiltonian.RestrictedHamiltonian):
expected = self._norb
else:
expected = self._norb * 2
if hamil.dim() != expected:
raise ValueError('Hamiltonian has incorrect size:' \
+ ' expected {}'.format(expected) \
+ ' provided {}'.format(hamil.dim()))
transformed = out._apply_array(hamil.tensors(), hamil.e_0())
| |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# "Reducing Failure-Inducing Inputs" - a chapter of "The Debugging Book"
# Web site: https://www.debuggingbook.org/html/DeltaDebugger.html
# Last change: 2021-03-03 15:43:27+01:00
#
# Copyright (c) 2021 CISPA Helmholtz Center for Information Security
# Copyright (c) 2018-2020 Saarland University, authors, and contributors
#
# 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
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
r'''
The Debugging Book - Reducing Failure-Inducing Inputs
This file can be _executed_ as a script, running all experiments:
$ python DeltaDebugger.py
or _imported_ as a package, providing classes, functions, and constants:
>>> from debuggingbook.DeltaDebugger import <identifier>
but before you do so, _read_ it and _interact_ with it at:
https://www.debuggingbook.org/html/DeltaDebugger.html
A _reducer_ takes a failure-inducing input and reduces it to the minimum that still reproduces the failure. This chapter provides a `DeltaDebugger` class that implements such a reducer.
Here is a simple example: An arithmetic expression causes an error in the Python interpreter:
>>> def myeval(inp: str) -> Any:
>>> return eval(inp)
>>> with ExpectError(ZeroDivisionError):
>>> myeval('1 + 2 * 3 / 0')
Traceback (most recent call last):
File "", line 2, in
myeval('1 + 2 * 3 / 0')
File "", line 2, in myeval
return eval(inp)
File "", line 1, in
ZeroDivisionError: division by zero (expected)
Can we reduce this input to a minimum? _Delta Debugging_ is a simple and robust reduction algorithm. We provide a `DeltaDebugger` class that is used in conjunction with a (failing) function call:
with DeltaDebugger() as dd:
fun(args...)
dd
The class automatically determines minimal arguments that cause the function to fail with the same exception as the original. Printing out the class object reveals the minimized call.
>>> with DeltaDebugger() as dd:
>>> myeval('1 + 2 * 3 / 0')
>>> dd
myeval(inp='3/0')
The input is reduced to the maximum: We get the essence of the division by zero.
There also is an interface to access the reduced input(s) programmatically. The method `min_args()` returns a dictionary in which all function arguments are minimized:
>>> dd.min_args()
{'inp': '3/0'}
In contrast, `max_args()` returns a dictionary in which all function arguments are maximized, but still pass:
>>> dd.max_args()
{'inp': '1 + 2 * 3 '}
The method `min_arg_diff()` returns a triple of
* passing input,
* failing input, and
* their minimal failure-inducing difference:
>>> dd.min_arg_diff()
({'inp': ' 3 '}, {'inp': ' 3 /0'}, {'inp': '/0'})
And you can also access the function itself, as well as its original arguments.
>>> dd.function().__name__, dd.args()
('myeval', {'inp': '1 + 2 * 3 / 0'})
`DeltaDebugger` processes (i.e., minimizes or maximizes) all arguments that support a `len()` operation and that can be indexed – notably _strings_ and _lists_. If a function has multiple arguments, all arguments that can be processed will be processed.
This chapter also provides a number of superclasses to `DeltaDebugger`, notably `CallCollector`, which obtains the first function call for `DeltaDebugger`. `CallReducer` classes allow for implementing alternate call reduction strategies.
For more details, source, and documentation, see
"The Debugging Book - Reducing Failure-Inducing Inputs"
at https://www.debuggingbook.org/html/DeltaDebugger.html
'''
# Allow to use 'from . import <module>' when run as script (cf. PEP 366)
if __name__ == '__main__' and __package__ is None:
__package__ = 'debuggingbook'
# Reducing Failure-Inducing Inputs
# ================================
if __name__ == '__main__':
print('# Reducing Failure-Inducing Inputs')
if __name__ == '__main__':
from .bookutils import YouTubeVideo
YouTubeVideo("6fmJ5l257bM")
## Synopsis
## --------
if __name__ == '__main__':
print('\n## Synopsis')
## Why Reducing?
## -------------
if __name__ == '__main__':
print('\n## Why Reducing?')
if __name__ == '__main__':
# We use the same fixed seed as the notebook to ensure consistency
import random
random.seed(2001)
from . import Tracer
from .bookutils import quiz
def mystery(inp: str) -> None:
x = inp.find(chr(0o17 + 0o31))
y = inp.find(chr(0o27 + 0o22))
if x >= 0 and y >= 0 and x < y:
raise ValueError("Invalid input")
else:
pass
import random
if __name__ == '__main__':
random.randrange(32, 128)
def fuzz() -> str:
length = random.randrange(10, 70)
fuzz = ""
for i in range(length):
fuzz += chr(random.randrange(32, 127))
return fuzz
if __name__ == '__main__':
for i in range(6):
print(repr(fuzz()))
if __name__ == '__main__':
while True:
fuzz_input = fuzz()
try:
mystery(fuzz_input)
except ValueError:
break
if __name__ == '__main__':
failing_input = fuzz_input
failing_input
if __name__ == '__main__':
len(failing_input)
from .ExpectError import ExpectError
if __name__ == '__main__':
with ExpectError(ValueError):
mystery(failing_input)
## Manual Input Reduction
## ----------------------
if __name__ == '__main__':
print('\n## Manual Input Reduction')
if __name__ == '__main__':
failing_input
if __name__ == '__main__':
half_length = len(failing_input) // 2 # // is integer division
first_half = failing_input[:half_length]
first_half
if __name__ == '__main__':
with ExpectError(ValueError):
mystery(first_half)
if __name__ == '__main__':
second_half = failing_input[half_length:]
assert first_half + second_half == failing_input
second_half
if __name__ == '__main__':
with ExpectError(ValueError):
mystery(second_half)
## Delta Debugging
## ---------------
if __name__ == '__main__':
print('\n## Delta Debugging')
if __name__ == '__main__':
quarter_length = len(failing_input) // 4
input_without_first_quarter = failing_input[quarter_length:]
input_without_first_quarter
if __name__ == '__main__':
with ExpectError(ValueError):
mystery(input_without_first_quarter)
if __name__ == '__main__':
input_without_first_and_second_quarter = failing_input[quarter_length * 2:]
input_without_first_and_second_quarter
if __name__ == '__main__':
with ExpectError(ValueError):
mystery(input_without_first_and_second_quarter)
if __name__ == '__main__':
second_half
if __name__ == '__main__':
input_without_first_and_second_quarter
if __name__ == '__main__':
input_without_first_and_third_quarter = failing_input[quarter_length:
quarter_length * 2] + failing_input[quarter_length * 3:]
input_without_first_and_third_quarter
if __name__ == '__main__':
with ExpectError(ValueError):
mystery(input_without_first_and_third_quarter)
PASS = 'PASS'
FAIL = 'FAIL'
UNRESOLVED = 'UNRESOLVED'
from typing import Sequence, Any, Callable, Optional, Type, Tuple, Any
from typing import Dict, Union, Set, List, FrozenSet, cast
def ddmin(test: Callable, inp: Sequence, *test_args: Any) -> Sequence:
"""Reduce the input inp, using the outcome of test(fun, inp)."""
assert test(inp, *test_args) != PASS
n = 2 # Initial granularity
while len(inp) >= 2:
start = 0
subset_length = int(len(inp) / n)
some_complement_is_failing = False
while start < len(inp):
complement = (inp[:int(start)] + inp[int(start + subset_length):]) # type: ignore
if test(complement, *test_args) == FAIL:
inp = complement
n = max(n - 1, 2)
some_complement_is_failing = True
break
start += subset_length
if not some_complement_is_failing:
if n == len(inp):
break
n = min(n * 2, len(inp))
return inp
def generic_test(inp: Sequence, fun: Callable,
expected_exc: Optional[Type] = None) -> str:
result = None
detail = ""
try:
result = fun(inp)
outcome = PASS
except Exception as exc:
detail = f" ({type(exc).__name__}: {str(exc)})"
if expected_exc is None:
outcome = FAIL
elif type(exc) == type(expected_exc) and str(exc) == str(expected_exc):
outcome = FAIL
else:
outcome = UNRESOLVED
print(f"{fun.__name__}({repr(inp)}): {outcome}{detail}")
return outcome
if __name__ == '__main__':
ddmin(generic_test, failing_input, mystery, ValueError('Invalid input'))
## A Simple DeltaDebugger Interface
## --------------------------------
if __name__ == '__main__':
print('\n## A Simple DeltaDebugger Interface')
### Excursion: Implementing DeltaDebugger
if __name__ == '__main__':
print('\n### Excursion: Implementing DeltaDebugger')
#### Collecting a Call
if __name__ == '__main__':
print('\n#### Collecting a Call')
import sys
from types import FunctionType, FrameType, TracebackType
import inspect
import traceback
class CallCollector:
"""
Collect an exception-raising function call f().
Use as `with CallCollector(): f()`
"""
def __init__(self) -> None:
"""Initialize collector"""
self.init()
def init(self) -> None:
"""Reset for new collection."""
self._function: Optional[Callable] = None
self._args: Dict[str, Any] = {}
self._exception: Optional[BaseException] = None
def search_frame(self, name: str, frame: Optional[FrameType]) -> \
Tuple[Optional[FrameType], Optional[Callable]]:
"""
Return a pair (`frame`, `item`)
in which the function `name` is defined as `item`.
"""
while frame:
item = None
if name in frame.f_globals:
item = frame.f_globals[name]
if name in frame.f_locals:
item = frame.f_locals[name]
if item and callable(item):
return frame, item
frame = frame.f_back
return None, None
def search_func(self, name: str, frame: Optional[FrameType]) -> Optional[Callable]:
"""Search in callers for a definition of the function `name`"""
frame, func = self.search_frame(name, frame)
return func
def traceit(self, frame: FrameType, event: str, arg: Any) -> None:
"""Tracing function. Collect first call, then turn tracing | |
> 1:
LOGGER.warning('You have created %d optimizers for this model. This is not recommended (High memory usage)',
self.nb_optimizers)
# Determining aggregation_method based on accumulate_n flag
aggregation_method = None
if self.hparams['grad_aggregation'].upper() == 'ACCUMULATE_N':
aggregation_method = tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N
elif self.hparams['grad_aggregation'].upper() == 'TREE':
aggregation_method = tf.AggregationMethod.EXPERIMENTAL_TREE
# Finding all trainable variables
all_trainable_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
ignored_scope_trainable_vars = []
if isinstance(ignored_scope, list):
for scope_name in ignored_scope:
ignored_scope_trainable_vars += scope_vars(scope_name, trainable_only=True)
elif ignored_scope is not None:
ignored_scope_trainable_vars = scope_vars(ignored_scope, trainable_only=True)
ignored_scope_trainable_vars = set(ignored_scope_trainable_vars)
# Building a list of all trainable vars, and removing them when used by an op
unused_trainable_vars = set(all_trainable_vars) - set(ignored_scope_trainable_vars)
# Summing gradients if we are optimizing multiple costs
global_gradients = {}
for cost, scope, local_ignored_scope in cost_and_scope:
local_ignored_vars = []
if isinstance(local_ignored_scope, list):
for scope_name in local_ignored_scope:
local_ignored_vars += scope_vars(scope_name, trainable_only=True)
elif local_ignored_scope is not None:
local_ignored_vars = scope_vars(local_ignored_scope, trainable_only=True)
local_ignored_vars = set(local_ignored_vars)
# Computing gradients with respect to all scope vars (except global ignored vars, but incl. local ignored)
scope_trainable_vars = []
scope = [scope] if not isinstance(scope, list) else scope
for scope_name in scope:
for variable in scope_vars(scope_name, trainable_only=True):
if variable not in scope_trainable_vars and variable not in ignored_scope_trainable_vars:
scope_trainable_vars += [variable]
# Computing gradients
if self.hparams['gradient_checkpoint']:
LOGGER.info('****** Optimizing graph with gradient checkpointing...')
gradients = gradient_checkpoint.gradients(cost, scope_trainable_vars,
checkpoints=self.hparams['gradient_checkpoint'],
aggregation_method=aggregation_method)
LOGGER.info('Done optimizing graph with gradient checkpointing...')
else:
LOGGER.info('****** Computing gradients with respect to %s...', str(cost))
gradients = tf.gradients(cost, scope_trainable_vars, aggregation_method=aggregation_method)
# Storing gradients in global_gradients
for trainable_var, gradient in zip(scope_trainable_vars, gradients):
if trainable_var in local_ignored_vars:
continue
if trainable_var in unused_trainable_vars:
unused_trainable_vars.remove(trainable_var)
if gradient is None:
LOGGER.warning('Gradient for %s is None. Is the graph disconnected?', str(trainable_var))
continue
if trainable_var.name in global_gradients:
global_gradients[str(trainable_var.name)] += [gradient]
else:
global_gradients[str(trainable_var.name)] = [gradient]
# Warning about missing trainable variables
for variable in unused_trainable_vars:
LOGGER.warning('The training variable %s has not been included in the optimizer_op.', str(variable))
# Warning about ignored training variables
for variable in ignored_scope_trainable_vars:
LOGGER.info('Ignoring variable: "%s" (Shape: %s).', str(variable.name), str(variable.shape))
# Computing and clipping gradients
gradients = []
for variable in all_trainable_vars:
var_gradients = global_gradients.get(str(variable.name), [])
if not var_gradients:
gradients += [None]
elif len(var_gradients) == 1:
gradients += var_gradients
else:
if [1 for grad in var_gradients if isinstance(grad, tf.IndexedSlices)]:
LOGGER.info('Adding IndexedSlices for %s', variable)
gradients += [tf.add_n(var_gradients, name='%s/Add_N' % (variable.name.split(':')[0]))]
gradients = [ensure_finite(gradient) for gradient in gradients]
if max_gradient_norm is not None:
gradients, _ = tf.clip_by_global_norm(gradients, max_gradient_norm)
# Finding update ops
update_ops = []
for _, scope, _ in cost_and_scope:
if isinstance(scope, list):
for scope_name in scope:
for update_op in tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope=scope_name):
if update_op not in update_ops:
update_ops += [update_op]
else:
update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope=scope)
# Printing number of variables
global_vars = tf.global_variables()
LOGGER.info('Model has %d global vars and %d trainable vars', len(global_vars), len(all_trainable_vars))
# Computing the number of parameters
nb_global_params = sum([reduce(mul, variable.shape.as_list(), 1) for variable in global_vars])
nb_trainable_params = sum([reduce(mul, variable.shape.as_list(), 1) for variable in all_trainable_vars])
LOGGER.info('Model has %s parameters (%s for trainable vars)',
'{:,}'.format(nb_global_params),
'{:,}'.format(nb_trainable_params))
# Creating optimizer op (with dependencies on update for batch norm)
with tf.control_dependencies(update_ops):
opt_op = self.optimizer.apply_gradients(zip(gradients, all_trainable_vars), global_step=self.global_step)
# Returning optimization op
return opt_op
def build_policy(self):
""" Builds a policy model (initial step) """
if hasattr(self, '_build_policy_initial'):
return getattr(self, '_build_policy_initial')()
if self.parent_model is None:
raise NotImplementedError()
# Calling our parent, and updating recursively
ret_val = self.parent_model.build_policy()
self.__dict__.update(self.parent_model.__dict__)
return ret_val
def build_value(self):
""" Builds a value model (initial step) """
if hasattr(self, '_build_value_initial'):
return getattr(self, '_build_value_initial')()
if self.parent_model is None:
raise NotImplementedError()
# Calling our parent, and updating recursively
ret_val = self.parent_model.build_value()
self.__dict__.update(self.parent_model.__dict__)
return ret_val
def build_draw(self):
""" Builds a draw model (initial step) """
if hasattr(self, '_build_draw_initial'):
return getattr(self, '_build_draw_initial')()
if self.parent_model is None:
raise NotImplementedError()
# Calling our parent, and updating recursively
ret_val = self.parent_model.build_draw()
self.__dict__.update(self.parent_model.__dict__)
return ret_val
def finalize_build(self):
""" Builds the policy, value, and draw model (final step) """
if self.build_finalized:
LOGGER.warning('Build already finalized. Skipping.')
return
if self.parent_model:
self.parent_model.finalize_build()
self.outputs.update(self.parent_model.outputs)
if hasattr(self, '_build_policy_final'):
getattr(self, '_build_policy_final')()
if hasattr(self, '_build_value_final'):
getattr(self, '_build_value_final')()
if hasattr(self, '_build_draw_final'):
getattr(self, '_build_draw_final')()
self.build_finalized = True
def encode_board(self, board_state, name, reuse=None):
""" Encodes a board state or prev orders state
:param board_state: The board state / prev orders state to encode - (batch, NB_NODES, initial_features)
:param name: The name to use for the encoding
:param reuse: Whether to reuse or not the weights from another encoding operation
:return: The encoded board state / prev_orders state
"""
if hasattr(self, '_encode_board'):
return getattr(self, '_encode_board')(board_state=board_state, name=name, reuse=reuse)
if self.parent_model is None:
raise NotImplementedError()
return self.parent_model.encode_board(board_state=board_state, name=name, reuse=reuse)
def get_board_state_conv(self, board_0yr_conv, is_training, prev_ord_conv=None):
""" Computes the board state conv to use as the attention target (memory)
:param board_0yr_conv: The board state encoding of the current (present) board state)
:param is_training: Indicate whether we are doing training or inference
:param prev_ord_conv: Optional. The encoding of the previous orders state.
:return: The board state conv to use as the attention target (memory)
"""
# pylint: disable=too-many-arguments
if hasattr(self, '_get_board_state_conv'):
return getattr(self, '_get_board_state_conv')(board_0yr_conv, is_training, prev_ord_conv)
if self.parent_model is None:
LOGGER.warning('Unable to find a get_board_state_conv function. Returning the `board_0yr_conv`.')
return board_0yr_conv
return self.parent_model.get_board_state_conv(board_0yr_conv, is_training, prev_ord_conv)
def get_board_value(self, board_state, current_power, name='board_state_value', reuse=None):
""" Computes the estimated value of a board state
:param board_state: The board state - (batch, NB_NODES, NB_FEATURES)
:param current_power: The power for which we want the board value - (batch,)
:param name: The name to use for the operaton
:param reuse: Whether to reuse or not the weights from another operation
:return: The value of the board state for the specified power - (batch,)
"""
from diplomacy_research.utils.tensorflow import tf
if hasattr(self, '_get_board_value'):
return getattr(self, '_get_board_value')(board_state, current_power, name, reuse)
if self.parent_model is None:
LOGGER.warning('Unable to find a value function. Returning 0. for `get_board_value`.')
return tf.zeros_like(current_power, dtype=tf.float32)
return self.parent_model.get_board_value(board_state, current_power, name, reuse)
def validate(self):
""" Validates the built model
Throws a RuntimeError if the model is not build properly.
"""
assert self.build_finalized, 'The model has not been finalized. Please call .finalize_build()'
self._validate()
if self.parent_model:
self.parent_model.validate()
def get_session_args(self, decode=False, eval_loop_ix=None):
""" Returns a dict of kwargs to feed to session.run
Expected format: {fetches, feed_dict=None}
"""
fetches, feed_dict = {}, {}
# Finding the list of models from the top parent downwards
current_model = self
models = [current_model]
while current_model.parent_model:
current_model = current_model.parent_model
models += [current_model]
# Updates the session args
while models:
current_model = models.pop(-1)
new_session_args = current_model._get_session_args(decode=decode, eval_loop_ix=eval_loop_ix) # pylint: disable=protected-access
new_fetches = new_session_args.get('fetches', {})
new_feed_dict = new_session_args.get('feed_dict', None) or {}
fetches.update(new_fetches)
feed_dict.update(new_feed_dict)
# Returning
return {'fetches': fetches, 'feed_dict': feed_dict}
def decode(self, **fetches):
""" Performs decoding on the output
:param fetches: A dictionary of fetches from the model.
:return: A dictionary of decoded results
"""
# Finding the list of models from the top parent downwards
current_model = self
models = [current_model]
while current_model.parent_model:
current_model = current_model.parent_model
models += [current_model]
# Decoding
decoded_results = {}
while models:
current_model = models.pop(-1)
new_decoded_results = current_model._decode(**fetches) # pylint: disable=protected-access
decoded_results = merge_complex_dicts(decoded_results, new_decoded_results)
# Returning
return decoded_results
def evaluate(self, decoded_results, feed_dict, eval_loop_ix, incl_detailed):
""" Evaluates the model
:param decoded_results: The decoded results (output of _decode() function)
:param feed_dict: The feed dictionary that was given to session.run()
:param eval_loop_ix: The current evaluation loop index
:param incl_detailed: is true if training is over, more statistics can be computed
:return: A tuple consisting of:
1) An ordered dictionary with result_name as key and result value as value (Regular results)
2) An ordered dictionary with result_name as key and a list of result values (Detailed results)
"""
# Finding the list of models from the top parent downwards
current_model = self
models = [current_model]
while current_model.parent_model:
current_model = current_model.parent_model
models += [current_model]
# Evaluating
regular, detailed = OrderedDict(), OrderedDict()
while models:
current_model = models.pop(-1)
new_regular, new_detailed = current_model._evaluate(decoded_results, feed_dict, eval_loop_ix, incl_detailed) # pylint: disable=protected-access
regular = merge_complex_dicts(regular, new_regular)
detailed = merge_complex_dicts(detailed, new_detailed)
# Returning
return regular, detailed
def post_process_results(self, detailed_results):
""" Perform post-processing on the detailed results
:param detailed_results: An dictionary which contains detailed evaluation statistics
:return: | |
2.0 * n))) / 6.0 + np.log10(np.pi) / 2.0
@jit(nopython=True, fastmath=True)
def sumRange(xmin, xmax):
"""[summary]
:param xmin: [description]
:type xmin: [type]
:param xmax: [description]
:type xmax: [type]
:return: [description]
:rtype: [type]
"""
csum = 0
for i in np.arange(xmin, xmax + 1):
csum += np.log10(i)
return csum
@jit(nopython=True, fastmath=True)
def sumFactorial(n):
csum = 0
if n > 1:
for i in np.arange(2, n + 1):
csum += np.log10(i)
return csum
def shuffled_edges(adjacency_matrix, is_directed):
"""Shuffles edges randomly.
:param adjacency_matrix: Matrix.
:type adjacency_matrix: numpy.ndarray
:param is_directed: True if graph is directed.
:type is_directed: bool
:return: Shuffled edgelist.
:rtype: mumpy.ndarray
"""
adj = adjacency_matrix.astype(bool).astype(np.int16)
if not is_directed:
adj = np.triu(adj)
edges = np.stack(adj.nonzero(), axis=-1)
np.random.shuffle(edges)
shuff_edges = edges.astype(np.int32)
return shuff_edges
def jaccard_sorted_edges(adjacency_matrix):
"""Returns edges ordered based on jaccard index.
:param adjacency_matrix: Matrix.
:type adjacency_matrix: numpy.ndarray
:return: Ordered edgelist.
:rtype: numpy.ndarray
"""
G = nx.from_numpy_matrix(adjacency_matrix)
jacc = nx.jaccard_coefficient(G, ebunch=G.edges())
jacc_array = []
for u, v, p in jacc:
jacc_array += [[u, v, p]]
jacc_array = np.array(jacc_array)
jacc_array = jacc_array[jacc_array[:, 2].argsort()][::-1]
sorted_edges = jacc_array[:, 0:2]
sorted_edges = sorted_edges.astype(np.int32)
return sorted_edges
def evaluate_surprise_clust_bin(adjacency_matrix,
cluster_assignment,
is_directed):
"""Calculates the logarithm of the surprise given the current partitions
for a binary network.
:param adjacency_matrix: Binary adjacency matrix.
:type adjacency_matrix: numpy.ndarray
:param cluster_assignment: Nodes memberships.
:type cluster_assignment: numpy.ndarray
:param is_directed: True if the graph is directed.
:type is_directed: bool
:return: Log-surprise.
:rtype: float
"""
if is_directed:
# intracluster links
p = cd.intracluster_links(adjacency_matrix,
cluster_assignment)
p = int(p)
# All the possible intracluster links
M = cd.calculate_possible_intracluster_links(cluster_assignment,
is_directed)
# Observed links
m = np.sum(adjacency_matrix.astype(bool))
# Possible links
n = adjacency_matrix.shape[0]
F = n * (n - 1)
else:
# intracluster links
p = cd.intracluster_links(adjacency_matrix,
cluster_assignment)
p = int(p / 2)
# All the possible intracluster links
M = int(cd.calculate_possible_intracluster_links(cluster_assignment,
is_directed))
# Observed links
m = np.sum(adjacency_matrix.astype(bool)) / 2
# Possible links
n = adjacency_matrix.shape[0]
F = int((n * (n - 1)) / 2)
surprise = surprise_hypergeometric(F, p, M, m)
return surprise
def surprise_hypergeometric(F, p, M, m):
surprise = 0
min_p = min(M, m)
for p_loop in np.arange(p, min_p + 1):
surprise += (comb(M, p_loop, exact=True) * comb(
F - M, m - p_loop,
exact=True)) / comb(F,
m,
exact=True)
return surprise
def evaluate_surprise_clust_weigh(adjacency_matrix,
cluster_assignment,
is_directed):
"""Calculates the logarithm of the surprise given the current partitions
for a weighted network.
:param adjacency_matrix: Weighted adjacency matrix.
:type adjacency_matrix: numpy.ndarray
:param cluster_assignment: Nodes memberships.
:type cluster_assignment: numpy.ndarray
:param is_directed: True if the graph is directed.
:type is_directed: bool
:return: Log-surprise.
:rtype: float
"""
if is_directed:
# intracluster weights
w = cd.intracluster_links(adjacency_matrix,
cluster_assignment)
# intracluster possible links
Vi = cd.calculate_possible_intracluster_links(cluster_assignment,
is_directed)
# Total Weight
W = np.sum(adjacency_matrix)
# Possible links
n = adjacency_matrix.shape[0]
V = n * (n - 1)
# extracluster links
Ve = V - Vi
else:
# intracluster weights
w = cd.intracluster_links(adjacency_matrix,
cluster_assignment) / 2
# intracluster possible links
Vi = cd.calculate_possible_intracluster_links(cluster_assignment,
is_directed)
# Total Weight
W = np.sum(adjacency_matrix) / 2
# Possible links
n = adjacency_matrix.shape[0]
V = int((n * (n - 1)) / 2)
# extracluster links
Ve = V - Vi
surprise = surprise_negative_hypergeometric(Vi, w, Ve, W, V)
return surprise
def surprise_negative_hypergeometric(Vi, w, Ve, W, V):
"""Computes the negative hypergeometric distribution.
"""
surprise = 0
for w_loop in range(w, W):
surprise += ((comb(Vi + w_loop - 1, w_loop, exact=True) * comb(
Ve + W - w_loop, W - w_loop, exact=True)) /
comb(V + W, W, exact=True))
return surprise
def evaluate_surprise_cp_bin(adjacency_matrix,
cluster_assignment,
is_directed):
"""Computes core-periphery binary log-surprise given a certain nodes'
partitioning.
:param adjacency_matrix: Binary adjacency matrix.
:type adjacency_matrix: numpy.ndarray
:param cluster_assignment: Core periphery assigments.
:type cluster_assignment: numpy.ndarray
:param is_directed: True if the graph is directed.
:type is_directed: bool
:return: Log-surprise
:rtype: float
"""
core_nodes = np.unique(np.where(cluster_assignment == 0)[0])
periphery_nodes = np.unique(np.where(cluster_assignment == 1)[0])
if is_directed:
n_c = core_nodes.shape[0]
n_x = periphery_nodes.shape[0]
p_c = n_c * (n_c - 1)
p_x = n_c * n_x * 2
l_c = cp.compute_sum(adjacency_matrix, core_nodes, core_nodes)
l_x = cp.compute_sum(adjacency_matrix, core_nodes,
periphery_nodes) + cp.compute_sum(
adjacency_matrix,
periphery_nodes,
core_nodes)
l_t = np.sum(adjacency_matrix)
n = n_c + n_x
p = n * (n - 1)
else:
n_c = core_nodes.shape[0]
n_x = periphery_nodes.shape[0]
p_c = (n_c * (n_c - 1)) / 2
p_x = n_c * n_x
l_c = cp.compute_sum(adjacency_matrix, core_nodes, core_nodes) / 2
l_x = (cp.compute_sum(adjacency_matrix, core_nodes,
periphery_nodes) + cp.compute_sum(
adjacency_matrix,
periphery_nodes,
core_nodes)) / 2
l_t = np.sum(adjacency_matrix) / 2
n = n_c + n_x
p = (n * (n - 1)) / 2
if (p_c + p_x) < (l_c + l_x):
return 0
surprise = surprise_bipartite_cp_bin(p, p_c, p_x, l_t, l_c, l_x)
return surprise
@jit(forceobj=True)
def surprise_bipartite_cp_bin(p, p_c, p_x, l, l_c, l_x):
surprise = 0
aux_first = 0
for l_c_loop in range(l_c, p_c + 1):
aux_first_temp = aux_first
for l_x_loop in range(l_x, p_x + 1):
if l_c_loop + l_x_loop > l:
continue
aux = multihyperprobability(p, p_c, p_x,
l, l_c_loop,
l_x_loop)
surprise += aux
if surprise == 0:
break
if aux/surprise < 1e-3:
break
aux_first = surprise
if aux_first - aux_first_temp:
if ((aux_first - aux_first_temp) / aux_first) < 1e-3:
# pass
break
return surprise
# @jit(nopython=True)
def multihyperprobability(p, p_c, p_x, l, l_c, l_x):
"""Computes the logarithm of the Multinomial Hypergeometric
distribution."""
logh = comb(p_c, l_c, True) * comb(p_x, l_x) + comb(
p - p_c - p_x,
l - l_c - l_x) - comb(p, l)
return logh
def evaluate_surprise_cp_enh(adjacency_matrix,
cluster_assignment,
is_directed):
"""Computes core-periphery weighted surprise given a
certain nodes' partitioning.
:param adjacency_matrix: Weighted adjacency matrix.
:type adjacency_matrix: numpy.ndarray
:param cluster_assignment: Core periphery assigments.
:type cluster_assignment: numpy.ndarray
:param is_directed: True if the graph is directed.
:type is_directed: bool
:return: Log-surprise
:rtype: float
"""
core_nodes = np.unique(np.where(cluster_assignment == 0)[0])
periphery_nodes = np.unique(np.where(cluster_assignment == 1)[0])
if is_directed:
n_o = core_nodes.shape[0]
n_p = periphery_nodes.shape[0]
V_o = n_o * (n_o - 1)
V_c = n_o * n_p * 2
l_o, w_o = cp.compute_sum_enh(adjacency_matrix, core_nodes, core_nodes)
l_c, w_c = cp.compute_sum_enh(adjacency_matrix,
core_nodes,
periphery_nodes) + cp.compute_sum_enh(
adjacency_matrix,
periphery_nodes,
core_nodes)
L = np.sum(adjacency_matrix.astype(bool))
W = np.sum(adjacency_matrix)
# w_p = W - w_o - w_c
n = n_o + n_p
V = n * (n - 1)
else:
n_o = core_nodes.shape[0]
n_p = periphery_nodes.shape[0]
V_o = n_o * (n_o - 1) / 2
V_c = n_o * n_p
l_o, w_o = (cp.compute_sum_enh(adjacency_matrix, core_nodes, core_nodes))
l_c1, w_c1 = cp.compute_sum_enh(adjacency_matrix,
core_nodes,
periphery_nodes)
l_c2, w_c2 = cp.compute_sum_enh(adjacency_matrix,
periphery_nodes,
core_nodes)
l_o = l_o / 2
w_o = w_o / 2
l_c = (l_c1 + l_c2) / 2
w_c = (w_c1 + w_c2) / 2
L = np.sum(adjacency_matrix.astype(bool)) / 2
W = np.sum(adjacency_matrix) / 2
# w_p = (W - w_o - w_c) / 2
n = n_o + n_p
V = n * (n - 1) / 2
# print("V_o", V_o, "l_o", l_o, "V_c", V_c, "l_c", l_c,
# "w_o", w_o, "w_c", w_c, "V", V, "L", L, "W", W)
surprise = surprise_bipartite_cp_enh(V_o, l_o, V_c, l_c,
w_o, w_c, V, L, W)
return surprise
@jit(forceobj=True)
def surprise_bipartite_cp_enh(V_o, l_o, V_c, l_c, w_o, w_c, V, L, W):
surprise = 0
min_l_o = min(L, V_o + V_c)
aux_first = 0
aux_second = 0
aux_third = 0
for l_o_loop in np.arange(l_o, min_l_o + 1):
aux_first_temp = aux_first
for l_c_loop in np.arange(l_c, min_l_o + 1 - l_o_loop):
aux_second_temp = aux_second
for w_o_loop in np.arange(w_o, W + 1):
aux_third_temp = aux_third
for w_c_loop in np.arange(w_c, W + 1 - w_o_loop):
aux = logmulti_hyperprobability_weightenh(
V_o, l_o_loop,
V_c, l_c_loop,
w_o_loop, w_c_loop,
V, L, W)
surprise += aux
# print(surprise)
if surprise == 0:
break
if aux / surprise < 1e-3:
break
aux_third = surprise
if aux_third - aux_third_temp:
if ((aux_third - aux_third_temp) / aux_third) < 1e-3:
# pass
break
else:
break
aux_second = aux_third
if aux_second - aux_second_temp:
if ((aux_second - aux_second_temp) / aux_second) < 1e-3:
# pass
break
else:
break
aux_first = aux_second
if aux_first - aux_first_temp:
if ((aux_first - aux_first_temp) / aux_first) < 1e-4:
# pass
break
else:
break
return surprise
@jit(forceobj=True)
def logmulti_hyperprobability_weightenh(V_o, l_o, V_c, l_c, w_o, w_c, V, L, W):
"""Computes the of the Negative Multinomial Hypergeometric
distribution."""
aux1 = (comb(V_o, l_o, exact=True) * | |
<filename>jupyterlab_translate/utils.py
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from collections import OrderedDict
from itertools import chain
from pathlib import Path
from typing import Dict
from typing import List
from typing import Optional
from typing import Pattern
from typing import Set
from typing import Tuple
from typing import Union
import babel
import polib
from cookiecutter.main import cookiecutter
from .constants import COOKIECUTTER_REF
from .constants import COOKIECUTTER_URL
from .constants import GETTEXT_CONFIG
from .constants import LC_MESSAGES
from .constants import LOCALE_FOLDER
# Constants
HERE = Path(__file__).parent
# --- Helpers
# ----------------------------------------------------------------------------
def get_version(repo_root_path: Path, project: str) -> str:
"""
Get the version of a language pack
Args:
repo_root_path: Path to the language pack
project: Project name
Returns:
Version string for project
"""
package = repo_root_path / project
version = ""
# Look for python version
try:
output = (
subprocess.check_output(
[sys.executable, "setup.py", "--version"], cwd=repo_root_path
)
.decode("utf8")
.strip()
)
except subprocess.CalledProcessError as e:
print(f"Failed to get the Python package version for '{package!s}.")
print(e)
else:
version = output.splitlines()[-1]
# Look for npm version
if not version:
pkg_path = package / "package.json"
if pkg_path.is_file():
data = json.loads(pkg_path.read_text())
version = data.get("version", "")
# Look for git version
if not version and repo_root_path.exists():
args = ["git", "describe", "--tags", "--abbrev=0"]
try:
version = (
subprocess.check_output(args, cwd=repo_root_path)
.decode("utf-8")
.strip()
)
if version.startswith("v"):
version = version[1:]
except Exception:
pass
return version
def create_new_language_pack(
output_dir: Union[str, Path],
locale: str,
cookiecutter_url: str = COOKIECUTTER_URL,
cookiecutter_ref: str = COOKIECUTTER_REF,
version: str = "0.1.post0",
) -> None:
"""
Creates a new language pack python package with cookiecutter.
Args:
output_dir: Ouput directory for the language pack
locale: Locale
cookiecutter_url: Language pack template
cookiecutter_ref: Template git reference
"""
if not check_locale(locale):
raise Exception("Invalid locale!")
loc = babel.Locale.parse(locale)
options = {
"locale": locale.replace("_", "-"),
"locale_underscore": locale,
"language": loc.english_name,
"version": version,
}
cookiecutter(
cookiecutter_url,
checkout=cookiecutter_ref,
extra_context=options,
no_input=True,
output_dir=str(output_dir),
)
def check_locale(locale: str) -> bool:
"""Check if a locale is a valid value."""
value = False
try:
babel.Locale.parse(locale)
value = True
except Exception as e:
print(str(e))
return value
def find_locales(output_dir: Path) -> Tuple[str]:
"""
Find available locales on the `output_dir` folder.
Args:
output_dir: Output folder
Returns:
Sorted locales found in the Jupyter language packs repository.
"""
locales = set()
locale_path = output_dir / LOCALE_FOLDER
folders = locale_path.iterdir() if locale_path.is_dir() else []
for locale_folder in folders:
locale_name = locale_folder.name
if locale_name not in locales and check_locale(locale_name):
locales.add(locale_name)
return tuple(sorted(locales))
# --- Find source files
# ----------------------------------------------------------------------------
def find_packages_source_files(
packages_path: Union[str, Path]
) -> Dict[str, List[Path]]:
"""
List packages source files.
Args:
packages_path: Path to the packages root directory
Returns:
Mapping (package name, source files list)
"""
package_files = OrderedDict()
for pkg in Path(packages_path).iterdir():
files = find_source_files(pkg)
if files:
package_files[pkg.name] = files
return package_files
def find_source_files(
path: Path,
extensions: Set[str] = {".ts", ".tsx", ".py"},
skip_folders: Set[str] = {
"tests",
"test",
"node_modules",
"lib",
".git",
".ipynb_checkpoints",
},
):
"""
Find source files in given `path`.
Args:
path: Path to introspect
extensions: Set of extensions to list
skip_folders: Set of folders to ignore
Returns
List of files found
"""
all_files = []
for ext in extensions:
for f in path.rglob(f"*{ext}"):
parents = set(map(lambda p: p.name, f.parents))
if len(parents.intersection(skip_folders)) > 0:
continue
all_files.append(f)
return all_files
# --- .pot and .po generation
# ----------------------------------------------------------------------------
def extract_tsx_strings(input_path: Union[str, Path]) -> List[Dict]:
"""
Use gettext-extract to extract strings from TS(X) files.
Args:
input_path: path to look for strings.
Returns:
List of translatable strings
"""
input_path = Path(input_path).expanduser()
with tempfile.NamedTemporaryFile("w+", suffix=".pot") as output:
config = GETTEXT_CONFIG.copy()
config["output"] = output.name
with tempfile.NamedTemporaryFile("w+", suffix=".json") as config_file:
json.dump(config, config_file)
config_file.seek(0) # Rewind to file beginning
subprocess.run(["cat", config_file.name])
cmd = ["gettext-extract", "--config", config_file.name]
subprocess.check_call(cmd, cwd=input_path)
# Fix the missing format
output_path = Path(output.name)
output_path.write_text("#, fuzzy\n" + output_path.read_text())
entries = []
pot = polib.pofile(str(output_path), wrapwidth=100000)
for entry in pot:
occurrences = entry.occurrences
data = {"msgid": entry.msgid, "occurrences": occurrences}
if entry.msgid_plural:
data["msgid_plural"] = entry.msgid_plural
data["msgstr_plural"] = entry.msgstr_plural
if entry.msgctxt:
data["msgctxt"] = entry.msgctxt
if entry.comment:
data["comment"] = entry.comment
if entry.encoding:
data["encoding"] = entry.encoding
if entry.obsolete:
data["obsolete"] = entry.obsolete
entries.append(data)
return entries
def get_line(lines: List[str], value: str) -> str:
"""Get the line position of the last ``value`` occurrence in ``lines``.
Args:
lines: Lines to inspect
value: Value searched for
Returns:
Position of ``value`` converted to string
"""
value1 = '"' + value + '"'
value2 = "'" + value + "'"
line_count = 0
for idx, line in enumerate(lines):
# TODO: Might be needed for other escaped chars?
line = line.replace(r"\n", "\n")
if value1 in line or value2 in line:
line_count = idx + 1
return str(line_count)
_default_schema_context = "schema"
_default_settings_context = "settings"
# mapping of selector to translation context
DEFAULT_SCHEMA_SELECTORS = {
"title": _default_schema_context,
"description": _default_schema_context,
"properties/.*/title": _default_settings_context,
"properties/.*/description": _default_settings_context,
"definitions/.*/properties/.*/title": _default_settings_context,
"definitions/.*/properties/.*/description": _default_settings_context,
# JupyterLab-specific
"jupyter\.lab\.setting-icon-label": _default_settings_context,
"jupyter\.lab\.menus/.*/label": "menu",
"jupyter\.lab\.toolbars/.*/label": "toolbar",
}
def _prepare_schema_patterns(schema: dict) -> Dict[Pattern, str]:
selectors = {
**DEFAULT_SCHEMA_SELECTORS,
**{
selector: _default_schema_context
for selector in schema.get("jupyter.lab.internationalization", {}).get(
"selectors", []
)
},
}
return {
re.compile("^/" + pattern + "$"): context
for pattern, context in selectors.items()
}
def _extract_schema_strings(
schema: dict,
ref_path: str,
prefix: str = "",
to_translate: Dict[Pattern, str] = None,
):
if to_translate is None:
to_translate = _prepare_schema_patterns(schema)
entries = []
for key, value in schema.items():
path = prefix + "/" + key
if isinstance(value, str):
matched = False
for pattern, context in to_translate.items():
if pattern.fullmatch(path):
matched = True
break
if matched:
entries.append(
dict(
msgctxt=context,
msgid=value,
occurrences=[(ref_path, path)],
)
)
elif isinstance(value, dict):
entries.extend(
_extract_schema_strings(
value, ref_path, prefix=path, to_translate=to_translate
)
)
elif isinstance(value, list):
for i, element in enumerate(value):
if not isinstance(element, dict):
continue
entries.extend(
_extract_schema_strings(
element,
ref_path,
prefix=path + "[" + str(i) + "]",
to_translate=to_translate,
)
)
return entries
def extract_schema_strings(input_path: Union[str, Path]) -> List[Dict]:
"""
Use gettext-extract to extract strings from JSON schema files.
Args:
input_path:
Returns
List of translatable strings
"""
input_paths = find_source_files(Path(input_path), extensions=("package.json",))
schema_paths: List[Path] = []
for path in input_paths:
if path.is_file():
data = json.loads(path.read_text())
schema_dir = data.get("jupyterlab", {}).get("schemaDir", None)
if schema_dir is not None:
schema_path = path.parent / schema_dir
if schema_path.is_dir():
for p in schema_path.rglob("*.json"):
schema_paths.append(p)
entries = []
for path in schema_paths:
if path.is_file():
data = path.read_text()
schema = json.loads(data)
ref_path = "/{!s}".format(path.relative_to(input_path))
entries.extend(_extract_schema_strings(schema, ref_path))
return entries
def extract_strings(
input_paths: List[Path], output_path: Union[str, Path], project: str, version: str
) -> Path:
"""
Extract localizable strings on input files.
Args:
input_paths: List of input folders
output_path: Output folder relative to the current one
project: Project name
version: Version
Returns
Output path
"""
mapping = HERE / "pybabel_config.cfg"
cmd = [
"pybabel",
"extract",
"--no-wrap",
"--charset=utf-8",
"-o",
str(output_path),
f"--project={project}",
f"--version={version}",
f"--mapping={mapping!s}",
] + list(str(i) for i in input_paths)
subprocess.check_call(cmd)
return Path.cwd() / output_path
def fix_location(
path_to_remove: str,
pot_path: Union[str, Path],
append_entries: Optional[List[Dict]] = None,
) -> Dict[str, str]:
"""
Remove any hardcoded paths on the pot file.
Args:
path: path to remove
pot_file: pot file path
append_entries: optional list of strings entries to append
Returns:
POT file metadata
"""
# Do not add column wrapping by using a large value!
pot = polib.pofile(str(pot_path), wrapwidth=100000, check_for_duplicates=False)
for entry in pot:
new_occurrences = []
string_fpaths = []
lines = []
for (string_fpath, line) in entry.occurrences:
# Convert absolute paths to relative paths
string_fpaths.append(Path(string_fpath).resolve())
lines.append(line)
if line != "":
string_fpath = " ".join(map(lambda p: str(p), string_fpaths)).replace(
path_to_remove, ""
)
# Normalize paths
string_fpath = string_fpath.replace("\\", "/")
new_occurrences.append((string_fpath, line))
string_fpaths.clear()
lines.clear()
entry.occurrences = new_occurrences
if append_entries:
for entry in append_entries:
entry = polib.POEntry(**entry)
pot.append(entry)
pot.save(str(pot_path))
return pot.metadata.copy()
def remove_duplicates(pot_path: Path, metadata: Dict[str, str]) -> None:
"""
Remove duplicate strings in POT file
Args:
pot_path: POT file path
metadata: POT metadata
"""
old_pot_name = pot_path.rename(f"{pot_path!s}.bak")
pot = polib.pofile(str(old_pot_name), wrapwidth=100000, check_for_duplicates=False)
entries = {}
entries_data = {}
duplicates = set()
for entry in pot:
# Remove empty msgid
if not bool(entry.msgid):
continue
# Create a unique key using context, singular and plurals
key = (entry.msgctxt, entry.msgid, entry.msgid_plural)
if key in entries:
entries[key].append(entry)
duplicates.add(key)
else:
entry.occurrences = list(sorted(entry.occurrences))
entries[key] = [entry]
entries_data[key] = entry
# Merge info from duplicate
print("Merging duplicates...")
for key in duplicates:
items = entries[key]
entry = entries_data[key]
new_occurences = []
for item in items:
new_occurences.extend(item.occurrences)
entry = polib.POEntry(
msgid=entry.msgid,
| |
validator=validate)
# def test_repos_leetcode():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'leetcode')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_leetcode_javascript():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'leetcode-javascript')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lell():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lell')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lerna():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lerna')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_less_js_middleware():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'less.js-middleware')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lets_code_javascript():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lets_code_javascript')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_letsrate():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'letsrate')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_libcanvas():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'libcanvas')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_libsignal_protocol_javascript():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'libsignal-protocol-javascript')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_libv8():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'libv8')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_libxmljs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'libxmljs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lifxjs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lifxjs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lightgallery_js():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lightgallery.js')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lighthouse():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lighthouse')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lightstep_tracer_javascript():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lightstep-tracer-javascript')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_limestone():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'limestone')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_linq():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'linq')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_liquid_js():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'liquid.js')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_liquidfun():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'liquidfun')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_listloading():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'listloading')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_live_cljs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'live-cljs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_live_log_analyzer():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'live-log-analyzer')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_livecss():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'livecss')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lively():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lively')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lmd():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lmd')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_loadrunner():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'loadrunner')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_localForage():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'localForage')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lodash():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lodash')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_log_sys():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'log-sys')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lookforward():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lookforward')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lottie_web():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lottie-web')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_loupe():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'loupe')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_love_webplayer():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'love-webplayer')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lrInfiniteScroll():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lrInfiniteScroll')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lvlDragDrop():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lvlDragDrop')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_lz_string():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'lz-string')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mach():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mach')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_machine_learning_for_software_engineers():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'machine-learning-for-software-engineers')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mage():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mage')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_magic_iterable():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'magic-iterable')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_magix_inspector():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'magix-inspector')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_magixjs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'magixjs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mailmao():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mailmao')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_make_me():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'make-me')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_manim():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'manim')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mantra_cli():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mantra-cli')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mantra_sample_blog_app():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mantra-sample-blog-app')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_map_stream():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'map-stream')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mapbox_js():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mapbox.js')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mapquery():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mapquery')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_maps_api_for_javascript_examples():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'maps-api-for-javascript-examples')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_markdown_here():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'markdown-here')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_markdown_js():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'markdown-js')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_markdown_live():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'markdown-live')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_marked():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'marked')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_markerclustererplus():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'markerclustererplus')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_marktext():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'marktext')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_marquette():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'marquette')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mastering_modular_javascript():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mastering-modular-javascript')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_matchmedia_ng():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'matchmedia-ng')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_material():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'material')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_material_theme_appbar():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'material-theme-appbar')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_material_ui():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'material-ui')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_material_ui_vue():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'material-ui-vue')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_materialize():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'materialize')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_materials():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'materials')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mathjs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mathjs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_matrix_react_sdk():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'matrix-react-sdk')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_md2react():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'md2react')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mechanic():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mechanic')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meeting_ticker():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meeting-ticker')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_megamanjs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'megamanjs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_melonJS():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'melonJS')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_memdiff():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'memdiff')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mermaid():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mermaid')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mers():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mers')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_chat_tutorial():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-chat-tutorial')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_collection_helpers():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-collection-helpers')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_ddp_analyzer():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-ddp-analyzer')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_pg():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-pg')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_polymer():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-polymer')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_react_layout():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-react-layout')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_react_router_ssr():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-react-router-ssr')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_rethinkdb():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-rethinkdb')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_spin():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-spin')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_tupperware():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-tupperware')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_typeahead():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-typeahead')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_vue():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-vue')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_webpack():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-webpack')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_meteor_webpack_react():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'meteor-webpack-react')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_metro():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'metro')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_metronome():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'metronome')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_micro_starter():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'micro-starter')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_microcosm():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'microcosm')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_midas():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'midas')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_minimal_gltf_loader():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'minimal-gltf-loader')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_minimatch():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'minimatch')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_minwidth_relocate():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'minwidth-relocate')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mithril_js():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mithril.js')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mixpanel_js():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mixpanel-js')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mjs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mjs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_ml():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'ml')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mobile_packages():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mobile-packages')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mobile_ui_patterns():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mobile-ui-patterns')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mobx():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mobx')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mobx_reactor():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mobx-reactor')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mocha():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mocha')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modalbox():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modalbox')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modelizr():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modelizr')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modern_backbone_starterkit():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modern-backbone-starterkit')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modern_javascript():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modern-javascript')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modulargrid():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modulargrid')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modulejs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modulejs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_modules():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'modules')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mojs():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mojs')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_moment():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'moment')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_monaco_editor():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'monaco-editor')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mongodb_engine():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mongodb-engine')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mongoose():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mongoose')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mongoose_q():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mongoose-q')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_monocles():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'monocles')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_monorouter():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'monorouter')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_moobile_core():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'moobile-core')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mootools_bootstrap():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mootools-bootstrap')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mootools_mobile():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mootools-mobile')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mostly_adequate_guide():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mostly-adequate-guide')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', validator=validate)
# def test_repos_mousetrap():
# path_name = os.path.join(constants.seeds_dir, 'repos', 'mousetrap')
# multicall.multicall_directories(path_name, fuzzer='quickfuzz', | |
# coding=utf-8
# Copyright 2021 The Tensor2Tensor 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.
"""Tests for pack_sequences_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensor2tensor.data_generators.ops import pack_sequences_ops
import tensorflow.compat.v1 as tf
def _pack_sequences_k(inputs, targets, input_max_length, target_max_length):
"""Wrapper for pack_sequences_k with same interface as pack_sequences_2."""
inputs = tf.convert_to_tensor(inputs, tf.int32)
targets = tf.convert_to_tensor(targets, tf.int32)
input_max_length = tf.convert_to_tensor(input_max_length, dtype=tf.int32)
target_max_length = tf.convert_to_tensor(target_max_length, dtype=tf.int32)
(packed, segmentation, position) = pack_sequences_ops.pack_sequences_k(
[inputs, targets], [input_max_length, target_max_length])
(inputs_packed, targets_packed) = packed
(inputs_segmentation, targets_segmentation) = segmentation
(inputs_position, targets_position) = position
return (inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position)
class PackSequencesOpsTest(tf.test.TestCase):
def do_test_pack_sequences_length3(self, pack_fn):
inputs = [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
]
targets = [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
]
inputs_max_length = 3
targets_max_length = 3
(inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position) = (
pack_fn(inputs, targets, inputs_max_length, targets_max_length))
self.assertAllEqual(inputs_packed, [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
])
self.assertAllEqual(inputs_segmentation, [
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
])
self.assertAllEqual(inputs_position, [
[0, 1, 2],
[0, 1, 0],
[0, 0, 0],
])
self.assertAllEqual(targets_packed, [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
])
self.assertAllEqual(targets_segmentation, [
[1, 0, 0],
[1, 1, 1],
[1, 1, 0],
])
self.assertAllEqual(targets_position, [
[0, 0, 0],
[0, 1, 2],
[0, 1, 0],
])
def do_test_pack_sequences_length4(self, pack_fn):
inputs = [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
]
targets = [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
]
inputs_max_length = 4
targets_max_length = 4
(inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position) = (
pack_fn(inputs, targets, inputs_max_length, targets_max_length))
self.assertAllEqual(inputs_packed, [
[1, 2, 3, 6],
[4, 5, 0, 0],
])
self.assertAllEqual(inputs_segmentation, [
[1, 1, 1, 2],
[1, 1, 0, 0],
])
self.assertAllEqual(inputs_position, [
[0, 1, 2, 0],
[0, 1, 0, 0],
])
self.assertAllEqual(targets_packed, [
[10, 50, 60, 0],
[20, 30, 40, 0],
])
self.assertAllEqual(targets_segmentation, [
[1, 2, 2, 0],
[1, 1, 1, 0],
])
self.assertAllEqual(targets_position, [
[0, 0, 1, 0],
[0, 1, 2, 0],
])
def do_test_pack_sequences_length5(self, pack_fn):
inputs = [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
]
targets = [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
]
max_length = 5
(inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position) = (
pack_fn(inputs, targets, max_length, max_length))
self.assertAllEqual(
inputs_packed, [
[1, 2, 3, 4, 5],
[6, 0, 0, 0, 0],
])
self.assertAllEqual(
inputs_segmentation, [
[1, 1, 1, 2, 2],
[1, 0, 0, 0, 0],
])
self.assertAllEqual(
inputs_position, [
[0, 1, 2, 0, 1],
[0, 0, 0, 0, 0],
])
self.assertAllEqual(
targets_packed, [
[10, 20, 30, 40, 0],
[50, 60, 0, 0, 0],
])
self.assertAllEqual(
targets_segmentation, [
[1, 2, 2, 2, 0],
[1, 1, 0, 0, 0],
])
self.assertAllEqual(
targets_position, [
[0, 0, 1, 2, 0],
[0, 1, 0, 0, 0],
])
def do_test_pack_sequences_length6(self, pack_fn):
inputs = [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
]
targets = [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
]
max_length = 6
(inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position) = (
pack_fn(inputs, targets, max_length, max_length))
self.assertAllEqual(inputs_packed, [
[1, 2, 3, 4, 5, 6],
])
self.assertAllEqual(inputs_segmentation, [
[1, 1, 1, 2, 2, 3],
])
self.assertAllEqual(inputs_position, [
[0, 1, 2, 0, 1, 0],
])
self.assertAllEqual(targets_packed, [
[10, 20, 30, 40, 50, 60],
])
self.assertAllEqual(targets_segmentation, [
[1, 2, 2, 2, 3, 3],
])
self.assertAllEqual(targets_position, [
[0, 0, 1, 2, 0, 1],
])
def do_test_pack_sequences_length7(self, pack_fn):
inputs = [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
]
targets = [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
]
max_length = 7
(inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position) = (
pack_fn(inputs, targets, max_length, max_length))
self.assertAllEqual(inputs_packed, [
[1, 2, 3, 4, 5, 6, 0],
])
self.assertAllEqual(inputs_segmentation, [
[1, 1, 1, 2, 2, 3, 0],
])
self.assertAllEqual(inputs_position, [
[0, 1, 2, 0, 1, 0, 0],
])
self.assertAllEqual(targets_packed, [
[10, 20, 30, 40, 50, 60, 0],
])
self.assertAllEqual(targets_segmentation, [
[1, 2, 2, 2, 3, 3, 0],
])
self.assertAllEqual(targets_position, [
[0, 0, 1, 2, 0, 1, 0],
])
def do_test_pack_sequences_length_different_lengths(self, pack_fn):
inputs = [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
]
targets = [
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
]
input_max_length = 3
target_max_length = 4
(inputs_packed, inputs_segmentation, inputs_position, targets_packed,
targets_segmentation, targets_position) = (
pack_fn(inputs, targets, input_max_length, target_max_length))
self.assertAllEqual(inputs_packed, [
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
])
self.assertAllEqual(inputs_segmentation, [
[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
])
self.assertAllEqual(inputs_position, [
[0, 1, 2],
[0, 1, 0],
[0, 0, 0],
])
self.assertAllEqual(targets_packed, [
[10, 0, 0, 0],
[20, 30, 40, 0],
[50, 60, 0, 0],
])
self.assertAllEqual(targets_segmentation, [
[1, 0, 0, 0],
[1, 1, 1, 0],
[1, 1, 0, 0],
])
self.assertAllEqual(targets_position, [
[0, 0, 0, 0],
[0, 1, 2, 0],
[0, 1, 0, 0],
])
def test_pack_sequences2(self):
self.do_test_pack_sequences_length3(pack_sequences_ops.pack_sequences2)
self.do_test_pack_sequences_length4(pack_sequences_ops.pack_sequences2)
self.do_test_pack_sequences_length5(pack_sequences_ops.pack_sequences2)
self.do_test_pack_sequences_length6(pack_sequences_ops.pack_sequences2)
self.do_test_pack_sequences_length7(pack_sequences_ops.pack_sequences2)
self.do_test_pack_sequences_length_different_lengths(
pack_sequences_ops.pack_sequences2)
def test_pack_sequences_k(self):
self.do_test_pack_sequences_length3(_pack_sequences_k)
self.do_test_pack_sequences_length4(_pack_sequences_k)
self.do_test_pack_sequences_length5(_pack_sequences_k)
self.do_test_pack_sequences_length6(_pack_sequences_k)
self.do_test_pack_sequences_length7(_pack_sequences_k)
self.do_test_pack_sequences_length_different_lengths(_pack_sequences_k)
def test_random_inputs(self):
for _ in range(10):
batch_size = np.random.randint(900, 1100, size=[])
input_seqlen = np.random.randint(1, 10, size=[])
target_seqlen = np.random.randint(1, 10, size=[])
inputs_list = []
targets_list = []
for _ in range(batch_size):
input_num_pads = np.random.randint(0, input_seqlen, size=[])
input_pads = np.full([input_num_pads], 0, dtype=np.int32)
inputs = np.random.randint(1, 10, size=[input_seqlen - input_num_pads])
inputs = np.concatenate([inputs, input_pads], axis=0)
target_num_pads = np.random.randint(0, target_seqlen, size=[])
target_pads = np.full([target_num_pads], 0, dtype=np.int32)
targets = np.random.randint(
1, 10, size=[target_seqlen - target_num_pads])
targets = np.concatenate([targets, target_pads], axis=0)
inputs_list.append(inputs)
targets_list.append(targets)
input_maxlen = np.random.randint(input_seqlen, input_seqlen + 10, size=[])
target_maxlen = np.random.randint(
target_seqlen, target_seqlen + 10, size=[])
(inputs_packed2, inputs_segmentation2, inputs_positions2, targets_packed2,
targets_segmentation2, targets_positions2) = (
pack_sequences_ops.pack_sequences2(inputs_list, targets_list,
input_maxlen, target_maxlen))
(inputs_packed_k, inputs_segmentation_k, inputs_positions_k,
targets_packed_k, targets_segmentation_k, targets_positions_k) = (
_pack_sequences_k(inputs_list, targets_list, input_maxlen,
target_maxlen))
self.assertAllEqual(inputs_packed2, inputs_packed_k)
self.assertAllEqual(inputs_segmentation2, inputs_segmentation_k)
self.assertAllEqual(inputs_positions2, inputs_positions_k)
self.assertAllEqual(targets_packed2, targets_packed_k)
self.assertAllEqual(targets_segmentation2, targets_segmentation_k)
self.assertAllEqual(targets_positions2, targets_positions_k)
def test_pack_sequences_k_multi_input(self):
input_tokens = tf.convert_to_tensor([
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
], dtype=tf.int32)
input_vectors = tf.convert_to_tensor([
[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[3, 4, 5], [4, 5, 6], [0, 0, 0]],
[[5, 6, 7], [0, 0, 0], [0, 0, 0]],
], dtype=tf.float32)
targets = tf.convert_to_tensor([
[10, 0, 0],
[20, 30, 40],
[50, 60, 0],
], dtype=tf.int32)
(packed, segmentation, position) = pack_sequences_ops.pack_sequences_k(
[input_tokens, input_vectors, targets],
[5, 3, 5])
(input_tokens_packed, input_vectors_packed, targets_packed) = packed
(input_tokens_segmentation, input_vectors_segmentation,
targets_segmentation) = segmentation
(input_tokens_position, input_vectors_position, targets_position) = position
self.assertAllEqual(
input_tokens_packed, [
[1, 2, 3, 0, 0],
[4, 5, 6, 0, 0],
])
self.assertAllEqual(
input_vectors_packed, [
[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[3, 4, 5], [4, 5, 6], [5, 6, 7]],
])
self.assertAllEqual(
input_tokens_segmentation, [
[1, 1, 1, 0, 0],
[1, 1, 2, 0, 0],
])
self.assertAllEqual(
input_vectors_segmentation, [
[1, 1, 1],
[1, 1, 2],
])
self.assertAllEqual(
input_tokens_position, [
[0, 1, 2, 0, 0],
[0, 1, 0, 0, 0],
])
self.assertAllEqual(
input_vectors_position, [
[0, 1, 2],
[0, 1, 0],
])
self.assertAllEqual(
targets_packed, [
[10, 0, 0, 0, 0],
[20, 30, 40, 50, 60],
])
self.assertAllEqual(
targets_segmentation, [
[1, 0, 0, 0, 0],
[1, 1, 1, 2, 2],
])
self.assertAllEqual(
targets_position, [
[0, 0, 0, 0, 0],
[0, 1, 2, 0, 1],
])
def test_pack_sequences_k_int64(self):
inputs = tf.convert_to_tensor([
[1, 2, 3],
[4, 5, 0],
[6, 0, 0],
], dtype=tf.int64)
max_length = tf.convert_to_tensor(5, dtype=tf.int32)
(packed, segmentation, position) = pack_sequences_ops.pack_sequences_k(
[inputs], [max_length])
(inputs_packed,) = packed
(inputs_segmentation,) = segmentation
(inputs_position,) = position
self.assertAllEqual(
inputs_packed, [
[1, 2, 3, 4, 5],
[6, 0, 0, 0, 0],
])
self.assertEqual(inputs_packed.dtype, tf.int64)
self.assertAllEqual(
inputs_segmentation, [
[1, 1, 1, 2, 2],
[1, 0, 0, 0, 0],
])
self.assertAllEqual(
inputs_position, | |
from typing import Callable
from fp.fp import FreeProxy
import random
import logging
import time
import requests
import tempfile
import urllib3
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait, TimeoutException
from selenium.webdriver.common.by import By
from selenium.common.exceptions import WebDriverException, UnexpectedAlertPresentException
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from urllib.parse import urlparse
from fake_useragent import UserAgent
from contextlib import contextmanager
from deprecated import deprecated
try:
import stem.process
from stem import Signal
from stem.control import Controller
except ImportError:
stem = None
from .data_types import ProxyMode
class DOSException(Exception):
"""DOS attack was detected."""
class MaxTriesExceededException(Exception):
"""Maximum number of tries by scholarly reached"""
class ProxyGenerator(object):
def __init__(self):
# setting up logger
self.logger = logging.getLogger('scholarly')
self._proxy_gen = None
# If we use a proxy or Tor, we set this to True
self._proxy_works = False
self.proxy_mode = None
# If we have a Tor server that we can refresh, we set this to True
self._tor_process = None
self._can_refresh_tor = False
self._tor_control_port = None
self._tor_password = None
self._session = None
self._TIMEOUT = 5
self._new_session()
def __del__(self):
if self._tor_process:
self._tor_process.kill()
self._tor_process.wait()
self._close_session()
def get_session(self):
return self._session
def Luminati(self, usr, passwd, proxy_port):
""" Setups a luminati proxy without refreshing capabilities.
:param usr: scholarly username, optional by default None
:type usr: string
:param passwd: scholarly password, optional by default None
:type passwd: string
:param proxy_port: port for the proxy,optional by default None
:type proxy_port: integer
:returns: whether or not the proxy was set up successfully
:rtype: {bool}
:Example::
>>> pg = ProxyGenerator()
>>> success = pg.Luminati(usr = foo, passwd = <PASSWORD>, port = 1200)
"""
if (usr is not None and passwd is not None and proxy_port is not None):
username = usr
password = <PASSWORD>
port = proxy_port
else:
self.logger.warning("Not enough parameters were provided for the Luminati proxy. Reverting to a local connection.")
return
session_id = random.random()
proxy = f"http://{username}-session-{session_id}:{password}@<EMAIL>:{port}"
proxy_works = self._use_proxy(http=proxy, https=proxy)
if proxy_works:
self.logger.info("Luminati proxy setup successfully")
self.proxy_mode = ProxyMode.LUMINATI
else:
self.logger.warning("Luminati does not seem to work. Reason unknown.")
return proxy_works
def SingleProxy(self, http=None, https=None):
"""
Use proxy of your choice
:param http: http proxy address
:type http: string
:param https: https proxy adress
:type https: string
:returns: whether or not the proxy was set up successfully
:rtype: {bool}
:Example::
>>> pg = ProxyGenerator()
>>> success = pg.SingleProxy(http = <http proxy adress>, https = <https proxy adress>)
"""
self.logger.info("Enabling proxies: http=%s https=%s", http, https)
proxy_works = self._use_proxy(http=http, https=https)
if proxy_works:
self.proxy_mode = ProxyMode.SINGLEPROXY
self.logger.info("Proxy setup successfully")
else:
self.logger.warning("Unable to setup the proxy: http=%s https=%s. Reason unknown." , http, https)
return proxy_works
def _check_proxy(self, proxies) -> bool:
"""Checks if a proxy is working.
:param proxies: A dictionary {'http': url1, 'https': url1}
with the urls of the proxies
:returns: whether the proxy is working or not
:rtype: {bool}
"""
with requests.Session() as session:
session.proxies = proxies
try:
resp = session.get("http://httpbin.org/ip", timeout=self._TIMEOUT)
if resp.status_code == 200:
self.logger.info("Proxy works! IP address: %s",
resp.json()["origin"])
return True
elif resp.status_code == 401:
self.logger.warning("Incorrect credentials for proxy!")
return False
except (TimeoutException, TimeoutError):
time.sleep(self._TIMEOUT)
except Exception as e:
# Failure is common and expected with free proxy.
# Do not log at warning level and annoy users.
level = logging.DEBUG if self.proxy_mode is ProxyMode.FREE_PROXIES else logging.WARNING
self.logger.log(level, "Exception while testing proxy: %s", e)
if self.proxy_mode in (ProxyMode.LUMINATI, ProxyMode.SCRAPERAPI):
self.logger.warning("Double check your credentials and try increasing the timeout")
return False
def _refresh_tor_id(self, tor_control_port: int, password: str) -> bool:
"""Refreshes the id by using a new Tor node.
:returns: Whether or not the refresh was succesful
:rtype: {bool}
"""
try:
with Controller.from_port(port=tor_control_port) as controller:
if password:
controller.authenticate(password=password)
else:
controller.authenticate()
controller.signal(Signal.NEWNYM)
self._new_session()
return (True, self._session)
except Exception as e:
err = f"Exception {e} while refreshing TOR. Retrying..."
self.logger.info(err)
return (False, None)
def _use_proxy(self, http: str, https: str = None) -> bool:
"""Allows user to set their own proxy for the connection session.
Sets the proxy if it works.
:param http: the http proxy
:type http: str
:param https: the https proxy (default to the same as http)
:type https: str
:returns: whether or not the proxy was set up successfully
:rtype: {bool}
"""
if https is None:
https = http
proxies = {'http': http, 'https': https}
self._proxy_works = self._check_proxy(proxies)
if self._proxy_works:
self._session.proxies = proxies
self._new_session()
return self._proxy_works
@deprecated(version='1.5', reason="Tor methods are deprecated and are not actively tested.")
def Tor_External(self, tor_sock_port: int, tor_control_port: int, tor_password: str):
"""
Setting up Tor Proxy. A tor service should be already running on the system. Otherwise you might want to use Tor_Internal
:param tor_sock_port: the port where the Tor sock proxy is running
:type tor_sock_port: int
:param tor_control_port: the port where the Tor control server is running
:type tor_control_port: int
:param tor_password: the password for the Tor control server
:type tor_password: str
:Example::
pg = ProxyGenerator()
pg.Tor_External(tor_sock_port = 9050, tor_control_port = 9051, tor_password = "<PASSWORD>")
Note: This method is deprecated since v1.5
"""
if stem is None:
raise RuntimeError("Tor methods are not supported with basic version of the package. "
"Please install scholarly[tor] to use this method.")
self._TIMEOUT = 10
proxy = f"socks5://127.0.0.1:{tor_sock_port}"
self._use_proxy(http=proxy, https=proxy)
self._can_refresh_tor, _ = self._refresh_tor_id(tor_control_port, tor_password)
if self._can_refresh_tor:
self._tor_control_port = tor_control_port
self._tor_password = <PASSWORD>
else:
self._tor_control_port = None
self._tor_password = None
self.proxy_mode = ProxyMode.TOR_EXTERNAL
# Setting requests timeout to be reasonably long
# to accommodate slowness of the Tor network
return {
"proxy_works": self._proxy_works,
"refresh_works": self._can_refresh_tor,
"tor_control_port": tor_control_port,
"tor_sock_port": tor_sock_port
}
@deprecated(version='1.5', reason="Tor methods are deprecated and are not actively tested")
def Tor_Internal(self, tor_cmd=None, tor_sock_port=None, tor_control_port=None):
'''
Starts a Tor client running in a scholarly-specific port, together with a scholarly-specific control port.
If no arguments are passed for the tor_sock_port and the tor_control_port they are automatically generated in the following ranges
- tor_sock_port: (9000, 9500)
- tor_control_port: (9500, 9999)
:param tor_cmd: tor executable location (absolute path if its not exported in PATH)
:type tor_cmd: string
:param tor_sock_port: tor socket port
:type tor_sock_port: int
:param tor_control_port: tor control port
:type tor_control_port: int
:Example::
pg = ProxyGenerator()
pg.Tor_Internal(tor_cmd = 'tor')
Note: This method is deprecated since v1.5
'''
if stem is None:
raise RuntimeError("Tor methods are not supported with basic version of the package. "
"Please install scholarly[tor] to use this method.")
self.logger.info("Attempting to start owned Tor as the proxy")
if tor_cmd is None:
self.logger.info("No tor_cmd argument passed. This should point to the location of Tor executable.")
return {
"proxy_works": False,
"refresh_works": False,
"tor_control_port": None,
"tor_sock_port": None
}
if tor_sock_port is None:
# Picking a random port to avoid conflicts
# with simultaneous runs of scholarly
tor_sock_port = random.randrange(9000, 9500)
if tor_control_port is None:
# Picking a random port to avoid conflicts
# with simultaneous runs of scholarly
tor_control_port = random.randrange(9500, 9999)
# TODO: Check that the launched Tor process stops after scholar is done
self._tor_process = stem.process.launch_tor_with_config(
tor_cmd=tor_cmd,
config={
'ControlPort': str(tor_control_port),
'SocksPort': str(tor_sock_port),
'DataDirectory': tempfile.mkdtemp()
# TODO Perhaps we want to also set a password here
},
# take_ownership=True # Taking this out for now, as it seems to cause trouble
)
self.proxy_mode = ProxyMode.TOR_INTERNAL
return self.Tor_External(tor_sock_port, tor_control_port, tor_password=None)
def _has_captcha(self, got_id, got_class) -> bool:
_CAPTCHA_IDS = [
"gs_captcha_ccl", # the normal captcha div
"recaptcha", # the form used on full-page captchas
"captcha-form", # another form used on full-page captchas
]
_DOS_CLASSES = [
"rc-doscaptcha-body",
]
if any([got_class(c) for c in _DOS_CLASSES]):
raise DOSException()
return any([got_id(i) for i in _CAPTCHA_IDS])
def _webdriver_has_captcha(self) -> bool:
"""Tests whether the current webdriver page contains a captcha.
:returns: whether or not the site contains a captcha
:rtype: {bool}
"""
return self._has_captcha(
lambda i : len(self._get_webdriver().find_elements(By.ID, i)) > 0,
lambda c : len(self._get_webdriver().find_elements(By.CLASS_NAME, c)) > 0,
)
def _get_webdriver(self):
if self._webdriver:
try:
_ = self._webdriver.current_url
return self._webdriver
except Exception as e:
self.logger.debug(e)
try:
return self._get_firefox_webdriver()
except Exception as err:
self.logger.debug("Cannot open Firefox/Geckodriver: %s", err)
try:
return self._get_chrome_webdriver()
except Exception as err:
self.logger.debug("Cannot open Chrome: %s", err)
self.logger.info("Neither Chrome nor Firefox/Geckodriver found in PATH")
def _get_chrome_webdriver(self):
if self._proxy_works:
webdriver.DesiredCapabilities.CHROME['proxy'] = {
"httpProxy": self._session.proxies['http'],
"sslProxy": self._session.proxies['https'],
"proxyType": "MANUAL"
}
options = webdriver.ChromeOptions()
options.add_argument('--headless')
self._webdriver = webdriver.Chrome('chromedriver', options=options)
self._webdriver.get("https://scholar.google.com") # Need to pre-load to | |
= next_link
class WorkflowParameter(msrest.serialization.Model):
"""The workflow parameters.
:param type: The type. Possible values include: "NotSpecified", "String", "SecureString",
"Int", "Float", "Bool", "Array", "Object", "SecureObject".
:type type: str or ~azure.mgmt.logic.models.ParameterType
:param value: The value.
:type value: object
:param metadata: The metadata.
:type metadata: object
:param description: The description.
:type description: str
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'value': {'key': 'value', 'type': 'object'},
'metadata': {'key': 'metadata', 'type': 'object'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
*,
type: Optional[Union[str, "ParameterType"]] = None,
value: Optional[object] = None,
metadata: Optional[object] = None,
description: Optional[str] = None,
**kwargs
):
super(WorkflowParameter, self).__init__(**kwargs)
self.type = type
self.value = value
self.metadata = metadata
self.description = description
class WorkflowOutputParameter(WorkflowParameter):
"""The workflow output parameter.
Variables are only populated by the server, and will be ignored when sending a request.
:param type: The type. Possible values include: "NotSpecified", "String", "SecureString",
"Int", "Float", "Bool", "Array", "Object", "SecureObject".
:type type: str or ~azure.mgmt.logic.models.ParameterType
:param value: The value.
:type value: object
:param metadata: The metadata.
:type metadata: object
:param description: The description.
:type description: str
:ivar error: Gets the error.
:vartype error: object
"""
_validation = {
'error': {'readonly': True},
}
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'value': {'key': 'value', 'type': 'object'},
'metadata': {'key': 'metadata', 'type': 'object'},
'description': {'key': 'description', 'type': 'str'},
'error': {'key': 'error', 'type': 'object'},
}
def __init__(
self,
*,
type: Optional[Union[str, "ParameterType"]] = None,
value: Optional[object] = None,
metadata: Optional[object] = None,
description: Optional[str] = None,
**kwargs
):
super(WorkflowOutputParameter, self).__init__(type=type, value=value, metadata=metadata, description=description, **kwargs)
self.error = None
class WorkflowReference(ResourceReference):
"""The workflow reference.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: The resource id.
:type id: str
:ivar type: Gets the resource type.
:vartype type: str
:param name: The workflow name.
:type name: str
"""
_validation = {
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
*,
id: Optional[str] = None,
name: Optional[str] = None,
**kwargs
):
super(WorkflowReference, self).__init__(id=id, **kwargs)
self.name = name
class WorkflowRun(SubResource):
"""The workflow run.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The resource id.
:vartype id: str
:ivar name: Gets the workflow run name.
:vartype name: str
:ivar type: Gets the workflow run type.
:vartype type: str
:ivar wait_end_time: Gets the wait end time.
:vartype wait_end_time: ~datetime.datetime
:ivar start_time: Gets the start time.
:vartype start_time: ~datetime.datetime
:ivar end_time: Gets the end time.
:vartype end_time: ~datetime.datetime
:ivar status: Gets the status. Possible values include: "NotSpecified", "Paused", "Running",
"Waiting", "Succeeded", "Skipped", "Suspended", "Cancelled", "Failed", "Faulted", "TimedOut",
"Aborted", "Ignored".
:vartype status: str or ~azure.mgmt.logic.models.WorkflowStatus
:ivar code: Gets the code.
:vartype code: str
:ivar error: Gets the error.
:vartype error: object
:ivar correlation_id: Gets the correlation id.
:vartype correlation_id: str
:param correlation: The run correlation.
:type correlation: ~azure.mgmt.logic.models.Correlation
:ivar workflow: Gets the reference to workflow version.
:vartype workflow: ~azure.mgmt.logic.models.ResourceReference
:ivar trigger: Gets the fired trigger.
:vartype trigger: ~azure.mgmt.logic.models.WorkflowRunTrigger
:ivar outputs: Gets the outputs.
:vartype outputs: dict[str, ~azure.mgmt.logic.models.WorkflowOutputParameter]
:ivar response: Gets the response of the flow run.
:vartype response: ~azure.mgmt.logic.models.WorkflowRunTrigger
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'wait_end_time': {'readonly': True},
'start_time': {'readonly': True},
'end_time': {'readonly': True},
'status': {'readonly': True},
'code': {'readonly': True},
'error': {'readonly': True},
'correlation_id': {'readonly': True},
'workflow': {'readonly': True},
'trigger': {'readonly': True},
'outputs': {'readonly': True},
'response': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'wait_end_time': {'key': 'properties.waitEndTime', 'type': 'iso-8601'},
'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'},
'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'},
'status': {'key': 'properties.status', 'type': 'str'},
'code': {'key': 'properties.code', 'type': 'str'},
'error': {'key': 'properties.error', 'type': 'object'},
'correlation_id': {'key': 'properties.correlationId', 'type': 'str'},
'correlation': {'key': 'properties.correlation', 'type': 'Correlation'},
'workflow': {'key': 'properties.workflow', 'type': 'ResourceReference'},
'trigger': {'key': 'properties.trigger', 'type': 'WorkflowRunTrigger'},
'outputs': {'key': 'properties.outputs', 'type': '{WorkflowOutputParameter}'},
'response': {'key': 'properties.response', 'type': 'WorkflowRunTrigger'},
}
def __init__(
self,
*,
correlation: Optional["Correlation"] = None,
**kwargs
):
super(WorkflowRun, self).__init__(**kwargs)
self.name = None
self.type = None
self.wait_end_time = None
self.start_time = None
self.end_time = None
self.status = None
self.code = None
self.error = None
self.correlation_id = None
self.correlation = correlation
self.workflow = None
self.trigger = None
self.outputs = None
self.response = None
class WorkflowRunAction(SubResource):
"""The workflow run action.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The resource id.
:vartype id: str
:ivar name: Gets the workflow run action name.
:vartype name: str
:ivar type: Gets the workflow run action type.
:vartype type: str
:ivar start_time: Gets the start time.
:vartype start_time: ~datetime.datetime
:ivar end_time: Gets the end time.
:vartype end_time: ~datetime.datetime
:ivar status: Gets the status. Possible values include: "NotSpecified", "Paused", "Running",
"Waiting", "Succeeded", "Skipped", "Suspended", "Cancelled", "Failed", "Faulted", "TimedOut",
"Aborted", "Ignored".
:vartype status: str or ~azure.mgmt.logic.models.WorkflowStatus
:ivar code: Gets the code.
:vartype code: str
:ivar error: Gets the error.
:vartype error: object
:ivar tracking_id: Gets the tracking id.
:vartype tracking_id: str
:param correlation: The correlation properties.
:type correlation: ~azure.mgmt.logic.models.RunActionCorrelation
:ivar inputs_link: Gets the link to inputs.
:vartype inputs_link: ~azure.mgmt.logic.models.ContentLink
:ivar outputs_link: Gets the link to outputs.
:vartype outputs_link: ~azure.mgmt.logic.models.ContentLink
:ivar tracked_properties: Gets the tracked properties.
:vartype tracked_properties: object
:param retry_history: Gets the retry histories.
:type retry_history: list[~azure.mgmt.logic.models.RetryHistory]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'start_time': {'readonly': True},
'end_time': {'readonly': True},
'status': {'readonly': True},
'code': {'readonly': True},
'error': {'readonly': True},
'tracking_id': {'readonly': True},
'inputs_link': {'readonly': True},
'outputs_link': {'readonly': True},
'tracked_properties': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'},
'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'},
'status': {'key': 'properties.status', 'type': 'str'},
'code': {'key': 'properties.code', 'type': 'str'},
'error': {'key': 'properties.error', 'type': 'object'},
'tracking_id': {'key': 'properties.trackingId', 'type': 'str'},
'correlation': {'key': 'properties.correlation', 'type': 'RunActionCorrelation'},
'inputs_link': {'key': 'properties.inputsLink', 'type': 'ContentLink'},
'outputs_link': {'key': 'properties.outputsLink', 'type': 'ContentLink'},
'tracked_properties': {'key': 'properties.trackedProperties', 'type': 'object'},
'retry_history': {'key': 'properties.retryHistory', 'type': '[RetryHistory]'},
}
def __init__(
self,
*,
correlation: Optional["RunActionCorrelation"] = None,
retry_history: Optional[List["RetryHistory"]] = None,
**kwargs
):
super(WorkflowRunAction, self).__init__(**kwargs)
self.name = None
self.type = None
self.start_time = None
self.end_time = None
self.status = None
self.code = None
self.error = None
self.tracking_id = None
self.correlation = correlation
self.inputs_link = None
self.outputs_link = None
self.tracked_properties = None
self.retry_history = retry_history
class WorkflowRunActionFilter(msrest.serialization.Model):
"""The workflow run action filter.
:param status: The status of workflow run action. Possible values include: "NotSpecified",
"Paused", "Running", "Waiting", "Succeeded", "Skipped", "Suspended", "Cancelled", "Failed",
"Faulted", "TimedOut", "Aborted", "Ignored".
:type status: str or ~azure.mgmt.logic.models.WorkflowStatus
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
*,
status: Optional[Union[str, "WorkflowStatus"]] = None,
**kwargs
):
super(WorkflowRunActionFilter, self).__init__(**kwargs)
self.status = status
class WorkflowRunActionListResult(msrest.serialization.Model):
"""The list of workflow run actions.
:param value: A list of workflow run actions.
:type value: list[~azure.mgmt.logic.models.WorkflowRunAction]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[WorkflowRunAction]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
*,
value: Optional[List["WorkflowRunAction"]] = None,
next_link: Optional[str] = None,
**kwargs
):
super(WorkflowRunActionListResult, self).__init__(**kwargs)
self.value = value
self.next_link = next_link
class WorkflowRunActionRepetitionDefinition(Resource):
"""The workflow run action repetition definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The resource id.
:vartype id: str
:ivar name: Gets the resource name.
:vartype name: str
:ivar type: Gets the resource type.
:vartype type: str
:param location: The resource location.
:type location: str
:param tags: A set of tags. The resource tags.
:type tags: dict[str, str]
:param start_time: The start time of the workflow scope repetition.
:type start_time: ~datetime.datetime
:param end_time: The end time of the workflow scope repetition.
:type end_time: ~datetime.datetime
:param correlation: The correlation properties.
:type correlation: ~azure.mgmt.logic.models.RunActionCorrelation
:param status: The status of the workflow scope repetition. Possible values include:
"NotSpecified", "Paused", "Running", "Waiting", "Succeeded", | |
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Dataloaders and dataset utils
"""
import glob
import hashlib
import json
import math
import os
import random
import shutil
import time
from itertools import repeat
from multiprocessing.pool import Pool, ThreadPool
from pathlib import Path
from threading import Thread
from zipfile import ZipFile
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from PIL import ExifTags, Image, ImageOps
from tqdm import tqdm
from .augmentations import letterbox
from .general import (xyn2xy, xywh2xyxy, xywhn2xyxy)
# Parameters
HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
IMG_FORMATS = ['bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp'] # include image suffixes
VID_FORMATS = ['asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'wmv'] # include video suffixes
# Get orientation exif tag
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
def get_hash(paths):
# Returns a single hash value of a list of paths (files or dirs)
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
h = hashlib.md5(str(size).encode()) # hash sizes
h.update(''.join(paths).encode()) # hash paths
return h.hexdigest() # return hash
def exif_size(img):
# Returns exif-corrected PIL size
s = img.size # (width, height)
try:
rotation = dict(img._getexif().items())[orientation]
if rotation == 6: # rotation 270
s = (s[1], s[0])
elif rotation == 8: # rotation 90
s = (s[1], s[0])
except:
pass
return s
def exif_transpose(image):
"""
Transpose a PIL image accordingly if it has an EXIF Orientation tag.
Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
:param image: The image to transpose.
:return: An image.
"""
exif = image.getexif()
orientation = exif.get(0x0112, 1) # default 1
if orientation > 1:
method = {2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
image = image.transpose(method)
del exif[0x0112]
image.info["exif"] = exif.tobytes()
return image
class LoadImages:
# YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
def __init__(self, path, img_size=640, stride=32, auto=True):
p = str(Path(path).resolve()) # os-agnostic absolute path
if '*' in p:
files = sorted(glob.glob(p, recursive=True)) # glob
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
elif os.path.isfile(p):
files = [p] # files
else:
raise Exception(f'ERROR: {p} does not exist')
images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.stride = stride
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = 'image'
self.auto = auto
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, f'No images or videos found in {p}. ' \
f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
while not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
self.frame += 1
s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
else:
# Read image
self.count += 1
img0 = cv2.imread(path) # BGR
assert img0 is not None, f'Image Not Found {path}'
s = f'image {self.count}/{self.nf} {path}: '
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return path, img, img0, self.cap, s
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf # number of files
def img2label_paths(img_paths):
# Define label paths as a function of image paths
sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
# Ancillary functions --------------------------------------------------------------------------------------------------
def load_image(self, i):
# loads 1 image from dataset index 'i', returns im, original hw, resized hw
im = self.imgs[i]
if im is None: # not cached in ram
npy = self.img_npy[i]
if npy and npy.exists(): # load npy
im = np.load(npy)
else: # read image
path = self.img_files[i]
im = cv2.imread(path) # BGR
assert im is not None, f'Image Not Found {path}'
h0, w0 = im.shape[:2] # orig hw
r = self.img_size / max(h0, w0) # ratio
if r != 1: # if sizes are not equal
im = cv2.resize(im, (int(w0 * r), int(h0 * r)),
interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
else:
return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized
def load_mosaic(self, index):
# YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
labels4, segments4 = [], []
s = self.img_size
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
random.shuffle(indices)
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img4
if i == 0: # top left
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
elif i == 1: # top right
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2: # bottom left
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3: # bottom right
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
padw = x1a - x1b
padh = y1a - y1b
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
# Concat/clip labels
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img4, labels4 = replicate(img4, labels4) # replicate
return img4, labels4
def load_mosaic9(self, index):
# YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
random.shuffle(indices)
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img9
if i == 0: # center
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
h0, w0 = h, w
c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
elif i == 1: # top
c = s, s - h, s + w, s
elif i == 2: # top right
c = s + wp, s - h, s + wp + w, s
elif i == 3: # right
c = s + w0, s, s + w0 + w, s + h
elif i == 4: # bottom right
c = s + w0, s + hp, s + w0 + w, s + hp + h
elif i == 5: # bottom
c = s + w0 - w, s + h0, s + w0, s + h0 | |
"""
normal_modes.py: Compute Cartesian Hessian and perform vibrational analysis
Copyright 2016-2020 Regents of the University of California and the Authors
Authors: <NAME>, <NAME>
Contributors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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 HOLDER 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.
"""
from __future__ import division
from __future__ import print_function
import os, shutil
import numpy as np
from .errors import FrequencyError
from .molecule import Molecule, PeriodicTable
from .nifty import logger, kb, kb_si, hbar, au2kj, au2kcal, ang2bohr, bohr2ang, c_lightspeed, avogadro, cm2au, amu2au, ambervel2au, wq_wait, getWorkQueue, commadash, bak
def calc_cartesian_hessian(coords, molecule, engine, dirname, read_data=True, verbose=0):
"""
Calculate the Cartesian Hessian using finite difference, and/or read data from disk.
Data is stored in a folder <prefix>.tmp/hessian, with gradient calculations found in
<prefix>.tmp/hessian/displace/001p.
Parameters
----------
coords : np.ndarray
Nx3 array of Cartesian coordinates in atomic units
molecule : Molecule
Molecule object
engine : Engine
Object containing methods for calculating energy and gradient
dirname : str
Directory name for files to be written, i.e. <prefix>.tmp
read_data : bool
Read Hessian data from disk if valid
Returns
-------
Hx : np.ndarray
(Nx3)x(Nx3) array containing Cartesian Hessian.
Files are also written to <prefix.tmp>/hessian.
"""
nc = len(coords)
# Attempt to read existing Hessian data if it exists.
hesstxt = os.path.join(dirname, "hessian", "hessian.txt")
hessxyz = os.path.join(dirname, "hessian", "coords.xyz")
if read_data and os.path.exists(hesstxt) and os.path.exists(hessxyz):
Hx = np.loadtxt(hesstxt)
if Hx.shape[0] == nc:
hess_mol = Molecule(hessxyz)
if np.allclose(coords.reshape(-1, 3)*bohr2ang, hess_mol.xyzs[0], atol=1e-6):
logger.info("Using Hessian matrix read from file\n")
return Hx
else:
logger.info("Coordinates for Hessian don't match current coordinates, recalculating.\n")
bak('hessian.txt', cwd=os.path.join(dirname, "hessian"), start=0)
bak('coords.xyz', cwd=os.path.join(dirname, "hessian"), start=0)
read_data=False
else:
logger.info("Hessian read from file doesn't have the right shape, recalculating.\n")
read_data=False
elif not os.path.exists(hessxyz):
logger.info("Coordinates for Hessian not found, recalculating.\n")
read_data = False
# Save Hessian to text file
oldxyz = molecule.xyzs[0].copy()
molecule.xyzs[0] = coords.reshape(-1, 3)*bohr2ang
if not os.path.exists(os.path.join(dirname, "hessian")):
os.makedirs(os.path.join(dirname, "hessian"))
molecule[0].write(hessxyz)
if not read_data:
if os.path.exists(os.path.join(dirname, "hessian", "displace")):
shutil.rmtree(os.path.join(dirname, "hessian", "displace"))
# Calculate Hessian using finite difference
# Finite difference step
h = 1.0e-3
wq = getWorkQueue()
Hx = np.zeros((nc, nc), dtype=float)
logger.info("Calculating Cartesian Hessian using finite difference on Cartesian gradients\n")
if wq:
for i in range(nc):
if verbose >= 2: logger.info(" Submitting gradient calculation for coordinate %i/%i\n" % (i+1, nc))
coords[i] += h
dirname_d = os.path.join(dirname, "hessian/displace/%03ip" % (i+1))
engine.calc_wq(coords, dirname_d, read_data=read_data, copydir=dirname)
coords[i] -= 2*h
dirname_d = os.path.join(dirname, "hessian/displace/%03im" % (i+1))
engine.calc_wq(coords, dirname_d, read_data=read_data, copydir=dirname)
coords[i] += h
wq_wait(wq, print_time=600)
for i in range(nc):
if verbose >= 2: logger.info(" Reading gradient results for coordinate %i/%i\n" % (i+1, nc))
coords[i] += h
dirname_d = os.path.join(dirname, "hessian/displace/%03ip" % (i+1))
gfwd = engine.read_wq(coords, dirname_d)['gradient']
coords[i] -= 2*h
dirname_d = os.path.join(dirname, "hessian/displace/%03im" % (i+1))
gbak = engine.read_wq(coords, dirname_d)['gradient']
coords[i] += h
Hx[i] = (gfwd-gbak)/(2*h)
else:
# First calculate a gradient at the central point, for linking scratch files.
engine.calc(coords, dirname, read_data=read_data)
for i in range(nc):
if verbose >= 2: logger.info(" Running gradient calculation for coordinate %i/%i\n" % (i+1, nc))
elif verbose >= 1 and (i%5 == 0): logger.info("%i / %i gradient calculations complete\n" % (i*2, nc*2))
coords[i] += h
dirname_d = os.path.join(dirname, "hessian/displace/%03ip" % (i+1))
gfwd = engine.calc(coords, dirname_d, read_data=read_data, copydir=dirname)['gradient']
coords[i] -= 2*h
dirname_d = os.path.join(dirname, "hessian/displace/%03im" % (i+1))
gbak = engine.calc(coords, dirname_d, read_data=read_data, copydir=dirname)['gradient']
coords[i] += h
Hx[i] = (gfwd-gbak)/(2*h)
if verbose == 1 and i == (nc-1) : logger.info("%i / %i gradient calculations complete\n" % (nc*2, nc*2))
# Save Hessian to text file
oldxyz = molecule.xyzs[0].copy()
molecule.xyzs[0] = coords.reshape(-1, 3)*bohr2ang
molecule[0].write(hessxyz)
molecule.xyzs[0] = oldxyz
np.savetxt(hesstxt, Hx)
# Delete displacement calcs because they take up too much space
keep_displace = False
if not keep_displace:
if os.path.exists(os.path.join(dirname, "hessian", "displace")):
shutil.rmtree(os.path.join(dirname, "hessian", "displace"))
return Hx
def frequency_analysis(coords, Hessian, elem=None, mass=None, energy=0.0, temperature=300.0, pressure=1.0, verbose=0, outfnm=None, note=None, wigner=None, normalized=True):
"""
Parameters
----------
coords : np.array
n_atoms*3 length array containing coordinates in bohr
Hessian : np.array
(n_atoms*3)*(n_atoms*3) length array containing Hessian elements in au
(i.e. Hessian/bohr^2), the typical units output by QM calculations
elem : list
n_atoms length list containing atomic symbols.
Used in printing displacements and for looking up masses if mass = None.
mass : list or np.array
n_atoms length list or 1D array containing atomic masses in amu.
If provided, masses will not be looked up using elem.
If neither mass nor elem will be provided, will assume masses are all unity.
energy : float
Electronic energy passed to the harmonic free energy module
temperature : float
Temperature passed to the harmonic free energy module
pressure : float
Pressure passed to the harmonic free energy module
verbose : int
Print debugging info
outfnm : str
If provided, write vibrational data to a ForceBalance-parsable vdata.txt file
note : str
If provided, write a note into the comment line of the xyz structure in vdata.txt
wigner : tuple
If provided, should be a 2-tuple containing (nSamples, dirname)
containing the output folder and number of samples and the output folder
to which samples should be written
normalized : bool
If True, normalize the un-mass-weighted Cartesian displacements of each normal mode (default)
If False, return the un-normalized vectors (necessary for IR and Raman intensities)
Returns
-------
freqs_wavenumber : np.array
n_vibmodes length array containing vibrational frequencies in wavenumber
(imaginary frequencies are reported as negative)
normal_modes_cart : np.array
n_vibmodes*n_atoms length array containing un-mass-weighted Cartesian displacements
of each normal mode
"""
# Create a copy of coords and reshape into a 2D array
coords = coords.copy().reshape(-1, 3)
na = coords.shape[0]
if mass is not None:
mass = np.array(mass)
assert len(mass) == na
elif elem:
mass = np.array([PeriodicTable[j] for j in elem])
assert len(elem) == na
else:
logger.warning("neither elem nor mass is provided; assuming all masses unity")
mass = np.ones(na)
assert coords.shape == (na, 3)
assert Hessian.shape == (3*na, 3*na)
# Convert Hessian eigenvalues into wavenumbers:
#
# omega = sqrt(k/m)
#
# X hartree bohr^-2 amu^-1 * 2625.5 (kJ mol^-1 / hartree) * (1/0.0529 bohr/nm)^2
# --> omega^2 = 938211*X ps^-2
#
# Frequencies in units of inverse ps:
# nu = sqrt(938211*X)/2*pi
#
# Convert to inverse wavelength in units of cm^-1:
#
# 1/lambda = nu/c = (sqrt(938211*X)/2*pi) / (2.998e8 m/s) * (m/100cm) * 10^12ps/s
bohr2nm = bohr2ang / 10
mwHess_wavenumber = 1e10*np.sqrt(au2kj / bohr2nm**2)/(2*np.pi*c_lightspeed)
TotDOF = 3*na
# Compute the mass weighted Hessian matrix
# Each element is H[i, j] / sqrt(m[i]) / sqrt(m[j])
invsqrtm3 = 1.0/np.sqrt(np.repeat(mass, 3))
wHessian = Hessian.copy() * np.outer(invsqrtm3, invsqrtm3)
if verbose >= 2:
# Eigenvalues before projection of translation and rotation
logger.info("Eigenvalues before projection of translation and rotation\n")
w_eigvals = np.linalg.eigvalsh(wHessian)
for i in range(TotDOF):
val = mwHess_wavenumber*np.sqrt(abs(w_eigvals[i]))
logger.info("%5i % 10.3f\n" % (i, val))
#=============================================#
#| Remove rotational and translational modes |#
#=============================================#
# Compute the center of mass
cxyz = np.sum(coords * mass[:, np.newaxis], axis=0)/np.sum(mass)
# Coordinates | |
# Copyright 2019 Google LLC
#
# 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
#
# https://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.
"""Tests for attribute_checker.py."""
import unittest
from compiler.front_end import attribute_checker
from compiler.front_end import glue
from compiler.front_end import test_util
from compiler.util import error
from compiler.util import ir_pb2
from compiler.util import ir_util
# These are not shared with attribute_checker.py because their values are part
# of the contract with back ends.
_BYTE_ORDER = "byte_order"
_FIXED_SIZE = "fixed_size_in_bits"
def _make_ir_from_emb(emb_text, name="m.emb"):
ir, unused_debug_info, errors = glue.parse_emboss_file(
name,
test_util.dict_file_reader({name: emb_text}),
stop_before_step="normalize_and_verify")
assert not errors
return ir
class NormalizeIrTest(unittest.TestCase):
def test_rejects_may_be_used_as_integer(self):
enum_ir = _make_ir_from_emb("enum Foo:\n"
" [may_be_used_as_integer: false]\n"
" VALUE = 1\n")
enum_type_ir = enum_ir.module[0].type[0]
self.assertEqual([[
error.error(
"m.emb", enum_type_ir.attribute[0].name.source_location,
"Unknown attribute 'may_be_used_as_integer' on enum 'Foo'.")
]], attribute_checker.normalize_and_verify(enum_ir))
def test_adds_fixed_size_attribute_to_struct(self):
# field2 is intentionally after field3, in order to trigger certain code
# paths in attribute_checker.py.
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" 0 [+2] UInt field1\n"
" 4 [+4] UInt field2\n"
" 2 [+2] UInt field3\n")
self.assertEqual([], attribute_checker.normalize_and_verify(struct_ir))
size_attr = ir_util.get_attribute(struct_ir.module[0].type[0].attribute,
_FIXED_SIZE)
self.assertEqual(64, ir_util.constant_value(size_attr.expression))
self.assertEqual(struct_ir.module[0].type[0].source_location,
size_attr.source_location)
def test_adds_fixed_size_attribute_to_struct_with_virtual_field(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" 0 [+2] UInt field1\n"
" let field2 = field1\n"
" 2 [+2] UInt field3\n")
self.assertEqual([], attribute_checker.normalize_and_verify(struct_ir))
size_attr = ir_util.get_attribute(struct_ir.module[0].type[0].attribute,
_FIXED_SIZE)
self.assertEqual(32, ir_util.constant_value(size_attr.expression))
self.assertEqual(struct_ir.module[0].type[0].source_location,
size_attr.source_location)
def test_adds_fixed_size_attribute_to_anonymous_bits(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" 0 [+4] bits:\n"
" 0 [+8] UInt field\n")
self.assertEqual([], attribute_checker.normalize_and_verify(struct_ir))
size_attr = ir_util.get_attribute(struct_ir.module[0].type[0].attribute,
_FIXED_SIZE)
self.assertEqual(32, ir_util.constant_value(size_attr.expression))
bits_size_attr = ir_util.get_attribute(
struct_ir.module[0].type[0].subtype[0].attribute, _FIXED_SIZE)
self.assertEqual(8, ir_util.constant_value(bits_size_attr.expression))
self.assertEqual(struct_ir.module[0].type[0].source_location,
size_attr.source_location)
def test_does_not_add_fixed_size_attribute_to_variable_size_struct(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" 0 [+4] UInt n\n"
" 4 [+n] UInt:8[] payload\n")
self.assertEqual([], attribute_checker.normalize_and_verify(struct_ir))
self.assertIsNone(ir_util.get_attribute(
struct_ir.module[0].type[0].attribute, _FIXED_SIZE))
def test_accepts_correct_fixed_size_and_size_attributes_on_struct(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" [fixed_size_in_bits: 64]\n"
" 0 [+2] UInt field1\n"
" 2 [+2] UInt field2\n"
" 4 [+4] UInt field3\n")
self.assertEqual([], attribute_checker.normalize_and_verify(struct_ir))
size_attr = ir_util.get_attribute(struct_ir.module[0].type[0].attribute,
_FIXED_SIZE)
self.assertTrue(size_attr)
self.assertEqual(64, ir_util.constant_value(size_attr.expression))
def test_accepts_correct_size_attribute_on_struct(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" [fixed_size_in_bits: 64]\n"
" 0 [+2] UInt field1\n"
" 4 [+4] UInt field3\n")
self.assertEqual([], attribute_checker.normalize_and_verify(struct_ir))
size_attr = ir_util.get_attribute(struct_ir.module[0].type[0].attribute,
_FIXED_SIZE)
self.assertTrue(size_attr.expression)
self.assertEqual(64, ir_util.constant_value(size_attr.expression))
def test_rejects_incorrect_fixed_size_attribute_on_variable_size_struct(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" [fixed_size_in_bits: 8]\n"
" 0 [+4] UInt n\n"
" 4 [+n] UInt:8[] payload\n")
struct_type_ir = struct_ir.module[0].type[0]
self.assertEqual([[error.error(
"m.emb", struct_type_ir.attribute[0].value.source_location,
"Struct is marked as fixed size, but contains variable-location "
"fields.")]], attribute_checker.normalize_and_verify(struct_ir))
def test_rejects_size_attribute_with_wrong_large_value_on_struct(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" [fixed_size_in_bits: 80]\n"
" 0 [+2] UInt field1\n"
" 2 [+2] UInt field2\n"
" 4 [+4] UInt field3\n")
struct_type_ir = struct_ir.module[0].type[0]
self.assertEqual([
[error.error("m.emb", struct_type_ir.attribute[0].value.source_location,
"Struct is 64 bits, but is marked as 80 bits.")]
], attribute_checker.normalize_and_verify(struct_ir))
def test_rejects_size_attribute_with_wrong_small_value_on_struct(self):
struct_ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" [fixed_size_in_bits: 40]\n"
" 0 [+2] UInt field1\n"
" 2 [+2] UInt field2\n"
" 4 [+4] UInt field3\n")
struct_type_ir = struct_ir.module[0].type[0]
self.assertEqual([
[error.error("m.emb", struct_type_ir.attribute[0].value.source_location,
"Struct is 64 bits, but is marked as 40 bits.")]
], attribute_checker.normalize_and_verify(struct_ir))
def test_accepts_variable_size_external(self):
external_ir = _make_ir_from_emb("external Foo:\n"
" [addressable_unit_size: 1]\n")
self.assertEqual([], attribute_checker.normalize_and_verify(external_ir))
def test_accepts_fixed_size_external(self):
external_ir = _make_ir_from_emb("external Foo:\n"
" [fixed_size_in_bits: 32]\n"
" [addressable_unit_size: 1]\n")
self.assertEqual([], attribute_checker.normalize_and_verify(external_ir))
def test_rejects_external_with_no_addressable_unit_size_attribute(self):
external_ir = _make_ir_from_emb("external Foo:\n"
" [is_integer: false]\n")
external_type_ir = external_ir.module[0].type[0]
self.assertEqual([
[error.error(
"m.emb", external_type_ir.source_location,
"Expected 'addressable_unit_size' attribute for external type.")]
], attribute_checker.normalize_and_verify(external_ir))
def test_rejects_is_integer_with_non_constant_value(self):
external_ir = _make_ir_from_emb(
"external Foo:\n"
" [is_integer: $static_size_in_bits == 1]\n"
" [addressable_unit_size: 1]\n")
external_type_ir = external_ir.module[0].type[0]
self.assertEqual([
[error.error(
"m.emb", external_type_ir.attribute[0].value.source_location,
"Attribute 'is_integer' must have a constant boolean value.")]
], attribute_checker.normalize_and_verify(external_ir))
def test_rejects_addressable_unit_size_with_non_constant_value(self):
external_ir = _make_ir_from_emb(
"external Foo:\n"
" [is_integer: true]\n"
" [addressable_unit_size: $static_size_in_bits]\n")
external_type_ir = external_ir.module[0].type[0]
self.assertEqual([
[error.error(
"m.emb", external_type_ir.attribute[1].value.source_location,
"Attribute 'addressable_unit_size' must have a constant value.")]
], attribute_checker.normalize_and_verify(external_ir))
def test_rejects_external_with_wrong_addressable_unit_size_attribute(self):
external_ir = _make_ir_from_emb("external Foo:\n"
" [addressable_unit_size: 4]\n")
external_type_ir = external_ir.module[0].type[0]
self.assertEqual([
[error.error(
"m.emb", external_type_ir.source_location,
"Only values '1' (bit) and '8' (byte) are allowed for the "
"'addressable_unit_size' attribute")]
], attribute_checker.normalize_and_verify(external_ir))
def test_rejects_duplicate_attribute(self):
ir = _make_ir_from_emb("external Foo:\n"
" [is_integer: true]\n"
" [is_integer: true]\n")
self.assertEqual([[
error.error("m.emb", ir.module[0].type[0].attribute[1].source_location,
"Duplicate attribute 'is_integer'."),
error.note("m.emb", ir.module[0].type[0].attribute[0].source_location,
"Original attribute"),
]], attribute_checker.normalize_and_verify(ir))
def test_rejects_duplicate_default_attribute(self):
ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
'[$default byte_order: "LittleEndian"]\n')
self.assertEqual(
[[
error.error("m.emb", ir.module[0].attribute[1].source_location,
"Duplicate attribute 'byte_order'."),
error.note("m.emb", ir.module[0].attribute[0].source_location,
"Original attribute"),
]], attribute_checker.normalize_and_verify(ir))
def test_rejects_unknown_attribute(self):
ir = _make_ir_from_emb("[gibberish: true]\n")
attr = ir.module[0].attribute[0]
self.assertEqual([[
error.error("m.emb", attr.name.source_location,
"Unknown attribute 'gibberish' on module 'm.emb'.")
]], attribute_checker.normalize_and_verify(ir))
def test_rejects_non_constant_attribute(self):
ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" [fixed_size_in_bits: field1]\n"
" 0 [+2] UInt field1\n")
attr = ir.module[0].type[0].attribute[0]
self.assertEqual(
[[
error.error(
"m.emb", attr.value.source_location,
"Attribute 'fixed_size_in_bits' must have a constant value.")
]],
attribute_checker.normalize_and_verify(ir))
def test_accepts_string_attribute(self):
ir = _make_ir_from_emb('[(cpp) namespace: "foo"]\n')
self.assertEqual([], attribute_checker.normalize_and_verify(ir))
def test_rejects_wrong_type_for_string_attribute(self):
ir = _make_ir_from_emb("[(cpp) namespace: 9]\n")
attr = ir.module[0].attribute[0]
self.assertEqual([[
error.error("m.emb", attr.value.source_location,
"Attribute 'namespace' must have a string value.")
]], attribute_checker.normalize_and_verify(ir))
def test_accepts_back_end_qualified_attribute(self):
ir = _make_ir_from_emb('[(cpp) namespace: "abc"]\n')
self.assertEqual([], attribute_checker.normalize_and_verify(ir))
def test_rejects_attribute_missing_required_back_end_specifier(self):
ir = _make_ir_from_emb('[namespace: "abc"]\n')
attr = ir.module[0].attribute[0]
self.assertEqual([[
error.error("m.emb", attr.name.source_location,
"Unknown attribute 'namespace' on module 'm.emb'.")
]], attribute_checker.normalize_and_verify(ir))
def test_rejects_attribute_with_wrong_back_end_specifier(self):
ir = _make_ir_from_emb('[(c) namespace: "abc"]\n')
attr = ir.module[0].attribute[0]
self.assertEqual([[
error.error("m.emb", attr.name.source_location,
"Unknown attribute '(c) namespace' on module 'm.emb'.")
]], attribute_checker.normalize_and_verify(ir))
def test_rejects_emboss_internal_attribute_with_back_end_specifier(self):
ir = _make_ir_from_emb('[(cpp) byte_order: "LittleEndian"]\n')
attr = ir.module[0].attribute[0]
self.assertEqual([[
error.error("m.emb", attr.name.source_location,
"Unknown attribute '(cpp) byte_order' on module 'm.emb'.")
]], attribute_checker.normalize_and_verify(ir))
def test_adds_byte_order_attributes_from_default(self):
ir = _make_ir_from_emb('[$default byte_order: "BigEndian"]\n'
"struct Foo:\n"
" 0 [+2] UInt bar\n"
" 2 [+2] UInt baz\n"
' [byte_order: "LittleEndian"]\n')
self.assertEqual([], attribute_checker.normalize_and_verify(ir))
byte_order_attr = ir_util.get_attribute(
ir.module[0].type[0].structure.field[0].attribute, _BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("BigEndian", byte_order_attr.string_constant.text)
byte_order_attr = ir_util.get_attribute(
ir.module[0].type[0].structure.field[1].attribute, _BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("LittleEndian", byte_order_attr.string_constant.text)
def test_adds_null_byte_order_attributes(self):
ir = _make_ir_from_emb("struct Foo:\n"
" 0 [+1] UInt bar\n"
" 1 [+1] UInt baz\n"
' [byte_order: "LittleEndian"]\n'
" 2 [+2] UInt:8[] baseball\n"
" 4 [+2] UInt:8[] bat\n"
' [byte_order: "LittleEndian"]\n')
self.assertEqual([], attribute_checker.normalize_and_verify(ir))
structure = ir.module[0].type[0].structure
byte_order_attr = ir_util.get_attribute(
structure.field[0].attribute, _BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("Null", byte_order_attr.string_constant.text)
self.assertEqual(structure.field[0].source_location,
byte_order_attr.source_location)
byte_order_attr = ir_util.get_attribute(structure.field[1].attribute,
_BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("LittleEndian", byte_order_attr.string_constant.text)
byte_order_attr = ir_util.get_attribute(structure.field[2].attribute,
_BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("Null", byte_order_attr.string_constant.text)
self.assertEqual(structure.field[2].source_location,
byte_order_attr.source_location)
byte_order_attr = ir_util.get_attribute(structure.field[3].attribute,
_BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("LittleEndian", byte_order_attr.string_constant.text)
def test_disallows_default_byte_order_on_field(self):
ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
" 0 [+2] UInt bar\n"
' [$default byte_order: "LittleEndian"]\n')
default_byte_order = ir.module[0].type[0].structure.field[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", default_byte_order.name.source_location,
"Attribute 'byte_order' may not be defaulted on struct field 'bar'."
)]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_default_byte_order_on_bits(self):
ir = _make_ir_from_emb("bits Foo:\n"
' [$default byte_order: "LittleEndian"]\n'
" 0 [+2] UInt bar\n")
default_byte_order = ir.module[0].type[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", default_byte_order.name.source_location,
"Attribute 'byte_order' may not be defaulted on bits 'Foo'.")]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_default_byte_order_on_enum(self):
ir = _make_ir_from_emb("enum Foo:\n"
' [$default byte_order: "LittleEndian"]\n'
" BAR = 1\n")
default_byte_order = ir.module[0].type[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", default_byte_order.name.source_location,
"Attribute 'byte_order' may not be defaulted on enum 'Foo'.")]],
attribute_checker.normalize_and_verify(ir))
def test_adds_byte_order_from_scoped_default(self):
ir = _make_ir_from_emb('[$default byte_order: "LittleEndian"]\n'
"struct Foo:\n"
' [$default byte_order: "BigEndian"]\n'
" 0 [+2] UInt bar\n")
self.assertEqual([], attribute_checker.normalize_and_verify(ir))
byte_order_attr = ir_util.get_attribute(
ir.module[0].type[0].structure.field[0].attribute, _BYTE_ORDER)
self.assertTrue(byte_order_attr.HasField("string_constant"))
self.assertEqual("BigEndian", byte_order_attr.string_constant.text)
def test_disallows_unknown_byte_order(self):
ir = _make_ir_from_emb("struct Foo:\n"
" 0 [+2] UInt bar\n"
' [byte_order: "NoEndian"]\n')
byte_order = ir.module[0].type[0].structure.field[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", byte_order.value.source_location,
"Attribute 'byte_order' must be 'BigEndian' or 'LittleEndian' or "
"'Null'.")]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_unknown_default_byte_order(self):
ir = _make_ir_from_emb('[$default byte_order: "NoEndian"]\n')
default_byte_order = ir.module[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", default_byte_order.value.source_location,
"Attribute 'byte_order' must be 'BigEndian' or 'LittleEndian' or "
"'Null'.")]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_byte_order_on_non_byte_order_dependent_fields(self):
ir = _make_ir_from_emb("struct Foo:\n"
' [$default byte_order: "LittleEndian"]\n'
" 0 [+2] UInt uint\n"
"struct Bar:\n"
" 0 [+2] Foo foo\n"
' [byte_order: "LittleEndian"]\n')
byte_order = ir.module[0].type[1].structure.field[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", byte_order.value.source_location,
"Attribute 'byte_order' not allowed on field which is not byte "
"order dependent.")]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_byte_order_on_virtual_field(self):
ir = _make_ir_from_emb("struct Foo:\n"
" let x = 10\n"
' [byte_order: "LittleEndian"]\n')
byte_order = ir.module[0].type[0].structure.field[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", byte_order.name.source_location,
"Unknown attribute 'byte_order' on virtual struct field 'x'.")]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_null_byte_order_on_multibyte_fields(self):
ir = _make_ir_from_emb("struct Foo:\n"
" 0 [+2] UInt uint\n"
' [byte_order: "Null"]\n')
byte_order = ir.module[0].type[0].structure.field[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", byte_order.value.source_location,
"Attribute 'byte_order' may only be 'Null' for one-byte fields.")]],
attribute_checker.normalize_and_verify(ir))
def test_disallows_null_byte_order_on_multibyte_array_elements(self):
ir = _make_ir_from_emb("struct Foo:\n"
" 0 [+4] UInt:16[] uint\n"
' [byte_order: "Null"]\n')
byte_order = ir.module[0].type[0].structure.field[0].attribute[0]
self.assertEqual(
[[error.error(
"m.emb", byte_order.value.source_location,
| |
= zoomed_inset_axes(ax, zoom=ZOOM, loc='lower right')
area_under_curve = []
for idx, filename in enumerate(SAMPLE_232p3_wet):
fp_rate, tp_rate, auc_mean = _read_csv_roc_auc(filename)
area_under_curve.append(auc_mean)
_plot_roc_and_auc(fp_rate, tp_rate, c=COLORS[idx],
linestyle='-', ax=ax, ax_ins=ax_ins)
ax = _add_auc_legend(area_under_curve, ax=ax)
plt.savefig('figures/Fig_06c' + SAVE_FIG_FORMAT, bbox_inches='tight')
plt.close()
# Figure 6 (d).
SAMPLE_244p1_cured = [ROC_AUC_TIRAMISU['244p1_cured'],
ROC_AUC_UNET['244p1_cured'],
ROC_AUC_TIRAMISU_3D['244p1_cured'],
ROC_AUC_UNET_3D['244p1_cured']]
_, ax = plt.subplots(figsize=FIGURE_SIZE)
ax_ins = zoomed_inset_axes(ax, zoom=ZOOM, loc='lower right')
area_under_curve = []
for idx, filename in enumerate(SAMPLE_244p1_cured):
fp_rate, tp_rate, auc_mean = _read_csv_roc_auc(filename)
area_under_curve.append(auc_mean)
_plot_roc_and_auc(fp_rate, tp_rate, c=COLORS[idx],
linestyle='-', ax=ax, ax_ins=ax_ins)
ax = _add_auc_legend(area_under_curve, ax=ax)
plt.savefig('figures/Fig_06d' + SAVE_FIG_FORMAT, bbox_inches='tight')
plt.close()
# Figure 6 (e).
SAMPLE_244p1_wet = [ROC_AUC_TIRAMISU['244p1_wet'],
ROC_AUC_UNET['244p1_wet'],
ROC_AUC_TIRAMISU_3D['244p1_wet'],
ROC_AUC_UNET_3D['244p1_wet']]
_, ax = plt.subplots(figsize=FIGURE_SIZE)
ax_ins = zoomed_inset_axes(ax, zoom=ZOOM, loc='lower right')
area_under_curve = []
for idx, filename in enumerate(SAMPLE_244p1_wet):
fp_rate, tp_rate, auc_mean = _read_csv_roc_auc(filename)
area_under_curve.append(auc_mean)
_plot_roc_and_auc(fp_rate, tp_rate, c=COLORS[idx],
linestyle='-', ax=ax, ax_ins=ax_ins)
ax = _add_auc_legend(area_under_curve, ax=ax)
_check_if_folder_exists(folder='./figures')
plt.savefig('figures/Fig_06e' + SAVE_FIG_FORMAT, bbox_inches='tight')
plt.close()
return None
def figure_8():
"""
Notes
-----
Colors from Bang Wong's color-blind friendly colormap. Available at:
https://www.nature.com/articles/nmeth.1618
Wong's map acquired from David Nichols page. Available at:
https://davidmathlogic.com/colorblind/.
"""
# choosing test sample and network.
sample = const.SAMPLE_232p3_wet
network_folder = const.FOLDER_PRED_UNET
# we will return a 10 x 10 matthews matrix; each for a crop
matthews_coefs = np.ones((10, 10))
worst_indexes = np.zeros((10, 10))
# a variable to obtain inlay data.
inlay_data = []
# reading input data.
is_registered = sample['registered_path'] is not None
data_pred, data_gs = _pred_and_goldstd(sample,
folder_prediction=network_folder,
is_registered=is_registered,
is_binary=True)
data_pred = data_pred[slice(*sample['segmentation_interval'])]
# comp_color starts as gray (background).
comp_color = np.ones(
(*data_pred[0].shape, 3)
) * (np.asarray((238, 238, 238)) / 255)
for idx, (img_pred, img_gs) in enumerate(zip(data_pred, data_gs)):
# crop images in 100 (256, 256) pieces.
crop_pred = util.view_as_blocks(img_pred,
block_shape=(256, 256))
crop_gs = util.view_as_blocks(img_gs,
block_shape=(256, 256))
for i, _ in enumerate(crop_pred):
for j, _ in enumerate(crop_pred[i]):
# calculate the Matthews coefficient for each crop.
aux_conf = _confusion_matrix(crop_gs[i, j],
crop_pred[i, j])
aux_matthews = _measure_matthews(aux_conf)
# if smaller than previously, save results.
# restricting aux_matthews > 0.1 due to errors in all-TN regions
if (0.1 < aux_matthews < matthews_coefs[i, j]):
matthews_coefs[i, j] = aux_matthews
worst_indexes[i, j] = idx
aux_comp = _comparison_color(crop_gs[i, j], crop_pred[i, j])
comp_color[i*256:(i+1)*256, j*256:(j+1)*256] = aux_comp
# grab inlay data from crops we want to highlight.
for i, j in [(2, 2), (8, 7)]:
inlay_data.append(comp_color[i*256:(i+1)*256, j*256:(j+1)*256])
# Figure 8(a).
plt.figure(figsize=FIGURE_SIZE)
plt.imshow(comp_color)
for idx in np.arange(start=0, stop=2560, step=256): # according to image
plt.axvline(idx, color='white')
plt.axhline(idx, color='white')
matthews_coefs = np.round(matthews_coefs * 100, decimals=2)
for i, j in product(range(10), repeat=2):
facecolor, textcolor = _label_color(matthews_coefs[j, i])
plt.text(x=i*256 + 30, y=j*256 + 50,
s=str(matthews_coefs[j, i]),
fontsize=8,
color=textcolor,
bbox=dict(facecolor=facecolor, alpha=0.9))
_check_if_folder_exists(folder='./figures')
plt.savefig('figures/Fig_08a' + SAVE_FIG_FORMAT, bbox_inches='tight')
plt.close()
# Figures 8(b, c).
indexes = {0: 'b', 1: 'c'}
for idx in indexes.keys():
plt.figure(figsize=FIGURE_SIZE)
plt.imshow(inlay_data[idx])
_check_if_folder_exists(folder='./figures')
plt.savefig(f'figures/Fig_08{indexes[idx]}' + SAVE_FIG_FORMAT,
bbox_inches='tight')
plt.close()
return None
def figure_9():
"""
Notes
-----
You should run this code inside a Jupyter Notebook.
"""
# reading all images from the sample.
pattern = 'unet/rec20160318_191511_232p3_2cm_cont__4097im_1500ms_ML17keV_6.h5/predict/*.png'
images = io.ImageCollection(pattern)
images = images.concatenate()[:, fc00:e968:6179::de52:7100, ::2]
# slicing the outer part to show inside fibers.
images = images[:, :1000, :]
images = itk.GetImageFromArray(images)
view(images, label_image_blend=0, gradient_opacity=0, shadow=False,
interpolation=False)
return None
def _label_color(coef):
"""
"""
colors = {100: '#ffffff', 90: '#fff5f0', 80: '#fee0d2', 70: '#fcbba1',
60: '#fc9272', 50: '#fb6a4a', 40: '#ef3b2c', 30: '#cb181d',
20: '#a50f15', 10: '#67000d', 0: '#000000'}
percentage = np.asarray(list(colors.keys()))
min_perc = min(percentage[percentage - coef >= 0])
if min_perc > 50:
textcolor = 'black'
else:
textcolor = 'white'
return colors[min_perc], textcolor
def _comparison_color(data_gs, data_pred):
"""
"""
# comp_color starts as gray (background).
comparison = np.ones(
(*data_gs.shape, 3)
) * (np.asarray((238, 238, 238)) / 255)
# calculating true positives, false positives, and false negatives.
true_pos = (data_gs & data_pred)
false_pos = (~data_gs & data_pred)
false_neg = (data_gs & ~data_pred)
# defining colors for the plot.
color_fp = np.asarray((213, 94, 0)) / 255 # vermillion
color_tp = np.asarray((0, 158, 115)) / 255 # bluish green
color_fn = np.asarray((230, 159, 0)) / 255 # orange
# determining where comparison will take TP, FP, and FN values.
np.copyto(comparison, color_fp, where=false_pos[..., np.newaxis])
np.copyto(comparison, color_tp, where=true_pos[..., np.newaxis])
np.copyto(comparison, color_fn, where=false_neg[..., np.newaxis])
return comparison
def _confusion_matrix(data_gs, data_pred):
"""Compares reference and test data to generate a confusion matrix.
Parameters
----------
data_gs : ndarray
Reference binary data (ground truth).
data_pred : ndarray
Test binary data.
Returns
-------
conf_matrix : array
Matrix containing the number of true positives, false positives,
false negatives, and true negatives.
Notes
-----
The values true positive, false positive, false negative, and false
positive are events obtained in the comparison between data_gs and
data_pred:
data_gs: True False
data_pred:
True True positive | False positive
----------------------------------
False False negative | True negative
References
----------
.. [1] <NAME>. (2006) "An Introduction to ROC Analysis." Pattern
Recognition Letters, 27 (8): 861-874, :DOI:`10.1016/j.patrec.2005.10.010`
.. [2] Google Developers. "Machine Learning Crash Course with TensorFlow
APIs: Classification: True vs. False and Positive vs. Negative."
Available at:
https://developers.google.com/machine-learning/crash-course/classification/true-false-positive-negative
.. [3] Wikipedia. "Confusion matrix." Available at:
https://en.wikipedia.org/wiki/Confusion_matrix
"""
true_pos = (data_gs & data_pred).sum() / data_gs.size
false_pos = (~data_gs & data_pred).sum() / data_gs.size
false_neg = (data_gs & ~data_pred).sum() / data_gs.size
true_neg = (~data_gs & ~data_pred).sum() / data_gs.size
return np.array([[true_pos, false_pos], [false_neg, true_neg]])
def _measure_matthews(conf_matrix):
"""Calculate the Matthews correlation coefficient for a confusion matrix.
Parameters
----------
conf_matrix : array
Matrix containing the number of true positives, false positives,
false_negatives, and true negatives.
Returns
-------
coef_matthews : float
Matthews correlation index for the input confusion matrix.
Notes
-----
Matthews correlation coefficient tends to be more informative than other
confusion matrix measures, such as matthews coefficient and accuracy, when
evaluating binary classification problems: it considers the balance ratios
of true positives, true negatives, false positives, and false negatives.
References
----------
.. [1] <NAME>. (1975) "Comparison of the predicted and observed
secondary structure of T4 phage lysozyme." Biochimica et Biophysica
Acta (BBA) - Protein Structure, 405 (2): 442-451,
:DOI:`10.1016/0005-2795(75)90109-9`
.. [2] <NAME>. (2017) "Ten quick tips for machine learning in computational
biology." BioData Mining, 10 (35): 35, :DOI:`10.1186/s13040-017-0155-3`
.. [3] Wikipedia. "Matthews correlation coefficient." Available at:
https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
Examples
--------
>>> from skimage.measures import confusion_matrix
>>> conf_matrix = confusion_matrix(data_true, data_test)
>>> coef_matthews = measure_matthews(conf_matrix)
"""
tr_pos, fl_pos, fl_neg, tr_neg = conf_matrix.ravel()
coef_matthews = (tr_pos * tr_neg - fl_pos * fl_neg) / \
np.sqrt((tr_pos + fl_pos) * (tr_pos + fl_neg) *
(tr_neg + fl_pos) * (tr_neg + fl_neg))
return coef_matthews
def _pred_and_goldstd(sample, folder_prediction, is_registered=False,
is_binary=True):
"""
"""
aux_folder = sample['folder']
if is_registered:
aux_folder += '_REG'
aux_subfolder = const.SUBFOLDER_GOLDSTD_REG
else:
aux_subfolder = const.SUBFOLDER_GOLDSTD
folder_pred = os.path.join(folder_prediction,
aux_folder,
const.SUBFOLDER_PRED,
f'*{const.EXT_PRED}')
folder_goldstd = os.path.join(const.FOLDER_GOLDSTD,
sample['folder'],
aux_subfolder,
f'*{const.EXT_GOLDSTD}')
data_prediction = io.ImageCollection(load_pattern=folder_pred,
load_func=imread_prediction,
is_binary=is_binary)
data_goldstd = io.ImageCollection(load_pattern=folder_goldstd,
load_func=imread_goldstd)
return data_prediction, data_goldstd
def imread_prediction(image, is_binary=True):
"""Auxiliary function intended to be used with skimage.io.ImageCollection.
Returns a binary prediction image — True when image > 0.5, False
when image <= 0.5.
"""
if is_binary:
return util.img_as_float(io.imread(image)) > 0.5
else:
return util.img_as_float(io.imread(image))
def imread_goldstd(image):
"""Auxiliary function intended to be used with skimage.io.ImageCollection.
Helps to read and process Larson et al's gold standard images.
"""
data = io.imread(image)
if np.unique(data).size > 2:
data = data == 217
return util.img_as_bool(data)
def _add_auc_legend(area_under_curve, ax=None):
"""
"""
if ax is None:
_, ax = plt.subplots(figsize=FIGURE_SIZE)
# Setting patches for the legends.
_ = np.round(np.asarray(area_under_curve[0]) * 100, decimals=2)
aux_label = f'Tiramisu (AUC$_\mu$: {_}%)'
leg_auc_tiramisu = mpatches.Patch(color=COLOR_TIRAMISU,
label=aux_label)
_ = np.round(np.asarray(area_under_curve[1]) * 100, decimals=2)
aux_label = f'U-net (AUC$_\mu$: {_}%)'
leg_auc_unet = mpatches.Patch(color=COLOR_UNET,
label=aux_label)
_ = np.round(np.asarray(area_under_curve[2]) * 100, decimals=2)
aux_label = f'3D Tiramisu (AUC$_\mu$: {_}%)'
leg_auc_tiramisu_3d = mpatches.Patch(color=COLOR_TIRAMISU_3D,
label=aux_label)
_ = np.round(np.asarray(area_under_curve[3]) * 100, decimals=2)
aux_label = f'3D U-net (AUC$_\mu$: {_}%)'
leg_auc_unet_3d = mpatches.Patch(color=COLOR_UNET_3D,
label=aux_label)
ax.legend(handles=[leg_auc_tiramisu,
leg_auc_unet,
leg_auc_tiramisu_3d,
leg_auc_unet_3d],
loc='lower left', bbox_to_anchor=BBOX_TO_ANCHOR, ncol=2,
borderaxespad=0, frameon=False)
return ax
def _check_if_folder_exists(folder: str) -> None:
"""Auxiliary function. Check if folder exists and create it if necessary."""
if not os.path.isdir(folder):
os.mkdir(folder)
return None
def segmentation_wusem(image, str_el='disk', initial_radius=10,
delta_radius=5, watershed_line=False):
"""Separates regions on a binary input image using successive
erosions as markers for the watershed algorithm. The algorithm stops
when the erosion image does not have objects anymore.
Parameters
----------
image : (N, M) ndarray
Binary input image.
| |
fulfilled = 'fulfilled'
class TargetCapacitySpecification1(BaseModel):
TotalTargetCapacity: Optional[Integer] = None
OnDemandTargetCapacity: Optional[Integer] = None
SpotTargetCapacity: Optional[Integer] = None
DefaultTargetCapacityType: Optional[DefaultTargetCapacityType] = None
class OnDemandOptions1(BaseModel):
AllocationStrategy: Optional[FleetOnDemandAllocationStrategy] = None
CapacityReservationOptions: Optional[CapacityReservationOptions] = None
SingleInstanceType: Optional[Boolean] = None
SingleAvailabilityZone: Optional[Boolean] = None
MinTargetCapacity: Optional[Integer] = None
MaxTotalPrice: Optional[String] = None
class FleetLaunchTemplateSpecification(BaseModel):
LaunchTemplateId: Optional[String] = None
LaunchTemplateName: Optional[LaunchTemplateName] = None
Version: Optional[String] = None
class FleetLaunchTemplateSpecificationRequest(BaseModel):
LaunchTemplateId: Optional[LaunchTemplateId] = None
LaunchTemplateName: Optional[LaunchTemplateName] = None
Version: Optional[String] = None
class PlacementResponse(BaseModel):
GroupName: Optional[PlacementGroupName] = None
class FleetLaunchTemplateOverrides(BaseModel):
InstanceType: Optional[InstanceType] = None
MaxPrice: Optional[String] = None
SubnetId: Optional[String] = None
AvailabilityZone: Optional[String] = None
WeightedCapacity: Optional[Double] = None
Priority: Optional[Double] = None
Placement: Optional[PlacementResponse] = None
class FleetReplacementStrategy(Enum):
launch = 'launch'
class FleetSpotCapacityRebalance(BaseModel):
ReplacementStrategy: Optional[FleetReplacementStrategy] = None
class FleetSpotCapacityRebalanceRequest(BaseModel):
ReplacementStrategy: Optional[FleetReplacementStrategy] = None
class FleetSpotMaintenanceStrategies(BaseModel):
CapacityRebalance: Optional[FleetSpotCapacityRebalance] = None
class Float(BaseModel):
__root__: float
class FpgaDeviceCount(BaseModel):
__root__: int
class FpgaDeviceName(BaseModel):
__root__: str
class FpgaDeviceManufacturerName(BaseModel):
__root__: str
class FpgaDeviceMemorySize(BaseModel):
__root__: int
class PciId(BaseModel):
DeviceId: Optional[String] = None
VendorId: Optional[String] = None
SubsystemId: Optional[String] = None
SubsystemVendorId: Optional[String] = None
class FpgaImageStateCode(Enum):
pending = 'pending'
failed = 'failed'
available = 'available'
unavailable = 'unavailable'
class TotalFpgaMemory(BaseModel):
__root__: int
class FreeTierEligibleFlag(BaseModel):
__root__: bool
class GetAssociatedEnclaveCertificateIamRolesRequest(BaseModel):
CertificateArn: Optional[ResourceArn] = None
DryRun: Optional[Boolean] = None
class GetAssociatedIpv6PoolCidrsRequest(BaseModel):
PoolId: Ipv6PoolEc2Id
NextToken: Optional[NextToken] = None
MaxResults: Optional[Ipv6PoolMaxResults] = None
DryRun: Optional[Boolean] = None
class GetCapacityReservationUsageRequestMaxResults(BaseModel):
__root__: conint(ge=1, le=1000)
class GetCapacityReservationUsageRequest(BaseModel):
CapacityReservationId: CapacityReservationId
NextToken: Optional[String] = None
MaxResults: Optional[GetCapacityReservationUsageRequestMaxResults] = None
DryRun: Optional[Boolean] = None
class GetConsoleOutputRequest(BaseModel):
InstanceId: InstanceId
DryRun: Optional[Boolean] = None
Latest: Optional[Boolean] = None
class GetConsoleScreenshotRequest(BaseModel):
DryRun: Optional[Boolean] = None
InstanceId: InstanceId
WakeUp: Optional[Boolean] = None
class UnlimitedSupportedInstanceFamily(Enum):
t2 = 't2'
t3 = 't3'
t3a = 't3a'
t4g = 't4g'
class GetDefaultCreditSpecificationRequest(BaseModel):
DryRun: Optional[Boolean] = None
InstanceFamily: UnlimitedSupportedInstanceFamily
class InstanceFamilyCreditSpecification(BaseModel):
InstanceFamily: Optional[UnlimitedSupportedInstanceFamily] = None
CpuCredits: Optional[String] = None
class GetEbsDefaultKmsKeyIdRequest(BaseModel):
DryRun: Optional[Boolean] = None
class GetEbsEncryptionByDefaultRequest(BaseModel):
DryRun: Optional[Boolean] = None
class GetGroupsForCapacityReservationRequestMaxResults(BaseModel):
__root__: conint(ge=1, le=1000)
class GetGroupsForCapacityReservationRequest(BaseModel):
CapacityReservationId: CapacityReservationId
NextToken: Optional[String] = None
MaxResults: Optional[GetGroupsForCapacityReservationRequestMaxResults] = None
DryRun: Optional[Boolean] = None
class RequestHostIdSet(BaseModel):
__root__: list[DedicatedHostId]
class GetHostReservationPurchasePreviewRequest(BaseModel):
HostIdSet: RequestHostIdSet
OfferingId: OfferingId1
class GetLaunchTemplateDataRequest(BaseModel):
DryRun: Optional[Boolean] = None
InstanceId: InstanceId
class GetManagedPrefixListAssociationsMaxResults(BaseModel):
__root__: conint(ge=5, le=255)
class GetManagedPrefixListAssociationsRequest(BaseModel):
DryRun: Optional[Boolean] = None
PrefixListId: PrefixListResourceId
MaxResults: Optional[GetManagedPrefixListAssociationsMaxResults] = None
NextToken: Optional[NextToken] = None
class GetManagedPrefixListEntriesRequest(BaseModel):
DryRun: Optional[Boolean] = None
PrefixListId: PrefixListResourceId
TargetVersion: Optional[Long] = None
MaxResults: Optional[PrefixListMaxResults] = None
NextToken: Optional[NextToken] = None
class GetPasswordDataRequest(BaseModel):
InstanceId: InstanceId
DryRun: Optional[Boolean] = None
class ReservationValue(BaseModel):
HourlyPrice: Optional[String] = None
RemainingTotalValue: Optional[String] = None
RemainingUpfrontValue: Optional[String] = None
class GetSerialConsoleAccessStatusRequest(BaseModel):
DryRun: Optional[Boolean] = None
class GetSubnetCidrReservationsMaxResults(BaseModel):
__root__: conint(ge=5, le=1000)
class GpuDeviceCount(BaseModel):
__root__: int
class GpuDeviceName(BaseModel):
__root__: str
class GpuDeviceManufacturerName(BaseModel):
__root__: str
class GpuDeviceMemorySize(BaseModel):
__root__: int
class TotalGpuMemory(BaseModel):
__root__: int
class GroupIdentifier(BaseModel):
GroupName: Optional[String] = None
GroupId: Optional[String] = None
class SecurityGroupIdentifier(BaseModel):
GroupId: Optional[String] = None
GroupName: Optional[String] = None
class GroupIdentifierSet(BaseModel):
__root__: list[SecurityGroupIdentifier]
class HibernationFlag(BaseModel):
__root__: bool
class HibernationOptions2(BaseModel):
Configured: Optional[Boolean] = None
class HibernationOptionsRequest(BaseModel):
Configured: Optional[Boolean] = None
class HistoryRecord(BaseModel):
EventInformation: Optional[EventInformation] = None
EventType: Optional[EventType1] = None
Timestamp: Optional[DateTime] = None
class HistoryRecordEntry(BaseModel):
EventInformation: Optional[EventInformation] = None
EventType: Optional[FleetEventType] = None
Timestamp: Optional[DateTime] = None
class HostProperties(BaseModel):
Cores: Optional[Integer] = None
InstanceType: Optional[String] = None
InstanceFamily: Optional[String] = None
Sockets: Optional[Integer] = None
TotalVCpus: Optional[Integer] = None
class HostInstance(BaseModel):
InstanceId: Optional[String] = None
InstanceType: Optional[String] = None
OwnerId: Optional[String] = None
class PaymentOption(Enum):
AllUpfront = 'AllUpfront'
PartialUpfront = 'PartialUpfront'
NoUpfront = 'NoUpfront'
class HostOffering(BaseModel):
CurrencyCode: Optional[CurrencyCodeValues] = None
Duration: Optional[Integer] = None
HourlyPrice: Optional[String] = None
InstanceFamily: Optional[String] = None
OfferingId: Optional[String] = None
PaymentOption: Optional[PaymentOption] = None
UpfrontPrice: Optional[String] = None
class ResponseHostIdSet(BaseModel):
__root__: list[String]
class ReservationState(Enum):
payment_pending = 'payment-pending'
payment_failed = 'payment-failed'
active = 'active'
retired = 'retired'
class HostTenancy(Enum):
dedicated = 'dedicated'
host = 'host'
class Hour(BaseModel):
__root__: conint(ge=0, le=23)
class HypervisorType(Enum):
ovm = 'ovm'
xen = 'xen'
class IKEVersionsListValue(BaseModel):
Value: Optional[String] = None
class IKEVersionsList(BaseModel):
__root__: list[IKEVersionsListValue]
class IKEVersionsRequestListValue(BaseModel):
Value: Optional[String] = None
class IamInstanceProfile(BaseModel):
Arn: Optional[String] = None
Id: Optional[String] = None
class IamInstanceProfileAssociationState(Enum):
associating = 'associating'
associated = 'associated'
disassociating = 'disassociating'
disassociated = 'disassociated'
class IdFormat(BaseModel):
Deadline: Optional[DateTime] = None
Resource: Optional[String] = None
UseLongIds: Optional[Boolean] = None
class ImageTypeValues(Enum):
machine = 'machine'
kernel = 'kernel'
ramdisk = 'ramdisk'
class ImageState(Enum):
pending = 'pending'
available = 'available'
invalid = 'invalid'
deregistered = 'deregistered'
transient = 'transient'
failed = 'failed'
error = 'error'
class StateReason(BaseModel):
Code: Optional[String] = None
Message: Optional[String] = None
class VirtualizationType(Enum):
hvm = 'hvm'
paravirtual = 'paravirtual'
class ImportClientVpnClientCertificateRevocationListRequest(BaseModel):
ClientVpnEndpointId: ClientVpnEndpointId1
CertificateRevocationList: String
DryRun: Optional[Boolean] = None
class ImportImageLicenseConfigurationResponse(BaseModel):
LicenseConfigurationArn: Optional[String] = None
class ImportImageLicenseSpecificationListRequest(BaseModel):
__root__: list[ImportImageLicenseConfigurationRequest]
class ImportImageLicenseSpecificationListResponse(BaseModel):
__root__: list[ImportImageLicenseConfigurationResponse]
class ImportInstanceVolumeDetailItem(BaseModel):
AvailabilityZone: Optional[String] = None
BytesConverted: Optional[Long] = None
Description: Optional[String] = None
Image: Optional[DiskImageDescription] = None
Status: Optional[String] = None
StatusMessage: Optional[String] = None
Volume: Optional[DiskImageVolumeDescription] = None
class SnapshotDiskContainer(BaseModel):
Description: Optional[String] = None
Format: Optional[String] = None
Url: Optional[String] = None
UserBucket: Optional[UserBucket] = None
class ImportVolumeRequest(BaseModel):
AvailabilityZone: String
Description: Optional[String] = None
DryRun: Optional[Boolean] = None
Image: DiskImageDetail
Volume: VolumeDetail
class InferenceDeviceCount(BaseModel):
__root__: int
class InferenceDeviceName(BaseModel):
__root__: str
class InferenceDeviceManufacturerName(BaseModel):
__root__: str
class InferenceDeviceInfo(BaseModel):
Count: Optional[InferenceDeviceCount] = None
Name: Optional[InferenceDeviceName] = None
Manufacturer: Optional[InferenceDeviceManufacturerName] = None
class InstanceLifecycleType(Enum):
spot = 'spot'
scheduled = 'scheduled'
class InstanceBlockDeviceMapping(BaseModel):
DeviceName: Optional[String] = None
Ebs: Optional[EbsInstanceBlockDevice] = None
class ListingState(Enum):
available = 'available'
sold = 'sold'
cancelled = 'cancelled'
pending = 'pending'
class InstanceCount5(BaseModel):
InstanceCount: Optional[Integer] = None
State: Optional[ListingState] = None
class InstanceCountList(BaseModel):
__root__: list[InstanceCount5]
class InstanceCreditSpecification(BaseModel):
InstanceId: Optional[String] = None
CpuCredits: Optional[String] = None
class InstanceCreditSpecificationListRequest(BaseModel):
__root__: list[InstanceCreditSpecificationRequest]
class InstanceEventId(BaseModel):
__root__: str
class InstanceEventWindowState(Enum):
creating = 'creating'
deleting = 'deleting'
active = 'active'
deleted = 'deleted'
class WeekDay(Enum):
sunday = 'sunday'
monday = 'monday'
tuesday = 'tuesday'
wednesday = 'wednesday'
thursday = 'thursday'
friday = 'friday'
saturday = 'saturday'
class InstanceEventWindowTimeRange(BaseModel):
StartWeekDay: Optional[WeekDay] = None
StartHour: Optional[Hour] = None
EndWeekDay: Optional[WeekDay] = None
EndHour: Optional[Hour] = None
class InstanceIdSet(BaseModel):
__root__: list[InstanceId]
class InstanceIpv4Prefix(BaseModel):
Ipv4Prefix: Optional[String] = None
class InstanceIpv4PrefixList(BaseModel):
__root__: list[InstanceIpv4Prefix]
class InstanceIpv6AddressRequest(BaseModel):
Ipv6Address: Optional[String] = None
class InstanceIpv6AddressListRequest(BaseModel):
__root__: list[InstanceIpv6AddressRequest]
class InstanceIpv6Prefix(BaseModel):
Ipv6Prefix: Optional[String] = None
class InstanceIpv6PrefixList(BaseModel):
__root__: list[InstanceIpv6Prefix]
class InstanceMetadataOptionsRequest(BaseModel):
HttpTokens: Optional[HttpTokensState] = None
HttpPutResponseHopLimit: Optional[Integer] = None
HttpEndpoint: Optional[InstanceMetadataEndpointState] = None
HttpProtocolIpv6: Optional[InstanceMetadataProtocolState] = None
class InstanceMetadataOptionsState(Enum):
pending = 'pending'
applied = 'applied'
class InstanceNetworkInterfaceAssociation(BaseModel):
CarrierIp: Optional[String] = None
IpOwnerId: Optional[String] = None
PublicDnsName: Optional[String] = None
PublicIp: Optional[String] = None
class InstanceNetworkInterfaceAttachment(BaseModel):
AttachTime: Optional[DateTime] = None
AttachmentId: Optional[String] = None
DeleteOnTermination: Optional[Boolean] = None
DeviceIndex: Optional[Integer] = None
Status: Optional[AttachmentStatus] = None
NetworkCardIndex: Optional[Integer] = None
class NetworkInterfaceStatus(Enum):
available = 'available'
associated = 'associated'
attaching = 'attaching'
in_use = 'in-use'
detaching = 'detaching'
class InstancePrivateIpAddress(BaseModel):
Association: Optional[InstanceNetworkInterfaceAssociation] = None
Primary: Optional[Boolean] = None
PrivateDnsName: Optional[String] = None
PrivateIpAddress: Optional[String] = None
class InstanceStateName(Enum):
pending = 'pending'
running = 'running'
shutting_down = 'shutting-down'
terminated = 'terminated'
stopping = 'stopping'
stopped = 'stopped'
class StatusName(Enum):
reachability = 'reachability'
class StatusType(Enum):
passed = 'passed'
failed = 'failed'
insufficient_data = 'insufficient-data'
initializing = 'initializing'
class InstanceStatusDetails(BaseModel):
ImpairedSince: Optional[DateTime] = None
Name: Optional[StatusName] = None
Status: Optional[StatusType] = None
class InstanceStatusDetailsList(BaseModel):
__root__: list[InstanceStatusDetails]
class InstanceStatusEvent(BaseModel):
InstanceEventId: Optional[InstanceEventId] = None
Code: Optional[EventCode] = None
Description: Optional[String] = None
NotAfter: Optional[DateTime] = None
NotBefore: Optional[DateTime] = None
NotBeforeDeadline: Optional[DateTime] = None
class SummaryStatus(Enum):
ok = 'ok'
impaired = 'impaired'
insufficient_data = 'insufficient-data'
not_applicable = 'not-applicable'
initializing = 'initializing'
class InstanceStorageFlag(BaseModel):
__root__: bool
class InstanceStorageInfo(BaseModel):
TotalSizeInGB: Optional[DiskSize] = None
Disks: Optional[DiskInfoList] = None
NvmeSupport: Optional[EphemeralNvmeSupport] = None
class InstanceTypeHypervisor(Enum):
nitro = 'nitro'
xen = 'xen'
class VirtualizationTypeList(BaseModel):
__root__: list[VirtualizationType]
class Location(BaseModel):
__root__: str
class InstanceTypeOffering(BaseModel):
InstanceType: Optional[InstanceType] = None
LocationType: Optional[LocationType] = None
Location: Optional[Location] = None
class InstanceUsage(BaseModel):
AccountId: Optional[String] = None
UsedInstanceCount: Optional[Integer] = None
class InterfaceProtocolType(Enum):
VLAN = 'VLAN'
GRE = 'GRE'
class InternetGatewayAttachment(BaseModel):
State: Optional[AttachmentStatus] = None
VpcId: Optional[String] = None
class IpRange(BaseModel):
CidrIp: Optional[String] = None
Description: Optional[String] = None
class IpRanges1(BaseModel):
__root__: list[String]
class Ipv4PrefixSpecificationResponse(BaseModel):
Ipv4Prefix: Optional[String] = None
class Ipv4PrefixListResponse(BaseModel):
__root__: list[Ipv4PrefixSpecificationResponse]
class Ipv4PrefixSpecification(BaseModel):
Ipv4Prefix: Optional[String] = None
class Ipv6Address2(BaseModel):
__root__: str
class Ipv6CidrAssociation(BaseModel):
Ipv6Cidr: Optional[String] = None
AssociatedResource: Optional[String] = None
class Ipv6CidrBlock7(BaseModel):
Ipv6CidrBlock: Optional[String] = None
class Ipv6CidrBlockSet(BaseModel):
__root__: list[Ipv6CidrBlock7]
class Ipv6Flag(BaseModel):
__root__: bool
class Ipv6PrefixSpecificationResponse(BaseModel):
Ipv6Prefix: Optional[String] = None
class Ipv6PrefixListResponse(BaseModel):
__root__: list[Ipv6PrefixSpecificationResponse]
class Ipv6PrefixSpecification(BaseModel):
Ipv6Prefix: Optional[String] = None
class Ipv6PrefixesList(BaseModel):
__root__: list[Ipv6PrefixSpecification]
class Ipv6Range(BaseModel):
CidrIpv6: Optional[String] = None
Description: Optional[String] = None
class SensitiveUserData(BaseModel):
__root__: SecretStr
class LastError(BaseModel):
Message: Optional[String] = None
Code: Optional[String] = None
class LaunchPermission(BaseModel):
Group: Optional[PermissionGroup] = None
UserId: Optional[String] = None
class LaunchTemplateEbsBlockDevice(BaseModel):
Encrypted: Optional[Boolean] = None
DeleteOnTermination: Optional[Boolean] = None
Iops: Optional[Integer] = None
KmsKeyId: Optional[KmsKeyId] = None
SnapshotId: Optional[SnapshotId4] = None
VolumeSize: Optional[Integer] = None
VolumeType: Optional[VolumeType] = None
Throughput: Optional[Integer] | |
inconsistency matrix.
Examples
--------
>>> from scipy.cluster.hierarchy import ward, inconsistent, is_valid_im
>>> from scipy.spatial.distance import pdist
Given a data set ``X``, we can apply a clustering method to obtain a
linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
be also used to obtain the inconsistency matrix ``R`` associated to
this clustering process:
>>> X = [[0, 0], [0, 1], [1, 0],
... [0, 4], [0, 3], [1, 4],
... [4, 0], [3, 0], [4, 1],
... [4, 4], [3, 4], [4, 3]]
>>> Z = ward(pdist(X))
>>> R = inconsistent(Z)
>>> Z
array([[ 0. , 1. , 1. , 2. ],
[ 3. , 4. , 1. , 2. ],
[ 6. , 7. , 1. , 2. ],
[ 9. , 10. , 1. , 2. ],
[ 2. , 12. , 1.29099445, 3. ],
[ 5. , 13. , 1.29099445, 3. ],
[ 8. , 14. , 1.29099445, 3. ],
[11. , 15. , 1.29099445, 3. ],
[16. , 17. , 5.77350269, 6. ],
[18. , 19. , 5.77350269, 6. ],
[20. , 21. , 8.16496581, 12. ]])
>>> R
array([[1. , 0. , 1. , 0. ],
[1. , 0. , 1. , 0. ],
[1. , 0. , 1. , 0. ],
[1. , 0. , 1. , 0. ],
[1.14549722, 0.20576415, 2. , 0.70710678],
[1.14549722, 0.20576415, 2. , 0.70710678],
[1.14549722, 0.20576415, 2. , 0.70710678],
[1.14549722, 0.20576415, 2. , 0.70710678],
[2.78516386, 2.58797734, 3. , 1.15470054],
[2.78516386, 2.58797734, 3. , 1.15470054],
[6.57065706, 1.38071187, 3. , 1.15470054]])
Now we can use `scipy.cluster.hierarchy.is_valid_im` to verify that
``R`` is correct:
>>> is_valid_im(R)
True
However, if ``R`` is wrongly constructed (e.g., one of the standard
deviations is set to a negative value), then the check will fail:
>>> R[-1,1] = R[-1,1] * -1
>>> is_valid_im(R)
False
"""
R = np.asarray(R, order='c')
valid = True
name_str = "%r " % name if name else ''
try:
if type(R) != np.ndarray:
raise TypeError('Variable %spassed as inconsistency matrix is not '
'a numpy array.' % name_str)
if R.dtype != np.double:
raise TypeError('Inconsistency matrix %smust contain doubles '
'(double).' % name_str)
if len(R.shape) != 2:
raise ValueError('Inconsistency matrix %smust have shape=2 (i.e. '
'be two-dimensional).' % name_str)
if R.shape[1] != 4:
raise ValueError('Inconsistency matrix %smust have 4 columns.' %
name_str)
if R.shape[0] < 1:
raise ValueError('Inconsistency matrix %smust have at least one '
'row.' % name_str)
if (R[:, 0] < 0).any():
raise ValueError('Inconsistency matrix %scontains negative link '
'height means.' % name_str)
if (R[:, 1] < 0).any():
raise ValueError('Inconsistency matrix %scontains negative link '
'height standard deviations.' % name_str)
if (R[:, 2] < 0).any():
raise ValueError('Inconsistency matrix %scontains negative link '
'counts.' % name_str)
except Exception as e:
if throw:
raise
if warning:
_warning(str(e))
valid = False
return valid
def is_valid_linkage(Z, warning=False, throw=False, name=None):
"""
Check the validity of a linkage matrix.
A linkage matrix is valid if it is a 2-D array (type double)
with :math:`n` rows and 4 columns. The first two columns must contain
indices between 0 and :math:`2n-1`. For a given row ``i``, the following
two expressions have to hold:
.. math::
0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1
0 \\leq Z[i,1] \\leq i+n-1
I.e., a cluster cannot join another cluster unless the cluster being joined
has been generated.
Parameters
----------
Z : array_like
Linkage matrix.
warning : bool, optional
When True, issues a Python warning if the linkage
matrix passed is invalid.
throw : bool, optional
When True, throws a Python exception if the linkage
matrix passed is invalid.
name : str, optional
This string refers to the variable name of the invalid
linkage matrix.
Returns
-------
b : bool
True if the inconsistency matrix is valid.
See Also
--------
linkage: for a description of what a linkage matrix is.
Examples
--------
>>> from scipy.cluster.hierarchy import ward, is_valid_linkage
>>> from scipy.spatial.distance import pdist
All linkage matrices generated by the clustering methods in this module
will be valid (i.e., they will have the appropriate dimensions and the two
required expressions will hold for all the rows).
We can check this using `scipy.cluster.hierarchy.is_valid_linkage`:
>>> X = [[0, 0], [0, 1], [1, 0],
... [0, 4], [0, 3], [1, 4],
... [4, 0], [3, 0], [4, 1],
... [4, 4], [3, 4], [4, 3]]
>>> Z = ward(pdist(X))
>>> Z
array([[ 0. , 1. , 1. , 2. ],
[ 3. , 4. , 1. , 2. ],
[ 6. , 7. , 1. , 2. ],
[ 9. , 10. , 1. , 2. ],
[ 2. , 12. , 1.29099445, 3. ],
[ 5. , 13. , 1.29099445, 3. ],
[ 8. , 14. , 1.29099445, 3. ],
[11. , 15. , 1.29099445, 3. ],
[16. , 17. , 5.77350269, 6. ],
[18. , 19. , 5.77350269, 6. ],
[20. , 21. , 8.16496581, 12. ]])
>>> is_valid_linkage(Z)
True
However, if we create a linkage matrix in a wrong way - or if we modify
a valid one in a way that any of the required expressions don't hold
anymore, then the check will fail:
>>> Z[3][1] = 20 # the cluster number 20 is not defined at this point
>>> is_valid_linkage(Z)
False
"""
Z = np.asarray(Z, order='c')
valid = True
name_str = "%r " % name if name else ''
try:
if type(Z) != np.ndarray:
raise TypeError('Passed linkage argument %sis not a valid array.' %
name_str)
if Z.dtype != np.double:
raise TypeError('Linkage matrix %smust contain doubles.' % name_str)
if len(Z.shape) != 2:
raise ValueError('Linkage matrix %smust have shape=2 (i.e. be '
'two-dimensional).' % name_str)
if Z.shape[1] != 4:
raise ValueError('Linkage matrix %smust have 4 columns.' % name_str)
if Z.shape[0] == 0:
raise ValueError('Linkage must be computed on at least two '
'observations.')
n = Z.shape[0]
if n > 1:
if ((Z[:, 0] < 0).any() or (Z[:, 1] < 0).any()):
raise ValueError('Linkage %scontains negative indices.' %
name_str)
if (Z[:, 2] < 0).any():
raise ValueError('Linkage %scontains negative distances.' %
name_str)
if (Z[:, 3] < 0).any():
raise ValueError('Linkage %scontains negative counts.' %
name_str)
if _check_hierarchy_uses_cluster_before_formed(Z):
raise ValueError('Linkage %suses non-singleton cluster before '
'it is formed.' % name_str)
if _check_hierarchy_uses_cluster_more_than_once(Z):
raise ValueError('Linkage %suses the same cluster more than once.'
% name_str)
except Exception as e:
if throw:
raise
if warning:
_warning(str(e))
valid = False
return valid
def _check_hierarchy_uses_cluster_before_formed(Z):
n = Z.shape[0] + 1
for i in range(0, n - 1):
if Z[i, 0] >= n + i or Z[i, 1] >= n + i:
return True
return False
def _check_hierarchy_uses_cluster_more_than_once(Z):
n = Z.shape[0] + 1
chosen = set([])
for i in range(0, n - 1):
if (Z[i, 0] in chosen) or (Z[i, 1] in chosen) or Z[i, 0] == Z[i, 1]:
return True
chosen.add(Z[i, 0])
chosen.add(Z[i, 1])
return False
def _check_hierarchy_not_all_clusters_used(Z):
n = Z.shape[0] + 1
chosen = set([])
for i in range(0, n - 1):
chosen.add(int(Z[i, 0]))
chosen.add(int(Z[i, 1]))
must_chosen = set(range(0, 2 * n - 2))
return len(must_chosen.difference(chosen)) > 0
def num_obs_linkage(Z):
"""
Return the number of original observations of the linkage matrix passed.
Parameters
----------
Z : ndarray
The linkage matrix on which to perform the operation.
Returns
-------
n : int
The number of original observations in the linkage.
Examples
--------
>>> from scipy.cluster.hierarchy import ward, num_obs_linkage
>>> from scipy.spatial.distance import pdist
>>> X = [[0, 0], [0, 1], [1, 0],
... [0, 4], [0, 3], [1, 4],
... [4, 0], [3, 0], [4, 1],
... [4, 4], [3, 4], [4, 3]]
>>> Z = ward(pdist(X))
``Z`` is a linkage matrix obtained after using the Ward clustering method
with ``X``, a dataset with 12 data points.
>>> num_obs_linkage(Z)
12
"""
Z = np.asarray(Z, order='c')
is_valid_linkage(Z, throw=True, name='Z')
return (Z.shape[0] + 1)
def correspond(Z, Y):
"""
Check for correspondence between linkage and condensed distance matrices.
They must have the same number of original observations for
the check to succeed.
This function is | |
<filename>galaxychop/core.py
# This file is part of
# the galxy-chop project (https://github.com/vcristiani/galaxy-chop)
# Copyright (c) 2020, <NAME>
# License: MIT
# Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt
"""Module galaxy-chop."""
# #####################################################
# IMPORTS
# #####################################################
import enum
from astropy import units as u
import attr
import dask.array as da
from galaxychop import utils
import numpy as np
import uttr
# #####################################################
# CONSTANTS
# #####################################################
"""Gravitational constant G.
Units: kpc Msun**(-1) (km/s)**2"""
G = 4.299e-6
# #####################################################
# GALAXY CLASS
# #####################################################
@attr.s(frozen=True)
class Galaxy:
"""
Galaxy class.
Builds a galaxy object from masses, positions, and
velocities of particles (stars, dark matter and gas).
Parameters
----------
m_s : `Quantity`
Star masses. Shape: (n_s,1). Default unit: M_sun
x_s, y_s, z_s : `Quantity`
Star positions. Shape: (n_s,1). Default unit: kpc.
vx_s, vy_s, vz_s : `Quantity`
Star velocities. Shape: (n_s,1). Default unit: km/s.
m_dm : `Quantity`
Dark matter masses. Shape: (n_dm,1). Default unit: M_sun
x_dm, y_dm, z_dm : `Quantity`
Dark matter positions. Shape: (n_dm,1). Default unit: kpc.
vx_dm, vy_dm, vz_dm : `Quantity`
Dark matter velocities. Shape: (n_dm,1). Default unit: km/s.
m_g : `Quantity`
Gas masses. Shape: (n_g,1). Default unit: M_sun
x_g, y_g, z_g : `Quantity`
Gas positions. Shape: (n_g,1). Default unit: kpc.
vx_g, vy_g, vz_g : `Quantity`
Gas velocities. Shape: (n_g,1). Default unit: km/s.
pot_s : `Quantity`, default value = 0
Specific potential energy of star particles.
Shape: (n_s,1). Default unit: (km/s)**2.
pot_dm : `Quantity`, default value = 0
Specific potential energy of dark matter particles.
Shape: (n_dm,1). Default unit: (km/s)**2.
pot_g : `Quantity`, default value = 0
Specific potential energy of gas particles.
Shape: (n_g,1). Default unit: (km/s)**2.
eps_s : `Quantity`, default value = 0
Softening radius of star particles. Shape: (1,). Default unit: kpc.
eps_dm : `Quantity`, default value = 0
Softening radius of dark matter particles.
Shape: (1,). Default unit: kpc.
eps_g : `Quantity`, default value = 0
Softening radius of gas particles. Shape: (1,). Default unit: kpc.
J_part : `Quantity`
Total specific angular momentum of all particles (stars, dark matter
and gas).
Shape: (n,3). Default units: kpc*km/s
J_star : `Quantity`
Total specific angular momentum of stars.
Shape: (n_s,1). Default unit: kpc*km/s
Jr_part : `Quantity`
Projection of the total specific angular momentum in the xy plane for
all particles.
Shape: (n,1). Default unit: kpc*km/s
Jr_star : `Quantity`
Projection of the specific angular momentum of stars in the xy plane.
Shape: (n_s,1). Default unit: kpc*km/s
x : `Quantity`
Normalized specific energy for the particle with the maximum
z-component of the normalized specific angular momentum per bin.
Default unit: dimensionless
y : `Quantity`
Maximum value of the z-component of the normalized specific angular
momentum per bin.
Default units: dimensionless
Attributes
----------
arr_: `uttr.ArrayAccessor`
Original array accessor object create by the *uttr* library.
Array accesor: it converts uttr attributes to the default unit and
afterward to a `numpy.ndarray`.
For more information see: https://pypi.org/project/uttrs/
"""
m_s = uttr.ib(unit=u.Msun)
x_s = uttr.ib(unit=u.kpc)
y_s = uttr.ib(unit=u.kpc)
z_s = uttr.ib(unit=u.kpc)
vx_s = uttr.ib(unit=(u.km / u.s))
vy_s = uttr.ib(unit=(u.km / u.s))
vz_s = uttr.ib(unit=(u.km / u.s))
m_dm = uttr.ib(unit=u.Msun)
x_dm = uttr.ib(unit=u.kpc)
y_dm = uttr.ib(unit=u.kpc)
z_dm = uttr.ib(unit=u.kpc)
vx_dm = uttr.ib(unit=(u.km / u.s))
vy_dm = uttr.ib(unit=(u.km / u.s))
vz_dm = uttr.ib(unit=(u.km / u.s))
m_g = uttr.ib(unit=u.Msun)
x_g = uttr.ib(unit=u.kpc)
y_g = uttr.ib(unit=u.kpc)
z_g = uttr.ib(unit=u.kpc)
vx_g = uttr.ib(unit=(u.km / u.s))
vy_g = uttr.ib(unit=(u.km / u.s))
vz_g = uttr.ib(unit=(u.km / u.s))
pot_s = uttr.ib(default=np.zeros(1), unit=(u.km / u.s) ** 2)
pot_dm = uttr.ib(default=np.zeros(1), unit=(u.km / u.s) ** 2)
pot_g = uttr.ib(default=np.zeros(1), unit=(u.km / u.s) ** 2)
eps_s = uttr.ib(default=0.0, unit=u.kpc)
eps_dm = uttr.ib(default=0.0, unit=u.kpc)
eps_g = uttr.ib(default=0.0, unit=u.kpc)
J_part = uttr.ib(default=None, unit=(u.kpc * u.km / u.s))
J_star = uttr.ib(default=None, unit=(u.kpc * u.km / u.s))
Jr_part = uttr.ib(default=None, unit=(u.kpc * u.km / u.s))
Jr_star = uttr.ib(default=None, unit=(u.kpc * u.km / u.s))
x = uttr.ib(default=None, unit=u.dimensionless_unscaled)
y = uttr.ib(default=None, unit=u.dimensionless_unscaled)
arr_ = uttr.array_accessor()
# components_s = attr.ib(default=None)
# components_g = attr.ib(default=None)
# metadata = attr.ib(default=None)
def __attrs_post_init__(self):
"""
Validate attrs with units.
Units length validator.
This method determines that the length of the different particles
families are the same.
Potential energy input validator.
This method determines the validation of input of the specific
potential energy.
"""
if np.all(self.arr_.pot_s) != 0.0:
length_s = np.array(
[
len(self.arr_.x_s),
len(self.arr_.y_s),
len(self.arr_.z_s),
len(self.arr_.vx_s),
len(self.arr_.vy_s),
len(self.arr_.vz_s),
len(self.arr_.pot_s),
]
)
else:
length_s = np.array(
[
len(self.arr_.x_s),
len(self.arr_.y_s),
len(self.arr_.z_s),
len(self.arr_.vx_s),
len(self.arr_.vy_s),
len(self.arr_.vz_s),
]
)
if np.any(len(self.arr_.m_s) != length_s):
raise ValueError("Stars inputs must have the same length")
if np.all(self.arr_.pot_dm) != 0.0:
length_dm = np.array(
[
len(self.arr_.x_dm),
len(self.arr_.y_dm),
len(self.arr_.z_dm),
len(self.arr_.vx_dm),
len(self.arr_.vy_dm),
len(self.arr_.vz_dm),
len(self.arr_.pot_dm),
]
)
else:
length_dm = np.array(
[
len(self.arr_.x_dm),
len(self.arr_.y_dm),
len(self.arr_.z_dm),
len(self.arr_.vx_dm),
len(self.arr_.vy_dm),
len(self.arr_.vz_dm),
]
)
if np.any(len(self.arr_.m_dm) != length_dm):
raise ValueError("Dark matter inputs must have the same length")
if np.all(self.arr_.pot_g) != 0.0:
length_g = np.array(
[
len(self.arr_.x_g),
len(self.arr_.y_g),
len(self.arr_.z_g),
len(self.arr_.vx_g),
len(self.arr_.vy_g),
len(self.arr_.vz_g),
len(self.arr_.pot_g),
]
)
else:
length_g = np.array(
[
len(self.arr_.x_g),
len(self.arr_.y_g),
len(self.arr_.z_g),
len(self.arr_.vx_g),
len(self.arr_.vy_g),
len(self.arr_.vz_g),
]
)
if np.any(len(self.arr_.m_g) != length_g):
raise ValueError("Gas inputs must have the same length")
# Potential energy input validator.
if np.any(self.arr_.pot_s != 0.0) and (
np.all(self.arr_.pot_dm == 0.0) or np.all(self.arr_.pot_g == 0.0)
):
raise ValueError(
"Potential energy must be instanced for all type particles"
)
if np.any(self.arr_.pot_dm != 0.0) and (
np.all(self.arr_.pot_s == 0.0) or np.all(self.arr_.pot_g == 0.0)
):
raise ValueError(
"Potential energy must be instanced for all type particles"
)
if np.any(self.arr_.pot_g != 0.0) and (
np.all(self.arr_.pot_s == 0.0) or np.all(self.arr_.pot_dm == 0.0)
):
raise ValueError(
"Potential energy must be instanced for all type particles"
)
@property
def kinetic_energy(self):
"""
Specific kinetic energy calculation.
Calculates the specific kinetic energy
of stars, dark matter and gas particles.
Returns
-------
tuple : `Quantity`
(k_s, k_dm, k_g): Specific kinetic energy of stars, dark matter and
gas respectively. Shape(n_s, n_dm, n_g). Unit: (km/s)**2
Examples
--------
This returns the specific kinetic energy of stars, dark matter and gas
particles respectively.
>>> import galaxychop as gc
>>> galaxy = gc.Galaxy(...)
>>> k_s, k_dm, k_g = galaxy.kinetic_energy
"""
vx_s = self.arr_.vx_s
vy_s = self.arr_.vy_s
vz_s = self.arr_.vz_s
vx_dm = self.arr_.vx_dm
vy_dm = self.arr_.vy_dm
vz_dm = self.arr_.vz_dm
vx_g = self.arr_.vx_g
vy_g = self.arr_.vy_g
vz_g = self.arr_.vz_g
k_s = 0.5 * (vx_s ** 2 + vy_s ** 2 + vz_s ** 2)
k_dm = 0.5 * (vx_dm ** 2 + vy_dm ** 2 + vz_dm ** 2)
k_g = 0.5 * (vx_g ** 2 + vy_g ** 2 + vz_g ** 2)
k_s = k_s * (u.km / u.s) ** 2
k_dm = k_dm * (u.km / u.s) ** 2
k_g = k_g * (u.km / u.s) ** 2
return (k_s, k_dm, k_g)
def potential_energy(self):
"""
Specific potential energy calculation.
Calculates the specific potencial energy
of dark matter, star and gas particles.
Returns
-------
gx : `galaxy object`
New instanced galaxy specific potencial energy calculated for
stars, dark matter and gas particles.
Examples
--------
This returns the specific potential energy of stars, dark matter and
gas particles.
>>> import galaxychop as gc
>>> galaxy = gc.Galaxy(...)
>>> gpot = galaxy.potential_energy()
>>> pot_s, pot_dm, pot_g = gpot.pot_s, gpot.pot_dm, gpot.pot_g
Note
----
If the potentials are entered when the `galaxy` object is instanced,
then, the calculation of `potential_energy` will raise a `ValueError`.
"""
m_s = self.arr_.m_s
x_s = self.arr_.x_s
y_s = self.arr_.y_s
z_s = self.arr_.z_s
m_dm = self.arr_.m_dm
x_dm = self.arr_.x_dm
y_dm = self.arr_.y_dm
z_dm = self.arr_.z_dm
m_g = self.arr_.m_g
x_g = self.arr_.x_g
y_g = self.arr_.y_g
z_g = self.arr_.z_g
pot_s = self.arr_.pot_s
pot_dm = self.arr_.pot_dm
pot_g = self.arr_.pot_g
pot_s = self.arr_.pot_s
pot_dm = self.arr_.pot_dm
pot_g = self.arr_.pot_g
eps_s = self.arr_.eps_s
eps_dm = self.arr_.eps_dm
eps_g = self.arr_.eps_g
potential = np.concatenate([pot_s, pot_dm, pot_g])
if np.all(potential == 0.0):
x = np.hstack((x_s, x_dm, x_g))
y = np.hstack((y_s, y_dm, y_g))
z = np.hstack((z_s, z_dm, z_g))
m = np.hstack((m_s, m_dm, m_g))
eps = np.max([eps_s, eps_dm, eps_g])
pot = utils.potential(
da.asarray(x, chunks=100),
da.asarray(y, chunks=100),
da.asarray(z, chunks=100),
da.asarray(m, chunks=100),
da.asarray(eps),
)
num_s = len(m_s)
num = len(m_s) + len(m_dm)
pot_s = pot[:num_s]
pot_dm = pot[num_s:num]
pot_g = pot[num:]
new = attr.asdict(self, recurse=False)
del new["arr_"]
new.update(
pot_s=-pot_s * (u.km / u.s) ** | |
# package NLP_ITB.POSTagger.HMM
from copy import deepcopy
import re
import math
class WordFreq:
def __init__(self, wordTagFreq={}):
self.wordTagFreq = wordTagFreq
def getWordTagFreq(self):
#Returns Map<String, Map<Integer, Integer>>
return self.wordTagFreq
def readWordTagFreq(reader, tagNumbers):
"""
Returns WordFreq
Parameters:
reader: file object
tagNumbers: Map<String, Integer>
"""
# Map<String, Map<Integer, Integer>>
wordTagFreq = {}
for line in reader.readlines():
lineParts = re.split("\\s+", line.strip())
word = lineParts[0]
wordTagFreq[word] = {};
for i in xrange(1, len(lineParts), 2):
wordTagFreq[word][tagNumbers[lineParts[i]]] = int(lineParts[i + 1])
return WordFreq(wordTagFreq)
class NGram:
def __init__(self, tagNumbers={}, numberTags={}, uniGramFreqs={}, biGramFreqs={}, triGramFreqs={}, quatoGramFreqs={}):
self.tagNumbers = tagNumbers;
self.numberTags = numberTags;
self.uniGramFreqs = uniGramFreqs;
self.biGramFreqs = biGramFreqs;
self.triGramFreqs = triGramFreqs;
self.quatoGramFreqs = quatoGramFreqs;
def getTagNumber(self):
#Returns Map<String, Integer>
return self.tagNumbers
def getNumberTag(self):
#Returns Map<Integer, String>
return self.numberTags
def getUniGramFreq(self):
#Returns Map<UniGram, Integer>
return self.uniGramFreqs
def getBiGramFreq(self):
#Returns Map<BiGram, Integer>
return self.biGramFreqs
def getTriGramFreq(self):
#Returns Map<TriGram, Integer>
return self.triGramFreqs
def getQuatoGramFreq(self):
#Returns Map<QuatoGram, Integer>
return self.quatoGramFreqs
def readNGrams(reader):
"""
Returns NGram
Parameters:
reader: file object
"""
# Map<String, Integer>
tagNumbers = {}
# Map<Integer, String>
numberTags = {}
# Map<UniGram, Integer>
uniGramFreqs = {}
# Map<BiGram, Integer>
biGramFreqs = {}
# Map<TriGram, Integer>
triGramFreqs = {}
# Map<QuatoGram, Integer>
quatoGramFreqs = {}
# int
tagNumber = 0
# String
for line in reader.readlines():
# String[]
lineParts = re.split("\\s+", line.strip())
# int
freq = int(lineParts[-1])
lplen = len(lineParts)
if lplen == 2:
tagNumbers[lineParts[0]] = tagNumber
numberTags[tagNumber] = lineParts[0]
uniGramFreqs[UniGram(tagNumber)] = freq
tagNumber += 1
elif lplen == 3:
biGramFreqs[BiGram(tagNumbers[lineParts[0]], tagNumbers[lineParts[1]])] = freq
elif lplen == 4:
triGramFreqs[TriGram(tagNumbers[lineParts[0]], tagNumbers[lineParts[1]], tagNumbers[lineParts[2]])] = freq
elif lplen == 5:
quatoGramFreqs[QuatoGram(tagNumbers[lineParts[0]], tagNumbers[lineParts[1]], tagNumbers[lineParts[2]], tagNumbers[lineParts[3]])] = freq
return NGram(tagNumbers, numberTags, uniGramFreqs, biGramFreqs, triGramFreqs, quatoGramFreqs)
class Model:
def __init__(self, wordTagFreqReader, nGramReader):
"""
Parameters:
wordTagFreqReader: file object
nGramReader: file object
"""
# NGram
nGrams = readNGrams(nGramReader)
# WordFreq
wordTagFreqs = readWordTagFreq(wordTagFreqReader, nGrams.getTagNumber())
self.wordTagFreqs = deepcopy(wordTagFreqs.getWordTagFreq())
self.tagNumbers = deepcopy(nGrams.getTagNumber())
self.numberTags = deepcopy(nGrams.getNumberTag())
self.uniGramFreqs = deepcopy(nGrams.getUniGramFreq())
self.biGramFreqs = deepcopy(nGrams.getBiGramFreq())
self.triGramFreqs = deepcopy(nGrams.getTriGramFreq())
self.quatoGramFreqs = deepcopy(nGrams.getQuatoGramFreq())
def getBiGrams(self):
#Returns Map<BiGram, Integer>
return self.biGramFreqs
def getLexicon(self):
#Returns Map<String, Map<Integer, Integer>>
return self.wordTagFreqs
def getNumberTags(self):
#Returns Map<Integer, String>
return self.numberTags
def getTagNumbers(self):
#Returns Map<String, Integer>
return self.tagNumbers
def getTriGrams(self):
#Returns Map<TriGram, Integer>
return self.triGramFreqs
def getQuatoGrams(self):
#Returns Map<QuatoGram, Integer>
return self.quatoGramFreqs
def getUniGrams(self):
#Returns Map<UniGram, Integer>
return self.uniGramFreqs
class UniGram:
def __init__(self, t1=-1):
self.tag1 = t1
def __eq__(self, other):
if other == None or self.__class__ != other.__class__:
return False
return (self.tag1 == other.tag1)
def __hash__(self):
return self.tag1
def t1(self):
return self.tag1
class BiGram:
def __init__(self, t1=-1, t2=-1):
self.tag1 = t1
self.tag2 = t2
def __eq__(self, other):
if other is None or self.__class__ != other.__class__:
return False
# BiGram
return self.tag1 == other.tag1 and self.tag2 == other.tag2
def __hash__(self):
# int
seed = self.tag1
seed ^= self.tag2 + -1640531527 + (seed << 6) + (seed >> 2)
return seed
def t1(self):
return self.tag1
def t2(self):
return self.tag2
class TriGram:
def __init__(self, t1, t2, t3):
self.tag1 = t1
self.tag2 = t2
self.tag3 = t3
def __eq__(self, other):
if other == None or self.__class__ != other.__class__:
return False
# TriGram
return (self.tag1 == other.tag1 and self.tag2 == other.tag2 and self.tag3 == other.tag3)
def __hash__(self):
# int
seed = 0;
seed = self.tag1
seed ^= self.tag2 + -1640531527 + (seed << 6) + (seed >> 2)
seed ^= self.tag3 + -1640531527 + (seed << 6) + (seed >> 2)
return seed
def t1(self):
return self.tag1
def t2(self):
return self.tag2
def t3(self):
return self.tag3
class QuatoGram:
def __init__(self, t1, t2, t3, t4):
self.tag1 = t1
self.tag2 = t2
self.tag3 = t3
self.tag4 = t4
def __eq__(self, other):
if other == None or self.__class__ != other.__class__:
return False
# QuatoGram
return (self.tag1 == other.tag1 and self.tag2 == other.tag2 and self.tag3 == other.tag3 and self.tag4 == other.tag4)
def __hash__(self):
# int
seed = 0;
seed = self.tag1
seed ^= self.tag2 + -1640531527 + (seed << 6) + (seed >> 2)
seed ^= self.tag3 + -1640531527 + (seed << 6) + (seed >> 2)
seed ^= self.tag4 + -1640531527 + (seed << 6) + (seed >> 2)
return seed
def t1(self):
return self.tag1
def t2(self):
return self.tag2
def t3(self):
return self.tag3
def t4(self):
return self.tag4
class Smoother:
"""
Parameters:
Map<UniGram, Integer> UniGramFreqs
Map<BiGram, Integer> BiGramFreqs
Map<TriGram, Integer> TriGramFreqs
Map<QuatoGram, Integer> QuatoGramFreqs
double BigramLambda
"""
def __init__(self, UniGramFreqs, BiGramFreqs, TriGramFreqs, QuatoGramFreqs, BigramLambda):
self.UniGramFreq = UniGramFreqs
self.BiGramFreq = BiGramFreqs
self.TriGramFreq = TriGramFreqs
self.QuatoGramFreq = QuatoGramFreqs
self.TriGramCache = {}
self.BiGramCache = {}
self.BigramLambda = BigramLambda
self.calculateCorpusSize()
self.calculateLambdas()
def uniGramProb(self, uniGram):
"""
Returns double
Parameters:
uniGram: UniGram
"""
# UniGram
t1 = UniGram(uniGram.t1())
# double
uniGramProb = math.log(self.UniGramFreq[t1] / float(self.corpusSize))
return uniGramProb
def biGramProb(self, biGram):
"""
Returns double
Parameters:
biGram: BiGram
"""
try:
if biGram in self.BiGramCache:
return self.BiGramCache[biGram]
# UniGram
t2 = UniGram(biGram.t2())
# double
uniGramProb = self.UniGramFreq[t2] / float(self.corpusSize)
# BiGram
t1t2 = BiGram(biGram.t1(), biGram.t2())
# UniGram
t1 = UniGram(biGram.t1())
# double
biGramProb = 0.0
if t1 in self.UniGramFreq and t1t2 in self.BiGramFreq:
biGramProb = self.BiGramFreq[t1t2] / float(self.UniGramFreq[t1])
# double
prob = math.log(self.BigramLambda * uniGramProb + (1 - self.BigramLambda) * biGramProb)
self.BiGramCache[biGram] = prob
return prob
except:
pass
def triGramProb(self, triGram):
"""
Returns double
Parameters:
triGram: TriGram
"""
if triGram in self.TriGramCache:
return self.TriGramCache[triGram]
# UniGram
t3 = UniGram(triGram.t3())
# double
uniGramProb = self.UniGramFreq[t3] / float(self.corpusSize)
# BiGram
t2t3 = BiGram(triGram.t2(), triGram.t3())
# UniGram
t2 = UniGram(triGram.t2())
# double
biGramProb = 0.0
if t2 in self.UniGramFreq and t2t3 in self.BiGramFreq:
biGramProb = self.BiGramFreq[t2t3] / float(self.UniGramFreq[t2])
# BiGram
t1t2 = BiGram(triGram.t1(), triGram.t2())
# double
triGramProb = 0.0
if t1t2 in self.BiGramFreq and triGram in self.TriGramFreq:
triGramProb = self.TriGramFreq[triGram] / float(self.BiGramFreq[t1t2])
# double
prob = math.log(self.d_l1 * uniGramProb + self.d_l2 * biGramProb + self.d_l3 * triGramProb)
self.TriGramCache[triGram] = prob
return prob
def triGramProbSucceed(self, triGram):
"""
Returns double
Parameters:
triGram: TriGram
"""
# int
B = 0
# int
N = 0
# int
X = 0
if triGram in self.TriGramCache:
return self.TriGramCache[triGram]
for entry in self.UniGramFreq:
t1t2t3 = TriGram(triGram.t1(), entry.t1(), triGram.t3())
if t1t2t3 in self.TriGramFreq:
B += 1
N += self.TriGramFreq[t1t2t3]
if triGram in self.TriGramFreq:
X = self.TriGramFreq[triGram]
# double
prob = 1.0E-8
if N != 0:
prob = float( X + 0.5) / float(N + (0.5 * B))
self.TriGramCache[triGram] = math.log(prob)
return math.log(prob)
def quatoGramProbSucceed(self, quatoGram):
"""
Returns double
Parameters:
quatoGram: QuatoGram
"""
# int
B = 0
# int
N = 0
# int
X = 0
for entry in self.UniGramFreq:
t1t2t3t4 = QuatoGram(quatoGram.t1(), quatoGram.t2(), entry.t1(), quatoGram.t4())
if t1t2t3t4 in self.QuatoGramFreq:
B += 1
N += self.QuatoGramFreq[t1t2t3t4]
if quatoGram in self.QuatoGramFreq:
X = self.QuatoGramFreq[quatoGram]
# double
prob = 1.0E-8
if N != 0:
prob = float( X + BigramLambda) / float(N + (BigramLambda * B))
return math.log(prob)
def calculateCorpusSize(self):
self.corpusSize = 0
for entry in self.UniGramFreq:
self.corpusSize += self.UniGramFreq[entry];
def calculateLambdas(self):
# int
l1f = 0
# int
l2f = 0
# int
l3f = 0
for triGramEntry in self.TriGramFreq:
t1t2t3 = triGramEntry
# BiGram
t1t2 = BiGram(t1t2t3.t1(), t1t2t3.t2())
# double
l3p = 0.0;
if t1t2 in self.BiGramFreq:
#l3p = (self.TriGramFreq[triGramEntry] - 1) / float(self.BiGramFreq[t1t2] - 1)
l3p = (self.TriGramFreq[triGramEntry] - 1) / float(self.BiGramFreq[t1t2])
# BiGram
t2t3 = BiGram(t1t2t3.t2(), t1t2t3.t3())
# UniGram
t2 = UniGram(t1t2t3.t2())
# double
l2p = 0.0
if t2 in self.UniGramFreq and t2t3 in self.BiGramFreq:
#l2p = (self.BiGramFreq[t2t3] - 1) / float(self.UniGramFreq[t2] - 1)
l2p = (self.BiGramFreq[t2t3] - 1) / float(self.UniGramFreq[t2])
# UniGram
t3 = UniGram(t1t2t3.t3())
# double
l1p = 0.0
if t3 in self.UniGramFreq:
l1p = (self.UniGramFreq[t3] - 1) / float(self.corpusSize - 1)
if l1p > l2p and l1p > l3p:
l1f += self.TriGramFreq[triGramEntry]
else:
if l2p > l1p and l2p > l3p:
l2f += self.TriGramFreq[triGramEntry]
else:
l3f += self.TriGramFreq[triGramEntry]
# double
totalTriGrams = l1f + l2f + l3f
if totalTriGrams == 0:
self.d_l1 = 1e300 #float('inf')
self.d_l2 = 1e300 #float('inf')
self.d_l3 = 1e300 #float('inf')
else:
totalTriGrams = float(totalTriGrams)
| |
<gh_stars>0
import sys
import json
import time
import calendar
import arrow
import click
from prettytable import PrettyTable
from datetime import datetime
try:
from zoneinfo import ZoneInfo
except ImportError:
from backports.zoneinfo import ZoneInfo
from calm.dsl.api import get_api_client
from calm.dsl.builtins import Job
from calm.dsl.builtins.models import job
from calm.dsl.cli import runbooks
from calm.dsl.cli import apps
from calm.dsl.config import get_context
from calm.dsl.constants import CACHE
from calm.dsl.log import get_logging_handle
from calm.dsl.store import Cache
from calm.dsl.tools import get_module_from_file
# from calm.dsl.builtins.models.metadata_payload import get_metadata_payload
from .utils import (
Display,
get_name_query,
highlight_text,
get_states_filter,
import_var_from_file,
)
from .constants import JOBS, JOBINSTANCES, SYSTEM_ACTIONS
LOG = get_logging_handle(__name__)
def create_job_command(job_file, name, description, force):
"""Creates a job in scheduler"""
# if job_file.endswith(".json"):
# res, err = create_job_from_json(
# client, job_file, name=name, description=description, force_create=force
# )
if job_file.endswith(".py"):
res, err = create_job_from_dsl(
job_file, name=name, description=description, force_create=force
)
else:
LOG.error("Unknown file format {}".format(job_file))
return
if err:
LOG.error(err["error"])
return err["error"]
job = res.json()
job_uuid = job["metadata"]["uuid"]
job_name = job["metadata"]["name"]
job_state = job["resources"]["state"]
LOG.debug("Job {} has uuid: {}".format(job_name, job_uuid))
if job_state != "ACTIVE":
msg_list = job.get("resources").get("message_list", [])
if not msg_list:
LOG.error("Job {} created with errors.".format(job_name))
LOG.debug(json.dumps(job))
return job
msgs = []
for msg_dict in msg_list:
msgs.append(msg_dict.get("message", ""))
LOG.error(
"Job {} created with {} error(s): {}".format(job_name, len(msg_list), msgs)
)
return job
LOG.info("Job {} created successfully.".format(job_name))
return job
#
# def create_job_from_json(
# client, path_to_json, name=None, description=None, force_create=False
# ):
#
# runbook_payload = json.loads(open(path_to_json, "r").read())
# return create_runbook(
# client,
# runbook_payload,
# name=name,
# description=description,
# force_create=force_create,
# )
def get_job_module_from_file(job_file):
"""Returns Job module given a user job dsl file (.py)"""
return get_module_from_file("calm.dsl.user_job", job_file)
def get_job_class_from_module(user_bp_module):
"""Returns Job class given a module"""
UserJob = None
for item in dir(user_bp_module):
obj = getattr(user_bp_module, item)
if isinstance(obj, (type(Job))):
if obj.__bases__[0] == Job:
UserJob = obj
return UserJob
def create_job_from_dsl(job_file, name=None, description=None, force_create=False):
job_payload = compile_job(job_file)
if job_payload is None:
err_msg = "User job not found in {}".format(job_file)
err = {"error": err_msg, "code": -1}
return None, err
return create_job(
job_payload,
name=name,
description=description,
force_create=force_create,
)
def create_job(job_payload, name=None, description=None, force_create=False):
if name:
job_payload["resources"]["name"] = name
job_payload["metadata"]["name"] = name
if description:
job_payload["resources"]["description"] = description
client = get_api_client()
return client.job.create(job_payload)
def compile_job(job_file):
"""returns compiled payload from dsl file"""
# metadata_payload = get_metadata_payload(job_file)
user_job_module = get_job_module_from_file(job_file)
UserJob = get_job_class_from_module(user_job_module)
if UserJob is None:
LOG.error("Job not found in {}".format(job_file))
return
# create job payload
job_payload = {
"resources": UserJob.get_dict(),
"metadata": {
"name": UserJob.get_dict()["name"],
"kind": "job",
},
"api_version": "3.0",
}
# if "project_reference" in metadata_payload:
# # Read metadata payload and set project reference
# job_payload["metadata"]["project_reference"] = metadata_payload[
# "project_reference"
# ]
# else:
# Read project name and uuid from config and set in job payload
ContextObj = get_context()
project_config = ContextObj.get_project_config()
project_name = project_config["name"]
project_cache_data = Cache.get_entity_data(
entity_type=CACHE.ENTITY.PROJECT, name=project_name
)
if not project_cache_data:
LOG.error(
"Project {} not found. Please run: calm update cache".format(project_name)
)
sys.exit("Project not found.")
project_uuid = project_cache_data.get("uuid", "")
job_payload["metadata"]["project_reference"] = {
"kind": "project",
"uuid": project_uuid,
"name": project_name,
}
executable_type = job_payload["resources"]["executable"].get("entity").get("type")
project_uuid = job_payload["metadata"]["project_reference"].get("uuid")
project_name = job_payload["metadata"]["project_reference"].get("name")
executable_uuid = job_payload["resources"]["executable"].get("entity").get("uuid")
if executable_type == "app":
# Get app uuid from name
client = get_api_client()
res, err = client.application.read(executable_uuid)
if err:
LOG.error("[{}] - {}".format(err["code"], err["error"]))
sys.exit(err["error"])
app = res.json()
# Check if project uuid in config is same as project uuid of the app
if app["metadata"]["project_reference"]["uuid"] != project_uuid:
application_name = app["metadata"]["name"]
LOG.error(
"Application {} does not belong to project {}.".format(
application_name, project_name
)
)
sys.exit(
"Application {} does not belong to project {}.".format(
application_name, project_name
)
)
elif executable_type == "runbook":
client = get_api_client()
res, err = client.runbook.read(executable_uuid)
if err:
LOG.error("[{}] - {}".format(err["code"], err["error"]))
sys.exit(err["error"])
runbook = res.json()
# Check if project uuid in config is same as project uuid of the runbook
if runbook["metadata"]["project_reference"]["uuid"] != project_uuid:
runbook_name = runbook["metadata"]["name"]
LOG.error(
"Runbook '{}' does not belong to project '{}'.".format(
runbook_name, project_name
)
)
sys.exit(
"Runbook '{}' does not belong to project '{}'.".format(
runbook_name, project_name
)
)
return job_payload
def get_job(client, name, all=False):
# find job
params = {"filter": "name=={}".format(name)}
if not all:
params["filter"] += ";deleted==FALSE"
res, err = client.job.list(params=params)
if err:
LOG.error("[{}] - {}".format(err["code"], err["error"]))
sys.exit(err["error"])
response = res.json()
entities = response.get("entities", None)
job_data = None
if entities:
if len(entities) != 1:
raise Exception("More than one job found - {}".format(entities))
LOG.info("Job {} found ".format(name))
job_data = entities[0]
else:
raise Exception("No job found with name {} found".format(name))
return job_data
def describe_job_command(job_name, out):
"""Displays job data"""
client = get_api_client()
job_get_res = get_job(client, job_name, all=True)
res, err = client.job.read(job_get_res["metadata"]["uuid"])
if err:
LOG.error("[{}] - {}".format(err["code"], err["error"]))
sys.exit(err["error"])
job_response = res.json()
if out == "json":
job_response.pop("status", None)
click.echo(json.dumps(job_response, indent=4, separators=(",", ": ")))
return
click.echo("\n----Job Summary----\n")
click.echo(
"Name: "
+ highlight_text(job_response["resources"]["name"])
+ " (uuid: "
+ highlight_text(job_response["metadata"]["uuid"])
+ " (project: "
+ highlight_text(job_response["metadata"]["project_reference"]["name"])
+ ")"
)
description = job_response["resources"].get("description", "")
click.echo("Description: " + highlight_text(description))
schedule_type = job_response["resources"]["type"]
click.echo("Status: " + highlight_text(job_response["resources"]["state"]))
owner = job_response["metadata"]["owner_reference"]["name"]
click.echo("Owner: " + highlight_text(owner))
created_on = int(job_response["metadata"]["creation_time"]) // 1000000
past = arrow.get(created_on).humanize()
click.echo(
"Created: {} ({})".format(
highlight_text(time.ctime(created_on)), highlight_text(past)
)
)
last_updated = int(job_response["metadata"]["last_update_time"]) // 1000000
past = arrow.get(last_updated).humanize()
click.echo(
"Last Updated: {} ({})\n".format(
highlight_text(time.ctime(last_updated)), highlight_text(past)
)
)
message_list = job_response["resources"].get("message_list", "")
messages = []
if len(message_list) != 0:
for message in message_list:
messages.append(message)
if len(messages) > 0:
click.echo("----Errors----")
click.echo("Messages:")
for message in messages:
click.echo(
highlight_text(message.get("reason", ""))
+ " for attribute "
+ highlight_text(message.get("details").get("attribute_name"))
+ " ."
+ highlight_text(message.get("message", ""))
)
click.echo("")
executable_type = job_response["resources"]["executable"]["entity"]["type"]
click.echo("--Schedule Info--")
click.echo("Schedule Type: " + highlight_text(schedule_type))
time_zone = job_response["resources"]["schedule_info"]["time_zone"]
click.echo("Time Zone: " + highlight_text(time_zone))
if schedule_type == "ONE-TIME":
start_time = int(job_response["resources"]["schedule_info"]["execution_time"])
past = arrow.get(start_time).humanize()
click.echo(
"Starts On: {} ({})".format(
highlight_text(time.ctime(start_time)), highlight_text(past)
)
)
elif schedule_type == "RECURRING":
start_time = int(job_response["resources"]["schedule_info"]["start_time"])
past = arrow.get(start_time).humanize()
click.echo(
"Starts On: {} ({})".format(
highlight_text(time.ctime(start_time)), highlight_text(past)
)
)
expiry_time = job_response["resources"]["schedule_info"].get("expiry_time", "")
if expiry_time == "":
click.echo("Ends: {}".format(highlight_text("Never")))
else:
past = arrow.get(expiry_time).humanize()
click.echo(
"Ends On: {} ({})".format(
highlight_text(time.ctime(int(expiry_time))), highlight_text(past)
)
)
schedule = job_response["resources"]["schedule_info"]["schedule"]
click.echo("Schedule: {}".format(highlight_text(schedule)))
next_execution_time = int(job_response["resources"]["next_execution_time"])
past = arrow.get(next_execution_time).humanize()
click.echo(
"Next Execution Time: {} ({})\n".format(
highlight_text(time.ctime(next_execution_time)), highlight_text(past)
)
)
if executable_type == "runbook":
runbook_uuid = job_response["resources"]["executable"]["entity"]["uuid"]
res, err = client.runbook.read(runbook_uuid)
runbook = res.json()
msg_list = runbook.get("message_list", [])
msgs = []
for msg_dict in msg_list:
msgs.append(msg_dict.get("message", ""))
click.echo("--Executable Info--")
click.echo("Type: " + highlight_text(executable_type))
# If runbook is not found
if len(msg_list) != 0 or len(msgs) != 0:
click.echo(msgs)
else:
click.echo(
"Name: "
+ highlight_text(runbook["metadata"]["name"])
+ " (uuid: "
+ highlight_text(runbook["metadata"]["uuid"])
+ ")"
)
variable_list_string = job_response["resources"]["executable"]["action"][
"spec"
].get("payload", "")
endpoint_name = ""
endpoint_uuid = ""
if variable_list_string != "":
variable_list = json.loads(variable_list_string)
endpoint_target_reference = variable_list.get("spec").get(
"default_target_reference"
)
if endpoint_target_reference is not None:
endpoint_name = endpoint_target_reference.get("name", "")
endpoint_uuid = endpoint_target_reference.get("uuid", "")
variable_list = variable_list["spec"]["args"]
click.echo("Runbook :")
variable_types = []
for var in variable_list:
var_name = var.get("name")
var_value = var.get("value", "")
variable_types.append(
"Name: " + var_name + " | " + "Value: " + var_value
)
click.echo(
"\tVariables [{}]:".format(highlight_text(len(variable_types)))
)
click.echo("\t\t{}\n".format(highlight_text(", ".join(variable_types))))
click.echo(
"Default Endpoint Target: "
+ highlight_text(endpoint_name)
+ " (uuid: "
+ highlight_text(endpoint_uuid)
+ ")"
)
elif executable_type == "app":
click.echo("--Executable Info--")
app_uuid = job_response["resources"]["executable"]["entity"]["uuid"]
res, err = client.application.read(app_uuid)
application = res.json()
click.echo("Type: " + highlight_text(executable_type.upper()))
click.echo(
"Application Name: " + highlight_text(application["metadata"]["name"])
)
app_spec = application["spec"]
calm_action_uuid = job_response["resources"]["executable"]["action"]["spec"][
"uuid"
]
action_payload = next(
(
action
for action in app_spec["resources"]["action_list"]
if action["uuid"] == calm_action_uuid
),
None,
)
click.echo(
"Application Action: " + highlight_text(action_payload.get("name", ""))
)
action_args = apps.get_action_runtime_args(
app_uuid=app_uuid,
action_payload=action_payload,
patch_editables=False,
runtime_params_file=False,
)
if not action_payload:
LOG.error("No action found")
sys.exit(-1)
if len(action_args) > 0:
variable_types = []
for var in action_args:
var_name = var.get("name")
var_value = var.get("value", "")
variable_types.append(
"Name: " + var_name + " | " + "Value: " + var_value
)
click.echo("\tVariables [{}]:".format(highlight_text(len(variable_types))))
click.echo("\t\t{}\n".format(highlight_text(", ".join(variable_types))))
def get_job_list_command(name, filter_by, limit, offset, quiet, all_items):
"""Get the runbooks, optionally filtered by a string"""
client = get_api_client()
params = {"length": limit, "offset": offset}
filter_query = ""
if name:
filter_query = get_name_query([name])
if filter_by:
filter_query = filter_query + ";(" + filter_by + ")"
if all_items:
filter_query += get_states_filter(JOBS.STATES)
if filter_query.startswith(";"):
filter_query = filter_query[1:]
if filter_query:
params["filter"] = filter_query
res, err = client.job.list(params=params)
if err:
LOG.warning("Cannot fetch jobs.")
return
json_rows = res.json().get("entities", "")
if not json_rows:
click.echo(highlight_text("No jobs found !!!\n"))
return
if quiet:
for _row in json_rows:
row = _row["resources"]
click.echo(highlight_text(row["name"]))
return
table = PrettyTable()
| |
<reponame>SoftwareQuTech/QLinkLayerSimulations<filename>simulations/data_analysis_scripts/tables/extract_fairness.py
#######################################################################################################################
# NOTE: This is very similar to simulations.generate_metrics_file with the difference that metrics are seperated #
# depending on the requesting node the be able to extract fairness metrics. Not recommended to be used for anything #
# else than this. #
#######################################################################################################################
import os
import json
import numpy as np
from argparse import ArgumentParser
from collections import defaultdict
from easysquid.toolbox import logger
from simulations.analysis_sql_data import parse_table_data_from_sql, calc_fidelity, parse_raw_queue_data, \
get_datacollection_version
from qlinklayer.datacollection import EGPErrorDataPoint
from simulations.generate_metrics_file import sort_data_by_request, get_avg_std_num, add_metric_data
def parse_thoughput(creates_and_oks_by_create_id, max_time, num_points=10000, time_window=1e9, min_time=0,
in_seconds=False):
priorities = list(range(3))
nodes = ["A", "B"]
timestamps_per_prio = {node: {p: [] for p in priorities} for node in nodes}
for create_id, create_data in creates_and_oks_by_create_id.items():
if not create_data["expired"]:
priority = create_data["create"].priority
origin_id = create_data["create"].node_id
origin = nodes[origin_id]
for node_id, node_data in create_data["oks"].items():
# Don't count OKs double
if node_id == 0:
for mhp_seq, mhp_data in node_data.items():
ok = mhp_data["ok"]
timestamps_per_prio[origin][priority].append(ok.timestamp)
throughputs_per_prio = {}
for node, node_timestamps in timestamps_per_prio.items():
throughputs_per_prio[node] = {}
for priority, timestamps in node_timestamps.items():
timestamps = sorted(timestamps)
if len(timestamps) == 0:
throughputs = [(None, 0)] * num_points
elif len(timestamps) == 1:
import pdb
pdb.set_trace()
raise RuntimeError()
else:
time_diff = max_time - min_time
shift = (time_diff - time_window) / (num_points - 1)
if shift > time_window:
logger.warning(
"Got to short time-window {} (s), making it {} (s)".format(time_window * 1e-9, shift * 1e-9))
time_window = shift
left_side = min_time
position = 0
throughputs = []
for _ in range(num_points):
right_side = left_side + time_window
i = position
num_oks_in_window = 0
while i < len(timestamps):
t = timestamps[i]
if t < left_side:
position += 1
elif t >= right_side:
break
else:
num_oks_in_window += 1
i += 1
if in_seconds:
throughputs.append((left_side * 1e-9, num_oks_in_window / time_window * 1e9))
else:
throughputs.append((left_side, num_oks_in_window / time_window))
left_side += shift
throughputs_per_prio[node][priority] = throughputs
return throughputs_per_prio
def get_metrics_from_single_file(filename):
# Get the correct datacollection version
get_datacollection_version(filename)
creates_and_oks_by_create_id, ok_keys_by_timestamp = sort_data_by_request(filename)
##########################
# Nr OKs and outstanding #
##########################
nodes = ["A", "B"]
nr_oks_per_prio = {node: {i: 0 for i in range(3)} for node in nodes}
nr_reqs_per_prio = {node: {i: 0 for i in range(3)} for node in nodes}
nr_outstanding_req_per_prio = {node: {i: 0 for i in range(3)} for node in nodes}
nr_outstanding_pairs_per_prio = {node: {i: 0 for i in range(3)} for node in nodes}
nr_expired_req_per_prio = {node: {i: 0 for i in range(3)} for node in nodes}
for create_id, create_data in creates_and_oks_by_create_id.items():
priority = create_data["create"].priority
origin_id = create_data["create"].node_id
origin = nodes[origin_id]
if create_data["expired"]:
nr_expired_req_per_prio[origin][priority] += 1
else:
node_id = 0
nr_reqs_per_prio[origin][priority] += 1
if node_id in create_data["oks"]:
oks = create_data["oks"][node_id]
nr_oks_per_prio[origin][priority] += len(oks)
pairs_left = create_data["create"].num_pairs - len(oks)
if pairs_left > 0:
nr_outstanding_req_per_prio[origin][priority] += 1
nr_outstanding_pairs_per_prio[origin][priority] += pairs_left
else:
nr_outstanding_req_per_prio[origin][priority] += 1
nr_outstanding_pairs_per_prio[origin][priority] += create_data["create"].num_pairs
##########
# Errors #
##########
errors_data = parse_table_data_from_sql(filename, "EGP_Errors")
num_errors = len(errors_data)
num_errors_per_code = defaultdict(int)
for e in errors_data:
error_datapoint = EGPErrorDataPoint(e)
num_errors_per_code[error_datapoint.error_code] += 1
################################
# Fidelities, QBER and latency #
################################
fids_per_prio = {node: {} for node in nodes}
qber_per_prio = {node: {} for node in nodes}
pair_latencies_per_prio_per_node = {}
req_latencies_per_prio_per_node = {}
scaled_req_latencies_per_prio_per_node = {origin: {} for origin in nodes}
attempts_per_prio = {i: 0 for i in range(3)}
cycles_per_attempt_per_prio = {i: [] for i in range(3)}
priorities = []
for create_id, request_data in creates_and_oks_by_create_id.items():
if not request_data["expired"]:
create_datapoint = request_data["create"]
priority = create_datapoint.priority
origin_id = create_datapoint.node_id
origin = nodes[origin_id]
if priority not in priorities:
priorities.append(priority)
for node_id, node_oks in request_data["oks"].items():
max_latency = -1
for mhp_seq, ok_data in node_oks.items():
# Qubit state
if "state" in ok_data:
state_datapoint = ok_data["state"]
d_matrix = state_datapoint.density_matrix
assert (state_datapoint.outcome1 == state_datapoint.outcome2)
outcome = state_datapoint.outcome1
fid = calc_fidelity(outcome, d_matrix)
if priority not in fids_per_prio[origin]:
fids_per_prio[origin][priority] = [fid]
else:
fids_per_prio[origin][priority].append(fid)
# QBER
if "QBER" in ok_data:
qber_datapoint = ok_data["QBER"]
qberxyz = {"X": qber_datapoint.x_err, "Y": qber_datapoint.y_err, "Z": qber_datapoint.z_err}
if priority not in qber_per_prio[origin]:
qber_per_prio[origin][priority] = {"X": [], "Y": [], "Z": []}
for basis, qber in qberxyz.items():
if qber != -1:
qber_per_prio[origin][priority][basis].append(qber)
# Latency
create_time = create_datapoint.create_time
ok_time = ok_data["ok"].timestamp
latency = (ok_time - create_time)
if latency > max_latency:
max_latency = latency
if priority not in pair_latencies_per_prio_per_node:
pair_latencies_per_prio_per_node[priority] = {}
if node_id not in pair_latencies_per_prio_per_node[priority]:
pair_latencies_per_prio_per_node[priority][node_id] = []
pair_latencies_per_prio_per_node[priority][node_id].append(latency)
# Attempts
# Only collect for one node
if node_id == 0:
ok_datapoint = ok_data["ok"]
attempts_per_prio[priority] += ok_datapoint.attempts
# Cycles per attempt
ok_datapoint = ok_data["ok"]
cycles_per_attempt_per_prio[priority].append(ok_datapoint.used_cycles / ok_datapoint.attempts)
num_pairs = create_datapoint.num_pairs
if len(node_oks) == num_pairs:
if priority not in req_latencies_per_prio_per_node:
req_latencies_per_prio_per_node[priority] = {}
if priority not in scaled_req_latencies_per_prio_per_node[origin]:
scaled_req_latencies_per_prio_per_node[origin][priority] = {}
if node_id not in req_latencies_per_prio_per_node[priority]:
req_latencies_per_prio_per_node[priority][node_id] = []
if node_id not in scaled_req_latencies_per_prio_per_node[origin][priority]:
scaled_req_latencies_per_prio_per_node[origin][priority][node_id] = []
req_latencies_per_prio_per_node[priority][node_id].append(max_latency)
scaled_req_latencies_per_prio_per_node[origin][priority][node_id].append(max_latency / num_pairs)
metric_fid_per_prio = {node: {priority: get_avg_std_num(fids) for priority, fids in fids_per_prio[node].items()} for
node in nodes}
metric_qber_per_prio = {}
for node, qber_per_prio_only in qber_per_prio.items():
metric_qber_per_prio[node] = {}
for priority, qbersxyz in qber_per_prio_only.items():
metric_qber_per_prio[node][priority] = {basis: get_avg_std_num(qbers) if len(qbers) > 0 else 0 for
basis, qbers in qbersxyz.items()}
metric_qber_per_prio[node][priority]["fid"] = 1 - sum(
[qber[0] for qber in metric_qber_per_prio[node][priority].values()]) / 2
# Pair latency
metric_pair_latencies_per_prio_per_node = {}
for priority, latencies_per_node in pair_latencies_per_prio_per_node.items():
metric_pair_latencies_per_prio_per_node[priority] = {}
for node_id, latencies in latencies_per_node.items():
latencies = [l * 1e-9 for l in latencies]
metric_pair_latencies_per_prio_per_node[priority][node_id] = get_avg_std_num(latencies)
# Request latency
metric_req_latencies_per_prio_per_node = {}
for priority, latencies_per_node in req_latencies_per_prio_per_node.items():
metric_req_latencies_per_prio_per_node[priority] = {}
for node_id, latencies in latencies_per_node.items():
latencies = [l * 1e-9 for l in latencies]
metric_req_latencies_per_prio_per_node[priority][node_id] = get_avg_std_num(latencies)
# Scaled request Latency
metric_scaled_req_latencies_per_prio_per_node = {origin: {} for origin in nodes}
for origin, node_latencies_per_node in scaled_req_latencies_per_prio_per_node.items():
for priority, latencies_per_node in node_latencies_per_node.items():
metric_scaled_req_latencies_per_prio_per_node[origin][priority] = {}
for node_id, latencies in latencies_per_node.items():
latencies = [l * 1e-9 for l in latencies]
metric_scaled_req_latencies_per_prio_per_node[origin][priority][node_id] = get_avg_std_num(latencies)
avg_cycles_per_attempt_per_prio = {priority: sum(c_p_a) / len(c_p_a) if len(c_p_a) > 0 else None for priority, c_p_a
in cycles_per_attempt_per_prio.items()}
#################
# Queue Lengths #
#################
queue_ids = range(3)
raw_all_queue_data = {qid: parse_table_data_from_sql(filename, "EGP_Local_Queue_A_{}".format(qid)) for qid in
queue_ids}
all_queue_lengths = {}
times_non_idle = {}
for qid, raw_queue_data in raw_all_queue_data.items():
queue_data = parse_raw_queue_data(raw_queue_data)
all_queue_lengths[qid] = queue_data[0]
times_non_idle[qid] = queue_data[-1]
all_queue_lengths = {qid: parse_raw_queue_data(raw_queue_data)[0] for qid, raw_queue_data in
raw_all_queue_data.items()}
all_avg_queue_lengths = {qid: sum(queue_lengths) / len(queue_lengths) for qid, queue_lengths in
all_queue_lengths.items()}
###############
# Matrix time #
###############
# Simulation time
additional_data_filename = filename[:-3] + "_additional_data.json"
with open(additional_data_filename, 'r') as f:
additional_data = json.load(f)
total_matrix_time = additional_data["total_real_time"]
##############
# Throughput #
##############
throughputs_per_prio = parse_thoughput(creates_and_oks_by_create_id, total_matrix_time)
metric_throughput_per_prio = {}
for node, node_throughputs in throughputs_per_prio.items():
metric_throughput_per_prio[node] = {}
for prio, throughputs in node_throughputs.items():
tps = [tp[1] for tp in throughputs]
metric_throughput_per_prio[node][prio] = get_avg_std_num(tps)
########################
# Outstanding requests #
########################
#############################
# Construct dict of metrics #
#############################
metrics = {}
for origin in nodes:
for priority in range(3):
if priority == 0:
prio_name = "NL"
elif priority == 1:
prio_name = "CK"
elif priority == 2:
prio_name = "MD"
else:
raise RuntimeError("Unkown priority {}".format(priority))
metrics["NrReqs_Prio{}_Origin{}".format(prio_name, origin)] = nr_reqs_per_prio[origin][priority]
metrics["NrOKs_Prio{}_Origin{}".format(prio_name, origin)] = nr_oks_per_prio[origin][priority]
metrics["NrRemReq_Prio{}_Origin{}".format(prio_name, origin)] = nr_outstanding_req_per_prio[origin][
priority]
metrics["NrRemPairs_Prio{}_Origin{}".format(prio_name, origin)] = nr_outstanding_pairs_per_prio[origin][
priority]
add_metric_data(metrics, "Throughp_Prio{}_Origin{} (1/s)".format(prio_name, origin),
metric_throughput_per_prio[origin][priority])
metrics["AvgCyc_per_Att_Prio{}".format(prio_name)] = avg_cycles_per_attempt_per_prio[priority]
for lat_name, lat_data in zip(["Pair", "Req"], [metric_pair_latencies_per_prio_per_node,
metric_req_latencies_per_prio_per_node]):
try:
metric_latencies_per_node = lat_data[priority]
except KeyError:
metric_latencies_per_node = {}
for node_id in range(2):
try:
add_metric_data(metrics, "{}Laten_Prio{}_NodeID{} (s)".format(lat_name, prio_name, node_id),
metric_latencies_per_node[node_id])
except KeyError:
add_metric_data(metrics, "{}Laten_Prio{}_NodeID{} (s)".format(lat_name, prio_name, node_id),
[None] * 3)
for node_id in range(2):
try:
add_metric_data(metrics,
"ScaledReqLaten_Prio{}_NodeID{}_Origin{} (s)".format(prio_name, node_id, origin),
metric_scaled_req_latencies_per_prio_per_node[origin][priority][node_id])
except KeyError:
add_metric_data(metrics,
"ScaledReqLaten_Prio{}_NodeID{}_Origin{} (s)".format(prio_name, node_id, origin),
[None] * 3)
if priority < 2:
try:
add_metric_data(metrics, "Fid_Prio{}_Origin{}".format(prio_name, origin),
metric_fid_per_prio[origin][priority])
except KeyError:
add_metric_data(metrics, "Fid_Prio{}_Origin{}".format(prio_name, origin), [None] * 3)
else:
try:
avg_fid_prio_tmp = metric_qber_per_prio[origin][priority]["fid"]
metrics["AvgFid_Prio{}_Origin{}".format(prio_name, origin)] = avg_fid_prio_tmp
metrics["StdFid_Prio{}_Origin{}".format(prio_name, origin)] = None
metrics["NumFid_Prio{}_Origin{}".format(prio_name, origin)] = None
except KeyError:
add_metric_data(metrics, "Fid_Prio{}_Origin{}".format(prio_name, origin), [None] * 3)
for basis in ["X", "Y", "Z"]:
try:
add_metric_data(metrics, "QBER{}_Prio{}_Origin{}".format(basis, prio_name, origin),
metric_qber_per_prio[origin][priority]["{}".format(basis)])
except KeyError:
add_metric_data(metrics, "QBER{}_Prio{}_Origin{}".format(basis, prio_name, origin), [None] * 3)
metrics["NumErrors"] = num_errors
metrics["ErrorCodes"] = "".join(
["{}({}), ".format(error_code, number) for error_code, number in num_errors_per_code.items()])[:-2]
metrics["TotalMatrixT (s)"] = total_matrix_time * 1e-9
for qid in range(3):
try:
avg_queue_length = all_avg_queue_lengths[qid]
except KeyError:
avg_queue_length = None
try:
time_idle = (total_matrix_time - times_non_idle[qid]) * 1e-9
except KeyError:
time_idle = None
metrics["AvgQueueLen_QID{}".format(qid)] = avg_queue_length
metrics["QueueIdle_QID{}".format(qid)] = | |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** 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
from ... import _utilities, _tables
from . import outputs
__all__ = [
'MySQLInstanceSpec',
'MySQLInstanceSpecClassRef',
'MySQLInstanceSpecClassSelector',
'MySQLInstanceSpecClassSelectorMatchExpressions',
'MySQLInstanceSpecResourceRef',
'MySQLInstanceSpecWriteConnectionSecretToRef',
'MySQLInstanceStatus',
'MySQLInstanceStatusConditions',
'NoSQLInstanceSpec',
'NoSQLInstanceSpecClassRef',
'NoSQLInstanceSpecClassSelector',
'NoSQLInstanceSpecClassSelectorMatchExpressions',
'NoSQLInstanceSpecResourceRef',
'NoSQLInstanceSpecWriteConnectionSecretToRef',
'NoSQLInstanceStatus',
'NoSQLInstanceStatusConditions',
'PostgreSQLInstanceSpec',
'PostgreSQLInstanceSpecClassRef',
'PostgreSQLInstanceSpecClassSelector',
'PostgreSQLInstanceSpecClassSelectorMatchExpressions',
'PostgreSQLInstanceSpecResourceRef',
'PostgreSQLInstanceSpecWriteConnectionSecretToRef',
'PostgreSQLInstanceStatus',
'PostgreSQLInstanceStatusConditions',
]
@pulumi.output_type
class MySQLInstanceSpec(dict):
"""
MySQLInstanceSpec specifies the desired state of a MySQLInstance.
"""
def __init__(__self__, *,
class_ref: Optional['outputs.MySQLInstanceSpecClassRef'] = None,
class_selector: Optional['outputs.MySQLInstanceSpecClassSelector'] = None,
engine_version: Optional[str] = None,
resource_ref: Optional['outputs.MySQLInstanceSpecResourceRef'] = None,
write_connection_secret_to_ref: Optional['outputs.MySQLInstanceSpecWriteConnectionSecretToRef'] = None):
"""
MySQLInstanceSpec specifies the desired state of a MySQLInstance.
:param 'MySQLInstanceSpecClassRefArgs' class_ref: A ClassReference specifies a resource class that will be used to dynamically provision a managed resource when the resource claim is created.
:param 'MySQLInstanceSpecClassSelectorArgs' class_selector: A ClassSelector specifies labels that will be used to select a resource class for this claim. If multiple classes match the labels one will be chosen at random.
:param str engine_version: EngineVersion specifies the desired MySQL engine version, e.g. 5.7.
:param 'MySQLInstanceSpecResourceRefArgs' resource_ref: A ResourceReference specifies an existing managed resource, in any namespace, to which this resource claim should attempt to bind. Omit the resource reference to enable dynamic provisioning using a resource class; the resource reference will be automatically populated by Crossplane.
:param 'MySQLInstanceSpecWriteConnectionSecretToRefArgs' write_connection_secret_to_ref: WriteConnectionSecretToReference specifies the name of a Secret, in the same namespace as this resource claim, to which any connection details for this resource claim should be written. Connection details frequently include the endpoint, username, and password required to connect to the managed resource bound to this resource claim.
"""
if class_ref is not None:
pulumi.set(__self__, "class_ref", class_ref)
if class_selector is not None:
pulumi.set(__self__, "class_selector", class_selector)
if engine_version is not None:
pulumi.set(__self__, "engine_version", engine_version)
if resource_ref is not None:
pulumi.set(__self__, "resource_ref", resource_ref)
if write_connection_secret_to_ref is not None:
pulumi.set(__self__, "write_connection_secret_to_ref", write_connection_secret_to_ref)
@property
@pulumi.getter(name="classRef")
def class_ref(self) -> Optional['outputs.MySQLInstanceSpecClassRef']:
"""
A ClassReference specifies a resource class that will be used to dynamically provision a managed resource when the resource claim is created.
"""
return pulumi.get(self, "class_ref")
@property
@pulumi.getter(name="classSelector")
def class_selector(self) -> Optional['outputs.MySQLInstanceSpecClassSelector']:
"""
A ClassSelector specifies labels that will be used to select a resource class for this claim. If multiple classes match the labels one will be chosen at random.
"""
return pulumi.get(self, "class_selector")
@property
@pulumi.getter(name="engineVersion")
def engine_version(self) -> Optional[str]:
"""
EngineVersion specifies the desired MySQL engine version, e.g. 5.7.
"""
return pulumi.get(self, "engine_version")
@property
@pulumi.getter(name="resourceRef")
def resource_ref(self) -> Optional['outputs.MySQLInstanceSpecResourceRef']:
"""
A ResourceReference specifies an existing managed resource, in any namespace, to which this resource claim should attempt to bind. Omit the resource reference to enable dynamic provisioning using a resource class; the resource reference will be automatically populated by Crossplane.
"""
return pulumi.get(self, "resource_ref")
@property
@pulumi.getter(name="writeConnectionSecretToRef")
def write_connection_secret_to_ref(self) -> Optional['outputs.MySQLInstanceSpecWriteConnectionSecretToRef']:
"""
WriteConnectionSecretToReference specifies the name of a Secret, in the same namespace as this resource claim, to which any connection details for this resource claim should be written. Connection details frequently include the endpoint, username, and password required to connect to the managed resource bound to this resource claim.
"""
return pulumi.get(self, "write_connection_secret_to_ref")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class MySQLInstanceSpecClassRef(dict):
"""
A ClassReference specifies a resource class that will be used to dynamically provision a managed resource when the resource claim is created.
"""
def __init__(__self__, *,
api_version: Optional[str] = None,
field_path: Optional[str] = None,
kind: Optional[str] = None,
name: Optional[str] = None,
namespace: Optional[str] = None,
resource_version: Optional[str] = None,
uid: Optional[str] = None):
"""
A ClassReference specifies a resource class that will be used to dynamically provision a managed resource when the resource claim is created.
:param str api_version: API version of the referent.
:param str field_path: If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.
:param str kind: Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
:param str name: Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
:param str namespace: Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/
:param str resource_version: Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
:param str uid: UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids
"""
if api_version is not None:
pulumi.set(__self__, "api_version", api_version)
if field_path is not None:
pulumi.set(__self__, "field_path", field_path)
if kind is not None:
pulumi.set(__self__, "kind", kind)
if name is not None:
pulumi.set(__self__, "name", name)
if namespace is not None:
pulumi.set(__self__, "namespace", namespace)
if resource_version is not None:
pulumi.set(__self__, "resource_version", resource_version)
if uid is not None:
pulumi.set(__self__, "uid", uid)
@property
@pulumi.getter(name="apiVersion")
def api_version(self) -> Optional[str]:
"""
API version of the referent.
"""
return pulumi.get(self, "api_version")
@property
@pulumi.getter(name="fieldPath")
def field_path(self) -> Optional[str]:
"""
If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.
"""
return pulumi.get(self, "field_path")
@property
@pulumi.getter
def kind(self) -> Optional[str]:
"""
Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def namespace(self) -> Optional[str]:
"""
Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/
"""
return pulumi.get(self, "namespace")
@property
@pulumi.getter(name="resourceVersion")
def resource_version(self) -> Optional[str]:
"""
Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
"""
return pulumi.get(self, "resource_version")
@property
@pulumi.getter
def uid(self) -> Optional[str]:
"""
UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids
"""
return pulumi.get(self, "uid")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
@pulumi.output_type
class MySQLInstanceSpecClassSelector(dict):
"""
A ClassSelector specifies labels that will be used to select a resource class for this claim. If multiple classes match the labels one will be chosen at random.
"""
def __init__(__self__, *,
match_expressions: Optional[Sequence['outputs.MySQLInstanceSpecClassSelectorMatchExpressions']] = None,
match_labels: Optional[Mapping[str, str]] = None):
"""
A ClassSelector specifies labels that will be used to select a resource class for this claim. If multiple classes match the labels one will be chosen at random.
:param Sequence['MySQLInstanceSpecClassSelectorMatchExpressionsArgs'] match_expressions: matchExpressions is a list of label selector requirements. The requirements are ANDed.
:param Mapping[str, str] match_labels: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed.
"""
if match_expressions is not None:
pulumi.set(__self__, "match_expressions", match_expressions)
if match_labels is not None:
pulumi.set(__self__, "match_labels", match_labels)
@property
@pulumi.getter(name="matchExpressions")
def match_expressions(self) -> Optional[Sequence['outputs.MySQLInstanceSpecClassSelectorMatchExpressions']]:
"""
matchExpressions is a list of label selector requirements. The requirements are ANDed.
"""
return pulumi.get(self, "match_expressions")
@property
@pulumi.getter(name="matchLabels")
def match_labels(self) -> Optional[Mapping[str, str]]:
"""
matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", | |
POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def3]
ret_code = self._lib_handle.G2_addRecordWithInfoWithReturnedRecordID(_dataSourceCode,_jsonData,_loadId,flags,tls_var.buf,sizeof(tls_var.buf),pointer(infoBuf),pointer(infoBufSize),self._resize_func3)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
recordID += tls_var.buf.value
info += tls_var3.buf.value
def replaceRecord(self,dataSourceCode,recordId,jsonData,loadId=None):
# type: (str,str,str,str) -> int
""" Replace the JSON record, loads if doesn't exist
Args:
dataSourceCode: The data source for the observation.
recordID: The ID for the record
jsonData: A JSON document containing the attribute information
for the observation.
loadID: The load ID for the record, can be null and will default to dataSourceCode
"""
_dataSourceCode = self.prepareStringArgument(dataSourceCode)
_loadId = self.prepareStringArgument(loadId)
_recordId = self.prepareStringArgument(recordId)
_jsonData = self.prepareStringArgument(jsonData)
ret_code = self._lib_handle.G2_replaceRecord(_dataSourceCode,_recordId,_jsonData,_loadId)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
def replaceRecordWithInfo(self,dataSourceCode,recordId,jsonData,response,loadId=None, flags=0):
# type: (str,str,str,str) -> int
""" Replace the JSON record, loads if doesn't exist
Args:
dataSourceCode: The data source for the observation.
recordID: The ID for the record
jsonData: A JSON document containing the attribute information
for the observation.
response: Json document with info about the modified resolved entities
loadID: The load ID for the record, can be null and will default to dataSourceCode
flags: reserved for future use
"""
_dataSourceCode = self.prepareStringArgument(dataSourceCode)
_loadId = self.prepareStringArgument(loadId)
_recordId = self.prepareStringArgument(recordId)
_jsonData = self.prepareStringArgument(jsonData)
response[::]=b''
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_replaceRecordWithInfo.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_replaceRecordWithInfo(_dataSourceCode,_recordId,_jsonData,_loadId,flags,pointer(responseBuf),pointer(responseSize),self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
#Add the bytes to the response bytearray from calling function
response += tls_var.buf.value
def deleteRecord(self,dataSourceCode,recordId,loadId=None):
# type: (str,str,str) -> int
""" Delete the record
Args:
dataSourceCode: The data source for the observation.
recordID: The ID for the record
loadID: The load ID for the record, can be null and will default to dataSourceCode
"""
_dataSourceCode = self.prepareStringArgument(dataSourceCode)
_loadId = self.prepareStringArgument(loadId)
_recordId = self.prepareStringArgument(recordId)
ret_code = self._lib_handle.G2_deleteRecord(_dataSourceCode,_recordId,_loadId)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
def deleteRecordWithInfo(self,dataSourceCode,recordId,response,loadId=None, flags=0):
# type: (str,str,str,str,int) -> int
""" Delete the record
Args:
dataSourceCode: The data source for the observation.
recordID: The ID for the record
response: A bytearray for returning the response document; if an error occurred, an error response is stored here
loadID: The load ID for the record, can be null and will default to dataSourceCode
flags: reserved for future use
"""
_dataSourceCode = self.prepareStringArgument(dataSourceCode)
_loadId = self.prepareStringArgument(loadId)
_recordId = self.prepareStringArgument(recordId)
response[::]=b''
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_deleteRecordWithInfo.argtypes = [c_char_p, c_char_p, c_char_p, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_deleteRecordWithInfo(_dataSourceCode,_recordId,_loadId,flags,pointer(responseBuf),pointer(responseSize),self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
#Add the bytes to the response bytearray from calling function
response += tls_var.buf.value
def reevaluateRecord(self,dataSourceCode,recordId,flags):
# type: (str,str,int) -> int
""" Reevaluate the JSON record
Args:
dataSourceCode: The data source for the observation.
recordID: The ID for the record
flags: Bitwise control flags
"""
_dataSourceCode = self.prepareStringArgument(dataSourceCode)
_recordId = self.prepareStringArgument(recordId)
ret_code = self._lib_handle.G2_reevaluateRecord(_dataSourceCode,_recordId,flags)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
def reevaluateRecordWithInfo(self,dataSourceCode,recordId,response,flags=0):
# type: (str,str,str,int) -> int
""" Reevaluate the JSON record and return modified resolved entities
Args:
dataSourceCode: The data source for the observation.
recordID: The ID for the record
response: json document with modified resolved entities
flags: Bitwise control flags
"""
_dataSourceCode = self.prepareStringArgument(dataSourceCode)
_recordId = self.prepareStringArgument(recordId)
response[::]=b''
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_reevaluateRecordWithInfo.argtypes = [c_char_p, c_char_p, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_reevaluateRecordWithInfo(_dataSourceCode,_recordId,flags,pointer(responseBuf),pointer(responseSize),self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
#Add the bytes to the response bytearray from calling function
response += tls_var.buf.value
def reevaluateEntity(self,entityID,flags):
# type: (int,int) -> int
""" Reevaluate the JSON record
Args:
entityID: The entity ID to reevaluate.
flags: Bitwise control flags
"""
ret_code = self._lib_handle.G2_reevaluateEntity(entityID,flags)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
def reevaluateEntityWithInfo(self,entityID,response,flags=0):
# type: (int,int,str) -> int
""" Reevaluate the JSON record and return the modified resolved entities
Args:
entityID: The entity ID to reevaluate.
response: json document with modified resolved entities
flags: Bitwise control flags
"""
response[::]=b''
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_reevaluateEntityWithInfo.argtypes = [c_int, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_reevaluateEntityWithInfo(entityID,flags,pointer(responseBuf),pointer(responseSize),self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
#Add the bytes to the response bytearray from calling function
response += tls_var.buf.value
def searchByAttributes(self,jsonData,response):
# type: (str,bytearray) -> int
""" Find records matching the provided attributes
Args:
jsonData: A JSON document containing the attribute information to search.
response: A bytearray for returning the response document; if an error occurred, an error response is stored here.
"""
response[::]=b''
_jsonData = self.prepareStringArgument(jsonData)
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_searchByAttributes.argtypes = [c_char_p, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_searchByAttributes(_jsonData,
pointer(responseBuf),
pointer(responseSize),
self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
response += tls_var.buf.value
def searchByAttributesV2(self,jsonData,flags,response):
# type: (str,bytearray) -> int
""" Find records matching the provided attributes
Args:
jsonData: A JSON document containing the attribute information to search.
flags: control flags.
response: A bytearray for returning the response document; if an error occurred, an error response is stored here.
"""
response[::]=b''
_jsonData = self.prepareStringArgument(jsonData)
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_searchByAttributes_V2.argtypes = [c_char_p, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_searchByAttributes_V2(_jsonData,flags,
pointer(responseBuf),
pointer(responseSize),
self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
response += tls_var.buf.value
def findPathByEntityID(self,startEntityID,endEntityID,maxDegree,response):
# type: (int) -> str
""" Find a path between two entities in the system.
Args:
startEntityID: The entity ID you want to find the path from
endEntityID: The entity ID you want to find the path to
maxDegree: The maximum path length to search for
response: A bytearray for returning the response document.
"""
response[::]=b''
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_findPathByEntityID.restype = c_int
self._lib_handle.G2_findPathByEntityID.argtypes = [c_longlong, c_longlong, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_findPathByEntityID(startEntityID,endEntityID,maxDegree,
pointer(responseBuf),
pointer(responseSize),
self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
response += tls_var.buf.value
def findPathByEntityIDV2(self,startEntityID,endEntityID,maxDegree,flags,response):
# type: (int) -> str
""" Find a path between two entities in the system.
Args:
startEntityID: The entity ID you want to find the path from
endEntityID: The entity ID you want to find the path to
maxDegree: The maximum path length to search for
flags: control flags.
response: A bytearray for returning the response document.
"""
response[::]=b''
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_findPathByEntityID_V2.restype = c_int
self._lib_handle.G2_findPathByEntityID_V2.argtypes = [c_longlong, c_longlong, c_int, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_findPathByEntityID_V2(startEntityID,endEntityID,maxDegree,flags,
pointer(responseBuf),
pointer(responseSize),
self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
response += tls_var.buf.value
def findNetworkByEntityID(self,entityList,maxDegree,buildOutDegree,maxEntities,response):
# type: (int) -> str
""" Find a network between entities in the system.
Args:
entityList: The entities to search for the network of
maxDegree: The maximum path length to search for between entities
buildOutDegree: The number of degrees to build out the surrounding network
maxEntities: The maximum number of entities to include in the result
response: A bytearray for returning the response document.
"""
response[::]=b''
_entityList = self.prepareStringArgument(entityList)
responseBuf = c_char_p(addressof(tls_var.buf))
responseSize = c_size_t(tls_var.bufSize)
self._lib_handle.G2_findNetworkByEntityID.restype = c_int
self._lib_handle.G2_findNetworkByEntityID.argtypes = [c_char_p, c_int, c_int, c_int, POINTER(c_char_p), POINTER(c_size_t), self._resize_func_def]
ret_code = self._lib_handle.G2_findNetworkByEntityID(_entityList,maxDegree,buildOutDegree,maxEntities,
pointer(responseBuf),
pointer(responseSize),
self._resize_func)
if ret_code == -1:
raise G2ModuleNotInitialized('G2Engine has not been succesfully initialized')
elif ret_code < 0:
self._lib_handle.G2_getLastException(tls_var.buf, sizeof(tls_var.buf))
raise TranslateG2ModuleException(tls_var.buf.value)
response += tls_var.buf.value
def findNetworkByEntityIDV2(self,entityList,maxDegree,buildOutDegree,maxEntities,flags,response):
# type: (int) -> str
""" Find a network between entities in the system.
Args:
entityList: The entities to search | |
<reponame>lokyst/ffxivcraftopt
# This file is part of DEAP.
#
# DEAP 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.
#
# DEAP 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with DEAP. If not, see <http://www.gnu.org/licenses/>.
"""
Regroup typical EC benchmarks functions to import easily and benchmark
examples.
"""
import random
from math import sin, cos, pi, exp, e, sqrt
from operator import mul
from functools import reduce
# Unimodal
def rand(individual):
"""Random test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization or maximization
* - Range
- none
* - Global optima
- none
* - Function
- :math:`f(\mathbf{x}) = \\text{\\texttt{random}}(0,1)`
"""
return random.random(),
def plane(individual):
"""Plane test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- none
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\mathbf{x}) = x_0`
"""
return individual[0],
def sphere(individual):
"""Sphere test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- none
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\mathbf{x}) = \sum_{i=1}^Nx_i^2`
"""
return sum(gene * gene for gene in individual),
def cigar(individual):
"""Cigar test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- none
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\mathbf{x}) = x_0^2 + 10^6\\sum_{i=1}^N\,x_i^2`
"""
return individual[0]**2 + 1e6 * sum(gene * gene for gene in individual),
def rosenbrock(individual):
"""Rosenbrock test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- none
* - Global optima
- :math:`x_i = 1, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\\mathbf{x}) = \\sum_{i=1}^{N-1} (1-x_i)^2 + 100 (x_{i+1} - x_i^2 )^2`
.. plot:: code/benchmarks/rosenbrock.py
:width: 67 %
"""
return sum(100 * (x * x - y)**2 + (1. - x)**2 \
for x, y in zip(individual[:-1], individual[1:])),
def h1(individual):
""" Simple two-dimensional function containing several local maxima.
From: The Merits of a Parallel Genetic Algorithm in Solving Hard
Optimization Problems, <NAME> and <NAME>, J. Biomech. Eng. 125, 141 (2003)
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- maximization
* - Range
- :math:`x_i \in [-100, 100]`
* - Global optima
- :math:`\mathbf{x} = (8.6998, 6.7665)`, :math:`f(\mathbf{x}) = 2`\n
* - Function
- :math:`f(\mathbf{x}) = \\frac{\sin(x_1 - \\frac{x_2}{8})^2 + \
\\sin(x_2 + \\frac{x_1}{8})^2}{\\sqrt{(x_1 - 8.6998)^2 + \
(x_2 - 6.7665)^2} + 1}`
.. plot:: code/benchmarks/h1.py
:width: 67 %
"""
num = (sin(individual[0] - individual[1] / 8))**2 + (sin(individual[1] + individual[0] / 8))**2
denum = ((individual[0] - 8.6998)**2 + (individual[1] - 6.7665)**2)**0.5 + 1
return num / denum,
#
# Multimodal
def ackley(individual):
"""Ackley test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-15, 30]`
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\\mathbf{x}) = 20 - 20\exp\left(-0.2\sqrt{\\frac{1}{N} \
\\sum_{i=1}^N x_i^2} \\right) + e - \\exp\\left(\\frac{1}{N}\sum_{i=1}^N \\cos(2\pi x_i) \\right)`
.. plot:: code/benchmarks/ackley.py
:width: 67 %
"""
N = len(individual)
return 20 - 20 * exp(-0.2*sqrt(1.0/N * sum(x**2 for x in individual))) \
+ e - exp(1.0/N * sum(cos(2*pi*x) for x in individual)),
def bohachevsky(individual):
"""Bohachevsky test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-100, 100]`
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\mathbf{x}) = \sum_{i=1}^{N-1}(x_i^2 + 2x_{i+1}^2 - \
0.3\cos(3\pi x_i) - 0.4\cos(4\pi x_{i+1}) + 0.7)`
.. plot:: code/benchmarks/bohachevsky.py
:width: 67 %
"""
return sum(x**2 + 2*x1**2 - 0.3*cos(3*pi*x) - 0.4*cos(4*pi*x1) + 0.7
for x, x1 in zip(individual[:-1], individual[1:])),
def griewank(individual):
"""Griewank test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-600, 600]`
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\\mathbf{x}) = \\frac{1}{4000}\\sum_{i=1}^N\,x_i^2 - \
\prod_{i=1}^N\\cos\\left(\\frac{x_i}{\sqrt{i}}\\right) + 1`
.. plot:: code/benchmarks/griewank.py
:width: 67 %
"""
return 1.0/4000.0 * sum(x**2 for x in individual) - \
reduce(mul, (cos(x/sqrt(i+1.0)) for i, x in enumerate(individual)), 1) + 1,
def rastrigin(individual):
"""Rastrigin test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-5.12, 5.12]`
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\\mathbf{x}) = 10N \sum_{i=1}^N x_i^2 - 10 \\cos(2\\pi x_i)`
.. plot:: code/benchmarks/rastrigin.py
:width: 67 %
"""
return 10 * len(individual) + sum(gene * gene - 10 * \
cos(2 * pi * gene) for gene in individual),
def rastrigin_scaled(individual):
"""Scaled Rastrigin test objective function.
:math:`f_{\\text{RastScaled}}(\mathbf{x}) = 10N + \sum_{i=1}^N \
\left(10^{\left(\\frac{i-1}{N-1}\\right)} x_i \\right)^2 x_i)^2 - \
10\cos\\left(2\\pi 10^{\left(\\frac{i-1}{N-1}\\right)} x_i \\right)`
"""
N = len(individual)
return 10*N + sum((10**(i/(N-1))*x)**2 -
10*cos(2*pi*10**(i/(N-1))*x) for i, x in enumerate(individual)),
def rastrigin_skew(individual):
"""Skewed Rastrigin test objective function.
:math:`f_{\\text{RastSkew}}(\mathbf{x}) = 10N \sum_{i=1}^N \left(y_i^2 - 10 \\cos(2\\pi x_i)\\right)`
:math:`\\text{with } y_i = \
\\begin{cases} \
10\\cdot x_i & \\text{ if } x_i > 0,\\\ \
x_i & \\text{ otherwise } \
\\end{cases}`
"""
N = len(individual)
return 10*N + sum((10*x if x > 0 else x)**2
- 10*cos(2*pi*(10*x if x > 0 else x)) for x in individual),
def schaffer(individual):
"""Schaffer test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-100, 100]`
* - Global optima
- :math:`x_i = 0, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\mathbf{x}) = \sum_{i=1}^{N-1} (x_i^2+x_{i+1}^2)^{0.25} \cdot \
\\left[ \sin^2(50\cdot(x_i^2+x_{i+1}^2)^{0.10}) + 1.0 \
\\right]`
.. plot:: code/benchmarks/schaffer.py
:width: 67 %
"""
return sum((x**2+x1**2)**0.25 * ((sin(50*(x**2+x1**2)**0.1))**2+1.0)
for x, x1 in zip(individual[:-1], individual[1:])),
def schwefel(individual):
"""Schwefel test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-500, 500]`
* - Global optima
- :math:`x_i = 420.96874636, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\mathbf{x}) = 418.9828872724339\cdot N - \
\sum_{i=1}^N\,x_i\sin\\left(\sqrt{|x_i|}\\right)`
.. plot:: code/benchmarks/schwefel.py
:width: 67 %
"""
N = len(individual)
return 418.9828872724339*N-sum(x*sin(sqrt(abs(x))) for x in individual),
def himmelblau(individual):
"""The Himmelblau's function is multimodal with 4 defined minimums in
:math:`[-6, 6]^2`.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-6, 6]`
* - Global optima
- :math:`\mathbf{x}_1 = (3.0, 2.0)`, :math:`f(\mathbf{x}_1) = 0`\n
:math:`\mathbf{x}_2 = (-2.805118, 3.131312)`, :math:`f(\mathbf{x}_2) = 0`\n
:math:`\mathbf{x}_3 = (-3.779310, -3.283186)`, :math:`f(\mathbf{x}_3) = 0`\n
:math:`\mathbf{x}_4 = (3.584428, -1.848126)`, :math:`f(\mathbf{x}_4) = 0`\n
* - Function
- :math:`f(x_1, x_2) = (x_1^2 + x_2 - 11)^2 + (x_1 + x_2^2 -7)^2`
.. plot:: code/benchmarks/himmelblau.py
:width: 67 %
"""
return (individual[0] * individual[0] + individual[1] - 11)**2 + \
(individual[0] + individual[1] * individual[1] - 7)**2,
def shekel(individual, a, | |
log("Evacuating to " + str(self.target[1]) + " " + str(self.target[0]))
next = self.path[0]
# If there is no possible path, consider exit blocked
if next == "blocked":
self.path = self.considerTargetBlocked()
return
# If currently waiting for other agents to move, attempt to recompute path
if self.waiting:
if (self.model.schedule.steps + self.offset) % (5 * self.freq) != 0:
log("Previously path was blocked. Waiting.")
else:
log("Path was blocked for 5 moves since the last time it was computed. "
+ "Attempting to recompute the path.")
self.path = computePath(self.model.grid, self.pos, self.target,
self.knownFires, self.knownHeat, self.knownObstacles)
next = self.path[0]
if next == "blocked":
self.path = self.considerTargetBlocked()
return
# Check whether the next cell is blocked
blocked = False
for obj in self.model.grid.get_cell_list_contents(next):
if obj.__class__.__name__ in ["Adult", "Child", "Obstacle", "Fire", "Heat", "Smoke"]:
log("Path blocked by " + obj.__class__.__name__)
# If next cell blocked by another agent, wait, and move randomly to avoid blockages
if obj.__class__.__name__ in ["Adult", "Child"]:
log("Waiting (" + str(self.waitingTime) + ")")
self.waiting = True
self.waitingTime += self.freq
# When waiting limit reached, consider the exit blocked
if self.waitingTime > self.patience:
self.path = self.considerTargetBlocked()
# Every 10 steps try to get the blocking agent to move out of the way
if self.waitingTime % (10 * self.freq) == 0 and obj.moved == False:
adjacentToNeighbor = self.model.grid.getObject(obj.pos, "Cell").neighbors
for cell in adjacentToNeighbor:
if self.model.grid.cellAvailable(adjacentToNeighbor[cell], ["Adult", "Child", "Exit", "Fire", "Heat", "Obstacle"]):
log("Asking agent " + obj.unique_id + " to move out of the way, to cell " + str(adjacentToNeighbor[cell]) + ".")
if obj.path != None:
obj.path = [obj.pos] + obj.path
self.model.grid.move_agent(obj, adjacentToNeighbor[cell])
obj.moved = True
break
#Move randomly from time to time
blocked = True
r = random.random()
if r < 0.2 and self.waitingTime > 20:
neighbors = self.model.grid.getObject(self.pos, "Cell").neighbors
for neighbor in neighbors:
free = True
for obj in self.model.grid.get_cell_list_contents(neighbors[neighbor]):
if obj.__class__.__name__ in ["Adult", "Child", "Obstacle", "Fire", "Heat", "Exit"]:
free = False
if free and self.target != None:
log("Moving to a free space to avoid potential blockage.")
log("MOVING " + str(neighbor) + ", TO " + str(neighbors[neighbor]))
self.model.grid.move_agent(self, neighbors[neighbor])
self.path = computePath(self.model.grid, self.pos, self.target,
self.knownFires, self.knownHeat, self.knownObstacles)
break
break
# If next cell blocked by a non-agent, attempt to update path
else:
self.path = computePath(self.model.grid, self.pos, self.target,
self.knownFires, self.knownHeat, self.knownObstacles)
next = self.path[0]
# If no path possible anymore, end step
if next == "blocked":
log("No path possible.")
blocked = True
# If the new path is blocked by an agent, end step
elif next != "reached" and next != None:
for obj in self.model.grid.get_cell_list_contents(next):
if obj.__class__.__name__ in ["Adult", "Child"]:
log("Path blocked by " + obj.__class__.__name__ + ".")
blocked = True
break
# If possible, move to the next cell
if not blocked:
log("MOVING TO " + str(next))
del(self.path[0])
self.model.grid.move_agent(self, next)
# Decrease waiting time counter:
self.waiting = False
if self.waitingTime > 0:
self.waitingTime -= 2* self.freq
elif self.state == "EXPLORING":
if self.model.grid.getObject(self.pos, "Cell").type == "room":
log("Agent currently in a room. Switching state to 'EXITING ROOM'.")
self.previousState = self.state
self.state = "EXITING_ROOM"
self.explorationDirection = None
return
# Check what directions are available from a given position
possibleDirections = self.model.grid.getObject(self.pos, "Cell").neighbors
log("Exploring the environment")
# If there are some visible signs, begin to follow the indicated path
if len(self.knownSigns) > 0:
for sign in self.knownSigns:
if self.knownSigns[sign]:
log("A new viable sign was located. switching state to 'FOLLOWING'")
self.previousState = self.state
self.state = "FOLLOWING"
self.path = []
self.target = None
return
# If no direction set, or cannot move further in the current direction, pick a new direction at random
if self.explorationDirection == None or self.explorationDirection not in possibleDirections:
self.explorationDirection = self.pickDirection(possibleDirections, self.explorationDirection)
if self.explorationDirection != None:
next = possibleDirections[self.explorationDirection]
blocked = False
for obj in self.model.grid.get_cell_list_contents(next):
if obj.__class__.__name__ in ["Obstacle", "Fire", "Heat"]:
blocked = True
self.explorationDirection = self.pickDirection(possibleDirections, self.explorationDirection)
log("No move possible in the currently followed direction.")
break
elif obj.__class__.__name__ == "Smoke":
inSmoke = False
for el in self.model.grid.get_cell_list_contents(self.pos):
if el.__class__.__name__ == "Smoke":
inSmoke = True
break
if not inSmoke:
self.explorationDirection = self.pickDirection(possibleDirections, self.explorationDirection)
elif obj.__class__.__name__ in ["Adult", "Child"]:
blocked = True
self.explorationDirection = self.pickDirection(possibleDirections, self.explorationDirection)
# Try to get the blocking agent to move out of the way with some probability
r = random.random()
if r < 0.2 and obj.moved == False:
adjacentToNeighbor = self.model.grid.getObject(obj.pos, "Cell").neighbors
for cell in adjacentToNeighbor:
if self.model.grid.cellAvailable(adjacentToNeighbor[cell],
["Adult", "Child", "Exit", "Fire", "Heat",
"Obstacle"]):
log("Asking agent " + obj.unique_id + " to move out of the way, to cell " + str(
adjacentToNeighbor[cell]) + ".")
if obj.path != None:
obj.path = [obj.pos] + obj.path
self.model.grid.move_agent(obj, adjacentToNeighbor[cell])
obj.moved = True
break
else:
blocked = True
self.explorationDirection = self.pickDirection(possibleDirections,
self.explorationDirection)
log("No move possible at the moment. Waiting.")
break
if not blocked:
log("MOVING TO " + str(next))
self.model.grid.move_agent(self, next)
else:
log("No move possible at the moment. Waiting.")
elif self.state == "EXITING_ROOM":
if self.stuck:
self.path = self.reachCorridor()
next = self.path[0]
if next == "blocked":
log("Currently not able to exit the room.")
elif next != "reached" and next != None:
self.stuck = False
else:
if self.model.grid.getObject(self.pos, "Cell").type != "room":
log("Exited room. Switching state to 'EXPLORING'.")
self.previousState = self.state
self.state = "EXPLORING"
return
self.path = self.reachCorridor()
next = self.path[0]
if next == "blocked":
log("There is no accessible exit from the room.")
self.stuck = True
elif next != "reached" and next != None:
blockedByAgent = False
for obj in self.model.grid.get_cell_list_contents(next):
if obj.__class__.__name__ in ["Adult", "Child"]:
blockedByAgent = True
log("Path blocked by an agent.")
# Try to get the blocking agent to move out of the way with some probability
r = random.random()
if r < 0.2 and obj.moved == False:
adjacentToNeighbor = self.model.grid.getObject(obj.pos, "Cell").neighbors
for cell in adjacentToNeighbor:
if self.model.grid.cellAvailable(adjacentToNeighbor[cell],
["Adult", "Child", "Exit", "Fire", "Heat",
"Obstacle"]):
log("Asking agent " + obj.unique_id + " to move out of the way, to cell "
+ str(adjacentToNeighbor[cell]) + ".")
if obj.path != None:
obj.path = [obj.pos] + obj.path
self.model.grid.move_agent(obj, adjacentToNeighbor[cell])
obj.moved = True
break
if not blockedByAgent:
log("MOVING TO " + str(next))
self.model.grid.move_agent(self, next)
# Move randomly from time to time
blocked = True
r = random.random()
if r < 0.2 and self.waitingTime > 20:
neighbors = self.model.grid.getObject(self.pos, "Cell").neighbors
for neighbor in neighbors:
free = True
for obj in self.model.grid.get_cell_list_contents(neighbors[neighbor]):
if obj.__class__.__name__ in ["Adult", "Child", "Obstacle", "Fire", "Heat", "Exit"]:
free = False
if free and self.target != None:
log("Moving to a free space to avoid potential blockage.")
log("MOVING " + str(neighbor) + ", TO " + str(neighbors[neighbor]))
self.model.grid.move_agent(self, neighbors[neighbor])
self.path = self.reachCorridor()
break
elif self.state == "FOLLOWING":
# Create a list of signs visible at a given moment
signs = []
# Store the currently followed sign
oldSign = self.nearestSign
for sign in self.knownSigns:
if self.knownSigns[sign]:
signs.append((eucDist(self.pos, (sign[0][0], sign[0][1])), sign))
# If all known signs are known as blocked, switch state to 'EXPLORING'
if signs == []:
log("No viable signs to follow at the moment. Switching state to 'EXPLORING'")
self.previousState = self.state
self.state = "EXPLORING"
return
# Pick the closest sign
self.nearestSign = min(signs)[1]
log("Following the emergency exit sign: " + str(self.nearestSign))
# If no previous path or switching signs, pick a target and path based on the sign
if self.path == [] or self.path == None or self.nearestSign != oldSign:
self.target = self.routeFromSign(self.nearestSign)
self.routeHistory.append(self.nearestSign)
self.path = computePath(self.model.grid, self.pos, self.target,
self.knownFires, self.knownHeat, self.knownObstacles)
next = self.path[0]
log("Route history: " + str(self.routeHistory))
log("Target: " + str(self.target))
# If there is no possible path, consider exit blocked
if next in ["blocked", "reached"]:
self.path = self.considerRouteBlocked()
return
# If currently waiting for other agents to move, attempt to recompute path
if self.waiting:
if (self.model.schedule.steps + self.offset) % (5 * self.freq) != 0:
log("Previously path was blocked. Waiting.")
else:
log("Path was blocked for 5 moves since the last time it was computed. "
+ "Attempting to recompute the path.")
self.path = computePath(self.model.grid, self.pos, self.target,
self.knownFires, self.knownHeat, self.knownObstacles)
next = self.path[0]
if next == "blocked":
self.path = self.considerTargetBlocked()
return
# Check whether the next cell is blocked
blocked | |
<gh_stars>1-10
#!/usr/bin/env python3
import argparse
import math
import bisect
import re
import logging
import time
import os.path as op
import multiprocessing
from decimal import localcontext
from itertools import chain, repeat
parser = argparse.ArgumentParser(description='Allomedia data selection tool')
parser.add_argument('--task', required=True, type=str,
help='Task file, the sentences we want to mimic')
parser.add_argument('--unadapted', required=True, type=str,
help='Unadapted sentences, the pool we want to pick from')
parser.add_argument('--batch', action='store_true', dest='batch',
help='Set this flag to enable batch mode')
parser.add_argument('--no-batch', action='store_false', dest='batch',
help='Set this flag to disable batch mode')
parser.set_defaults(batch=False)
parser.add_argument('--mincount', type=int, default=3,
help='Minimum wordcount in each file')
parser.add_argument('--keep', action='store_true', dest='keep',
help='Set this flag to keep boring words')
parser.add_argument('--no-keep', action='store_false', dest='keep',
help='Set this flag to NOT keep boring words')
parser.set_defaults(keep=False)
parser.add_argument('--lower', action='store_true', dest='lower',
help='Set this flag to lowercase all text')
parser.add_argument('--no-lower', action='store_false', dest='lower',
help='Set this flag to NOT lowercase all text')
parser.set_defaults(lower=True)
parser.add_argument('--maxlen', type=int, default=250,
help='Maximum sentence length')
parser.add_argument('--smoothing', type=float, default=0.01,
help='Smoothing factor for lenght penalty computation')
parser.add_argument('--iterate', action='store_true', dest='iterate',
help=("Set this flag to iterate until we can't reduce " +
"selected data by no more than 10%"))
parser.add_argument('--no-iterate', action='store_false', dest='iterate',
help='Set this flag to iterate on data only once')
parser.add_argument('--splitsize', type=int, default=2500000,
help='Size of parts when splitting big corpora')
parser.set_defaults(iterate=False)
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance()
@singleton
class Logger():
def __init__(self):
self.logger = logging.getLogger(__name__)
self.logger.setLevel('DEBUG')
def add_fh(self, name):
logfile = logging.FileHandler(name, encoding='utf-8')
logfile.setLevel('DEBUG')
formatter = logging.Formatter('%(asctime)s | %(message)s')
logfile.setFormatter(formatter)
self.logger.addHandler(logfile)
def get_logger(logname):
"""Returns a file logger with DEBUG level.
args: argparse object containing the cmd arguments
returns: logger object
"""
logger = logging.getLogger(__name__)
logger.setLevel('DEBUG')
logfile = logging.FileHandler(logname, encoding='utf-8')
logfile.setLevel('DEBUG')
formatter = logging.Formatter('%(asctime)s | %(message)s')
logfile.setFormatter(formatter)
logger.addHandler(logfile)
return logger
def compute_counts(corpus):
"""Compute the word counts and probs for a given corpus
corpus: list of sentences
returns: dict of words, containing counts & probs
"""
words = {}
size = 0
# Let's count words first
for line in corpus:
for token in line.split():
if token in words:
words[token]['count'] += 1
else:
words[token] = {}
words[token]['count'] = 1
size += 1
# Then we compute all the probs once we know the final size
for k in words.keys():
words[k]['prob'] = words[k]['count'] / size
return words
def float_to_str(num):
"""Gets rid of exponent notation in floats
num: the float to return as a string
"""
with localcontext() as ctx:
ctx.prec = 20
d = ctx.create_decimal(repr(num))
return format(d, 'f')
def compute_ratios(task_vocab, unadapted_vocab):
"""Computes the stats between the two vocabularies
task_vocab: dict of task words with count and prob
unadapted_vocab: dict of unadapted words with count and prob
returns:
ratios: initialized dict (word-indexed) with computed stats
sizes: dict of task & unadapted data sizes
"""
ratios = {}
sizes = {}
sizes['task'] = 0
sizes['unadapted'] = 0
# We iterate on the unadapted vocab first
for word in unadapted_vocab.keys():
ratios[word] = {}
# Word is in task vocab, let's compute the delta
# and add the probs and counts
if word in task_vocab:
ratios[word]['delta'] = (task_vocab[word]['prob'] /
unadapted_vocab[word]['prob'])
ratios[word]['t_prob'] = task_vocab[word]['prob']
ratios[word]['t_count'] = task_vocab[word]['count']
sizes['task'] += task_vocab[word]['count']
del task_vocab[word]
# Minimal delta, prob & count are 0
else:
ratios[word]['delta'] = 0.5 / unadapted_vocab[word]['count']
ratios[word]['t_prob'] = 0
ratios[word]['t_count'] = 0
# Add the stats for the unadapted part
ratios[word]['u_prob'] = unadapted_vocab[word]['prob']
ratios[word]['u_count'] = unadapted_vocab[word]['count']
sizes['unadapted'] += unadapted_vocab[word]['count']
# Let's add the "orphan" task words with delta = count * 2
for word in task_vocab.keys():
ratios[word] = {}
ratios[word]['delta'] = task_vocab[word]['count'] * 2
ratios[word]['t_prob'] = task_vocab[word]['prob']
ratios[word]['t_count'] = task_vocab[word]['count']
ratios[word]['u_prob'] = 0
ratios[word]['u_count'] = 0
sizes['task'] += task_vocab[word]['count']
return ratios, sizes
def squish_ratios(ratios, mincount, keep):
"""Reduces the ratios to interesting words with some clustering.
ratios: the dict of stats
mincount: min count of given word in each vocab to be taken into account
keep: do we keep the boring words as is or do we cluster them?
returns: updated ratios dict & words replacement dict
"""
replace = {}
# Group every 0 after the decimal dot (used in boring clustering)
re_band = re.compile(r'.*\.(?P<band>0*).*')
# Impossible words are task words not in unadapted
ratios['@@IMPOSSIBLE'] = {}
# Useless words are unadapted words not in task
ratios['@@USELESS'] = {}
# Dubious words are under the mincount
ratios['@@DUBIOUS'] = {}
# t_count is task words, u_count is unadapted words
ratios['@@IMPOSSIBLE']['t_count'] = 0
ratios['@@USELESS']['t_count'] = 0
ratios['@@DUBIOUS']['t_count'] = 0
ratios['@@IMPOSSIBLE']['u_count'] = 0
ratios['@@USELESS']['u_count'] = 0
ratios['@@DUBIOUS']['u_count'] = 0
for word in list(ratios.keys()):
# Don't mess with the special words while we create them
if word.startswith('@@'):
continue
# Squished words are deleted, but they are kept in the replace dict
if ratios[word]['t_count'] == 0:
replace[word] = '@@USELESS'
ratios['@@USELESS']['u_count'] += ratios[word]['u_count']
del ratios[word]
elif ratios[word]['u_count'] == 0:
replace[word] = '@@IMPOSSIBLE'
ratios['@@IMPOSSIBLE']['t_count'] += ratios[word]['t_count']
del ratios[word]
elif ratios[word]['t_count'] < mincount \
and ratios[word]['u_count'] < mincount:
replace[word] = '@@DUBIOUS'
ratios['@@DUBIOUS']['t_count'] += ratios[word]['t_count']
ratios['@@DUBIOUS']['u_count'] += ratios[word]['u_count']
del ratios[word]
# Words between a certain delta are either bucketed
# into boring words or kept as is
elif ratios[word]['delta'] < math.exp(1) \
and ratios[word]['delta'] > math.exp(-1) \
and not keep:
# Get the band name (number of 0's)
band = re_band.sub(r'\g<band>',
float_to_str(ratios[word]['u_prob']))
bucket = '@@BORING__' + band
replace[word] = bucket
# Create the bucket if it doesn't exists
if bucket not in ratios:
ratios[bucket] = {}
ratios[bucket]['t_count'] = 0
ratios[bucket]['u_count'] = 0
ratios[bucket]['delta'] = bucket
ratios[bucket]['t_count'] += ratios[word]['t_count']
ratios[bucket]['u_count'] += ratios[word]['u_count']
del ratios[word]
# Log-negative words (delta < 1)
# They are bucketed into the form @@-1, @@-2, etc.
# (Truncation on the integer part)
elif ratios[word]['delta'] < 1:
trunc = int(math.log(ratios[word]['delta']))
bucket = '@@' + str(trunc)
replace[word] = bucket
if bucket not in ratios:
ratios[bucket] = {}
ratios[bucket]['t_count'] = 0
ratios[bucket]['u_count'] = 0
ratios[bucket]['delta'] = bucket
ratios[bucket]['t_count'] += ratios[word]['t_count']
ratios[bucket]['u_count'] += ratios[word]['u_count']
del ratios[word]
# Else we keep it as is
else:
replace[word] = word
return ratios, replace
def init_model(ratios, sizes):
"""Initialize the hconstant parameter for each word
and populate the model dict
ratios: the ratios dict, nothing new
sizes: the sizes dict
returns: the updated ratios dict & the initialized model
"""
model = {}
for word in ratios.keys():
ratios[word]['hconstant'] = ratios[word]['t_count'] / sizes['task']
if word not in model:
model[word] = {}
model[word]['prob'] = 0
model[word]['count'] = 0
return ratios, model
def squish_corpus(corpus, replace):
"""Squishes a corpus of data using a replacement dict
corpus: text data to squish
replace: the replacement dict
returns: the squished corpus (list of strings)
"""
squished = []
for line in corpus:
squished.append(' '.join([replace[token] for token in line.split()]))
return squished
def init_penalty(maxlen, smoothing):
"""Initializes the penalty used in cross-entropy computation
maxlen: maximum allowed length of a sentence
smoothing: smoothing factor to avoid dividing by 0 (default 0.01)
returns: the penalty list
"""
penalty = []
for i in range(maxlen):
penalty.append(math.log((i + 2 * smoothing) / smoothing))
return penalty
def count_tokens(tokens):
"""Count words into token lists
tokens: list of tokens (typically a sentence) to count
returns: dict of words with individual counts
"""
count = {}
for token in tokens:
if token in count:
count[token] += 1
else:
count[token] = 1
return count
def index_unadapted(squish, ratios, smoothing, penalty, logger):
"""Index the squished unadapted sentences in the ratios dict
squish: the squished unadapted sentences list
ratios: the ratios dict
smoothing: the smoothing factor
penalty: the initialized penalty list
logger: logging facility
returns:
pool: the pool of available sentences
ratios: the updated ratios dict
"""
pool = {}
for lineid, line in enumerate(squish):
tokens = line.split()
# Ignore longer sentences
if len(tokens) > len(penalty):
continue
# Put the sentence and its length in the pool
pool[lineid] = {}
pool[lineid]['string'] = line
pool[lineid]['count'] = len(tokens)
sge = 0
count = count_tokens(tokens)
# Compute the initial sentence gain estimate (SGE)
for token in count.keys():
sge += (ratios[token]['hconstant'] * math.log(smoothing /
count[token]))
# Score = penalty (positive) + gain (negative)
# We aim at sentences whose score < 0
score = penalty[len(tokens) - 1] + sge
if 'line_list' not in ratios[token]:
ratios[token]['line_list'] = []
# Append sentence score, SGE and pool lineid
# to the word's list of sentences
ratios[token]['line_list'].append((score, sge, lineid))
pool[lineid]['SGE'] = sge
# Sort the lists of sentences by score
for word in | |
# coding=UTF-8
import tensorflow as tf
import numpy as np
import time, os, io
import re
#----------- for network -------------
#%%
def activate(layer_name, x, act, trainable=True, print_shape=True):
with tf.variable_scope(layer_name):
x = act(x)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def dropout(layer_name, x, keep=1.0, trainable=True, training=True, print_shape=True):
if not training:
keep = 1.0
with tf.variable_scope(layer_name):
x = tf.nn.dropout(x, keep)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%% tflite not support
def batch_norm(layer_name, x, trainable=True, training=True, print_shape=True):
with tf.variable_scope(layer_name):
x = tf.layers.batch_normalization(x, training=training, trainable=trainable)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def concat(layer_name, x, axis=3, trainable=True, print_shape=True):
with tf.variable_scope(layer_name):
x = tf.concat(x, axis=axis)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def dense(layer_name, x, units,
act=tf.identity, trainable=True, print_shape=True):
x_shape = x.get_shape()
in_size = x.get_shape()[-1]
if len(x_shape) == 4:
in_size = x.get_shape()[1]*x.get_shape()[2]*in_size
if len(x_shape) == 3:
in_size = x.get_shape()[1]*in_size
with tf.variable_scope(layer_name):
x = tf.reshape(x, [-1, int(in_size)])
x = tf.layers.dense(x, units, activation=act, trainable=trainable)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def separable_conv(layer_name, x, out_channels,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
print_shape=True):
use_bias = False
if b_init is not None:
use_bias = True
with tf.variable_scope(layer_name):
x = tf.layers.separable_conv2d(x, out_channels, kernel, stride,
padding=padding, trainable=trainable, use_bias=use_bias, bias_initializer=b_init,
activation=act, name='spconv')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def conv(layer_name, x, out_channels,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
print_shape=True):
in_channels = x.get_shape()[-1]
with tf.variable_scope(layer_name):
w = tf.get_variable(name='weights',
trainable=trainable,
shape=[kernel[0], kernel[1], in_channels, out_channels],
initializer=W_init)
x = tf.nn.conv2d(x, w, [1,stride[0],stride[1], 1], padding=padding, name='conv')
if b_init is not None:
b = tf.get_variable(name='biases',
trainable=trainable,
shape=[out_channels],
initializer=b_init)
x = tf.nn.bias_add(x, b, name='bias_add')
x = act(x, name='act')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
def conv_bn(layer_name, x, out_channels,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
training=False,
print_shape=True):
in_channels = x.get_shape()[-1]
with tf.variable_scope(layer_name):
w = tf.get_variable(name='weights',
trainable=trainable,
shape=[kernel[0], kernel[1], in_channels, out_channels],
initializer=W_init)
x = tf.nn.conv2d(x, w, [1,stride[0],stride[1], 1], padding=padding, name='conv')
if b_init is not None:
b = tf.get_variable(name='biases',
trainable=trainable,
shape=[out_channels],
initializer=b_init)
x = tf.nn.bias_add(x, b, name='bias_add')
x = batch_norm('bn1', x, trainable=trainable,
training=training, print_shape=training)
x = act(x, name='act')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def c_relu(layer_name, x, out_channels,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.nn.relu,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
use_bn = True,
training=False,
print_shape=True):
with tf.variable_scope(layer_name):
x = conv('conv1', x, out_channels, kernel, stride,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
if use_bn:
x = batch_norm('bn1', x, trainable=trainable,
training=training, print_shape=training)
x = tf.concat([x, -x], axis=3, name='concat')
x = act(x, name='act')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def pool(layer_name, x, kernel=[2,2], stride=[2,2], padding='SAME', is_max_pool=True, print_shape=True):
with tf.variable_scope(layer_name):
if is_max_pool:
x = tf.nn.max_pool(x, [1,kernel[0],kernel[1],1], strides=[1,stride[0],stride[1],1], padding=padding, name='pool')
else:
x = tf.nn.avg_pool(x, [1,kernel[0],kernel[1],1], strides=[1,stride[0],stride[1],1], padding=padding, name='pool')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%% down sample
def inception(layer_name, x, out_channels=[64, [48, 128], [24, 48, 48], 128, 256],
stride=[2, 2],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
training=False,
print_shape=True):
with tf.variable_scope(layer_name):
with tf.variable_scope('1x1'):
b1x1 = conv('b1x1', x, out_channels[0], [1, 1], stride, act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('5x5'):
b5x5 = conv('b5x5_1', x, out_channels[1][0], [1, 1], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
b5x5 = conv('b5x5_2', b5x5, out_channels[1][1], [5, 5], stride, act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('3x3'):
b3x3 = conv('b3x3_1', x, out_channels[2][0], [1, 1], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
b3x3 = conv('b3x3_2', b3x3, out_channels[2][1], [3, 3], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
b3x3 = conv('b3x3_3', b3x3, out_channels[2][1], [3, 3], stride, act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('pool'):
b_pool = pool('pool_1', x, [3, 3], stride, padding='SAME', is_max_pool=True, print_shape=training)
b_pool = conv('pool_2', b_pool, out_channels[3], [1, 1], [1, 1],
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('concat'):
x = tf.concat([b1x1, b5x5, b3x3, b_pool], axis=3, name='concat')
with tf.variable_scope('conv'):
x = conv('conv', x, out_channels[4], [1, 1], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%% no down sample
def inception_nopool(layer_name, x, out_channels=[64, [48, 128], [24, 48, 48], 256],
stride=[1, 1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
training=False,
print_shape=True):
with tf.variable_scope(layer_name):
with tf.variable_scope('1x1'):
b1x1 = conv('b1x1', x, out_channels[0], [1, 1], stride, act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('5x5'):
b5x5 = conv('b5x5_1', x, out_channels[1][0], [1, 1], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
b5x5 = conv('b5x5_2', b5x5, out_channels[1][1], [5, 5], stride, act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('3x3'):
b3x3 = conv('b3x3_1', x, out_channels[2][0], [1, 1], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
b3x3 = conv('b3x3_2', b3x3, out_channels[2][1], [3, 3], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
b3x3 = conv('b3x3_3', b3x3, out_channels[2][1], [3, 3], stride, act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
with tf.variable_scope('concat'):
x = tf.concat([b1x1, b5x5, b3x3], axis=3, name='concat')
with tf.variable_scope('conv'):
x = conv('conv', x, out_channels[3], [1, 1], [1, 1], act=act,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
def up_sampling(layer_name, x, size, print_shape=True):
with tf.variable_scope(layer_name):
x = tf.image.resize_bilinear(x, size=size)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def gauss_blur(layer_name, x, kernel=None, print_shape=True):
with tf.variable_scope(layer_name):
# kernel = np.array([[1.0/16, 1.0/8, 1.0/16], [1.0/8, 1.0/4, 1.0/8], [1.0/16, 1.0/8, 1.0/16]])
if kernel is None:
kernel = np.array([[0.003765,0.015019,0.023792,0.015019,0.003765],
[0.015019,0.059912,0.094907,0.059912,0.015019],
[0.023792,0.094907,0.150342,0.094907,0.023792],
[0.015019,0.059912,0.094907,0.059912,0.015019],
[0.003765,0.015019,0.023792,0.015019,0.003765]], dtype=np.float32)#5x5
w = tf.constant(kernel.reshape((kernel.shape[0],kernel.shape[1], 1, 1)), dtype=tf.float32)
rgb = tf.unstack(x, axis=3)
out = []
for i in range(len(rgb)):
tmp = rgb[i]
tmp = tf.reshape(tmp, [tf.shape(tmp)[0], tf.shape(tmp)[1], tf.shape(tmp)[2], 1])
tmp = tf.nn.conv2d(tmp, w, [1, 1, 1, 1], padding="SAME", name='conv'+str(i))
tmp = tf.reshape(tmp, [tf.shape(tmp)[0], tf.shape(tmp)[1], tf.shape(tmp)[2]])
out.append(tmp)
x = tf.stack(out, axis=3)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def toYCbCr(layer_name, x, print_shape=True):
with tf.variable_scope(layer_name):
x = tf.unstack(x, axis=3)
R = x[0]
G = x[1]
B = x[2]
Y = 0.257*R+0.564*G+0.098*B+16
Cb = -0.148*R-0.291*G+0.439*B+128
Cr = 0.439*R-0.368*G-0.071*B+128
x = tf.stack([Y, Cb, Cr], axis=3)
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def deconv(layer_name, x, out_shape,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
print_shape=True):
in_channels = x.get_shape()[-1]
with tf.variable_scope(layer_name):
w = tf.get_variable(name='weights',
trainable=trainable,
shape=[kernel[0], kernel[1], out_shape[3], in_channels],
initializer=W_init)
x = tf.nn.conv2d_transpose(x, w, out_shape, [1,stride[0],stride[1], 1], padding=padding, name='deconv')
if b_init is not None:
b = tf.get_variable(name='biases',
trainable=trainable,
shape=[out_shape[3]],
initializer=b_init)
x = tf.nn.bias_add(x, b, name='bias_add')
x = act(x, name='act')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
def deconv_hed(layer_name, x, out_shape,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
print_shape=True):
in_channels = x.get_shape()[-1]
with tf.variable_scope(layer_name):
w_np = np.zeros([kernel[0], kernel[1], out_shape[3], in_channels], dtype=np.float32)
upsample_kernel = upsample_filt(kernel[0])
for i in range(out_shape[3]):
w_np[:, :, i, i] = upsample_kernel
w = tf.constant(w_np)
x = tf.nn.conv2d_transpose(x, w, out_shape, [1,stride[0],stride[1], 1], padding=padding, name='deconv')
if b_init is not None:
b = tf.get_variable(name='biases',
trainable=trainable,
shape=[out_shape[3]],
initializer=b_init)
x = tf.nn.bias_add(x, b, name='bias_add')
x = act(x, name='act')
if print_shape:
x = tf.Print(x, [tf.shape(x)], message=x.name, summarize=4, first_n=1)
return x
#%%
def GCN(layer_name, x, out_channels,
kernel=[3,3],
stride=[1,1],
padding = 'SAME',
act = tf.identity,
W_init = tf.truncated_normal_initializer(stddev=0.02),
b_init = None,
trainable=True,
print_shape=True):
with tf.variable_scope(layer_name):
left = conv('convl1', x, out_channels, [kernel[0], 1], stride,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
left = conv('convl2', left, out_channels, [1, kernel[1]], stride,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
right = conv('convr1', x, out_channels, [1, kernel[1]], stride,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
right = conv('convr2', right, out_channels, [kernel[0], 1], stride,
padding=padding, W_init=W_init, b_init=b_init,
trainable=trainable, print_shape=print_shape)
x = left+right
if print_shape:
| |
"""
send a gRPC command that has streaming results
capture the results in the db as StoredResponse objects
"""
import copy
import uuid
from random import random
import math
import numpy as np
from django.conf import settings
from django.http import JsonResponse
from tworaven_apps.utils.static_keys import KEY_SUCCESS, KEY_DATA
from tworaven_apps.utils.json_helper import json_loads
from tworaven_apps.utils.proto_util import message_to_json
from tworaven_apps.utils.basic_response import (ok_resp, err_resp)
from tworaven_apps.utils.view_helper import get_json_error
from tworaven_apps.ta2_interfaces.ta2_connection import TA2Connection
from tworaven_apps.ta2_interfaces.models import \
(StoredRequest, StoredResponse)
from tworaven_apps.ta2_interfaces.stored_data_util import StoredRequestUtil
from tworaven_apps.ta2_interfaces.websocket_message import WebsocketMessage
from tworavensproject.celery import celery_app
from tworaven_apps.utils.random_info import get_timestamp_string
from tworaven_apps.utils.file_util import create_directory
import grpc
import core_pb2
from google.protobuf.json_format import \
(Parse, ParseError)
import shutil
from os import path
import os
import json
from d3m.container.dataset import Dataset
from sklearn.model_selection import train_test_split
import pandas as pd
from pandas.api.types import is_numeric_dtype
#
# Import Tasks to SearchSolutions/GetSearchSolutionsResults,
# FitSolution/GetFitSolutionResults,
# ScoreSolution/GetScoreSolutionResults
#
from tworaven_apps.ta2_interfaces.ta2_search_solutions_helper import \
SearchSolutionsHelper
from tworaven_apps.ta2_interfaces.ta2_fit_solution_helper import FitSolutionHelper
from tworaven_apps.ta2_interfaces.ta2_score_solution_helper import ScoreSolutionHelper
from tworaven_apps.user_workspaces.models import UserWorkspace
from tworaven_solver import approx_seconds, get_date
import csv
from dateutil import parser
from collections import deque
@celery_app.task(ignore_result=True)
def stream_and_store_results(raven_json_str, stored_request_id,
grpc_req_obj_name, grpc_call_name, **kwargs):
"""Make the grpc call which has a streaming response
grpc_req_obj_name: "core_pb2.GetSearchSolutionsResultsRequest", etc
grpc_call_name: "GetSearchSolutionsResults", etc
"""
core_stub, err_msg = TA2Connection.get_grpc_stub()
if err_msg:
StoredRequestUtil.set_error_status(stored_request_id, err_msg)
return
# optional: used to stream messages back to client via channels
#
websocket_id = kwargs.get('websocket_id', None)
#
grpc_req_obj = eval(grpc_req_obj_name)
grpc_rpc_call_function = eval('core_stub.%s' % grpc_call_name)
# --------------------------------
# convert the JSON string to a gRPC request
# Yes: done for the 2nd time
# --------------------------------
try:
req = Parse(raven_json_str,
grpc_req_obj())
except ParseError as err_obj:
err_msg = 'Failed to convert JSON to gRPC: %s' % (err_obj)
StoredRequestUtil.set_error_status(stored_request_id, err_msg)
return
# --------------------------------
# Send the gRPC request
# --------------------------------
msg_cnt = 0
try:
# -----------------------------------------
# Iterate through the streaming responses
# -----------------------------------------
for reply in grpc_rpc_call_function(\
req, timeout=settings.TA2_GRPC_LONG_TIMEOUT):
msg_cnt += 1
stored_resp = None # to hold a StoredResponse object
# -----------------------------------------
# parse the response
# -----------------------------------------
msg_json_str = message_to_json(reply)
msg_json_info = json_loads(msg_json_str)
# -----------------------------------------
# does it look ok?
# -----------------------------------------
if not msg_json_info.success:
print('PROBLEM HERE TO LOG!')
user_msg = 'failed to store response: %s' % \
msg_json_info.err_msg
ws_msg = WebsocketMessage.get_fail_message(\
grpc_call_name, user_msg, msg_cnt=msg_cnt)
ws_msg.send_message(websocket_id)
continue
# -----------------------------------------
# Looks good, save the response
# -----------------------------------------
stored_resp_info = StoredResponse.add_response(\
stored_request_id,
response=msg_json_info.result_obj)
# -----------------------------------------
# Make sure the response was saved (probably won't happen)
# -----------------------------------------
if not stored_resp_info.success:
# Not good but probably won't happen
# send a message to the user...
#
user_msg = 'failed to store response: %s' % \
msg_json_info.err_msg
ws_msg = WebsocketMessage.get_fail_message(\
grpc_call_name, user_msg, msg_cnt=msg_cnt)
ws_msg.send_message(websocket_id)
# Wait for the next response...
continue
# -----------------------------------------------
# send responses back to any open WebSockets
# ---------------------------------------------
if websocket_id:
stored_resp = stored_resp_info.result_obj
ws_msg = WebsocketMessage.get_success_message(\
grpc_call_name,
'it worked',
msg_cnt=msg_cnt,
data=stored_resp.as_dict())
print('ws_msg: %s' % ws_msg)
#print('ws_msg', ws_msg.as_dict())
ws_msg.send_message(websocket_id)
StoredResponse.mark_as_read(stored_resp)
# -----------------------------------------------
print('msg received #%d' % msg_cnt)
except grpc.RpcError as err_obj:
StoredRequestUtil.set_error_status(\
stored_request_id,
str(err_obj))
return
#except Exception as err_obj:
# StoredRequestUtil.set_error_status(\
# stored_request_id,
# str(err_obj))
# return
StoredRequestUtil.set_finished_ok_status(stored_request_id)
def rewrite_dataset_schema(problem, dataset_schema, all_variables, dataset_id, update_roles=False):
dataset_schema['about']['datasetID'] = dataset_id
resource_schema = next(i for i in dataset_schema['dataResources'] if i['resType'] == 'table')
# rewrite datasetDoc in output datasets if new problem metadata is supplied
keep_variables = list({
*problem.get('indexes', ['d3mIndex']),
*problem['predictors'],
*problem['targets']
})
ordering_column = problem.get('forecastingHorizon', {}).get("column")
if ordering_column and ordering_column not in keep_variables:
keep_variables.append(ordering_column)
# preserve column order, and only keep variables that already existed
keep_variables = sorted(list(i for i in keep_variables if i in all_variables), key=lambda x: all_variables.index(x))
passthrough_roles = [
'multiIndex', 'key', 'interval', 'boundingPolygon',
'edgeSource', "directedEdgeSource", "undirectedEdgeSource", "multiEdgeSource", "simpleEdgeSource",
"edgeTarget", "directedEdgeTarget", "undirectedEdgeTarget", "multiEdgeTarget", "simpleEdgeTarget"
]
map_roles = {
"indexes": 'index',
'predictors': 'attribute',
'targets': 'suggestedTarget',
'crossSection': 'suggestedGroupingKey',
'location': 'locationIndicator',
'boundary': 'boundaryIndicator',
'weights': 'instanceWeight',
'privileged': 'suggestedPriviligedData'
}
def do_update_roles(prev_roles, col_name):
roles = [i for i in prev_roles if i in passthrough_roles]
for role_name in map_roles:
if col_name in problem[role_name]:
roles.append(map_roles[role_name])
# if col_name == ordering_column and 'timeIndicator' not in col_schema['role']:
# col_schema['role'].append('timeIndicator')
return roles
def update_col_schema(i, col_name):
col_schema = next((col_schema for col_schema in resource_schema['columns'] if col_schema['colName'] == col_name), None)
if col_schema is None:
return
col_schema['colIndex'] = i
if update_roles:
col_schema['role'] = do_update_roles(col_schema['role'], col_name)
return col_schema
# modify in place
updated_schemas = []
for i, col_name in enumerate(keep_variables):
updated_schema = update_col_schema(i, col_name)
if updated_schema is None:
continue
updated_schemas.append(updated_schema)
resource_schema['columns'] = updated_schemas
# these are no longer necessarily valid after rewriting
resource_schema.pop("columnsCount", None)
dataset_schema.pop('metadata', None)
return keep_variables, dataset_schema
@celery_app.task()
def split_dataset(configuration, workspace):
# parse input data
split_options = configuration.get('split_options', {})
problem = configuration.get('problem')
dataset_schema = json.load(open(configuration['dataset_schema'], 'r'))
dataset_id = configuration['dataset_id']
# actual variable names in the data
all_variables = pd.read_csv(configuration['dataset_path'], nrows=1).columns.tolist()
# dataset schema will change because predictors and targets does not span all variables
# dataset id needs to be coordinated or else the TA2 will reject eventual produce calls on other datasets
keep_variables, dataset_schema = rewrite_dataset_schema(
problem=problem,
dataset_schema=dataset_schema,
all_variables=all_variables,
dataset_id=dataset_id,
update_roles=configuration.get('update_roles'))
# find the learningData resource, which is by convention the first table
resource_schema = next(i for i in dataset_schema['dataResources'] if i['resType'] == 'table')
cross_section_date_limits = None
inferred_freq = None
dtypes = {}
# WARNING: dates are assumed to be monotonically increasing
# this is to make it possible to support arbitrarily large datasets
if problem.get('taskType') == 'FORECASTING' and problem['forecastingHorizon']['column']:
time_column = problem['forecastingHorizon']['column']
time_format = problem.get('time_format', {}).get(time_column)
if time_format:
dtypes[time_column] = str
for cross_section in problem.get('crossSection', []):
dtypes[cross_section] = str
cross_section_date_limits = {}
time_buffer = []
candidate_frequencies = set()
# create generator that provides a data chunk on every iteration
data_file_generator = pd.read_csv(
configuration['dataset_path'],
chunksize=10 ** 5,
usecols=keep_variables,
dtype=dtypes)
infer_count = 0
for dataframe_chunk in data_file_generator:
if time_format:
dataframe_chunk[time_column] = dataframe_chunk[time_column].apply(
lambda x: get_date(x, time_format=time_format))
dataframe_chunk = dataframe_chunk.sort_values(by=[time_column])
for _, row in dataframe_chunk.iterrows():
# with open(configuration['dataset_path'], 'r') as infile:
# reader = csv.DictReader(infile)
# for row in reader:
date = row[time_column]
if not date:
continue
# limit the number of times frequency is inferred
if infer_count < 1000:
buffer_is_empty = len(time_buffer) == 0
date_is_newer = len(time_buffer) > 0 and time_buffer[-1] < date
if buffer_is_empty or date_is_newer:
time_buffer.append(date)
if len(time_buffer) > 3:
del time_buffer[0]
# at minimum three time points are needed to infer a date offset frequency
if len(time_buffer) == 3:
infer_count += 1
if time_format:
try:
candidate_frequency = pd.infer_freq(time_buffer)
if candidate_frequency:
candidate_frequencies.add(candidate_frequency)
except Exception:
# pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime
pass
else:
candidate_frequencies.add(abs(time_buffer[1] - time_buffer[0]))
# collect the highest date within each cross section
section = tuple(row[col] for col in problem.get('crossSection', []))
cross_section_date_limits.setdefault(section, date)
cross_section_date_limits[section] = max(cross_section_date_limits[section], date)
# if data has a trio of evenly spaced records
if candidate_frequencies:
if time_format:
# sort inferred frequency by approximate time durations, select shortest
inferred_freq = sorted([(i, approx_seconds(i)) for i in candidate_frequencies], key=lambda x: x[1])[0][0]
inferred_freq = pd.tseries.frequencies.to_offset(inferred_freq)
else:
inferred_freq = min(candidate_frequencies)
# create new directory structure for the data in a role
def get_dataset_paths(role):
dest_dir_info = create_destination_directory(workspace, name=role)
if not dest_dir_info[KEY_SUCCESS]:
return JsonResponse(get_json_error(dest_dir_info.err_msg))
dest_directory = dest_dir_info[KEY_DATA]
# copy all files, remove the csv_path (we'll be overwriting it)
csv_path = path.join(dest_directory, resource_schema['resPath'])
shutil.rmtree(dest_directory)
shutil.copytree(workspace.d3m_config.training_data_root, dest_directory)
os.remove(csv_path)
role_dataset_schema_path = path.join(dest_directory, 'datasetDoc.json')
role_dataset_schema = copy.deepcopy(dataset_schema)
with open(role_dataset_schema_path, 'w') as dataset_schema_file:
json.dump(role_dataset_schema, dataset_schema_file)
return role_dataset_schema_path, role_dataset_schema, csv_path
all_datasetDoc_path, all_datasetDoc, all_datasetCsv = get_dataset_paths('all')
dataset_schemas = {'all': all_datasetDoc}
dataset_schema_paths = {'all': all_datasetDoc_path}
dataset_paths = {'all': all_datasetCsv}
# indicates if data was successfully stratified (prone to failure on highly imbalanced data)
dataset_stratified = {}
if split_options.get('outOfSampleSplit'):
train_datasetDoc_path, train_datasetDoc, train_datasetCsv = get_dataset_paths('train')
test_datasetDoc_path, test_datasetDoc, test_datasetCsv = get_dataset_paths('test')
dataset_schemas = {
**dataset_schemas,
'train': train_datasetDoc,
'test': test_datasetDoc
}
dataset_schema_paths = {
**dataset_schema_paths,
'train': train_datasetDoc_path,
'test': test_datasetDoc_path
}
dataset_paths = {
**dataset_paths,
'train': train_datasetCsv,
'test': test_datasetCsv,
}
dataset_stratified = {
'train': split_options.get('stratified'),
'test': split_options.get('stratified')
}
DEFAULT_TRAIN_TEST_RATIO = .7
train_test_ratio = split_options.get('trainTestRatio', DEFAULT_TRAIN_TEST_RATIO)
if not (0 < train_test_ratio <= 1):
raise ValueError("train-test ratio must be between 0 and 1")
random_seed = split_options.get('randomSeed', 0)
# traverse the entire file for a row count. Informs the sampling ratios when chunking
with open(configuration['dataset_path'], 'r') as infile:
_header_line = next(infile)
row_count = sum(1 for _ in infile)
# write out blank csv files for each split
for split_name in ['train', 'test', 'all']:
pd.DataFrame(data=[], columns=keep_variables).to_csv(dataset_paths[split_name], index=False, quoting=csv.QUOTE_NONNUMERIC)
# by default, the split is trivially forever None, which exhausts all zips
splits_file_generator = iter(lambda: None, 1)
if split_options.get('splitsDir') and split_options.get('splitsFile'):
splits_file_path = | |
<reponame>tylerclair/py3canvas<gh_stars>0
"""OutcomeResults API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel
class OutcomeResultsAPI(BaseCanvasAPI):
"""OutcomeResults API Version 1.0."""
def __init__(self, *args, **kwargs):
"""Init method for OutcomeResultsAPI."""
super(OutcomeResultsAPI, self).__init__(*args, **kwargs)
self.logger = logging.getLogger("py3canvas.OutcomeResultsAPI")
def get_outcome_results(
self,
course_id,
include=None,
include_hidden=None,
outcome_ids=None,
user_ids=None,
):
"""
Get outcome results.
Gets the outcome results for users and outcomes in the specified context.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""
ID
"""
path["course_id"] = course_id
# OPTIONAL - user_ids
"""
If specified, only the users whose ids are given will be included in the
results. SIS ids can be used, prefixed by "sis_user_id:".
It is an error to specify an id for a user who is not a student in
the context.
"""
if user_ids is not None:
params["user_ids"] = user_ids
# OPTIONAL - outcome_ids
"""
If specified, only the outcomes whose ids are given will be included in the
results. it is an error to specify an id for an outcome which is not linked
to the context.
"""
if outcome_ids is not None:
params["outcome_ids"] = outcome_ids
# OPTIONAL - include
"""
[String, "alignments"|"outcomes"|"outcomes.alignments"|"outcome_groups"|"outcome_links"|"outcome_paths"|"users"]
Specify additional collections to be side loaded with the result.
"alignments" includes only the alignments referenced by the returned
results.
"outcomes.alignments" includes all alignments referenced by outcomes in the
context.
"""
if include is not None:
params["include"] = include
# OPTIONAL - include_hidden
"""
If true, results that are hidden from the learning mastery gradebook and student rollup
scores will be included
"""
if include_hidden is not None:
params["include_hidden"] = include_hidden
self.logger.debug(
"GET /api/v1/courses/{course_id}/outcome_results with query params: {params} and form data: {data}".format(
params=params, data=data, **path
)
)
return self.generic_request(
"GET",
"/api/v1/courses/{course_id}/outcome_results".format(**path),
data=data,
params=params,
no_data=True,
)
def get_outcome_result_rollups(
self,
course_id,
aggregate=None,
aggregate_stat=None,
exclude=None,
include=None,
outcome_ids=None,
sort_by=None,
sort_order=None,
sort_outcome_id=None,
user_ids=None,
):
"""
Get outcome result rollups.
Gets the outcome rollups for the users and outcomes in the specified
context.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""
ID
"""
path["course_id"] = course_id
# OPTIONAL - aggregate
"""
If specified, instead of returning one rollup for each user, all the user
rollups will be combined into one rollup for the course that will contain
the average (or median, see below) rollup score for each outcome.
"""
if aggregate is not None:
self._validate_enum(aggregate, ["course"])
params["aggregate"] = aggregate
# OPTIONAL - aggregate_stat
"""
If aggregate rollups requested, then this value determines what
statistic is used for the aggregate. Defaults to "mean" if this value
is not specified.
"""
if aggregate_stat is not None:
self._validate_enum(aggregate_stat, ["mean", "median"])
params["aggregate_stat"] = aggregate_stat
# OPTIONAL - user_ids
"""
If specified, only the users whose ids are given will be included in the
results or used in an aggregate result. it is an error to specify an id
for a user who is not a student in the context
"""
if user_ids is not None:
params["user_ids"] = user_ids
# OPTIONAL - outcome_ids
"""
If specified, only the outcomes whose ids are given will be included in the
results. it is an error to specify an id for an outcome which is not linked
to the context.
"""
if outcome_ids is not None:
params["outcome_ids"] = outcome_ids
# OPTIONAL - include
"""
[String, "courses"|"outcomes"|"outcomes.alignments"|"outcome_groups"|"outcome_links"|"outcome_paths"|"users"]
Specify additional collections to be side loaded with the result.
"""
if include is not None:
params["include"] = include
# OPTIONAL - exclude
"""
Specify additional values to exclude. "missing_user_rollups" excludes
rollups for users without results.
"""
if exclude is not None:
self._validate_enum(exclude, ["missing_user_rollups"])
params["exclude"] = exclude
# OPTIONAL - sort_by
"""
If specified, sorts outcome result rollups. "student" sorting will sort
by a user's sortable name. "outcome" sorting will sort by the given outcome's
rollup score. The latter requires specifying the "sort_outcome_id" parameter.
By default, the sort order is ascending.
"""
if sort_by is not None:
self._validate_enum(sort_by, ["student", "outcome"])
params["sort_by"] = sort_by
# OPTIONAL - sort_outcome_id
"""
If outcome sorting requested, then this determines which outcome to use
for rollup score sorting.
"""
if sort_outcome_id is not None:
params["sort_outcome_id"] = sort_outcome_id
# OPTIONAL - sort_order
"""
If sorting requested, then this allows changing the default sort order of
ascending to descending.
"""
if sort_order is not None:
self._validate_enum(sort_order, ["asc", "desc"])
params["sort_order"] = sort_order
self.logger.debug(
"GET /api/v1/courses/{course_id}/outcome_rollups with query params: {params} and form data: {data}".format(
params=params, data=data, **path
)
)
return self.generic_request(
"GET",
"/api/v1/courses/{course_id}/outcome_rollups".format(**path),
data=data,
params=params,
no_data=True,
)
class Outcomeresult(BaseModel):
"""Outcomeresult Model.
A student's result for an outcome"""
def __init__(
self,
id=None,
score=None,
submitted_or_assessed_at=None,
links=None,
percent=None,
):
"""Init method for Outcomeresult class."""
self._id = id
self._score = score
self._submitted_or_assessed_at = submitted_or_assessed_at
self._links = links
self._percent = percent
self.logger = logging.getLogger("py3canvas.Outcomeresult")
@property
def id(self):
"""A unique identifier for this result."""
return self._id
@id.setter
def id(self, value):
"""Setter for id property."""
self.logger.warn(
"Setting values on id will NOT update the remote Canvas instance."
)
self._id = value
@property
def score(self):
"""The student's score."""
return self._score
@score.setter
def score(self, value):
"""Setter for score property."""
self.logger.warn(
"Setting values on score will NOT update the remote Canvas instance."
)
self._score = value
@property
def submitted_or_assessed_at(self):
"""The datetime the resulting OutcomeResult was submitted at, or absent that, when it was assessed."""
return self._submitted_or_assessed_at
@submitted_or_assessed_at.setter
def submitted_or_assessed_at(self, value):
"""Setter for submitted_or_assessed_at property."""
self.logger.warn(
"Setting values on submitted_or_assessed_at will NOT update the remote Canvas instance."
)
self._submitted_or_assessed_at = value
@property
def links(self):
"""Unique identifiers of objects associated with this result."""
return self._links
@links.setter
def links(self, value):
"""Setter for links property."""
self.logger.warn(
"Setting values on links will NOT update the remote Canvas instance."
)
self._links = value
@property
def percent(self):
"""score's percent of maximum points possible for outcome, scaled to reflect any custom mastery levels that differ from the learning outcome."""
return self._percent
@percent.setter
def percent(self, value):
"""Setter for percent property."""
self.logger.warn(
"Setting values on percent will NOT update the remote Canvas instance."
)
self._percent = value
class Outcomerollupscorelinks(BaseModel):
"""Outcomerollupscorelinks Model."""
def __init__(self, outcome=None):
"""Init method for Outcomerollupscorelinks class."""
self._outcome = outcome
self.logger = logging.getLogger("py3canvas.Outcomerollupscorelinks")
@property
def outcome(self):
"""The id of the related outcome."""
return self._outcome
@outcome.setter
def outcome(self, value):
"""Setter for outcome property."""
self.logger.warn(
"Setting values on outcome will NOT update the remote Canvas instance."
)
self._outcome = value
class Outcomerollupscore(BaseModel):
"""Outcomerollupscore Model."""
def __init__(self, score=None, count=None, links=None):
"""Init method for Outcomerollupscore class."""
self._score = score
self._count = count
self._links = links
self.logger = logging.getLogger("py3canvas.Outcomerollupscore")
@property
def score(self):
"""The rollup score for the outcome, based on the student alignment scores related to the outcome. This could be null if the student has no related scores."""
return self._score
@score.setter
def score(self, value):
"""Setter for score property."""
self.logger.warn(
"Setting values on score will NOT update the remote Canvas instance."
)
self._score = value
@property
def count(self):
"""The number of alignment scores included in this rollup."""
return self._count
@count.setter
def count(self, value):
"""Setter for count property."""
self.logger.warn(
"Setting values on count will NOT update the remote Canvas instance."
)
self._count = value
@property
def links(self):
"""links."""
return self._links
@links.setter
def links(self, value):
"""Setter for links property."""
self.logger.warn(
"Setting values on links will NOT update the remote Canvas instance."
)
self._links = value
class Outcomerolluplinks(BaseModel):
"""Outcomerolluplinks Model."""
def __init__(self, course=None, user=None, section=None):
"""Init method for Outcomerolluplinks class."""
self._course = course
self._user = user
self._section = section
self.logger = logging.getLogger("py3canvas.Outcomerolluplinks")
@property
def course(self):
"""If an aggregate result was requested, the course field will be present. Otherwise, the user and section field will be present (Optional) The id of the course that this rollup applies to."""
return self._course
@course.setter
def course(self, value):
"""Setter for course property."""
self.logger.warn(
"Setting values on course will NOT update the remote Canvas instance."
)
self._course = value
@property
def user(self):
"""(Optional) The id of the | |
# Copyright (c) 2021, <NAME>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. 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.
# 3. Neither the name of the copyright holder 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 HOLDER 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.
"""This module doesn't contain a service, but a mixin.
Implement the CRUX protocol as a mixin that services can inherit from.
The CRUX protocol is used to communicate safely between a server,
running on the portal process, and clients (called HOST clients).
CRUX also implements answers and message broadcasting.
This mixin is used by the CRUX (server) and HOST (client) service, as
communication is similar.
CRUX protocol:
A secret key is randomly generated by the CRUX server, running on
the portal, when it starts. This key is stored in the
user keyring, so it can be retrieved by other processes
running on the same machine, with the same username.
This first key will be used for signature. Another one is generated
for encryption.
The CRUX server then creates a simple TCP server. HOST clients
can connect to it. The communication between them can follow
different rules, detailed below.
1. Unverified: in this mode, messages aren't signed nor
encryupted. This mode should be avoided, even locally.
At worst, signing doesn't take a huge toll on performance
and is preferable, since messages could contain things
better left out of your system.
2. Signed: in this mode, messages are signed, that is to say,
they travel in clear on the network with a hash at the end
indicated whether the message can be trusted or not. Depending
on your needs, signing messages might be enough for most situations.
3. Encrypted: in this mode, messages are encrypted to travel.
They may or may not be signed (you can combine both modes
at once). The Fernet protocol is used for cryptography
and the secret key is generated and handled by the CRUX server
(the key doesn't travel on the network).
The mode to use isn't specific to a CRUX server and its HOST
clients, but can be different for every message.
The message, as sent through the network, looks like this:
One byte indicating the mode(s) to use. This is a flag
(1 => unverified, 2 => signed, 4 => encrypted, 6 => signed
and encrypted).
A 8-byte packet, containing the length of the message.
The message as a pickled object. If the mode is encrypted,
this message should be read by Fernet. If the mode is signed,
the message should be checked by itsdangerous before being unpickled.
A message, once unsigned, looks like a tuple containing
the command name (as a string), the command ID (which is used
for answers) and the command arguments (wrapped in a dictionary).
This tuple is unpickled (hence the importance of signature)
from network, whether from client or server. The service
then tries to find a method that can execute this command:
a method called `handle_{command name}` should be defined
on the service or in one of its parents. If so,
call this method with the relevant information.
Command methods can answer to whoever has called them. In order
to do so, they emit a message, "answer", with the same command
ID of the original request. The original caller can wait
for this answer and use it.
"""
import asyncio
from itertools import count
import os.path
import pickle
import platform
from struct import calcsize, error as struct_error, pack, unpack
import time
from typing import Any, Optional
from async_timeout import timeout as async_timeout
import keyring
from service.origin import Origin
from service.message import MessageMode
# Constants
INITIAL_PACKET_FORMAT_STRING = "!bQ"
INITIAL_PACKET_SIZE = calcsize(INITIAL_PACKET_FORMAT_STRING)
class CmdMixin:
"""Command mixin, used to transfer commands with arguments.
A command name, identifier and arguments are pickled, signed and
sent over the network to the client or server. If you want to
learn more about this, please read `CRUX protocol` above which details
the structure of a CRUX message.
However, most of the time, you don't need to worry about
the implementation details. Use asynchronous methods to handle
communication.
Asynchronous methods:
write_cmd(writer, command name, arguments): send a command.
answer(origin, arguments): answer to a specific command.
wait_for_cmd(reader, command name, timeout): wait for a command
to be received.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.commands = {}
self.answers = {}
self.cmd_id = count(0)
async def init(self):
"""The service is initialized."""
self.secret_key = ""
self.register_hook("error_read")
self.register_hook("error_write")
async def setup(self):
"""Set the communication up."""
self.read_secret_key()
def read_secret_key(self, override: bool = False):
"""Read the secret key from keyring.
Args:
override (bool): if set to True, don't check whether
a secret key exists.
"""
if not override and self.secret_key:
return
self.logger.debug(
self.indented("Fetching the secret key...", added_depth=1)
)
if platform.system() == "Linux":
if os.path.exists(".crux"):
with open(".crux", "r", encoding="utf-8") as file:
self.secret_key = file.read()
else:
self.secret_key = keyring.get_password("<PASSWORD>", "<PASSWORD>")
if not self.secret_key:
self.logger.debug(
self.indented(
"The secret key couldn't be loaded.",
added_depth=1,
),
)
return
MessageMode.setup(self.secret_key, ...)
async def read_commands(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
):
"""Enter an asynchronous loop to read commands from `reader`."""
# Creates the asynchronous queue for the reader if it doesn't exist:
queue = self.commands.get(reader)
if queue is None:
queue = asyncio.Queue()
self.commands[reader] = queue
while True:
# Read exactly 8 bytes, the length of the packet to read.
try:
initial_packet = await reader.readexactly(INITIAL_PACKET_SIZE)
except ConnectionError:
await queue.put(None)
await self.call_hook("error_read", reader)
return
except asyncio.CancelledError:
await queue.put(None)
return
except asyncio.IncompleteReadError:
# An EOF occurred, disconnect.
await self.call_hook("error_read", reader)
await queue.put(None)
return
except Exception:
self.logger.exception(
"An exception was raised on read_commands"
)
await self.call_hook("error_read", reader)
return
# Extract the flag and size, using `struct.unpack`.
try:
packet = unpack(INITIAL_PACKET_FORMAT_STRING, initial_packet)
except struct_error:
# Not a valid initial packet, disconnect.
await queue.put(None)
return
# Read the message mode.
flag, size = packet
# Check that the flag is valid, build a MessageMode member.
try:
mode = MessageMode(flag)
except ValueError:
self.logger.error(
f"a packet with an invalid flag of {flag} was received"
)
await queue.put(None)
await self.call_hook("error_read", reader)
return
# Read exactly `size` bytes. The read byte should contain
# a pickled collection, more or less wrapped.
try:
data = await reader.readexactly(size)
except ConnectionError:
await queue.put(None)
await self.call_hook("error_read", reader)
return
except asyncio.CancelledError:
await queue.put(None)
return
except asyncio.IncompleteReadError:
# An EOF occurred, disconnect.
self.logger.warning(
f"EOF was encountered while reading a promise of {size} "
"bytes. This connection is closed, but there might "
"be unprocessed data."
)
await queue.put(None)
return
except Exception:
self.logger.exception(
"An exception was raised on read_commands"
)
await self.call_hook("error_read", reader)
return
# Unsign/unpickle the data.
try:
obj = mode.get_content(data)
except (pickle.PickleError, EOFError):
# The stream can't be read, it's an obvious error at
# that point.
self.logger.exception(
"An error occurred while unpickling a CRUX command:"
)
await self.call_hook("error_read", reader)
else:
# An object has been unpickled.
# If it's a command, it should be a tuple | |
self.name())
# Non-repeated fields have a member of just the type name.
max_size = self.max_size()
if max_size == 0:
return (self.type_name(from_root), self.name())
# Fixed size fields use std::array.
if self.fixed_size():
return ('std::array<{}, {}>'.format(self.type_name(from_root),
max_size), self.name())
# Otherwise prefer pw::Vector for repeated fields.
return ('::pw::Vector<{}, {}>'.format(self.type_name(from_root),
max_size), self.name())
def _varint_type_table_entry(self) -> str:
if self.wire_type() == 'kVarint':
return '{}::VarintType::{}'.format(PROTOBUF_NAMESPACE,
self.varint_decode_type())
return f'static_cast<{PROTOBUF_NAMESPACE}::VarintType>(0)'
def _wire_type_table_entry(self) -> str:
return '{}::WireType::{}'.format(PROTOBUF_NAMESPACE, self.wire_type())
def _elem_size_table_entry(self) -> str:
return 'sizeof({})'.format(self.type_name())
def table_entry(self) -> List[str]:
"""Table entry."""
return [
self.field_cast(),
self._wire_type_table_entry(),
self._elem_size_table_entry(),
self._varint_type_table_entry(),
'true' if self.fixed_size() else 'false',
'true' if self._field.is_repeated() else 'false',
'true' if self.is_optional() else 'false',
'true' if self.use_callback() else 'false',
'offsetof(Message, {})'.format(self.name()),
'sizeof(Message::{})'.format(self.name()),
self.sub_table(),
]
@abc.abstractmethod
def _size_fn(self) -> str:
"""Returns the name of the field size function."""
def _size_length(self) -> Optional[str]: # pylint: disable=no-self-use
"""Returns the length to add to the maximum encoded size."""
return None
def max_encoded_size(self) -> str:
"""Returns a constant expression for field's maximum encoded size."""
size_call = '{}::{}({})'.format(PROTOBUF_NAMESPACE, self._size_fn(),
self.field_cast())
size_length: Optional[str] = self._size_length()
if size_length is None:
return size_call
return f'{size_call} + {size_length}'
def include_in_scratch_size(self) -> bool: # pylint: disable=no-self-use
"""Returns whether the field contributes to the scratch buffer size."""
return False
#
# The following code defines write and read methods for each of the
# complex protobuf types.
#
class SubMessageEncoderMethod(ProtoMethod):
"""Method which returns a sub-message encoder."""
def name(self) -> str:
return 'Get{}Encoder'.format(self._field.name())
def return_type(self, from_root: bool = False) -> str:
return '{}::StreamEncoder'.format(
self._relative_type_namespace(from_root))
def params(self) -> List[Tuple[str, str]]:
return []
def body(self) -> List[str]:
line = 'return {}::StreamEncoder({}::GetNestedEncoder({}));'.format(
self._relative_type_namespace(), self._base_class,
self.field_cast())
return [line]
# Submessage methods are not defined within the class itself because the
# submessage class may not yet have been defined.
def in_class_definition(self) -> bool:
return False
class SubMessageDecoderMethod(ReadMethod):
"""Method which returns a sub-message decoder."""
def name(self) -> str:
return 'Get{}Decoder'.format(self._field.name())
def return_type(self, from_root: bool = False) -> str:
return '{}::StreamDecoder'.format(
self._relative_type_namespace(from_root))
def _decoder_body(self) -> List[str]:
line = 'return {}::StreamDecoder(GetNestedDecoder());'.format(
self._relative_type_namespace())
return [line]
# Submessage methods are not defined within the class itself because the
# submessage class may not yet have been defined.
def in_class_definition(self) -> bool:
return False
class SubMessageProperty(MessageProperty):
"""Property which contains a sub-message."""
def _dependency_removed(self) -> bool:
"""Returns true if the message dependency was removed to break a cycle.
Proto allows cycles between messages, but C++ doesn't allow cycles
between class references. So when we're forced to break one, the
struct member is replaced with a callback.
"""
type_node = self._field.type_node()
assert type_node is not None
return type_node in cast(ProtoMessage, self._scope).dependency_cycles()
def _elem_size_table_entry(self) -> str:
# Since messages can't be repeated (as we couldn't set callbacks),
# only field size is used. Set elem_size to 0 so space can be saved by
# not using more than 4 bits for it.
return '0'
def type_name(self, from_root: bool = False) -> str:
return '{}::Message'.format(self._relative_type_namespace(from_root))
def use_callback(self) -> bool:
# Always use a callback for a message dependency removed to break a
# cycle, and for repeated fields, since in both cases there's no way
# to handle the size of nested field.
options = self._field.options()
assert options is not None
return (options.use_callback or self._dependency_removed()
or self._field.is_repeated())
def wire_type(self) -> str:
return 'kDelimited'
def sub_table(self) -> str:
if self.use_callback():
return 'nullptr'
return '&{}::kMessageFields'.format(self._relative_type_namespace())
def _size_fn(self) -> str:
# This uses the WithoutValue method to ensure that the maximum length
# of the delimited field size varint is used. This is because the nested
# message might include callbacks and be longer than we expect, and to
# account for scratch overhead when used with MemoryEncoder.
return 'SizeOfDelimitedFieldWithoutValue'
def _size_length(self) -> Optional[str]:
if self.use_callback():
return None
return '{}::kMaxEncodedSizeBytes'.format(
self._relative_type_namespace())
def include_in_scratch_size(self) -> bool:
return True
class BytesReaderMethod(ReadMethod):
"""Method which returns a bytes reader."""
def name(self) -> str:
return 'Get{}Reader'.format(self._field.name())
def return_type(self, from_root: bool = False) -> str:
return f'{PROTOBUF_NAMESPACE}::StreamDecoder::BytesReader'
def _decoder_fn(self) -> str:
return 'GetBytesReader'
#
# The following code defines write and read methods for each of the
# primitive protobuf types.
#
class DoubleWriteMethod(WriteMethod):
"""Method which writes a proto double value."""
def params(self) -> List[Tuple[str, str]]:
return [('double', 'value')]
def _encoder_fn(self) -> str:
return 'WriteDouble'
class PackedDoubleWriteMethod(PackedWriteMethod):
"""Method which writes a packed list of doubles."""
def params(self) -> List[Tuple[str, str]]:
return [('std::span<const double>', 'values')]
def _encoder_fn(self) -> str:
return 'WritePackedDouble'
class PackedDoubleWriteVectorMethod(PackedWriteMethod):
"""Method which writes a packed vector of doubles."""
def params(self) -> List[Tuple[str, str]]:
return [('const ::pw::Vector<double>&', 'values')]
def _encoder_fn(self) -> str:
return 'WriteRepeatedDouble'
class DoubleReadMethod(ReadMethod):
"""Method which reads a proto double value."""
def _result_type(self) -> str:
return 'double'
def _decoder_fn(self) -> str:
return 'ReadDouble'
class PackedDoubleReadMethod(PackedReadMethod):
"""Method which reads packed double values."""
def _result_type(self) -> str:
return 'double'
def _decoder_fn(self) -> str:
return 'ReadPackedDouble'
class PackedDoubleReadVectorMethod(PackedReadVectorMethod):
"""Method which reads packed double values."""
def _result_type(self) -> str:
return 'double'
def _decoder_fn(self) -> str:
return 'ReadRepeatedDouble'
class DoubleProperty(MessageProperty):
"""Property which holds a proto double value."""
def type_name(self, from_root: bool = False) -> str:
return 'double'
def wire_type(self) -> str:
return 'kFixed64'
def _size_fn(self) -> str:
return 'SizeOfFieldDouble'
class FloatWriteMethod(WriteMethod):
"""Method which writes a proto float value."""
def params(self) -> List[Tuple[str, str]]:
return [('float', 'value')]
def _encoder_fn(self) -> str:
return 'WriteFloat'
class PackedFloatWriteMethod(PackedWriteMethod):
"""Method which writes a packed list of floats."""
def params(self) -> List[Tuple[str, str]]:
return [('std::span<const float>', 'values')]
def _encoder_fn(self) -> str:
return 'WritePackedFloat'
class PackedFloatWriteVectorMethod(PackedWriteMethod):
"""Method which writes a packed vector of floats."""
def params(self) -> List[Tuple[str, str]]:
return [('const ::pw::Vector<float>&', 'values')]
def _encoder_fn(self) -> str:
return 'WriteRepeatedFloat'
class FloatReadMethod(ReadMethod):
"""Method which reads a proto float value."""
def _result_type(self) -> str:
return 'float'
def _decoder_fn(self) -> str:
return 'ReadFloat'
class PackedFloatReadMethod(PackedReadMethod):
"""Method which reads packed float values."""
def _result_type(self) -> str:
return 'float'
def _decoder_fn(self) -> str:
return 'ReadPackedFloat'
class PackedFloatReadVectorMethod(PackedReadVectorMethod):
"""Method which reads packed float values."""
def _result_type(self) -> str:
return 'float'
def _decoder_fn(self) -> str:
return 'ReadRepeatedFloat'
class FloatProperty(MessageProperty):
"""Property which holds a proto float value."""
def type_name(self, from_root: bool = False) -> str:
return 'float'
def wire_type(self) -> str:
return 'kFixed32'
def _size_fn(self) -> str:
return 'SizeOfFieldFloat'
class Int32WriteMethod(WriteMethod):
"""Method which writes a proto int32 value."""
def params(self) -> List[Tuple[str, str]]:
return [('int32_t', 'value')]
def _encoder_fn(self) -> str:
return 'WriteInt32'
class PackedInt32WriteMethod(PackedWriteMethod):
"""Method which writes a packed list of int32."""
def params(self) -> List[Tuple[str, str]]:
return [('std::span<const int32_t>', 'values')]
def _encoder_fn(self) -> str:
return 'WritePackedInt32'
class PackedInt32WriteVectorMethod(PackedWriteMethod):
"""Method which writes a packed vector of int32."""
def params(self) -> List[Tuple[str, str]]:
return [('const ::pw::Vector<int32_t>&', 'values')]
def _encoder_fn(self) -> str:
return 'WriteRepeatedInt32'
class Int32ReadMethod(ReadMethod):
"""Method which reads a proto int32 value."""
def _result_type(self) -> str:
return 'int32_t'
def _decoder_fn(self) -> str:
return 'ReadInt32'
class PackedInt32ReadMethod(PackedReadMethod):
"""Method which reads packed int32 values."""
def _result_type(self) -> str:
return 'int32_t'
def _decoder_fn(self) -> str:
return 'ReadPackedInt32'
class PackedInt32ReadVectorMethod(PackedReadVectorMethod):
"""Method which reads packed int32 values."""
def _result_type(self) -> str:
return 'int32_t'
def _decoder_fn(self) -> str:
return 'ReadRepeatedInt32'
class Int32Property(MessageProperty):
"""Property which holds a proto int32 value."""
def type_name(self, from_root: bool = False) -> str:
return 'int32_t'
def wire_type(self) -> str:
return 'kVarint'
def varint_decode_type(self) -> str:
return 'kNormal'
def _size_fn(self) -> str:
return 'SizeOfFieldInt32'
class Sint32WriteMethod(WriteMethod):
"""Method which writes a proto sint32 value."""
def params(self) -> List[Tuple[str, str]]:
return [('int32_t', 'value')]
def _encoder_fn(self) -> str:
return 'WriteSint32'
class PackedSint32WriteMethod(PackedWriteMethod):
"""Method which writes a packed list of sint32."""
def params(self) -> List[Tuple[str, str]]:
return [('std::span<const int32_t>', 'values')]
def _encoder_fn(self) -> str:
return 'WritePackedSint32'
class PackedSint32WriteVectorMethod(PackedWriteMethod):
"""Method which writes a packed vector of sint32."""
def params(self) -> List[Tuple[str, str]]:
return [('const ::pw::Vector<int32_t>&', 'values')]
def _encoder_fn(self) -> str:
return 'WriteRepeatedSint32'
class Sint32ReadMethod(ReadMethod):
"""Method which reads a proto sint32 value."""
def _result_type(self) -> str:
return 'int32_t'
def _decoder_fn(self) -> str:
return 'ReadSint32'
class PackedSint32ReadMethod(PackedReadMethod):
"""Method which reads packed sint32 values."""
def _result_type(self) -> str:
return 'int32_t'
def _decoder_fn(self) -> str:
return 'ReadPackedSint32'
class PackedSint32ReadVectorMethod(PackedReadVectorMethod):
"""Method which reads packed sint32 values."""
def _result_type(self) -> str:
return 'int32_t'
def _decoder_fn(self) -> str:
return 'ReadRepeatedSint32'
class Sint32Property(MessageProperty):
"""Property which holds a proto sint32 value."""
def type_name(self, from_root: bool = False) -> str:
return 'int32_t'
def wire_type(self) -> str:
return 'kVarint'
def varint_decode_type(self) -> str:
return 'kZigZag'
def _size_fn(self) | |
value to start a new operation, excluding this value in the new request.
If ``LastEvaluatedKey`` is empty, then the "last page" of results has been processed and there is no more data to be retrieved.
If ``LastEvaluatedKey`` is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when ``LastEvaluatedKey`` is empty.
- *(string) --*
- *(dict) --*
Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see `Data Types <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes>`__ in the *Amazon DynamoDB Developer Guide* .
- **S** *(string) --*
An attribute of type String. For example:
``"S": "Hello"``
- **N** *(string) --*
An attribute of type Number. For example:
``"N": "123.45"``
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
- **B** *(bytes) --*
An attribute of type Binary. For example:
``"B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk"``
- **SS** *(list) --*
An attribute of type String Set. For example:
``"SS": ["Giraffe", "Hippo" ,"Zebra"]``
- *(string) --*
- **NS** *(list) --*
An attribute of type Number Set. For example:
``"NS": ["42.2", "-19", "7.5", "3.14"]``
Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
- *(string) --*
- **BS** *(list) --*
An attribute of type Binary Set. For example:
``"BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="]``
- *(bytes) --*
- **M** *(dict) --*
An attribute of type Map. For example:
``"M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}}``
- *(string) --*
- *(dict) --*
Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see `Data Types <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes>`__ in the *Amazon DynamoDB Developer Guide* .
- **L** *(list) --*
An attribute of type List. For example:
``"L": [ {"S": "Cookies"} , {"S": "Coffee"}, {"N", "3.14159"}]``
- *(dict) --*
Represents the data for an attribute.
Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
For more information, see `Data Types <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes>`__ in the *Amazon DynamoDB Developer Guide* .
- **NULL** *(boolean) --*
An attribute of type Null. For example:
``"NULL": true``
- **BOOL** *(boolean) --*
An attribute of type Boolean. For example:
``"BOOL": true``
- **ConsumedCapacity** *(dict) --*
The capacity units consumed by the ``Scan`` operation. The data returned includes the total provisioned throughput consumed, along with statistics for the table and any indexes involved in the operation. ``ConsumedCapacity`` is only returned if the ``ReturnConsumedCapacity`` parameter was specified. For more information, see `Provisioned Throughput <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html>`__ in the *Amazon DynamoDB Developer Guide* .
- **TableName** *(string) --*
The name of the table that was affected by the operation.
- **CapacityUnits** *(float) --*
The total number of capacity units consumed by the operation.
- **ReadCapacityUnits** *(float) --*
The total number of read capacity units consumed by the operation.
- **WriteCapacityUnits** *(float) --*
The total number of write capacity units consumed by the operation.
- **Table** *(dict) --*
The amount of throughput consumed on the table affected by the operation.
- **ReadCapacityUnits** *(float) --*
The total number of read capacity units consumed on a table or an index.
- **WriteCapacityUnits** *(float) --*
The total number of write capacity units consumed on a table or an index.
- **CapacityUnits** *(float) --*
The total number of capacity units consumed on a table or an index.
- **LocalSecondaryIndexes** *(dict) --*
The amount of throughput consumed on each local index affected by the operation.
- *(string) --*
- *(dict) --*
Represents the amount of provisioned throughput capacity consumed on a table or an index.
- **ReadCapacityUnits** *(float) --*
The total number of read capacity units consumed on a table or an index.
- **WriteCapacityUnits** *(float) --*
The total number of write capacity units consumed on a table or an index.
- **CapacityUnits** *(float) --*
The total number of capacity units consumed on a table or an index.
- **GlobalSecondaryIndexes** *(dict) --*
The amount of throughput consumed on each global index affected by the operation.
- *(string) --*
- *(dict) --*
Represents the amount of provisioned throughput capacity consumed on a table or an index.
- **ReadCapacityUnits** *(float) --*
The total number of read capacity units consumed on a table or an index.
- **WriteCapacityUnits** *(float) --*
The total number of write capacity units consumed on a table or an index.
- **CapacityUnits** *(float) --*
The total number of capacity units consumed on a table or an index.
:type IndexName: string
:param IndexName:
The name of a secondary index to scan. This index can be any local secondary index or global secondary index. Note that if you use the ``IndexName`` parameter, you must also provide ``TableName`` .
:type AttributesToGet: list
:param AttributesToGet:
This is a legacy parameter. Use ``ProjectionExpression`` instead. For more information, see `AttributesToGet <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html>`__ in the *Amazon DynamoDB Developer Guide* .
- *(string) --*
:type Limit: integer
:param Limit:
The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in ``LastEvaluatedKey`` to apply in a subsequent operation to continue the operation. For more information, see `Query and Scan <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html>`__ in the *Amazon DynamoDB Developer Guide* .
:type Select: string
:param Select:
The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index.
* ``ALL_ATTRIBUTES`` - Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required.
* ``ALL_PROJECTED_ATTRIBUTES`` - Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ``ALL_ATTRIBUTES`` .
* ``COUNT`` - Returns the number of matching items, rather than the matching items themselves.
* ``SPECIFIC_ATTRIBUTES`` - Returns only the attributes listed in ``AttributesToGet`` . This return value is equivalent to specifying ``AttributesToGet`` without specifying any value for ``Select`` . If you query or scan a local secondary index and request only attributes that are projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected into the local secondary index, DynamoDB will fetch each of | |
<gh_stars>0
# *****************************************************************************
# Copyright (c) 2019-2020, Intel Corporation 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.
#
# 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 HOLDER 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.
# *****************************************************************************
import pandas as pd
import pandas.api.types
import numpy as np
import numba
from numba.extending import (typeof_impl, unbox, register_model, models,
NativeValue, box, intrinsic)
from numba import types
from numba.core import cgutils
from numba.np import numpy_support
from numba.core.typing import signature
from numba.core.boxing import box_array, unbox_array, box_list, unbox_none
from numba.core.boxing import _NumbaTypeHelper
from numba.cpython import listobj
from sdc.hiframes.pd_dataframe_type import DataFrameType
from sdc.str_ext import string_type, list_string_array_type
from sdc.str_arr_ext import (string_array_type, unbox_str_series, box_str_arr)
from sdc.datatypes.categorical.types import CategoricalDtypeType, Categorical
from sdc.datatypes.categorical.boxing import unbox_Categorical, box_Categorical
from sdc.hiframes.pd_series_ext import SeriesType
from sdc.hiframes.pd_series_type import _get_series_array_type
from sdc.hiframes.pd_dataframe_ext import get_structure_maps
from .. import hstr_ext
import llvmlite.binding as ll
from llvmlite import ir as lir
from llvmlite.llvmpy.core import Type as LLType
from sdc.datatypes.range_index_type import RangeIndexType
from sdc.extensions.indexes.range_index_ext import box_range_index, unbox_range_index
from sdc.str_arr_type import StringArrayType
ll.add_symbol('array_size', hstr_ext.array_size)
ll.add_symbol('array_getptr1', hstr_ext.array_getptr1)
@typeof_impl.register(pd.DataFrame)
def typeof_pd_dataframe(val, c):
col_names = tuple(val.columns.tolist())
# TODO: support other types like string and timestamp
col_types = get_hiframes_dtypes(val)
index_type = _infer_index_type(val.index)
column_loc, _, _ = get_structure_maps(col_types, col_names)
return DataFrameType(col_types, index_type, col_names, True, column_loc=column_loc)
# register series types for import
@typeof_impl.register(pd.Series)
def typeof_pd_series(val, c):
index_type = _infer_index_type(val.index)
is_named = val.name is not None
return SeriesType(
_infer_series_dtype(val), index=index_type, is_named=is_named)
@unbox(DataFrameType)
def unbox_dataframe(typ, val, c):
"""unbox dataframe to an empty DataFrame struct
columns will be extracted later if necessary.
"""
n_cols = len(typ.columns)
column_strs = [numba.cpython.unicode.make_string_from_constant(
c.context, c.builder, string_type, a) for a in typ.columns]
# create dataframe struct and store values
dataframe = cgutils.create_struct_proxy(typ)(c.context, c.builder)
errorptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit)
col_list_type = types.List(string_type)
ok, inst = listobj.ListInstance.allocate_ex(c.context, c.builder, col_list_type, n_cols)
with c.builder.if_else(ok, likely=True) as (if_ok, if_not_ok):
with if_ok:
inst.size = c.context.get_constant(types.intp, n_cols)
for i, column_str in enumerate(column_strs):
inst.setitem(c.context.get_constant(types.intp, i), column_str, incref=False)
dataframe.columns = inst.value
with if_not_ok:
c.builder.store(cgutils.true_bit, errorptr)
# If an error occurred, drop the whole native list
with c.builder.if_then(c.builder.load(errorptr)):
c.context.nrt.decref(c.builder, col_list_type, inst.value)
_, data_typs_map, types_order = get_structure_maps(typ.data, typ.columns)
for col_typ in types_order:
type_id, col_indices = data_typs_map[col_typ]
n_type_cols = len(col_indices)
list_type = types.List(col_typ)
ok, inst = listobj.ListInstance.allocate_ex(c.context, c.builder, list_type, n_type_cols)
with c.builder.if_else(ok, likely=True) as (if_ok, if_not_ok):
with if_ok:
inst.size = c.context.get_constant(types.intp, n_type_cols)
for i, col_idx in enumerate(col_indices):
series_obj = c.pyapi.object_getattr_string(val, typ.columns[col_idx])
arr_obj = c.pyapi.object_getattr_string(series_obj, "values")
ty_series = typ.data[col_idx]
if isinstance(ty_series, types.Array):
native_val = unbox_array(typ.data[col_idx], arr_obj, c)
elif ty_series == string_array_type:
native_val = unbox_str_series(string_array_type, series_obj, c)
inst.setitem(c.context.get_constant(types.intp, i), native_val.value, incref=False)
dataframe.data = c.builder.insert_value(dataframe.data, inst.value, type_id)
with if_not_ok:
c.builder.store(cgutils.true_bit, errorptr)
# If an error occurred, drop the whole native list
with c.builder.if_then(c.builder.load(errorptr)):
c.context.nrt.decref(c.builder, list_type, inst.value)
index_obj = c.pyapi.object_getattr_string(val, "index")
dataframe.index = _unbox_index_data(typ.index, index_obj, c).value
c.pyapi.decref(index_obj)
dataframe.parent = val
# increase refcount of stored values
if c.context.enable_nrt:
# TODO: other objects?
for var in column_strs:
c.context.nrt.incref(c.builder, string_type, var)
return NativeValue(dataframe._getvalue(), is_error=c.builder.load(errorptr))
def get_hiframes_dtypes(df):
"""get hiframe data types for a pandas dataframe
"""
col_names = df.columns.tolist()
hi_typs = [_get_series_array_type(_infer_series_dtype(df[cname]))
for cname in col_names]
return tuple(hi_typs)
def _infer_series_dtype(S):
if S.dtype == np.dtype('O'):
# XXX assuming the whole column is strings if 1st val is string
# TODO: handle NA as 1st value
i = 0
while i < len(S) and (S.iloc[i] is np.nan or S.iloc[i] is None):
i += 1
if i == len(S):
raise ValueError(
"object dtype infer out of bounds for {}".format(S.name))
first_val = S.iloc[i]
if isinstance(first_val, list):
return _infer_series_list_dtype(S)
elif isinstance(first_val, str):
return string_type
else:
raise ValueError(
"object dtype infer: data type for column {} not supported".format(S.name))
elif isinstance(S.dtype, pd.CategoricalDtype):
return numba.typeof(S.dtype)
# regular numpy types
try:
return numpy_support.from_dtype(S.dtype)
except NotImplementedError:
raise ValueError("np dtype infer: data type for column {} not supported".format(S.name))
def _infer_series_list_dtype(S):
for i in range(len(S)):
first_val = S.iloc[i]
if not isinstance(first_val, list):
raise ValueError(
"data type for column {} not supported".format(S.name))
if len(first_val) > 0:
# TODO: support more types
if isinstance(first_val[0], str):
return types.List(string_type)
else:
raise ValueError(
"data type for column {} not supported".format(S.name))
raise ValueError(
"data type for column {} not supported".format(S.name))
def _infer_index_type(index):
""" Deduces native Numba type used to represent index Python object """
if isinstance(index, pd.RangeIndex):
# depending on actual index value unbox to diff types: none-index if it matches
# positions or to RangeIndexType in general case
if (index.start == 0 and index.step == 1 and index.name is None):
return types.none
else:
if index.name is None:
return RangeIndexType()
else:
return RangeIndexType(is_named=True)
# for unsupported pandas indexes we explicitly unbox to None
if isinstance(index, pd.DatetimeIndex):
return types.none
if index.dtype == np.dtype('O'):
# TO-DO: should we check that all elements are strings?
if len(index) > 0 and isinstance(index[0], str):
return string_array_type
else:
return types.none
numba_index_type = numpy_support.from_dtype(index.dtype)
return types.Array(numba_index_type, 1, 'C')
@box(DataFrameType)
def box_dataframe(typ, val, c):
context = c.context
builder = c.builder
col_names = typ.columns
arr_typs = typ.data
dataframe = cgutils.create_struct_proxy(typ)(context, builder, value=val)
pyapi = c.pyapi
# gil_state = pyapi.gil_ensure() # acquire GIL
mod_name = context.insert_const_string(c.builder.module, "pandas")
class_obj = pyapi.import_module_noblock(mod_name)
df_dict = pyapi.dict_new()
arrays_list_objs = {}
for cname, arr_typ in zip(col_names, arr_typs):
# df['cname'] = boxed_arr
# TODO: datetime.date, DatetimeIndex?
name_str = context.insert_const_string(c.builder.module, cname)
cname_obj = pyapi.string_from_string(name_str)
col_loc = typ.column_loc[cname]
type_id, col_id = col_loc.type_id, col_loc.col_id
# dataframe.data looks like a tuple(list(array))
# e.g. ([array(int64, 1d, C), array(int64, 1d, C)], [array(float64, 1d, C)])
arrays_list_obj = arrays_list_objs.get(type_id)
if arrays_list_obj is None:
list_typ = types.List(arr_typ)
# extracting list from the tuple
list_val = builder.extract_value(dataframe.data, type_id)
# getting array from the list to box it then
arrays_list_obj = box_list(list_typ, list_val, c)
arrays_list_objs[type_id] = arrays_list_obj
# PyList_GetItem returns borrowed reference
arr_obj = pyapi.list_getitem(arrays_list_obj, col_id)
pyapi.dict_setitem(df_dict, cname_obj, arr_obj)
pyapi.decref(cname_obj)
df_obj = pyapi.call_method(class_obj, "DataFrame", (df_dict,))
pyapi.decref(df_dict)
# set df.index if necessary
if typ.index != types.none:
index_obj = _box_index_data(typ.index, dataframe.index, c)
pyapi.object_setattr_string(df_obj, 'index', index_obj)
pyapi.decref(index_obj)
for arrays_list_obj in arrays_list_objs.values():
pyapi.decref(arrays_list_obj)
pyapi.decref(class_obj)
# pyapi.gil_release(gil_state) # release GIL
return df_obj
@intrinsic
def unbox_dataframe_column(typingctx, df, i=None):
def codegen(context, builder, sig, args):
pyapi = context.get_python_api(builder)
c = numba.pythonapi._UnboxContext(context, builder, pyapi)
df_typ = sig.args[0]
col_ind = sig.args[1].literal_value
data_typ = df_typ.data[col_ind]
col_name = df_typ.columns[col_ind]
# TODO: refcounts?
dataframe = cgutils.create_struct_proxy(
sig.args[0])(context, builder, value=args[0])
series_obj = c.pyapi.object_getattr_string(dataframe.parent, col_name)
arr_obj = c.pyapi.object_getattr_string(series_obj, "values")
# TODO: support column of tuples?
native_val = _unbox_series_data(
data_typ.dtype, data_typ, arr_obj, c)
c.pyapi.decref(series_obj)
c.pyapi.decref(arr_obj)
c.context.nrt.incref(builder, df_typ.index, dataframe.index)
# assign array and set unboxed flag
dataframe.data = builder.insert_value(
dataframe.data, native_val.value, col_ind)
return dataframe._getvalue()
return signature(df, df, i), codegen
def _unbox_index_data(index_typ, index_obj, c):
""" Unboxes Pandas index object basing on the native type inferred previously.
Params:
index_typ: native Numba type the object is to be unboxed into
index_obj: Python object to be unboxed
c: LLVM context object
Returns: LLVM instructions to generate native value
"""
if isinstance(index_typ, RangeIndexType):
return unbox_range_index(index_typ, index_obj, c)
if index_typ == string_array_type:
return unbox_str_series(index_typ, index_obj, c)
if isinstance(index_typ, types.Array):
index_data = c.pyapi.object_getattr_string(index_obj, "_data")
res = unbox_array(index_typ, index_data, c)
c.pyapi.decref(index_data)
return res
if isinstance(index_typ, types.NoneType):
return unbox_none(index_typ, index_obj, c)
assert False, f"_unbox_index_data: unexpected index type({index_typ}) while unboxing"
@unbox(SeriesType)
def unbox_series(typ, val, c):
arr_obj = c.pyapi.object_getattr_string(val, "values")
series = cgutils.create_struct_proxy(typ)(c.context, c.builder)
series.data = _unbox_series_data(typ.dtype, typ.data, arr_obj, c).value
index_obj = c.pyapi.object_getattr_string(val, "index")
series.index = _unbox_index_data(typ.index, index_obj, c).value
if typ.is_named:
name_obj = c.pyapi.object_getattr_string(val, "name")
series.name = numba.cpython.unicode.unbox_unicode_str(
string_type, name_obj, c).value
c.pyapi.decref(name_obj)
c.pyapi.decref(arr_obj)
c.pyapi.decref(index_obj)
return NativeValue(series._getvalue())
def _unbox_series_data(dtype, data_typ, arr_obj, c):
if data_typ == string_array_type:
return unbox_str_series(string_array_type, arr_obj, c)
elif | |
O0
ii1I1i11 = Iii1 . get_rloc ( i1IIIIi1Ii111 )
if ( ii1I1i11 == None ) : continue
if 77 - 77: I1ii11iIi11i + OoooooooOO * OoO0O00 * iIii1I11I1II1 % I1Ii111
if 22 - 22: i1IIi
if 61 - 61: IiII
if 3 - 3: ooOoO0o . Oo0Ooo . ooOoO0o / OoO0O00 / o0oOOo0O0Ooo . I1Ii111
i1Iii1i = 0 if iIIOO0OO . has_key ( "packet-count" ) == False else iIIOO0OO [ "packet-count" ]
if 18 - 18: OOooOOo * O0 % ooOoO0o - ooOoO0o
I1i = 0 if iIIOO0OO . has_key ( "byte-count" ) == False else iIIOO0OO [ "byte-count" ]
if 46 - 46: o0oOOo0O0Ooo * oO0o / oO0o . oO0o + I11i * OOooOOo
III11I1 = 0 if iIIOO0OO . has_key ( "seconds-last-packet" ) == False else iIIOO0OO [ "seconds-last-packet" ]
if 48 - 48: iII111i + Ii1I
if 10 - 10: I1IiiI + o0oOOo0O0Ooo
ii1I1i11 . stats . packet_count += i1Iii1i
ii1I1i11 . stats . byte_count += I1i
ii1I1i11 . stats . last_increment = lisp_get_timestamp ( ) - III11I1
if 75 - 75: Oo0Ooo
lprint ( "Update stats {}/{}/{}s for {} RLOC {}" . format ( i1Iii1i , I1i ,
III11I1 , oo0ooooO , I111I ) )
if 100 - 100: i1IIi / Oo0Ooo / II111iiii + iII111i . II111iiii * oO0o
if 36 - 36: Oo0Ooo + iII111i / OOooOOo + OOooOOo % i11iIiiIii / I1IiiI
if 59 - 59: ooOoO0o / I11i
if 32 - 32: iIii1I11I1II1 % oO0o / I1Ii111
if 42 - 42: I11i / I1ii11iIi11i - I1IiiI * iII111i / I1IiiI / i11iIiiIii
if ( Iii1 . group . is_null ( ) and Iii1 . has_ttl_elapsed ( ) ) :
oo0ooooO = green ( Iii1 . print_eid_tuple ( ) , False )
lprint ( "Refresh map-cache entry {}" . format ( oo0ooooO ) )
lisp_send_map_request ( lisp_sockets , lisp_port , None , Iii1 . eid , None )
if 75 - 75: Oo0Ooo + IiII / I11i % I11i % IiII / I1Ii111
if 95 - 95: OoOoOO00
return
if 78 - 78: I11i
if 62 - 62: iIii1I11I1II1 . o0oOOo0O0Ooo . ooOoO0o % oO0o % O0 % oO0o
if 51 - 51: Oo0Ooo / IiII - Oo0Ooo
if 71 - 71: I11i * I1ii11iIi11i * OOooOOo * o0oOOo0O0Ooo
if 53 - 53: I1IiiI % I1IiiI
if 80 - 80: OoO0O00 - i11iIiiIii / iII111i * I1ii11iIi11i / I1IiiI - I1Ii111
if 85 - 85: IiII
if 72 - 72: iII111i * OoOoOO00
if 65 - 65: iIii1I11I1II1 / iIii1I11I1II1 % O0 / II111iiii . OOooOOo . O0
if 65 - 65: I11i
if 35 - 35: o0oOOo0O0Ooo - i11iIiiIii
if 78 - 78: ooOoO0o - II111iiii - i1IIi
if 18 - 18: OoooooooOO % OoOoOO00 - IiII / oO0o . OOooOOo . I1IiiI
if 77 - 77: I1ii11iIi11i . OoO0O00 / OoOoOO00 / O0
if 67 - 67: ooOoO0o % I11i % oO0o
if 74 - 74: II111iiii
if 44 - 44: Oo0Ooo + OoO0O00 + OoOoOO00 - I1IiiI
if 68 - 68: i11iIiiIii / OOooOOo . i1IIi . i11iIiiIii . I11i
if 56 - 56: iIii1I11I1II1 - II111iiii * i1IIi / Ii1I
if 65 - 65: OOooOOo / I1IiiI . OoooooooOO + I1IiiI + OoooooooOO + i11iIiiIii
if 20 - 20: I1IiiI + iII111i + O0 * O0
if 18 - 18: I11i - I11i . OoOoOO00 . ooOoO0o
if 31 - 31: ooOoO0o
def lisp_process_data_plane_decap_stats ( msg , lisp_ipc_socket ) :
if 87 - 87: OoooooooOO + OOooOOo - I1ii11iIi11i / I1IiiI + ooOoO0o - Oo0Ooo
if 19 - 19: ooOoO0o + I1ii11iIi11i - ooOoO0o
if 17 - 17: I11i * i1IIi + iIii1I11I1II1 % I1IiiI
if 44 - 44: IiII + I1IiiI . Ii1I % Oo0Ooo
if 97 - 97: O0
if ( lisp_i_am_itr ) :
lprint ( "Send decap-stats IPC message to lisp-etr process" )
Oooo000 = "stats%{}" . format ( json . dumps ( msg ) )
Oooo000 = lisp_command_ipc ( Oooo000 , "lisp-itr" )
lisp_ipc ( Oooo000 , lisp_ipc_socket , "lisp-etr" )
return
if 95 - 95: OoO0O00 % iII111i / I1IiiI * OoooooooOO
if 31 - 31: iIii1I11I1II1
if 62 - 62: o0oOOo0O0Ooo - iII111i / II111iiii . o0oOOo0O0Ooo
if 20 - 20: iIii1I11I1II1 % OOooOOo
if 91 - 91: ooOoO0o
if 96 - 96: I1IiiI . OOooOOo
if 94 - 94: OoooooooOO + II111iiii % ooOoO0o - II111iiii / O0
if 34 - 34: IiII % oO0o
Oooo000 = bold ( "IPC" , False )
lprint ( "Process decap-stats {} message: '{}'" . format ( Oooo000 , msg ) )
if 54 - 54: I1IiiI
if ( lisp_i_am_etr ) : msg = json . loads ( msg )
if 80 - 80: OoOoOO00 . I1IiiI / I1ii11iIi11i . iII111i
i1Iii11iiiII1 = [ "good-packets" , "ICV-error" , "checksum-error" ,
"lisp-header-error" , "no-decrypt-key" , "bad-inner-version" ,
"outer-header-error" ]
if 78 - 78: i11iIiiIii . o0oOOo0O0Ooo
for OOOo0oOOOO0 in i1Iii11iiiII1 :
i1Iii1i = 0 if msg . has_key ( OOOo0oOOOO0 ) == False else msg [ OOOo0oOOOO0 ] [ "packet-count" ]
if 23 - 23: I1IiiI - O0 - iII111i . II111iiii / oO0o
lisp_decap_stats [ OOOo0oOOOO0 ] . packet_count += i1Iii1i
if 1 - 1: I11i . OOooOOo / oO0o % I11i * Oo0Ooo + Oo0Ooo
I1i = 0 if msg . has_key ( OOOo0oOOOO0 ) == False else msg [ OOOo0oOOOO0 ] [ "byte-count" ]
if 23 - 23: Ii1I % i1IIi - I1Ii111
lisp_decap_stats [ OOOo0oOOOO0 ] . byte_count += I1i
if 95 - 95: OoOoOO00 - ooOoO0o . i1IIi . OoooooooOO
III11I1 = 0 if msg . has_key ( OOOo0oOOOO0 ) == False else msg [ OOOo0oOOOO0 ] [ "seconds-last-packet" ]
if 38 - 38: I1IiiI + I1ii11iIi11i - Oo0Ooo . i11iIiiIii - i1IIi
lisp_decap_stats [ OOOo0oOOOO0 ] . last_increment = lisp_get_timestamp ( ) - III11I1
if 11 - 11: IiII / I1IiiI . I1IiiI
return
if 87 - 87: OoooooooOO * OoO0O00 * iIii1I11I1II1
if 16 - 16: o0oOOo0O0Ooo * I11i + OoooooooOO + O0 / iIii1I11I1II1
if 60 - 60: Ii1I % IiII * OoooooooOO * ooOoO0o * Ii1I
if 8 - 8: I1Ii111 - o0oOOo0O0Ooo
if 52 - 52: OoOoOO00 % O0 + I1ii11iIi11i . i11iIiiIii
if 59 - 59: Ii1I - I1Ii111 . ooOoO0o - OoOoOO00 + oO0o . OoO0O00
if 88 - 88: OOooOOo - ooOoO0o * o0oOOo0O0Ooo . OoooooooOO
if 3 - 3: I1Ii111
if 24 - 24: Ii1I + i11iIiiIii * I1Ii111 - OoOoOO00 / Ii1I - OoOoOO00
if 69 - 69: I11i - I1IiiI . oO0o - OoooooooOO
if 33 - 33: o0oOOo0O0Ooo - o0oOOo0O0Ooo
if 55 - 55: OoooooooOO / IiII + i1IIi
if 54 - 54: ooOoO0o * Ii1I / Ii1I
if 15 - 15: oO0o * I1Ii111
if 11 - 11: Ii1I + o0oOOo0O0Ooo * OoooooooOO % iIii1I11I1II1
if 87 - 87: OoO0O00 + o0oOOo0O0Ooo
if 46 - 46: oO0o + OoOoOO00
def lisp_process_punt ( punt_socket , lisp_send_sockets , lisp_ephem_port ) :
I1I , IIi1IiIii = punt_socket . recvfrom ( 4000 )
if 40 - 40: OOooOOo - i11iIiiIii - I11i . i1IIi * o0oOOo0O0Ooo
iIiiIIiII1iII11 = json . loads ( I1I )
if ( type ( iIiiIIiII1iII11 ) != dict ) :
lprint ( "Invalid punt message from {}, not in JSON format" . format ( IIi1IiIii ) )
if 2 - 2: I1ii11iIi11i * IiII
return
if 64 - 64: OoooooooOO % OoooooooOO
III111ii1ii = bold ( "Punt" , False )
lprint ( "{} message from '{}': '{}'" . format ( III111ii1ii , IIi1IiIii , iIiiIIiII1iII11 ) )
if 16 - 16: OOooOOo - iII111i
if ( iIiiIIiII1iII11 . has_key ( "type" ) == False ) :
lprint ( "Punt IPC message has no 'type' key" )
return
if 5 - 5: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.