class MenuItem(BaseModel): """Menu items for dispensaries.""" name = properties.String('Name of the item.', ) type = properties.StringChoice( 'Type of item.', choices=['strain', 'flower', 'extract', 'edible', 'product'], ) item = properties.Property('The strain, extract, edible, or product.', ) price = properties.Float( 'The price for the item. This is not set for strains and extracts.', ) price_half_gram = properties.Float( 'Price for one half gram of the item. This is not set for edibles ' 'and products.', ) price_gram = properties.Float( 'Price for one gram of this item. This is not set for edibles and ' 'products.', ) price_eighth = properties.Float( 'Price for one eighth ounce of this item. This is not set for ' 'edibles and products.', ) price_quarter = properties.Float( 'Price for one quarter ounce of this item. This is not set for ' 'edibles and products.', ) price_half_ounce = properties.Float( 'Price for one half ounce of this item. This is not set for ' 'edibles and products.', ) price_ounce = properties.Float( 'Price for one ounce of this item. This is not set for ' 'edibles and products.', )
class LineageModel(LinksModelWithImage): lineage = properties.Property( 'Countries of origin for the genetics for the strain. Object keys ' 'are the country name and the values are the two character country ' 'codes.', )
def main(): wsgiref.handlers.CGIHandler().run(appl) #erase() prs = db.GqlQuery("select * from Property where name=:name", name="init") if (prs.count() == 0 or prs[0].value == "false"): init() pr = properties.Property(name="init", value="true") pr.put()
# Repeat command try: command = runInput("Command to repeat? (Type '#' to cancel) > ") if command != "#": commandRepetition = int(runInput("Number of times to repeat command? (Leave blank to cancel) > ")) + 1 except: pass elif command == "new property": # New property propertyLabel = runInput("New property's label? (Leave blank to generate) > ") propertyIsDominant = runInput("Is property dominant? [y/N] > ").lower() == "y" newProperty = properties.Property(propertyIsDominant) if propertyLabel != "": newProperty.label = propertyLabel propertySet.append(newProperty) print("New property " + str(newProperty.label) + " created") elif command == "list properties": # List properties for propertyID in range(0, len(propertySet)): print("[" + str(propertyID) + "] " + str(propertySet[propertyID].label) + " (dominant: " + str(propertySet[propertyID].isDominant) + ")") elif command == "new inhabitant": # New inhabitant
class RichardsProblem(Problem.BaseTimeProblem): """docstring for RichardsProblem""" modelMap = properties.Property("the mapping") boundaryConditions = properties.Array("boundary conditions.") initialConditions = properties.Array("boundary conditions.") surveyPair = RichardsSurvey mapPair = RichardsMap debug = properties.Bool("Show all messages") Solver = Solver solverOpts = {} def __init__(self, mesh, modelMap=None, **kwargs): assert (isinstance( modelMap, self.mapPair)), ('modelMap must be a {} class not {}'.format( self.mapPair.__class__.__name__, modelMap)) self.modelMap = modelMap Problem.BaseTimeProblem.__init__(self, mesh, **kwargs) def getBoundaryConditions(self, ii, u_ii): if type(self.boundaryConditions) is np.ndarray: return self.boundaryConditions time = self.timeMesh.vectorCCx[ii] return self.boundaryConditions(time, u_ii) method = properties.StringChoice( "Formulation used, See notes in Celia et al., 1990.", choices=['mixed', 'head']) doNewton = properties.Bool("Do a Newton iteration vs. a Picard iteration ", default=False) maxIterRootFinder = properties.Integer( "Maximum iterations for rootFinder iteration.", default=30) tolRootFinder = properties.Float( "Maximum iterations for rootFinder iteration.", default=1e-4) @properties.observer(['doNewton', 'maxIterRootFinder', 'tolRootFinder']) def _on_root_finder_update(self, change): """ Setting doNewton will clear the rootFinder, which will be reinitialized when called """ if hasattr(self, '_rootFinder'): del self._rootFinder @property def rootFinder(self): """Root-finding Algorithm""" if getattr(self, '_rootFinder', None) is None: self._rootFinder = Optimization.NewtonRoot( doLS=self.doNewton, maxIter=self.maxIterRootFinder, tol=self.tolRootFinder, Solver=self.Solver) return self._rootFinder @Utils.timeIt def fields(self, m): tic = time.time() u = list(range(self.nT + 1)) u[0] = self.initialConditions for ii, dt in enumerate(self.timeSteps): bc = self.getBoundaryConditions(ii, u[ii]) u[ii + 1] = self.rootFinder.root( lambda hn1m, return_g=True: self.getResidual( m, u[ii], hn1m, dt, bc, return_g=return_g), u[ii]) if self.debug: print("Solving Fields ({0:4d}/{1:d} - {2:3.1f}% Done) {3:d} " "Iterations, {4:4.2f} seconds".format( ii + 1, self.nT, 100.0 * (ii + 1) / self.nT, self.rootFinder.iter, time.time() - tic)) return u @property def Dz(self): if self.mesh.dim == 1: Dz = self.mesh.faceDivx elif self.mesh.dim == 2: Dz = sp.hstack((Utils.spzeros( self.mesh.nC, self.mesh.vnF[0]), self.mesh.faceDivy), format='csr') elif self.mesh.dim == 3: Dz = sp.hstack( (Utils.spzeros(self.mesh.nC, self.mesh.vnF[0] + self.mesh.vnF[1]), self.mesh.faceDivz), format='csr') return Dz @Utils.timeIt def diagsJacobian(self, m, hn, hn1, dt, bc): DIV = self.mesh.faceDiv GRAD = self.mesh.cellGrad BC = self.mesh.cellGradBC AV = self.mesh.aveF2CC.T Dz = self.Dz dT = self.modelMap.thetaDerivU(hn, m) dT1 = self.modelMap.thetaDerivU(hn1, m) K1 = self.modelMap.k(hn1, m) dK1 = self.modelMap.kDerivU(hn1, m) dKm1 = self.modelMap.kDerivM(hn1, m) # Compute part of the derivative of: # # DIV*diag(GRAD*hn1+BC*bc)*(AV*(1.0/K))^-1 DdiagGh1 = DIV * Utils.sdiag(GRAD * hn1 + BC * bc) diagAVk2_AVdiagK2 = (Utils.sdiag( (AV * (1. / K1))**(-2)) * AV * Utils.sdiag(K1**(-2))) # The matrix that we are computing has the form: # # - - - - - - # | Adiag | | h1 | | b1 | # | Asub Adiag | | h2 | | b2 | # | Asub Adiag | | h3 | = | b3 | # | ... ... | | .. | | .. | # | Asub Adiag | | hn | | bn | # - - - - - - Asub = (-1.0 / dt) * dT Adiag = ((1.0 / dt) * dT1 - DdiagGh1 * diagAVk2_AVdiagK2 * dK1 - DIV * Utils.sdiag(1. / (AV * (1. / K1))) * GRAD - Dz * diagAVk2_AVdiagK2 * dK1) B = DdiagGh1 * diagAVk2_AVdiagK2 * dKm1 + Dz * diagAVk2_AVdiagK2 * dKm1 return Asub, Adiag, B @Utils.timeIt def getResidual(self, m, hn, h, dt, bc, return_g=True): """ Where h is the proposed value for the next time iterate (h_{n+1}) """ DIV = self.mesh.faceDiv GRAD = self.mesh.cellGrad BC = self.mesh.cellGradBC AV = self.mesh.aveF2CC.T Dz = self.Dz T = self.modelMap.theta(h, m) dT = self.modelMap.thetaDerivU(h, m) Tn = self.modelMap.theta(hn, m) K = self.modelMap.k(h, m) dK = self.modelMap.kDerivU(h, m) aveK = 1. / (AV * (1. / K)) RHS = DIV * Utils.sdiag(aveK) * (GRAD * h + BC * bc) + Dz * aveK if self.method == 'mixed': r = (T - Tn) / dt - RHS elif self.method == 'head': r = dT * (h - hn) / dt - RHS if not return_g: return r J = dT / dt - DIV * Utils.sdiag(aveK) * GRAD if self.doNewton: DDharmAve = Utils.sdiag(aveK**2) * AV * Utils.sdiag(K**(-2)) * dK J = J - DIV * Utils.sdiag(GRAD * h + BC * bc) * DDharmAve - Dz * DDharmAve return r, J @Utils.timeIt def Jfull(self, m, f=None): if f is None: f = self.fields(m) nn = len(f) - 1 Asubs, Adiags, Bs = list(range(nn)), list(range(nn)), list(range(nn)) for ii in range(nn): dt = self.timeSteps[ii] bc = self.getBoundaryConditions(ii, f[ii]) Asubs[ii], Adiags[ii], Bs[ii] = self.diagsJacobian( m, f[ii], f[ii + 1], dt, bc) Ad = sp.block_diag(Adiags) zRight = Utils.spzeros((len(Asubs) - 1) * Asubs[0].shape[0], Adiags[0].shape[1]) zTop = Utils.spzeros(Adiags[0].shape[0], len(Adiags) * Adiags[0].shape[1]) As = sp.vstack((zTop, sp.hstack((sp.block_diag(Asubs[1:]), zRight)))) A = As + Ad B = np.array(sp.vstack(Bs).todense()) Ainv = self.Solver(A, **self.solverOpts) P = self.survey.evalDeriv(f, m) AinvB = Ainv * B z = np.zeros((self.mesh.nC, B.shape[1])) zAinvB = np.vstack((z, AinvB)) J = P * zAinvB return J @Utils.timeIt def Jvec(self, m, v, f=None): if f is None: f = self.fields(m) JvC = list(range(len(f) - 1)) # Cell to hold each row of the long vector # This is done via forward substitution. bc = self.getBoundaryConditions(0, f[0]) temp, Adiag, B = self.diagsJacobian(m, f[0], f[1], self.timeSteps[0], bc) Adiaginv = self.Solver(Adiag, **self.solverOpts) JvC[0] = Adiaginv * (B * v) for ii in range(1, len(f) - 1): bc = self.getBoundaryConditions(ii, f[ii]) Asub, Adiag, B = self.diagsJacobian(m, f[ii], f[ii + 1], self.timeSteps[ii], bc) Adiaginv = self.Solver(Adiag, **self.solverOpts) JvC[ii] = Adiaginv * (B * v - Asub * JvC[ii - 1]) P = self.survey.evalDeriv(f, m) return P * np.concatenate([np.zeros(self.mesh.nC)] + JvC) @Utils.timeIt def Jtvec(self, m, v, f=None): if f is None: f = self.field(m) P = self.survey.evalDeriv(f, m) PTv = P.T * v # This is done via backward substitution. minus = 0 BJtv = 0 for ii in range(len(f) - 1, 0, -1): bc = self.getBoundaryConditions(ii - 1, f[ii - 1]) Asub, Adiag, B = self.diagsJacobian(m, f[ii - 1], f[ii], self.timeSteps[ii - 1], bc) # select the correct part of v vpart = list( range((ii) * Adiag.shape[0], (ii + 1) * Adiag.shape[0])) AdiaginvT = self.Solver(Adiag.T, **self.solverOpts) JTvC = AdiaginvT * (PTv[vpart] - minus) minus = Asub.T * JTvC # this is now the super diagonal. BJtv = BJtv + B.T * JTvC return BJtv
class PropOpts(properties.HasProperties): myprop = properties.Property('empty property') maybe_none = properties.Property('maybe None', required=False)
def test_base_functionality(self): with self.assertRaises(AttributeError): properties.GettableProperty('bad kwarg', _default=5) with self.assertRaises(AttributeError): properties.GettableProperty('bad kwarg', defualt=5) with self.assertRaises(TypeError): properties.Property('bad kwarg', required=5) class GettablePropOpt(properties.HasProperties): mygp = properties.GettableProperty('gettable prop') with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].name = 5 with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].doc = 5 with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].terms = 5 with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].terms = {'one': 1, 'two': 2} with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].doc = {'args': (1,), 'otherargs': 5} gpo = GettablePropOpt() with self.assertRaises(AttributeError): setattr(gpo, 'mygp', 5) with self.assertRaises(AttributeError): GettablePropOpt(not_mygp=0) with self.assertRaises(AttributeError): GettablePropOpt(help='help') assert gpo.validate() assert gpo._props['mygp'].terms.name == 'mygp' assert gpo._props['mygp'].terms.cls is properties.GettableProperty assert gpo._props['mygp'].terms.args == ('gettable prop',) assert gpo._props['mygp'].terms.kwargs == {} assert gpo._props['mygp'].terms.meta == {} def twelve(): return 12 class GettablePropOpt(properties.HasProperties): mygp = properties.GettableProperty('gettable prop', default=twelve) assert GettablePropOpt().validate() assert GettablePropOpt().mygp == 12 class PropOpts(properties.HasProperties): myprop = properties.Property('empty property') maybe_none = properties.Property('maybe None', required=False) with self.assertRaises(ValueError): PropOpts().validate() assert PropOpts(myprop=5).validate() with warnings.catch_warnings(record=True) as w: assert PropOpts().equal(PropOpts()) assert len(w) == 1 assert issubclass(w[0].category, FutureWarning) assert properties.equal(PropOpts(), PropOpts()) assert properties.equal(PropOpts(myprop=5), PropOpts(myprop=5)) assert not properties.equal(PropOpts(myprop=5, maybe_none=3), PropOpts(myprop=5)) assert properties.equal(PropOpts(myprop=5, maybe_none=3), PropOpts(myprop=5, maybe_none=3)) assert not properties.equal(PropOpts(myprop=5), PropOpts()) assert not properties.equal(PropOpts(myprop=5), PropOpts(myprop=6)) assert not properties.equal(None, PropOpts(myprop=6)) assert not properties.equal(PropOpts(myprop=5), None) assert properties.equal(None, None) assert properties.Property('').equal(5, 5) assert not properties.Property('').equal(5, 'hi') assert properties.Property('').equal(np.array([1., 2.]), np.array([1., 2.])) assert not properties.Property('').equal(np.array([1., 2.]), np.array([3., 4.])) class NoAttributes(properties.HasProperties): a = properties.Integer('a') def __setattr__(self, attr, value): if attr[0] != '_' and value is not properties.undefined: raise AttributeError() return super(NoAttributes, self).__setattr__(attr, value) na = NoAttributes() with self.assertRaises(AttributeError): na.a = 5
class PrivateProperty(properties.HasProperties): _doc_private = True _something = properties.Property('empty property')
class DifferentDocOrder(WithDocOrder): myprop4 = properties.Property('empty property')
class SameDocOrder(WithDocOrder): _my_private_prop = properties.Property('empty property')
class WithDocOrder(properties.HasProperties): _doc_order = ['myprop1', 'myprop3', 'myprop2'] myprop1 = properties.Property('empty property') myprop2 = properties.Property('empty property') myprop3 = properties.Property('empty property')
class BadDocOrder(properties.HasProperties): _doc_order = ['myprop', 'another_prop'] myprop = properties.Property('empty property')
class RichardsProblem(Problem.BaseTimeProblem): """RichardsProblem""" hydraulic_conductivity = properties.Instance( 'hydraulic conductivity function', BaseHydraulicConductivity ) water_retention = properties.Instance( 'water retention curve', BaseWaterRetention ) # TODO: This can also be a function(time, u_ii) boundary_conditions = properties.Array('boundary conditions') initial_conditions = properties.Array('initial conditions') debug = properties.Bool('Show all messages', default=False) Solver = properties.Property('Numerical Solver', default=lambda: Solver) solverOpts = {} method = properties.StringChoice( 'Formulation used, See notes in Celia et al., 1990', default='mixed', choices=['mixed', 'head'] ) do_newton = properties.Bool( 'Do a Newton iteration vs. a Picard iteration', default=False ) root_finder_max_iter = properties.Integer( 'Maximum iterations for root_finder iteration', default=30 ) root_finder_tol = properties.Float( 'tolerance of the root_finder', default=1e-4 ) @properties.observer('model') def _on_model_change(self, change): """Update the nested model functions when the model of the problem changes. Specifically :code:`hydraulic_conductivity` and :code:`water_retention` models are updated iff they have mappings. """ if ( not self.hydraulic_conductivity.needs_model and not self.water_retention.needs_model ): warnings.warn('There is no model to set.') return model = change['value'] if self.hydraulic_conductivity.needs_model: self.hydraulic_conductivity.model = model if self.water_retention.needs_model: self.water_retention.model = model def getBoundaryConditions(self, ii, u_ii): if type(self.boundary_conditions) is np.ndarray: return self.boundary_conditions time = self.timeMesh.vectorCCx[ii] return self.boundary_conditions(time, u_ii) @properties.observer([ 'do_newton', 'root_finder_max_iter', 'root_finder_tol' ]) def _on_root_finder_update(self, change): """Setting do_newton etc. will clear the root_finder, which will be reinitialized when called """ if hasattr(self, '_root_finder'): del self._root_finder @property def root_finder(self): """Root-finding Algorithm""" if getattr(self, '_root_finder', None) is None: self._root_finder = Optimization.NewtonRoot( doLS=self.do_newton, maxIter=self.root_finder_max_iter, tol=self.root_finder_tol, Solver=self.Solver ) return self._root_finder @Utils.timeIt def fields(self, m=None): if self.water_retention.needs_model or self.hydraulic_conductivity.needs_model: assert m is not None else: assert m is None tic = time.time() u = list(range(self.nT+1)) u[0] = self.initial_conditions for ii, dt in enumerate(self.timeSteps): bc = self.getBoundaryConditions(ii, u[ii]) u[ii+1] = self.root_finder.root( lambda hn1m, return_g=True: self.getResidual( m, u[ii], hn1m, dt, bc, return_g=return_g ), u[ii] ) if self.debug: print( 'Solving Fields ({0:4d}/{1:d} - {2:3.1f}% Done) {3:d} ' 'Iterations, {4:4.2f} seconds'.format( ii+1, self.nT, 100.0*(ii+1)/self.nT, self.root_finder.iter, time.time() - tic ) ) return u @property def Dz(self): if self.mesh.dim == 1: return self.mesh.faceDivx if self.mesh.dim == 2: mats = ( Utils.spzeros(self.mesh.nC, self.mesh.vnF[0]), self.mesh.faceDivy ) elif self.mesh.dim == 3: mats = ( Utils.spzeros(self.mesh.nC, self.mesh.vnF[0]+self.mesh.vnF[1]), self.mesh.faceDivz ) return sp.hstack(mats, format='csr') @Utils.timeIt def diagsJacobian(self, m, hn, hn1, dt, bc): """Diagonals and rhs of the jacobian system The matrix that we are computing has the form:: .- -. .- -. .- -. | Adiag | | h1 | | b1 | | Asub Adiag | | h2 | | b2 | | Asub Adiag | | h3 | = | b3 | | ... ... | | .. | | .. | | Asub Adiag | | hn | | bn | '- -' '- -' '- -' """ if m is not None: self.model = m DIV = self.mesh.faceDiv GRAD = self.mesh.cellGrad BC = self.mesh.cellGradBC AV = self.mesh.aveF2CC.T Dz = self.Dz dT = self.water_retention.derivU(hn) dT1 = self.water_retention.derivU(hn1) dTm = self.water_retention.derivM(hn) dTm1 = self.water_retention.derivM(hn1) K1 = self.hydraulic_conductivity(hn1) dK1 = self.hydraulic_conductivity.derivU(hn1) dKm1 = self.hydraulic_conductivity.derivM(hn1) # Compute part of the derivative of: # # DIV*diag(GRAD*hn1+BC*bc)*(AV*(1.0/K))^-1 DdiagGh1 = DIV*Utils.sdiag(GRAD*hn1+BC*bc) diagAVk2_AVdiagK2 = ( Utils.sdiag((AV*(1./K1))**(-2)) * AV*Utils.sdiag(K1**(-2)) ) Asub = (-1.0/dt)*dT Adiag = ( (1.0/dt)*dT1 - DdiagGh1*diagAVk2_AVdiagK2*dK1 - DIV*Utils.sdiag(1./(AV*(1./K1)))*GRAD - Dz*diagAVk2_AVdiagK2*dK1 ) B = ( DdiagGh1*diagAVk2_AVdiagK2*dKm1 + Dz*diagAVk2_AVdiagK2*dKm1 + (1.0/dt)*(dTm - dTm1) ) return Asub, Adiag, B @Utils.timeIt def getResidual(self, m, hn, h, dt, bc, return_g=True): """Used by the root finder when going between timesteps Where h is the proposed value for the next time iterate (h_{n+1}) """ if m is not None: self.model = m DIV = self.mesh.faceDiv GRAD = self.mesh.cellGrad BC = self.mesh.cellGradBC AV = self.mesh.aveF2CC.T Dz = self.Dz T = self.water_retention(h) dT = self.water_retention.derivU(h) Tn = self.water_retention(hn) K = self.hydraulic_conductivity(h) dK = self.hydraulic_conductivity.derivU(h) aveK = 1./(AV*(1./K)) RHS = DIV*Utils.sdiag(aveK)*(GRAD*h+BC*bc) + Dz*aveK if self.method == 'mixed': r = (T-Tn)/dt - RHS elif self.method == 'head': r = dT*(h - hn)/dt - RHS if not return_g: return r J = dT/dt - DIV*Utils.sdiag(aveK)*GRAD if self.do_newton: DDharmAve = Utils.sdiag(aveK**2)*AV*Utils.sdiag(K**(-2)) * dK J = J - DIV*Utils.sdiag(GRAD*h + BC*bc)*DDharmAve - Dz*DDharmAve return r, J @Utils.timeIt def Jfull(self, m=None, f=None): if f is None: f = self.fields(m) nn = len(f)-1 Asubs, Adiags, Bs = list(range(nn)), list(range(nn)), list(range(nn)) for ii in range(nn): dt = self.timeSteps[ii] bc = self.getBoundaryConditions(ii, f[ii]) Asubs[ii], Adiags[ii], Bs[ii] = self.diagsJacobian( m, f[ii], f[ii+1], dt, bc ) Ad = sp.block_diag(Adiags) zRight = Utils.spzeros( (len(Asubs)-1)*Asubs[0].shape[0], Adiags[0].shape[1] ) zTop = Utils.spzeros( Adiags[0].shape[0], len(Adiags)*Adiags[0].shape[1] ) As = sp.vstack((zTop, sp.hstack((sp.block_diag(Asubs[1:]), zRight)))) A = As + Ad B = np.array(sp.vstack(Bs).todense()) Ainv = self.Solver(A, **self.solverOpts) AinvB = Ainv * B z = np.zeros((self.mesh.nC, B.shape[1])) du_dm = np.vstack((z, AinvB)) J = self.survey.deriv(f, du_dm_v=du_dm) # not multiplied by v return J @Utils.timeIt def Jvec(self, m, v, f=None): if f is None: f = self.fields(m) JvC = list(range(len(f)-1)) # Cell to hold each row of the long vector # This is done via forward substitution. bc = self.getBoundaryConditions(0, f[0]) temp, Adiag, B = self.diagsJacobian( m, f[0], f[1], self.timeSteps[0], bc ) Adiaginv = self.Solver(Adiag, **self.solverOpts) JvC[0] = Adiaginv * (B*v) for ii in range(1, len(f)-1): bc = self.getBoundaryConditions(ii, f[ii]) Asub, Adiag, B = self.diagsJacobian( m, f[ii], f[ii+1], self.timeSteps[ii], bc ) Adiaginv = self.Solver(Adiag, **self.solverOpts) JvC[ii] = Adiaginv * (B*v - Asub*JvC[ii-1]) du_dm_v = np.concatenate([np.zeros(self.mesh.nC)] + JvC) Jv = self.survey.deriv(f, du_dm_v=du_dm_v, v=v) return Jv @Utils.timeIt def Jtvec(self, m, v, f=None): if f is None: f = self.field(m) PTv, PTdv = self.survey.derivAdjoint(f, v=v) # This is done via backward substitution. minus = 0 BJtv = 0 for ii in range(len(f)-1, 0, -1): bc = self.getBoundaryConditions(ii-1, f[ii-1]) Asub, Adiag, B = self.diagsJacobian( m, f[ii-1], f[ii], self.timeSteps[ii-1], bc ) # select the correct part of v vpart = list(range((ii)*Adiag.shape[0], (ii+1)*Adiag.shape[0])) AdiaginvT = self.Solver(Adiag.T, **self.solverOpts) JTvC = AdiaginvT * (PTv[vpart] - minus) minus = Asub.T*JTvC # this is now the super diagonal. BJtv = BJtv + B.T*JTvC return BJtv + PTdv
class PropOpts(properties.HasProperties): myprop = properties.Property('empty property')
def test_base_functionality(self): with self.assertRaises(AttributeError): properties.GettableProperty('bad kwarg', _default=5) with self.assertRaises(AttributeError): properties.GettableProperty('bad kwarg', defualt=5) with self.assertRaises(TypeError): properties.Property('bad kwarg', required=5) with self.assertRaises(AttributeError): class PrivateProperty(properties.HasProperties): _secret = properties.GettableProperty('secret prop') class GettablePropOpt(properties.HasProperties): mygp = properties.GettableProperty('gettable prop') with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].name = 5 with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].doc = 5 with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].terms = 5 with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].terms = {'one': 1, 'two': 2} with self.assertRaises(TypeError): GettablePropOpt._props['mygp'].doc = { 'args': (1, ), 'otherargs': 5 } gpo = GettablePropOpt() with self.assertRaises(AttributeError): setattr(gpo, 'mygp', 5) with self.assertRaises(AttributeError): GettablePropOpt(not_mygp=0) with self.assertRaises(AttributeError): GettablePropOpt(help='help') assert gpo.validate() assert gpo._props['mygp'].terms.name == 'mygp' assert gpo._props['mygp'].terms.cls is properties.GettableProperty assert gpo._props['mygp'].terms.args == ('gettable prop', ) assert gpo._props['mygp'].terms.kwargs == {} assert gpo._props['mygp'].terms.meta == {} def twelve(): return 12 class GettablePropOpt(properties.HasProperties): mygp = properties.GettableProperty('gettable prop', default=twelve) assert GettablePropOpt().validate() assert GettablePropOpt().mygp == 12 class PropOpts(properties.HasProperties): myprop = properties.Property('empty property') with self.assertRaises(ValueError): PropOpts().validate() assert PropOpts(myprop=5).validate() with warnings.catch_warnings(record=True) as w: assert PropOpts().equal(PropOpts()) assert len(w) == 1 assert issubclass(w[0].category, FutureWarning) assert properties.equal(PropOpts(), PropOpts()) assert properties.equal(PropOpts(myprop=5), PropOpts(myprop=5)) assert not properties.equal(PropOpts(myprop=5), PropOpts()) assert not properties.equal(PropOpts(myprop=5), PropOpts(myprop=6)) with self.assertRaises(AttributeError): class BadDocOrder(properties.HasProperties): _doc_order = 5 with self.assertRaises(AttributeError): class BadDocOrder(properties.HasProperties): _doc_order = ['myprop', 'another_prop'] myprop = properties.Property('empty property') class WithDocOrder(properties.HasProperties): _doc_order = ['myprop1', 'myprop3', 'myprop2'] myprop1 = properties.Property('empty property') myprop2 = properties.Property('empty property') myprop3 = properties.Property('empty property') assert WithDocOrder().__doc__ == ( '\n\n**Required Properties:**\n\n' '* **myprop1** (:class:`Property <properties.Property>`): ' 'empty property\n' '* **myprop3** (:class:`Property <properties.Property>`): ' 'empty property\n' '* **myprop2** (:class:`Property <properties.Property>`): ' 'empty property') class NoMoreDocOrder(WithDocOrder): _doc_order = None assert properties.Property('').equal(5, 5) assert not properties.Property('').equal(5, 'hi') assert properties.Property('').equal(np.array([1., 2.]), np.array([1., 2.])) assert not properties.Property('').equal(np.array([1., 2.]), np.array([3., 4.]))
import random import properties inhabitantIterator = 0 maleGender = properties.Property(False) femaleGender = properties.Property(False) maleGender.label = "male" femaleGender.label = "female" MALE = 0 FEMALE = 1 class Inhabitant: def __init__(self, birthtick, passedPropertyPairs): global inhabitantIterator self.birthtick = birthtick self.propertyPairs = passedPropertyPairs self.expressedProperties = [] for propertyPair in self.propertyPairs: self.expressedProperties.append(propertyPair.dominantProperty) self.gender = None for propertyObject in self.expressedProperties: if propertyObject is maleGender: